diff --git a/docs/de/platform/projects/task-automation.md b/docs/de/platform/projects/task-automation.md index 7d286a2f41..31ebb3faa6 100644 --- a/docs/de/platform/projects/task-automation.md +++ b/docs/de/platform/projects/task-automation.md @@ -134,6 +134,8 @@ Bei behebbaren Fehlern folgen bis zu drei automatische Wiederholungsversuche, di Eine automatische Wiederholung setzt die Arbeit der Person fort, die den Lauf gestartet hat. Sie startet deshalb nur dort, wo diese Person den Lauf jetzt selbst starten könnte: Das Projekt muss noch aktiv sein, und sie muss die Aufgabe weiterhin ändern dürfen. Archiviert ein Admin das Projekt, verlässt die Person die Organisation oder darf sie die Aufgabe nicht mehr ändern, startet keine weitere Wiederholung, und der Lauf bleibt fehlgeschlagen. Das gilt auch für eine Erwähnung, die den Agenten erst nach dem Ende seines Laufs erreicht. Sobald das Projekt wiederhergestellt ist, kann jeder, der die Aufgabe ändern darf, **Erneut ausführen** nutzen. +Bevor ein neuer Lauf mit der Arbeit beginnt, kann sich eine kurze Verbindungsstörung zum Abo-Broker innerhalb desselben Laufs beheben. Hat der Lauf die vollen Berechtigungen des Agenten, sendet Tale höchstens drei GET-Anfragen mit mindestens fünf und danach zehn Sekunden Abstand. Für die Anfragen und die Annahme des Ergebnisses gilt ein gemeinsames Budget von 60 Sekunden. Innerhalb dieses Abrufs hält Tale die vom Broker verlangte Wartezeit ein oder bricht ab, wenn sie nicht mehr ins Budget passt. Diese Wartezeit wird nicht auf einen späteren Lauf übertragen; die Regeln für Wiederholungen und stündliche Starts gelten weiterhin. Datenbank- und DNS-Prüfungen sowie das Schließen der Verbindung können die abschließende Ablehnung verzögern. Diese Anfragen zählen weder als zusätzlicher Aufgabenstart noch als automatische Wiederholung. Vor einer weiteren Anfrage und vor der Rückgabe eines Tokens prüft Tale den Lauf und den Zugang erneut. Für eingeschränkte Läufe von Mitgliedern, POST-Broker, abgelehnte Zugänge und pausierende Broker-Konten ändert sich nichts. + Ein Agent, der über einen Abo-Broker arbeitet, kann sein Token mitten in der Arbeit verlieren, wenn der Broker das Konto erneuert. Die Wiederholung setzt die Konversation dann mit einem neuen Token fort, ohne den Versuchszähler zu erhöhen: Sie zeigt denselben Stand wie der Lauf, den sie ersetzt. Zeigte dieser keinen oder hatte er mindestens fünfzehn Minuten gearbeitet und damit ein neues Versuchskontingent erhalten, steht dort **Nach einer Token-Erneuerung fortgesetzt**. Nach zwei solchen Unterbrechungen in Folge zählt eine weitere wie jeder andere Fehler. Ein Lauf kann auch gar nicht erst starten, weil alle Konten seines Abo-Brokers nach Erreichen eines Rate-Limits pausieren. Seine Wiederholung wird dann sofort eingereiht, startet aber erst, sobald das erste Konto wieder verfügbar ist, spätestens eine Minute später. Die Wartezeit verbraucht keinen Versuch, wenn der abgelehnte Lauf unmittelbar auf einen HTTP-429-Fehler desselben Agenten folgt. Diese eine Wartezeit erhöht auch nicht die stündliche Zahl automatisierter Starts der Aufgabe: Der Fehler wegen des Rate-Limits wurde bereits gezählt. Eine weitere Ablehnung wegen der Broker-Wartezeit direkt danach oder eine nach einem anderen Fehler zählt für beide Grenzen. diff --git a/docs/en/platform/projects/task-automation.md b/docs/en/platform/projects/task-automation.md index 770b537d33..9da71555eb 100644 --- a/docs/en/platform/projects/task-automation.md +++ b/docs/en/platform/projects/task-automation.md @@ -134,6 +134,8 @@ Recoverable failures get up to three automatic retries, which start right away e An automatic retry continues the work of the person who started the run, so it starts only where that person could start the run now: the project must still be active, and they must still be allowed to change the task. If an admin archives the project, or that person leaves the organization or loses the right to change the task, no further retry starts and the run stays failed. The same applies to a mention that reaches the agent only after its run has ended. Once the project is restored, anyone who can change the task can use **Retry**. +Before a new run starts working, a short connection failure to its subscription broker can recover within that same run. For a run with the agent’s full permissions, Tale makes at most three GET requests, waiting at least five seconds and then ten seconds between them, within a shared 60-second request-and-result budget. Within that resolution, Tale waits at least as long as the broker requests or stops if the wait cannot fit. That transport wait is not carried into a later run; normal retry and hourly-start rules still apply. Database and DNS checks, as well as connection cleanup, can delay the final refusal. These requests add no task start or automatic retry. Tale checks the run and credential again before retrying or returning a token. Member-confined runs, POST brokers, rejected credentials and account cooldowns keep their existing behavior. + An agent served by a subscription broker can lose its token while it works, when the broker refreshes the account. The retry then continues the conversation on a fresh token, and the attempt count does not advance: the retry shows the same count as the run it replaces, or **Resumed after a token refresh** when that run showed none or had worked for at least fifteen minutes, which earned it a fresh retry allowance. After two such interruptions in a row, a further one counts like any other failure. A run can also fail to start because every account of its subscription broker is cooling down after a rate limit. Its retry is queued at once but starts only when the first account is available again, at most a minute later. The wait uses no attempt when the refused run immediately follows the same agent’s HTTP 429 failure. That single wait also adds no start to the task’s hourly automated-start count: the rate-limit failure already counted. A consecutive cooldown refusal, or one following any other failure, counts toward both limits. diff --git a/docs/fr/platform/projects/task-automation.md b/docs/fr/platform/projects/task-automation.md index 1138f39d4c..8973c19af6 100644 --- a/docs/fr/platform/projects/task-automation.md +++ b/docs/fr/platform/projects/task-automation.md @@ -134,6 +134,8 @@ Un échec récupérable donne lieu à jusqu’à trois nouvelles tentatives apr Une nouvelle tentative automatique poursuit le travail de la personne qui a démarré l’exécution : elle ne démarre donc que là où cette personne pourrait la lancer maintenant. Le projet doit encore être actif, et cette personne doit toujours avoir le droit de modifier la tâche. Si un administrateur archive le projet, ou si cette personne quitte l’organisation ou perd le droit de modifier la tâche, aucune nouvelle tentative ne démarre et l’exécution reste en échec. Il en va de même pour une mention qui n’atteint l’agent qu’après la fin de son exécution. Une fois le projet restauré, toute personne qui peut modifier la tâche peut utiliser **Relancer**. +Avant qu’une nouvelle exécution commence à travailler, une brève panne de connexion au courtier d’abonnement peut être surmontée au sein de cette même exécution. Si celle-ci dispose de tous les droits de l’agent, Tale effectue au plus trois requêtes GET, espacées d’au moins cinq puis dix secondes, avec un budget commun de 60 secondes pour les requêtes et l’acceptation du résultat. Pour cet accès au courtier, Tale respecte au moins l’attente demandée ou s’arrête si elle dépasse le budget restant. Cette attente n’est pas reportée sur une exécution ultérieure ; les règles de relance et la limite horaire des démarrages continuent de s’appliquer. Les vérifications en base de données et DNS, ainsi que la fermeture des connexions, peuvent retarder le refus final. Ces requêtes n’ajoutent ni démarrage de tâche ni tentative automatique. Tale vérifie à nouveau l’exécution et l’identifiant avant chaque nouvelle requête et avant de renvoyer un jeton. Les exécutions limitées des Membres, les courtiers POST, les identifiants refusés et les comptes en période d’attente conservent leur fonctionnement actuel. + Un agent servi par un courtier d’abonnement peut perdre son jeton en cours de travail, lorsque le courtier actualise le compte. La nouvelle tentative poursuit alors la conversation avec un nouveau jeton, sans faire avancer le compteur de tentatives : elle affiche le même compteur que l’exécution qu’elle remplace, ou **Reprise après l'actualisation du jeton** si celle-ci n’en affichait aucun ou avait travaillé au moins quinze minutes, ce qui lui a valu une nouvelle réserve de tentatives. Après deux interruptions de ce type d’affilée, une nouvelle interruption compte comme n’importe quel autre échec. Une exécution peut aussi ne pas démarrer du tout, parce que tous les comptes de son courtier d’abonnement sont en pause après avoir atteint une limite de requêtes. Sa nouvelle tentative est alors mise en file d’attente aussitôt, mais ne démarre que lorsque le premier compte redevient disponible, au plus tard une minute après. Cette attente ne consomme aucune tentative si l’exécution refusée suit immédiatement un échec HTTP 429 du même agent. Cette seule attente n’ajoute pas non plus de démarrage au compteur horaire des démarrages automatisés de la tâche : l’échec dû à la limite de requêtes a déjà été compté. Un refus consécutif pour la même attente, ou un refus après un autre échec, compte pour les deux limites. diff --git a/services/platform/backend/core/provider_credentials/broker_transport.test.ts b/services/platform/backend/core/provider_credentials/broker_transport.test.ts new file mode 100644 index 0000000000..3d5327e34d --- /dev/null +++ b/services/platform/backend/core/provider_credentials/broker_transport.test.ts @@ -0,0 +1,353 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { + safeFetch, + SafeFetchError, + setSafeFetchResolverForTests, + type ResolvedAddress, + type SafeFetchResponse, +} from '../../../lib/net/safe-fetch'; +import { + brokerTransportDeadline, + withBrokerTransport, + type BrokerTransportScope, +} from './broker_transport'; + +function response(status = 200, retryAfter?: string): SafeFetchResponse { + return { + status, + statusText: '', + body: '{}', + finalUrl: 'https://broker.example/pool', + headers: new Headers( + retryAfter === undefined ? {} : { 'retry-after': retryAfter }, + ), + }; +} + +function settled(promise: Promise) { + return promise.then( + (value) => ({ value, error: undefined }), + (error: unknown) => ({ value: undefined, error }), + ); +} + +function fixture( + extra: Partial> = {}, +) { + const scope = { + deadlineAt: Date.now() + 120_000, + assertCurrent: vi.fn(async () => {}), + ...extra, + }; + const credential = vi.fn(async () => {}); + const fetch = vi.fn(async (_remaining: number, _signal: AbortSignal) => + response(), + ); + return { + scope, + credential, + fetch, + run: () => + settled( + withBrokerTransport(scope, credential, (transport) => + transport.request(fetch), + ), + ), + }; +} + +beforeEach(() => { + vi.useFakeTimers({ + toFake: ['Date', 'performance', 'setTimeout', 'clearTimeout'], + }); + vi.setSystemTime(new Date('2026-10-08T04:30:00Z')); + vi.spyOn(Math, 'random').mockReturnValue(0); +}); + +afterEach(() => { + expect(vi.getTimerCount()).toBe(0); + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +it('backs off 5s then10s and stops after three requests', async () => { + const f = fixture(); + f.fetch.mockResolvedValue(response(521)); + const result = f.run(); + await vi.advanceTimersByTimeAsync(4_999); + expect(f.fetch).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(1); + expect(f.fetch).toHaveBeenCalledTimes(2); + await vi.advanceTimersByTimeAsync(9_999); + expect(f.fetch).toHaveBeenCalledTimes(2); + await vi.advanceTimersByTimeAsync(1); + expect((await result).value?.status).toBe(521); + expect(f.fetch).toHaveBeenCalledTimes(3); + expect(f.fetch.mock.calls.map(([remaining]) => remaining)).toEqual([ + 60_000, 55_000, 45_000, + ]); +}); + +it.each(['network_error', 'dns_failed', 'timeout'] as const)( + 'recovers typed %s only', + async (kind) => { + const f = fixture(); + f.fetch.mockRejectedValueOnce( + new SafeFetchError(kind, 'synthetic diagnostic'), + ); + const result = f.run(); + await vi.advanceTimersByTimeAsync(5_000); + expect((await result).value?.status).toBe(200); + expect(f.fetch).toHaveBeenCalledTimes(2); + }, +); + +it.each([ + 'tls_error', + 'aborted', + 'private_ip', + 'host_not_allowed', + 'response_too_large', + 'redirect_limit_exceeded', +] as const)('does not retry %s', async (kind) => { + const f = fixture(); + const error = new SafeFetchError(kind, 'synthetic diagnostic'); + f.fetch.mockRejectedValue(error); + expect((await f.run()).error).toBe(error); + expect(f.fetch).toHaveBeenCalledTimes(1); +}); + +it('does not retry untyped errors that resemble a transport failure', async () => { + const f = fixture(); + const error = new Error('HTTP521 timeout'); + f.fetch.mockRejectedValue(error); + expect((await f.run()).error).toBe(error); + expect(f.fetch).toHaveBeenCalledTimes(1); +}); + +it.each([400, 401, 403, 404, 429, 500, 522])( + 'does not retry HTTP%s', + async (status) => { + const f = fixture(); + f.fetch.mockResolvedValue(response(status)); + expect((await f.run()).value?.status).toBe(status); + expect(f.fetch).toHaveBeenCalledTimes(1); + }, +); + +describe('Retry-After floors', () => { + it.each(['12', 'Thu, 08 Oct 2026 04:30:12 GMT'])( + 'honors %s even across a wall-clock jump', + async (header) => { + const f = fixture(); + f.fetch.mockResolvedValueOnce(response(503, header)); + const result = f.run(); + await vi.advanceTimersByTimeAsync(1); + vi.setSystemTime(new Date('2026-10-07T04:30:00Z')); + await vi.advanceTimersByTimeAsync(11_998); + expect(f.fetch).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(1); + expect((await result).value?.status).toBe(200); + expect(f.fetch).toHaveBeenCalledTimes(2); + }, + ); + + it.each(['0', 'Thu, 08 Oct 2026 04:29:00 GMT'])( + 'keeps local backoff for %s', + async (header) => { + const f = fixture(); + f.fetch.mockResolvedValueOnce(response(503, header)); + const result = f.run(); + await vi.advanceTimersByTimeAsync(4_999); + expect(f.fetch).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(1); + expect((await result).value?.status).toBe(200); + }, + ); + + it.each(['60', '9999999999999999999999999', '-1', '1.5', 'later', '1, 2'])( + 'holds without shortening %s', + async (header) => { + const f = fixture(); + f.fetch.mockResolvedValue(response(503, header)); + expect((await f.run()).value?.status).toBe(503); + expect(f.fetch).toHaveBeenCalledTimes(1); + }, + ); + + it.each([ + 'Abc, 08 Oct 2026 04:30:12 GMT', + 'Mon, 08 Oct 2026 04:30:12 GMT', + 'Thu, 31 Feb 2026 04:30:12 GMT', + ])('refuses a noncanonical HTTP date: %s', async (header) => { + const f = fixture(); + f.fetch.mockResolvedValue(response(503, header)); + const result = f.run(); + await vi.advanceTimersByTimeAsync(30_000); + expect((await result).value?.status).toBe(503); + expect(f.fetch).toHaveBeenCalledTimes(1); + }); +}); + +it('aborts backoff on the existing job signal', async () => { + const controller = new AbortController(); + const f = fixture({ signal: controller.signal }); + f.fetch.mockResolvedValue(response(521)); + const result = f.run(); + await vi.advanceTimersByTimeAsync(1); + controller.abort(); + expect((await result).error).toMatchObject({ kind: 'aborted' }); + expect(f.fetch).toHaveBeenCalledTimes(1); +}); + +it('refuses late DNS completion without abandoning the resolver or dialing', async () => { + const dns = Promise.withResolvers(); + const lookup = vi.fn(() => dns.promise); + const fetch = vi.fn(); + const f = fixture(); + setSafeFetchResolverForTests(lookup); + vi.stubGlobal('fetch', fetch); + f.fetch.mockImplementation((remaining, signal) => + safeFetch('https://broker.example/pool', { + timeoutMs: Math.min(30_000, remaining), + signal, + }), + ); + const result = f.run(); + let finished = false; + void result.then(() => { + finished = true; + }); + try { + await vi.advanceTimersByTimeAsync(60_000); + expect(lookup).toHaveBeenCalledTimes(1); + expect(finished).toBe(false); + expect(fetch).not.toHaveBeenCalled(); + dns.resolve([{ address: '8.8.8.8', family: 4 }]); + expect((await result).error).toMatchObject({ kind: 'aborted' }); + expect(fetch).not.toHaveBeenCalled(); + } finally { + dns.resolve([]); + await result; + setSafeFetchResolverForTests(null); + vi.unstubAllGlobals(); + } +}); + +it('forwards job abort to the in-flight response without exposing its reason', async () => { + const controller = new AbortController(); + const f = fixture({ signal: controller.signal }); + f.fetch.mockImplementation( + (_ms, signal) => + new Promise((_resolve, reject) => { + signal.addEventListener( + 'abort', + () => reject(new SafeFetchError('aborted', 'request aborted')), + { once: true }, + ); + }), + ); + const result = f.run(); + await vi.advanceTimersByTimeAsync(1); + controller.abort(new Error('synthetic-secret')); + expect((await result).error).toMatchObject({ + kind: 'aborted', + message: 'Broker transport stopped.', + }); + expect(f.fetch).toHaveBeenCalledTimes(1); +}); + +it('refuses an already-aborted job before reading or fetching', async () => { + const controller = new AbortController(); + controller.abort(); + const f = fixture({ signal: controller.signal }); + expect((await f.run()).error).toMatchObject({ kind: 'aborted' }); + expect(f.credential).not.toHaveBeenCalled(); + expect(f.fetch).not.toHaveBeenCalled(); +}); + +it('observes native cancellation before another request, without polling while sleeping', async () => { + const f = fixture(); + f.fetch.mockResolvedValue(response(521)); + const result = f.run(); + await vi.advanceTimersByTimeAsync(1); + const calls = f.scope.assertCurrent.mock.calls.length; + f.scope.assertCurrent.mockRejectedValue(new Error('native cancellation')); + await vi.advanceTimersByTimeAsync(4_998); + expect(f.scope.assertCurrent).toHaveBeenCalledTimes(calls); + await vi.advanceTimersByTimeAsync(1); + expect((await result).error).toMatchObject({ + message: 'native cancellation', + }); + expect(f.fetch).toHaveBeenCalledTimes(1); +}); + +it('refuses a result when authority changes at final publication', async () => { + const f = fixture(); + f.scope.assertCurrent + .mockResolvedValueOnce() + .mockResolvedValueOnce() + .mockRejectedValue(new Error('rotated')); + expect((await f.run()).error).toMatchObject({ message: 'rotated' }); + expect(f.fetch).toHaveBeenCalledTimes(1); +}); + +it('rechecks native authority after the final awaited credential read', async () => { + const f = fixture(); + let live = true; + f.scope.assertCurrent.mockImplementation(async () => { + if (!live) throw new Error('native run rotated during credential read'); + }); + let reads = 0; + f.credential.mockImplementation(async () => { + if (++reads === 3) live = false; + }); + expect((await f.run()).error).toMatchObject({ + message: 'native run rotated during credential read', + }); + expect(f.fetch).toHaveBeenCalledTimes(1); +}); + +it('counts initial lookup time and awaits a late query without publishing its result', async () => { + const f = fixture(); + const deadline = brokerTransportDeadline(f.scope); + await vi.advanceTimersByTimeAsync(59_000); + let finish: (() => void) | undefined; + f.credential.mockImplementationOnce( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + const result = settled( + withBrokerTransport( + f.scope, + f.credential, + (transport) => transport.request(f.fetch), + deadline, + ), + ); + await vi.advanceTimersByTimeAsync(2_000); + expect(f.fetch).not.toHaveBeenCalled(); + expect(finish).toBeDefined(); + finish?.(); + expect((await result).error).toMatchObject({ kind: 'aborted' }); +}); + +it('caps the request at native remaining time and refuses its late completion', async () => { + const f = fixture({ deadlineAt: Date.now() + 1_000 }); + let finish: ((value: SafeFetchResponse) => void) | undefined; + f.fetch.mockImplementation( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + const result = f.run(); + await vi.advanceTimersByTimeAsync(1_001); + expect(f.fetch.mock.calls[0]?.[0]).toBe(1_000); + expect(f.fetch.mock.calls[0]?.[1].aborted).toBe(true); + finish?.(response()); + expect((await result).error).toMatchObject({ kind: 'aborted' }); +}); diff --git a/services/platform/backend/core/provider_credentials/broker_transport.ts b/services/platform/backend/core/provider_credentials/broker_transport.ts new file mode 100644 index 0000000000..f5e70d867c --- /dev/null +++ b/services/platform/backend/core/provider_credentials/broker_transport.ts @@ -0,0 +1,152 @@ +import { + SafeFetchError, + type SafeFetchResponse, +} from '../../../lib/net/safe-fetch'; + +/** Internal execution scope, never accepted from a credential or task input. */ +export interface BrokerTransportScope { + readonly deadlineAt: number; + readonly signal?: AbortSignal; + readonly assertCurrent: () => Promise; +} + +export interface BrokerTransport { + readonly request: ( + fetch: ( + remainingMs: number, + signal: AbortSignal, + ) => Promise, + ) => Promise; +} + +const TRANSIENT_STATUSES = new Set([502, 503, 504, 521]); +const TRANSIENT_KINDS = new Set(['network_error', 'dns_failed', 'timeout']); +const BACKOFF_MS = [5_000, 10_000]; + +/** Capture both clocks before the first credential lookup, never per retry. */ +export function brokerTransportDeadline(scope: BrokerTransportScope): number { + return ( + performance.now() + + Math.max(0, Math.min(60_000, scope.deadlineAt - Date.now())) + ); +} + +/** A malformed header must not make us retry earlier than the server asked. */ +function retryAfterMs(value: string | null): number | null { + if (value === null) return 0; + if (/^\d+$/.test(value)) { + const seconds = Number(value); + return Number.isSafeInteger(seconds) && + seconds <= Number.MAX_SAFE_INTEGER / 1_000 + ? seconds * 1_000 + : null; + } + if ( + !/^[A-Z][a-z]{2}, \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test( + value, + ) + ) { + return null; + } + const date = Date.parse(value); + return Number.isFinite(date) && new Date(date).toUTCString() === value + ? Math.max(0, date - Date.now()) + : null; +} + +function wait(ms: number, signal: AbortSignal): Promise { + return new Promise((resolve, reject) => { + const abort = () => { + clearTimeout(timer); + signal.removeEventListener('abort', abort); + reject(new SafeFetchError('aborted', 'Broker transport stopped.')); + }; + const timer = setTimeout(() => { + signal.removeEventListener('abort', abort); + resolve(); + }, ms); + signal.addEventListener('abort', abort, { once: true }); + if (signal.aborted) abort(); + }); +} + +/** + * One admitted task's GET transport budget. Only the request is replayed; + * mapping and durable account selection belong to resolve, once. SQL reads + * are awaited, not raced/abandoned: elapsed time still refuses a late result. + */ +export async function withBrokerTransport( + scope: BrokerTransportScope, + assertCredential: () => Promise, + resolve: (transport: BrokerTransport) => Promise, + deadline = brokerTransportDeadline(scope), +): Promise { + const budget = deadline - performance.now(); + const controller = new AbortController(); + const abort = () => controller.abort(); + scope.signal?.addEventListener('abort', abort, { once: true }); + if (scope.signal?.aborted) abort(); + const timer = setTimeout(abort, Math.max(0, budget)); + const remaining = () => { + const left = deadline - performance.now(); + if (controller.signal.aborted || left <= 0 || !Number.isFinite(left)) { + throw new SafeFetchError('aborted', 'Broker transport stopped.'); + } + return Math.max(1, Math.floor(left)); + }; + const validate = async () => { + remaining(); + await assertCredential(); + remaining(); + await scope.assertCurrent(); + remaining(); + }; + try { + const value = await resolve({ + request: async (fetch) => { + for (let attempt = 0; ; attempt++) { + await validate(); + let response: SafeFetchResponse; + try { + response = await fetch(remaining(), controller.signal); + } catch (error) { + remaining(); + const backoff = BACKOFF_MS[attempt]; + if ( + !(error instanceof SafeFetchError) || + !TRANSIENT_KINDS.has(error.kind) || + backoff === undefined + ) { + throw error; + } + const delay = backoff + Math.floor(Math.random() * 1_001); + if (delay >= remaining()) throw error; + await wait(delay, controller.signal); + continue; + } + remaining(); + const backoff = BACKOFF_MS[attempt]; + if ( + !TRANSIENT_STATUSES.has(response.status) || + backoff === undefined + ) { + await validate(); + return response; + } + const retryAfter = retryAfterMs(response.headers.get('retry-after')); + const delay = Math.max( + backoff + Math.floor(Math.random() * 1_001), + retryAfter ?? 0, + ); + if (retryAfter === null || delay >= remaining()) return response; + await wait(delay, controller.signal); + } + }, + }); + await validate(); + return value; + } finally { + clearTimeout(timer); + scope.signal?.removeEventListener('abort', abort); + } +} diff --git a/services/platform/backend/core/provider_credentials/resolve_credential.test.ts b/services/platform/backend/core/provider_credentials/resolve_credential.test.ts index 211e5e638b..d00574c01a 100644 --- a/services/platform/backend/core/provider_credentials/resolve_credential.test.ts +++ b/services/platform/backend/core/provider_credentials/resolve_credential.test.ts @@ -15,6 +15,7 @@ import { safeFetch } from '../../../lib/net/safe-fetch'; import { AppError } from '../../../lib/shared/errors/app-error'; import type { ActionCtx } from '../lib/ctx'; import { encryptSecret } from '../lib/secret_box'; +import { classifyStartFailure } from '../tasks/start_failure'; import type { BrokerSelectionResult } from './broker_pool'; import { credentialRefusalCode, @@ -74,9 +75,13 @@ function ctxServingBroker(endpoint: string) { fellBack: false, }), ); + const runQuery = vi.fn(async (): Promise => ({ ...row })); return Object.assign( - { runQuery: vi.fn(async () => row), runMutation } as unknown as ActionCtx, - { mockRunMutation: runMutation }, + { + runQuery, + runMutation, + } as unknown as ActionCtx, + { mockRunMutation: runMutation, mockRunQuery: runQuery, row }, ); } @@ -112,6 +117,155 @@ beforeEach(() => { mockedFetch.mockReset(); }); +describe('opt-in task broker transport', () => { + beforeEach(() => { + vi.useFakeTimers({ + toFake: ['Date', 'performance', 'setTimeout', 'clearTimeout'], + }); + vi.spyOn(Math, 'random').mockReturnValue(0); + }); + afterEach(() => { + expect(vi.getTimerCount()).toBe(0); + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + const scope = () => ({ + deadlineAt: Date.now() + 120_000, + assertCurrent: async () => {}, + }); + const args = { organizationId: ORG, providerSlug: 'anthropic' }; + + it('leaves callers without opt-in and POST brokers single-shot', async () => { + mockedFetch.mockResolvedValue({ ...poolResponse(), status: 521 }); + const ctx = ctxServingBroker('https://broker.example/pool'); + expect(await caughtCode(resolveProviderCredential(ctx, args))).toBe( + 'CREDENTIAL_BROKER_FETCH_FAILED', + ); + ctx.row.encryptedData = encryptSecret( + JSON.stringify({ + ...brokerDocument('https://broker.example/pool'), + httpMethod: 'POST', + }), + ); + expect( + await caughtCode(resolveProviderCredential(ctx, args, scope())), + ).toBe('CREDENTIAL_BROKER_FETCH_FAILED'); + expect(mockedFetch).toHaveBeenCalledTimes(2); + expect(ctx.mockRunMutation).not.toHaveBeenCalled(); + }); + + it.each(['disabled', 'changed', 'deleted'] as const)( + 'refuses a %s credential before retrying', + async (change) => { + mockedFetch.mockResolvedValue({ ...poolResponse(), status: 521 }); + const ctx = ctxServingBroker('https://broker.example/pool'); + const result = caughtCode(resolveProviderCredential(ctx, args, scope())); + await vi.advanceTimersByTimeAsync(1); + if (change === 'disabled') ctx.row.status = 'disabled'; + if (change === 'changed') + ctx.row.encryptedData = encryptSecret( + JSON.stringify(brokerDocument('https://changed.example/pool')), + ); + if (change === 'deleted') ctx.mockRunQuery.mockResolvedValue(null); + await vi.advanceTimersByTimeAsync(4_999); + expect(await result).toBe( + change === 'disabled' + ? 'CREDENTIAL_DISABLED' + : change === 'deleted' + ? 'CREDENTIAL_NONE_CONFIGURED' + : 'CREDENTIAL_BROKER_FETCH_FAILED', + ); + expect(mockedFetch).toHaveBeenCalledTimes(1); + expect(ctx.mockRunMutation).not.toHaveBeenCalled(); + }, + ); + + it('refuses revocation after selection without publishing a token or selecting again', async () => { + const ctx = ctxServingBroker('https://broker.example/pool'); + mockedFetch.mockResolvedValue(poolResponse()); + ctx.mockRunMutation.mockImplementation(async (_ref, input) => { + ctx.row.status = 'disabled'; + return { hash: input.candidates[0]?.hash ?? null, fellBack: false }; + }); + expect( + await caughtCode(resolveProviderCredential(ctx, args, scope())), + ).toBe('CREDENTIAL_DISABLED'); + expect(ctx.mockRunMutation).toHaveBeenCalledTimes(1); + expect(mockedFetch).toHaveBeenCalledTimes(1); + }); + + it('does not replay malformed successful responses or pool cooldowns', async () => { + const ctx = ctxServingBroker('https://broker.example/pool'); + mockedFetch.mockResolvedValueOnce({ + ...poolResponse(), + body: 'invalid-json synthetic-secret', + }); + expect( + await caughtCode(resolveProviderCredential(ctx, args, scope())), + ).toBe('CREDENTIAL_BROKER_FETCH_FAILED'); + mockedFetch.mockResolvedValueOnce(poolResponse()); + const retryAtMs = Date.now() + 90_000; + ctx.mockRunMutation.mockResolvedValue({ + hash: null, + fellBack: false, + retryAtMs, + }); + const failure = await resolveProviderCredential(ctx, args, scope()).catch( + (error: unknown) => error, + ); + expect(credentialRetryAtMs(failure)).toBe(retryAtMs); + expect(credentialRefusalCode(failure)).toBe('CREDENTIAL_BROKER_EXHAUSTED'); + expect(mockedFetch).toHaveBeenCalledTimes(2); + expect(ctx.mockRunMutation).toHaveBeenCalledTimes(1); + }); + + it('keeps an out-of-budget transport Retry-After an ordinary counted failure', async () => { + const ctx = ctxServingBroker('https://broker.example/pool'); + mockedFetch.mockResolvedValue({ + ...poolResponse(), + status: 503, + headers: new Headers({ 'retry-after': '300' }), + }); + const failure = await resolveProviderCredential(ctx, args, scope()).catch( + (error: unknown) => error, + ); + expect(classifyStartFailure(failure)).toMatchObject({ + failureCode: 'start_failed', + }); + expect(classifyStartFailure(failure)).not.toHaveProperty('retryAtMs'); + expect(credentialRetryAtMs(failure)).toBeUndefined(); + expect(mockedFetch).toHaveBeenCalledTimes(1); + expect(ctx.mockRunMutation).not.toHaveBeenCalled(); + }); +}); + +it('recovers a transient broker refusal inside one credential resolution', async () => { + vi.useFakeTimers(); + try { + mockedFetch + .mockResolvedValueOnce({ ...poolResponse(), status: 521 }) + .mockResolvedValueOnce(poolResponse()); + const ctx = ctxServingBroker('https://broker.example/pool'); + const result = resolveProviderCredential( + ctx, + { organizationId: ORG, providerSlug: 'anthropic' }, + { deadlineAt: Date.now() + 60_000, assertCurrent: async () => {} }, + ).then( + (value) => ({ value }), + (error: unknown) => ({ error }), + ); + await vi.advanceTimersByTimeAsync(4_999); + expect(mockedFetch).toHaveBeenCalledTimes(1); + expect(ctx.mockRunMutation).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1_001); + expect(await result).toMatchObject({ value: { token: 'tok-a' } }); + expect(mockedFetch).toHaveBeenCalledTimes(2); + expect(ctx.mockRunMutation).toHaveBeenCalledTimes(1); + } finally { + vi.useRealTimers(); + } +}); + describe('broker account selection boundary', () => { it('hands only scoped hashes to durable selection and preserves vendor metadata', async () => { mockedFetch.mockResolvedValue({ diff --git a/services/platform/backend/core/provider_credentials/resolve_credential.ts b/services/platform/backend/core/provider_credentials/resolve_credential.ts index e7210d6b98..92bde8673f 100644 --- a/services/platform/backend/core/provider_credentials/resolve_credential.ts +++ b/services/platform/backend/core/provider_credentials/resolve_credential.ts @@ -24,6 +24,8 @@ * only failure classes and actionable hints. */ +import { isDeepStrictEqual } from 'node:util'; + import { isPrivateIp } from '@tale/shared/net/private-ip'; import { BROKER_SECRET_ENV_REGEX, @@ -54,6 +56,12 @@ import { diagnoseTokenMapping, type BrokerSelectionResult, } from './broker_pool'; +import { + brokerTransportDeadline, + withBrokerTransport, + type BrokerTransport, + type BrokerTransportScope, +} from './broker_transport'; import { hashBrokerAccount, hashBrokerToken } from './token_hash'; /** The full row shape the internal queries return (`returns: v.any()` @@ -364,21 +372,30 @@ function policeBrokerEndpoint( async function fetchBrokerJson( row: CredentialRow, broker: BrokerCredentialData, + transport?: BrokerTransport, ): Promise { - const allowedHosts = policeBrokerEndpoint(row, broker.endpoint); let response; try { - response = await safeFetch(broker.endpoint, { - allowPrivateAddresses: privateProviderHostsAllowed(), - method: broker.httpMethod, - headers: buildBrokerAuthHeaders(broker.auth, brokerAuthSecret(broker)), - timeoutMs: broker.timeoutMs, - maxResponseBytes: broker.maxResponseBytes, - ...(allowedHosts !== undefined - ? { allowedHosts: [...allowedHosts] } - : {}), - }); + const fetch = (remainingMs: number, signal?: AbortSignal) => { + const allowedHosts = policeBrokerEndpoint(row, broker.endpoint); + return safeFetch(broker.endpoint, { + allowPrivateAddresses: privateProviderHostsAllowed(), + method: broker.httpMethod, + headers: buildBrokerAuthHeaders(broker.auth, brokerAuthSecret(broker)), + timeoutMs: Math.min(broker.timeoutMs, remainingMs), + ...(signal !== undefined ? { signal } : {}), + maxResponseBytes: broker.maxResponseBytes, + ...(allowedHosts !== undefined + ? { allowedHosts: [...allowedHosts] } + : {}), + }); + }; + response = + transport === undefined + ? await fetch(broker.timeoutMs) + : await transport.request(fetch); } catch (err) { + if (err instanceof AppError) throw err; const kind = err instanceof SafeFetchError ? err.kind : 'network_error'; throw credentialError( 'CREDENTIAL_BROKER_FETCH_FAILED', @@ -405,6 +422,8 @@ async function resolveBroker( ctx: ActionCtx, row: CredentialRow, args: ResolveCredentialArgs, + scope?: BrokerTransportScope, + transportDeadline?: number, ): Promise { if (!row.encryptedData) throw shapeError(row); let broker: BrokerCredentialData; @@ -420,7 +439,49 @@ async function resolveBroker( throw err; } - const json = await fetchBrokerJson(row, broker); + if (scope === undefined || broker.httpMethod !== 'GET') { + return resolveBrokerPool(ctx, row, args, broker); + } + const authSecret = brokerAuthSecret(broker); + return withBrokerTransport( + scope, + async () => { + const current = await loadRow(ctx, args); + if (current.status === 'disabled') { + throw credentialError( + 'CREDENTIAL_DISABLED', + `Credential "${row.name}" is disabled — enable it in Settings → AI providers, or pick another credential.`, + ); + } + if ( + current._id !== row._id || + current.organizationId !== row.organizationId || + current.providerSlug !== row.providerSlug || + current.authMethod !== row.authMethod || + current.endpointUrl !== row.endpointUrl || + !isDeepStrictEqual(current.encryptedData, row.encryptedData) || + brokerAuthSecret(broker) !== authSecret + ) { + throw credentialError( + 'CREDENTIAL_BROKER_FETCH_FAILED', + 'The broker credential changed while the task was starting.', + ); + } + policeBrokerEndpoint(current, broker.endpoint); + }, + (transport) => resolveBrokerPool(ctx, row, args, broker, transport), + transportDeadline, + ); +} + +async function resolveBrokerPool( + ctx: ActionCtx, + row: CredentialRow, + args: ResolveCredentialArgs, + broker: BrokerCredentialData, + transport?: BrokerTransport, +): Promise { + const json = await fetchBrokerJson(row, broker, transport); const diagnostics = diagnoseTokenMapping( json, broker.responseMapping, @@ -528,7 +589,12 @@ async function subscriptionKeyTargetEnvVar( export async function resolveProviderCredential( ctx: ActionCtx, args: ResolveCredentialArgs, + brokerTransport?: BrokerTransportScope, ): Promise { + const transportDeadline = + brokerTransport === undefined + ? undefined + : brokerTransportDeadline(brokerTransport); const row = await loadRow(ctx, args); if (row.status === 'disabled') { throw credentialError( @@ -597,7 +663,13 @@ export async function resolveProviderCredential( }; } case 'subscription-broker': - return await resolveBroker(ctx, row, args); + return await resolveBroker( + ctx, + row, + args, + brokerTransport, + transportDeadline, + ); default: { const _exhaustive: never = row.authMethod; return _exhaustive; diff --git a/services/platform/backend/core/tasks/agent_run_host.context_window.test.ts b/services/platform/backend/core/tasks/agent_run_host.context_window.test.ts index 2d32c93786..54c2149795 100644 --- a/services/platform/backend/core/tasks/agent_run_host.context_window.test.ts +++ b/services/platform/backend/core/tasks/agent_run_host.context_window.test.ts @@ -11,6 +11,7 @@ import type { ModelCatalogEntry } from '@tale/shared/schemas/providers'; import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { safeFetch } from '../../../lib/net/safe-fetch'; import { AppError } from '../../../lib/shared/errors/app-error'; import { functionRefName } from '../../../lib/shared/handlers/function-refs'; import { @@ -19,6 +20,7 @@ import { } from '../../domains/sandbox/external-turn-outcome'; import { releaseTurnKey } from '../automations/agent_host'; import { resolveModel } from '../lib/providers/resolve_model'; +import { encryptSecret } from '../lib/secret_box'; import { resolveProviderCredential } from '../provider_credentials/resolve_credential'; import { AWAITING_ROOM_RESULT_STATUS, @@ -42,6 +44,13 @@ const io = vi.hoisted(() => ({ | { providerSlug: string; modelId: string; apiBaseUrl: string }, /** What the session ensure throws, when it refuses. */ sessionRefusal: undefined as Error | undefined, + brokerRow: null as unknown, + ensures: 0, +})); + +vi.mock('../../../lib/net/safe-fetch', async (importOriginal) => ({ + ...(await importOriginal()), + safeFetch: vi.fn(), })); vi.mock('../chat/external_turn_shared', async (importActual) => { @@ -101,6 +110,7 @@ vi.mock('../node_only/sandbox/helpers/session_client', async (importActual) => { }); vi.mock('../node_only/sandbox/agent_session', () => ({ ensureAgentSession: async () => { + io.ensures++; if (io.sessionRefusal !== undefined) throw io.sessionRefusal; return { liveCreatedAt: 1000 }; }, @@ -166,6 +176,8 @@ function servesWindow(contextWindow: number): void { interface RunState { status: string; execId: string; + confined?: boolean; + rotateAfterSelection?: boolean; } function makeCtx(run: RunState, contextCap: number | null = null) { @@ -182,6 +194,8 @@ function makeCtx(run: RunState, contextCap: number | null = null) { organizationId: 'org-1', }; } + if (name === 'provider_credentials/queries:getDefaultCredentialInternal') + return io.brokerRow; if (name === 'projects/internal_queries:getProjectAgentSkillScope') { return null; } @@ -213,7 +227,17 @@ function makeCtx(run: RunState, contextCap: number | null = null) { } // An editor's run: the agent's full equipment. if (name === 'tasks/agent_runs:getTaskAgentRunAuthority') { - return { confined: false }; + if ( + run.rotateAfterSelection && + mutations.some( + ({ name: mutationName }) => + mutationName === + 'provider_credentials/mutations:selectBrokerAccountInternal', + ) + ) { + run.execId = 'successor-exec'; + } + return { confined: run.confined ?? false }; } throw new Error(`unexpected query ${name}`); }, @@ -231,6 +255,12 @@ function makeCtx(run: RunState, contextCap: number | null = null) { if (name === 'sandbox/session_mutations:reserveTurnBudget') { return { allowed: true, budgetCents: 500 }; } + if ( + name === 'provider_credentials/mutations:selectBrokerAccountInternal' + ) { + const candidates = args.candidates as { hash: string }[]; + return { hash: candidates[0]?.hash ?? null, fellBack: false }; + } return null; }, runAction: async () => null, @@ -269,6 +299,8 @@ beforeEach(() => { io.windows = []; io.subscription = undefined; io.sessionRefusal = undefined; + io.brokerRow = null; + io.ensures = 0; vi.mocked(resolveProviderCredential).mockReset(); vi.mocked(resolveModel).mockReset(); vi.spyOn(console, 'warn').mockImplementation(() => {}); @@ -276,6 +308,128 @@ beforeEach(() => { }); describe('a task agent start', () => { + it.each([ + 'recover', + 'cancel', + 'rotate', + 'rotate-during-final-authority', + 'confine', + 'job-abort', + 'initially-confined', + ] as const)( + 'keeps real broker recovery inside one admitted task: %s', + async (mode) => { + vi.useFakeTimers({ + toFake: ['Date', 'performance', 'setTimeout', 'clearTimeout'], + }); + vi.spyOn(Math, 'random').mockReturnValue(0); + vi.stubEnv('ENCRYPTION_SECRET_HEX', 'test-key-material'); + try { + const actual = await vi.importActual< + typeof import('../provider_credentials/resolve_credential') + >('../provider_credentials/resolve_credential'); + vi.mocked(resolveProviderCredential).mockImplementation( + actual.resolveProviderCredential, + ); + io.subscription = { + providerSlug: 'anthropic', + modelId: 'claude-sonnet', + apiBaseUrl: 'https://api.anthropic.com', + }; + io.brokerRow = { + _id: 'credential-1', + organizationId: 'org-1', + providerSlug: 'anthropic', + authMethod: 'subscription-broker', + status: 'active', + name: 'Synthetic broker', + encryptedData: encryptSecret( + JSON.stringify({ + endpoint: 'https://broker.example/pool', + httpMethod: 'GET', + auth: { method: 'none' }, + responseMapping: { + tokensPath: '$.tokens', + tokenField: 'access_token', + }, + targetEnvVar: 'CLAUDE_CODE_OAUTH_TOKEN', + selection: 'first', + }), + ), + }; + const response = { + status: 200, + statusText: 'OK', + headers: new Headers(), + finalUrl: 'https://broker.example/pool', + body: JSON.stringify({ + tokens: [{ access_token: 'synthetic-token' }], + }), + }; + vi.mocked(safeFetch) + .mockReset() + .mockResolvedValueOnce({ ...response, status: 521 }) + .mockResolvedValue(response); + const run = { + status: 'queued', + execId: 'exec-1', + confined: mode === 'initially-confined', + rotateAfterSelection: mode === 'rotate-during-final-authority', + }; + const { ctx, mutations } = makeCtx(run); + const controller = new AbortController(); + const promise = startTaskAgentTurnImpl( + ctx, + { + ...KEYS, + modelProvider: 'anthropic', + model: 'claude-sonnet', + deadlineAt: Date.now() + 60_000, + } as never, + { signal: controller.signal }, + ); + await vi.advanceTimersByTimeAsync(1); + expect(safeFetch).toHaveBeenCalledTimes(1); + expect(io.starts).toHaveLength(0); + if (mode === 'cancel') run.status = 'cancelled'; + if (mode === 'rotate') run.execId = 'successor-exec'; + if (mode === 'confine') run.confined = true; + if (mode === 'job-abort') controller.abort(); + await vi.advanceTimersByTimeAsync(4_999); + await promise; + expect(io.ensures).toBe(1); + const selected = + mode === 'recover' || mode === 'rotate-during-final-authority'; + expect(safeFetch).toHaveBeenCalledTimes(selected ? 2 : 1); + expect(io.starts).toHaveLength(mode === 'recover' ? 1 : 0); + expect( + mutations.filter( + ({ name }) => name === 'tasks/agent_runs:setTaskAgentRunRunning', + ), + ).toHaveLength(mode === 'recover' ? 1 : 0); + expect( + mutations.filter( + ({ name }) => + name === + 'provider_credentials/mutations:selectBrokerAccountInternal', + ), + ).toHaveLength(selected ? 1 : 0); + if (mode === 'recover') { + expect(io.starts[0]?.execId).toBe('exec-1'); + expect(console.error).not.toHaveBeenCalled(); + } + if (mode === 'initially-confined') + expect( + vi.mocked(resolveProviderCredential).mock.calls[0]?.[2], + ).toBeUndefined(); + expect(vi.getTimerCount()).toBe(0); + } finally { + vi.useRealTimers(); + vi.mocked(Math.random).mockRestore(); + vi.unstubAllEnvs(); + } + }, + ); it.each( [ { @@ -339,6 +493,10 @@ describe('a task agent start', () => { expect.objectContaining({ requireBrokerAccountId: harness === 'codex', }), + expect.objectContaining({ + deadlineAt: KEYS.deadlineAt, + assertCurrent: expect.any(Function), + }), ); if (providerSlug === 'openai') { expect(io.starts[0]?.env.TALE_SUBSCRIPTION_ACCOUNT_ID).toBe( diff --git a/services/platform/backend/core/tasks/agent_run_host.ts b/services/platform/backend/core/tasks/agent_run_host.ts index 9fa3d3dd36..218c2068d7 100644 --- a/services/platform/backend/core/tasks/agent_run_host.ts +++ b/services/platform/backend/core/tasks/agent_run_host.ts @@ -87,6 +87,7 @@ import { TurnBudgetExceededError, } from '../node_only/sandbox/turn_budget'; import { resolveTurnEquipmentEnv } from '../node_only/sandbox/turn_equipment'; +import type { BrokerTransportScope } from '../provider_credentials/broker_transport'; import { credentialRetryAtMs, resolveProviderCredential, @@ -840,6 +841,7 @@ async function mintTurnServing( excludeBrokerTokenHashes?: string[]; }, resolved: TaskServing, + brokerTransport?: BrokerTransportScope, ): Promise { if (resolved.lane === 'gateway') { // Claude Code + a connector with a native Anthropic harness endpoint @@ -916,15 +918,21 @@ async function mintTurnServing( ...(vision !== null ? { visionPolyfillReads: vision.polyfillReads } : {}), }; } - const credential = await resolveProviderCredential(ctx, { - organizationId: args.organizationId, - providerSlug: resolved.providerSlug, - requireBrokerAccountId: harnessRequiresSubscriptionAccountId(args.harness), - ...(args.excludeBrokerTokenHashes !== undefined && - args.excludeBrokerTokenHashes.length > 0 - ? { excludeBrokerTokenHashes: args.excludeBrokerTokenHashes } - : {}), - }); + const credential = await resolveProviderCredential( + ctx, + { + organizationId: args.organizationId, + providerSlug: resolved.providerSlug, + requireBrokerAccountId: harnessRequiresSubscriptionAccountId( + args.harness, + ), + ...(args.excludeBrokerTokenHashes !== undefined && + args.excludeBrokerTokenHashes.length > 0 + ? { excludeBrokerTokenHashes: args.excludeBrokerTokenHashes } + : {}), + }, + brokerTransport, + ); if ( credential.authMethod !== 'subscription-key' && credential.authMethod !== 'subscription-broker' @@ -1125,6 +1133,7 @@ export interface StartTaskAgentTurnArgs extends TurnKeys { export async function startTaskAgentTurnImpl( ctx: ActionCtx, args: StartTaskAgentTurnArgs, + execution?: { signal?: AbortSignal }, ): Promise { { // Idempotency gate: the kick, the capacity wake, and the watchdog retry @@ -1309,7 +1318,44 @@ export async function startTaskAgentTurnImpl( ? visionUnreadableGuidance(resolved.vision) : ''; - const prepared = await mintTurnServing(ctx, args, resolved); + // Added transport waiting is only for an unconfined fresh start. + // Member starts and steer retain their existing single-shot behavior. + const brokerTransport: BrokerTransportScope | undefined = + resolved.lane === 'subscription' && + !(await isTurnConfined(ctx, args.runId)) + ? { + deadlineAt: args.deadlineAt, + ...(execution?.signal !== undefined + ? { signal: execution.signal } + : {}), + assertCurrent: async () => { + const confined = await isTurnConfined(ctx, args.runId); + const current = await ctx.runQuery( + internal.tasks.agent_runs.getTaskAgentRunForDrive, + { runId: args.runId }, + ); + if ( + current === null || + current.status !== 'queued' || + current.execId !== args.execId || + current.sessionId !== args.sessionId || + current.organizationId !== args.organizationId || + Date.now() >= args.deadlineAt || + confined + ) { + throw new Error( + 'The task no longer authorizes this credential request.', + ); + } + }, + } + : undefined; + const prepared = await mintTurnServing( + ctx, + args, + resolved, + brokerTransport, + ); // Clear a predecessor's account when this launch uses another lane. // Fenced on THIS exec, like the selected-account stamp itself. await ctx.runMutation( diff --git a/services/platform/backend/core/tasks/task_auto_retry.ts b/services/platform/backend/core/tasks/task_auto_retry.ts index 4451abbd07..c86754074d 100644 --- a/services/platform/backend/core/tasks/task_auto_retry.ts +++ b/services/platform/backend/core/tasks/task_auto_retry.ts @@ -4,9 +4,10 @@ * database; the orchestration (collect → decide → kick) lives in * `tasks/mutations.ts` (`kickAutoRetryRun`). * - * Semantics (2026-08-20): a failed run auto-retries immediately — no - * backoff, the harness already backed off per-request — unless the task is - * in a rapid crash loop. The loop detector is a CONSECUTIVE-failure budget + * Semantics (2026-08-20): after per-request recovery, a failed run retries + * immediately unless the task is in a rapid crash loop. The harness backs + * off its requests; an unconfined fresh task start bounds transient broker + * GET recovery within the admitted run. The loop detector is a CONSECUTIVE-failure budget * with a progress reset, not a sliding window: a sliding window plus any * retry spacing lets a deterministically-broken task drip retries forever, * while a streak terminates it and still refreshes the budget whenever an diff --git a/services/platform/backend/jobs/task-list.agent-start.test.ts b/services/platform/backend/jobs/task-list.agent-start.test.ts new file mode 100644 index 0000000000..d6bad8a522 --- /dev/null +++ b/services/platform/backend/jobs/task-list.agent-start.test.ts @@ -0,0 +1,73 @@ +import type { Sql } from 'postgres'; +import { expect, it, vi } from 'vitest'; + +import { startTaskAgentTurnImpl } from '../core/tasks/agent_run_host.ts'; +import { createTaskList } from './task-list.ts'; + +vi.mock('../core/tasks/agent_run_host.ts', async (original) => ({ + ...(await original()), + startTaskAgentTurnImpl: vi.fn(async () => null), +})); +vi.mock('../domains/tasks/kick-plan.ts', async (original) => ({ + ...(await original()), + resolveTaskKickStartArgs: async () => ({ sweep: true }), +})); + +it('hands the admitted queued start its existing job cancellation signal', async () => { + const sql = ((parts: TemplateStringsArray) => { + const query = parts.join('?'); + if (query.includes('FROM app.project_agent_runs')) + return Promise.resolve([ + { + taskId: 'task-1', + agentId: 'agent-1', + sessionId: 'session-1', + harness: 'claude-code', + model: 'model', + modelProvider: 'provider', + feedback: null, + mentionSource: null, + deadlineAt: Date.now() + 60_000, + status: 'queued', + execId: 'exec-1', + startedVia: null, + viaAutomation: null, + viaAgentName: null, + projectId: 'project-1', + startedBy: 'user:starter', + }, + ]); + if (query.includes('FROM app.project_agents')) + return Promise.resolve([ + { + instructions: null, + skills: [], + connectors: [], + tools: [], + secrets: [], + }, + ]); + throw new Error('Unexpected start query'); + }) as unknown as Sql; + const controller = new AbortController(); + const handler = createTaskList({ sql })['task.agent_turn']; + expect(handler).toBeDefined(); + await handler?.( + { organizationId: 'org-1', runId: 'run-1', execId: 'exec-1' }, + { signal: controller.signal }, + ); + expect(startTaskAgentTurnImpl).toHaveBeenCalledTimes(1); + expect(startTaskAgentTurnImpl).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + runId: 'run-1', + execId: 'exec-1', + sessionId: 'session-1', + }), + { signal: controller.signal }, + ); + controller.abort(); + expect( + vi.mocked(startTaskAgentTurnImpl).mock.calls[0]?.[2]?.signal?.aborted, + ).toBe(true); +}); diff --git a/services/platform/backend/jobs/task-list.ts b/services/platform/backend/jobs/task-list.ts index 8e45513138..e394f4e214 100644 --- a/services/platform/backend/jobs/task-list.ts +++ b/services/platform/backend/jobs/task-list.ts @@ -1340,7 +1340,7 @@ export function createTaskList(deps: TaskDeps): BackendTaskList { await wakeParkedAgentRun(deps.sql, input); }, - 'task.agent_turn': async (payload) => { + 'task.agent_turn': async (payload, context) => { const input = z .object({ organizationId: z.string().min(1), @@ -1497,6 +1497,7 @@ export function createTaskList(deps: TaskDeps): BackendTaskList { : {}), ...plan, }, + context !== undefined ? { signal: context.signal } : undefined, ); }, 'task.agent_retry': agentRetry, diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index ffe709cbfd..25fa8d332e 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -304,6 +304,7 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [knowledge](../suites/knowledge.md) / [settings](../suites/settings.md) | Direct embeddings refuse subscription-key and subscription-broker credentials before allocating a broker account or constructing an API client; a settings race is checked again after resolution, and the refusal is classified as non-retryable | ✅ backend | `backend/core/knowledge/embedding_credentials.test.ts`; API-key and environment credentials retain endpoint precedence | | [settings](../suites/settings.md) / [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | Broker selection filters malformed metadata, provider mismatches, inactive/expired tokens and exhausted quota — with `refresh_at` mapped as the expiry and an hour's safety margin, a Tale AI gateway token inside the gateway's hand-out floor is dropped, and the empty-pool reason names both a spent quota and a due refresh; stable broker IDs keep retry identity across token refresh; round-robin atomically chooses the least recently selected eligible account across concurrent backend connections, with organization and credential isolation and durable history; HTTP 429 records a shared 60-second account cooldown before retry, and advisory retry exclusions never bypass quota or cooldown; an account the broker holds back only for its coming refresh (`hold: "refresh"`) passes every other filter as a fallback and is vended — the latest refresh first — only when every available account is cooling down or lacks OpenAI's vendor account id, never while one can serve, and a broker that names no `hold` keeps it excluded; a pool whose every account cools down refuses with the moment the first comes back (`retryAtMs`) | ✅ backend + real Postgres | `backend/core/provider_credentials/broker_pool.test.ts`, `backend/core/provider_credentials/token_hash.test.ts`, `backend/core/provider_credentials/resolve_credential.test.ts`, `backend/domains/provider_credentials/broker-selection.test.ts`, `backend/domains/tasks/agent-turn-shim.broker.test.ts`, `backend/domains/automations/shim.broker.test.ts`, `backend/domains/provider_credentials/broker-selection.integration.ts` (`checkBrokerAccountSelection` in `backend:integration`); actual vendor acceptance remains a deployment check | | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | Anthropic broker credentials preserve the configured OAuth target while clearing competing credentials; OpenAI broker credentials use Codex's ChatGPT Responses connection with a separate vendor account ID; unsupported target variables and missing OpenAI account IDs are refused; provider-prefixed model IDs are normalized and credential model allowlists are enforced; static coding-plan keys retain their transport; Codex's native 429/401 errors retain their retry classification | ✅ backend + launcher | `backend/core/chat/external_turn_shared.subscription.test.ts`, `backend/core/lib/providers/agent_serving.test.ts`, `lib/harnesses/exec-builder.test.ts`, `backend/core/tasks/agent_run_host.context_window.test.ts`, `backend/core/automations/agent_host.context_window.test.ts`, `backend/core/tasks/agent_run_host.budget_exceeded.test.ts`, `backend/core/automations/agent_host.retry_resume.test.ts`, `lib/harnesses/parsers/codex-jsonl.test.ts`; synthetic transport fixtures do not prove live OAuth approval or a vendor model response | +| [tasks](../suites/tasks.md) | An unconfined fresh task start recovers transient broker GET failures within one run: three bounded requests,5s/10s backoff, Retry-After floors, job abort, current run/credential refusal and unchanged circuit/cooldown/POST/member behavior; real task-host recovery launches the same exec once | ✅ unit + task host | `backend/core/provider_credentials/broker_transport.test.ts`, `backend/core/provider_credentials/resolve_credential.test.ts`, `backend/core/tasks/agent_run_host.context_window.test.ts`, `backend/jobs/task-list.agent-start.test.ts`, `backend/jobs/task-list.agent-retry.test.ts` | | [settings](../suites/settings.md) / [tasks](../suites/tasks.md) / [automations](../suites/automations.md) / [chat](../suites/chat.md) | The shipped OpenAI catalog offers `gpt-6-astra`, `gpt-6-sol`, `gpt-6-luna` and `gpt-6.1-sol` with their exact model IDs; Sol and Luna declare `toolsRequireOff`, Astra and Sol 6.1 the Responses tool API. Native chat and Auto serve a Responses-only model over the Responses API (request body, streamed text, tool calls, usage, finish reasons and in-stream failures); Anthropic-format connectors never offer one. Agent serving runs it on a managed or subscription Codex harness and refuses every other wire with the Responses reason, naming Codex; the agent pickers, the project-agent check, the standard agent's chooser and the **Agent runtimes** status offer, accept or count it only for Codex; the Chat Completions model endpoints leave it out. | 🔶 backend | `backend/core/lib/providers/load_system_config.test.ts`, `backend/core/lib/providers/harness_status.test.ts`, `backend/core/automations_builder/chat_wire.test.ts`, `backend/core/chat/turn_action.responses.test.ts`, `backend/core/lib/providers/chat_catalog.test.ts`, `lib/chat/turn.test.ts`, `backend/core/lib/providers/agent_serving.test.ts`, `backend/domains/projects/agent-equipment.test.ts`, `backend/domains/projects/standard-agent.test.ts`, `app/features/projects/lib/model-options.test.ts`, `backend/domains/model_api/models.test.ts`; completed replies through a live OpenAI key (CHAT-F60) and the Codex subscription remain manual | | [settings](../suites/settings.md) / [chat](../suites/chat.md) | A subscription credential is said to serve tasks and automations, never chat: the add form's info notice for both subscription methods, the credentials table's row line, the chat model list's note naming the providers it leaves out, and the direct-chat refusal's reason. | ✅ unit | `app/features/settings/providers/components/providers-settings.test.tsx`, `app/features/chat/components/composer.test.tsx`, `lib/shared/providers/resolve_execution.test.ts`; layout and wording per locale stay manual (SET-F74, CHAT-F59) | | [settings](../suites/settings.md) | Replacing a broker configuration with blank secret fields preserves the stored broker secret, an explicit environment reference without a new secret switches the source, and unauthenticated replacement removes the old secret | ✅ backend | `backend/domains/provider_credentials/service.validation.test.ts`; entering and replacing the configuration in the settings dialog remains manual |