diff --git a/apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts b/apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts index be14f45ec0e6b..5a3420f2cf28f 100644 --- a/apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts +++ b/apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts @@ -137,7 +137,7 @@ import { formatPeerEnvelope, } from "./EnvelopeFormatter.ts"; import { A2ALedger, layer as ledgerLayer } from "./LedgerService.ts"; -import { readReceiverBacklog } from "./receiverBacklog.ts"; +import { readReceiverBacklog, withDeliveryNotice } from "./receiverBacklog.ts"; import { noneLayer as peerDirectoryNoneLayer } from "./PeerDirectory.ts"; import { A2ALifecycleService, manualLayer as lifecycleServiceLayer } from "./LifecycleService.ts"; import { @@ -1124,11 +1124,19 @@ it.effect("measures the backlog a send waits behind on a busy receiver", () => // Committed sends the worker has not handed over yet are waiting too. yield* send.send(sendInput(caller, "second")); const third = yield* send.send(sendInput(caller, "third")); - assert.deepStrictEqual(yield* backlogFor(third), { waiting: 2, fromCaller: 2 }); + assert.deepStrictEqual(yield* backlogFor(third), { + type: "behind_turn", + waiting: 2, + fromCaller: 2, + }); // Queued runs and pending deliveries add up; another sender's count is not the caller's. yield* worker.drain; yield* send.send(sendInput(other, "other")); - assert.deepStrictEqual(yield* backlogFor(third), { waiting: 3, fromCaller: 2 }); + assert.deepStrictEqual(yield* backlogFor(third), { + type: "behind_turn", + waiting: 3, + fromCaller: 2, + }); // Only agents on this server are measured. assert.isUndefined( @@ -1185,25 +1193,7 @@ it.effect("counts a message queued before an Astra turn became steerable", () => callerThreadId: ThreadId.make("thread:j5-a2a-delivery-backlog-astra-queued-caller"), sentMessageId: target.messageId, }), - { waiting: 1, fromCaller: 0 }, - ); - }).pipe(Effect.provide(makeTestLayer(harness))); - }), -); - -it.effect("reports no backlog while the receiver's queue is held", () => - Effect.gen(function* () { - const harness = yield* makeHarness; - yield* Effect.gen(function* () { - const target = yield* seedTarget("backlog-held"); - yield* holdTargetQueue(target); - // A held queue waits for someone to resume the thread, not for the turn to end. - assert.isUndefined( - yield* readReceiverBacklog({ - receiverId: target.receiverId, - callerThreadId: ThreadId.make("thread:j5-a2a-delivery-backlog-held-caller"), - sentMessageId: target.messageId, - }), + { type: "behind_turn", waiting: 1, fromCaller: 0 }, ); }).pipe(Effect.provide(makeTestLayer(harness))); }), @@ -3492,6 +3482,48 @@ it.effect("keeps a delivery unsent while a usage limit blocks the receiver's hel }), ); +/** Leaves a target idle with one held message after a run that failed to set up its worktree. */ +const idleAfterFailedWorktreeSetup = Effect.fn("A2AIntegration.idleAfterFailedWorktreeSetup")( + function* ( + harness: DeliveryHarness, + target: { readonly projectId: ProjectId; readonly threadId: ThreadId }, + ) { + const earlierRunId = yield* idleWithHeldQueue(harness, target, { + class: "provider_error", + message: "Worktree setup failed.", + code: null, + retryable: null, + }); + // The failed run had been preparing a worktree that never got bound to the thread. + yield* (yield* OrchestratorV2).dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make(`command:held-worktree:unbind:${target.threadId}`), + threadId: target.threadId, + worktreePath: null, + }); + const failed = (yield* (yield* ThreadManagementService).getThreadProjection( + target.threadId, + )).runs.find((run) => run.status === "failed")!; + yield* (yield* EventSinkV2).write({ + events: [ + { + id: EventId.make(`event:held-worktree:preparation:${target.threadId}`), + type: "run.updated", + threadId: target.threadId, + runId: failed.id, + providerInstanceId: failed.providerInstanceId, + occurredAt: yield* DateTime.now, + payload: { + ...failed, + workspacePreparation: { type: "worktree", baseRef: "main", startFromOrigin: false }, + }, + }, + ], + }); + return earlierRunId; + }, +); + it.effect("keeps a delivery unsent while a failed worktree setup holds the receiver's queue", () => Effect.gen(function* () { const harness = yield* makeHarness; @@ -3499,38 +3531,7 @@ it.effect("keeps a delivery unsent while a failed worktree setup holds the recei const target = yield* seedTarget("held-worktree", "gpt-5.4"); const threads = yield* ThreadManagementService; const transport = yield* A2ADeliveryTransport; - const earlierRunId = yield* idleWithHeldQueue(harness, target, { - class: "provider_error", - message: "Worktree setup failed.", - code: null, - retryable: null, - }); - // The failed run had been preparing a worktree that never got bound to the thread. - yield* (yield* OrchestratorV2).dispatch({ - type: "thread.metadata.update", - commandId: CommandId.make("command:held-worktree:unbind"), - threadId: target.threadId, - worktreePath: null, - }); - const failed = (yield* threads.getThreadProjection(target.threadId)).runs.find( - (run) => run.status === "failed", - )!; - yield* (yield* EventSinkV2).write({ - events: [ - { - id: EventId.make("event:held-worktree:preparation"), - type: "run.updated", - threadId: target.threadId, - runId: failed.id, - providerInstanceId: failed.providerInstanceId, - occurredAt: yield* DateTime.now, - payload: { - ...failed, - workspacePreparation: { type: "worktree", baseRef: "main", startFromOrigin: false }, - }, - }, - ], - }); + const earlierRunId = yield* idleAfterFailedWorktreeSetup(harness, target); const error = yield* transport.deliverAgent(target.delivery).pipe(Effect.flip); @@ -3543,6 +3544,120 @@ it.effect("keeps a delivery unsent while a failed worktree setup holds the recei }), ); +/** Sends to the target from a seeded caller and returns the send result's notice. */ +const sendNoticeTo = Effect.fn("A2AIntegration.sendNoticeTo")(function* ( + suffix: string, + target: { readonly ledgerProjectId: LedgerProjectId; readonly receiverId: ParticipantId }, +) { + const caller = yield* seedTarget( + `${suffix}-caller`, + modelSelection.model, + undefined, + target.ledgerProjectId, + ); + const sent = yield* (yield* A2ASendService).send({ + commandId: CommCommandId.make(`command:j5-a2a-delivery-${suffix}-notice`), + senderThreadId: caller.threadId, + to: target.receiverId, + message: "An update", + acceptedAt: "2026-09-24T00:00:00.000Z", + }); + return (yield* withDeliveryNotice(sent, { + receiverId: target.receiverId, + callerThreadId: caller.threadId, + })).deliveryNotice; +}); + +it.effect("tells the sender a busy receiver's held queue keeps its message waiting", () => + Effect.gen(function* () { + const harness = yield* makeHarness; + yield* Effect.gen(function* () { + const target = yield* seedTarget("notice-held-busy"); + yield* holdTargetQueue(target); + assert.equal( + yield* sendNoticeTo("notice-held-busy", target), + `${target.receiverId}'s queue is on hold, so your message waits until a person resumes it. It will run then, in the order it was sent. Don't send it again.`, + ); + }).pipe(Effect.provide(makeLifecycleTestLayer(harness))); + }), +); + +it.effect("tells the sender a failed worktree setup keeps its message waiting", () => + Effect.gen(function* () { + const harness = yield* makeHarness; + yield* Effect.gen(function* () { + const target = yield* seedTarget("notice-held-worktree"); + yield* idleAfterFailedWorktreeSetup(harness, target); + assert.equal( + yield* sendNoticeTo("notice-held-worktree", target), + `${target.receiverId}'s queue is on hold, so your message waits until a person resumes it. It will run then, in the order it was sent. Don't send it again.`, + ); + }).pipe(Effect.provide(makeLifecycleTestLayer(harness))); + }), +); + +it.effect("tells the sender a usage limit pauses the receiver until a person continues it", () => + Effect.gen(function* () { + const harness = yield* makeHarness; + yield* Effect.gen(function* () { + const target = yield* seedTarget("notice-limit-paused"); + yield* idleWithHeldQueue(harness, target, { + class: "usage_limit", + message: "Usage limit reached.", + code: null, + retryable: null, + resetAt: "2099-01-01T00:00:00.000Z", + }); + assert.equal( + yield* sendNoticeTo("notice-limit-paused", target), + `${target.receiverId} hit its provider's usage limit and is paused until a person continues it. Your message is saved and will run then, in the order it was sent. Don't send it again.`, + ); + }).pipe(Effect.provide(makeLifecycleTestLayer(harness))); + }), +); + +it.effect("tells the sender when upstream continues a usage-limited receiver", () => + Effect.gen(function* () { + const harness = yield* makeHarness; + yield* Effect.gen(function* () { + const target = yield* seedTarget("notice-limit-auto"); + const resetAt = "2099-01-01T00:00:00.000Z"; + yield* idleWithHeldQueue(harness, target, { + class: "usage_limit", + message: "Usage limit reached.", + code: null, + retryable: null, + resetAt, + }); + const limited = (yield* (yield* ThreadManagementService).getThreadProjection( + target.threadId, + )).runs.find((run) => run.status === "failed")!; + // What the thread's "Resume at reset" does. + yield* (yield* OrchestratorV2).dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("command:notice-limit-auto:arm"), + threadId: target.threadId, + limitRecovery: { runId: limited.id, resetAt, autoResume: true }, + }); + assert.equal( + yield* sendNoticeTo("notice-limit-auto", target), + `${target.receiverId} hit its provider's usage limit and continues automatically at ${resetAt}. Your message is saved and will run then, in the order it was sent. Don't send it again.`, + ); + }).pipe(Effect.provide(makeLifecycleTestLayer(harness))); + }), +); + +it.effect("adds no notice for an idle receiver whose held queue the delivery resumes", () => + Effect.gen(function* () { + const harness = yield* makeHarness; + yield* Effect.gen(function* () { + const target = yield* seedTarget("notice-held-idle"); + yield* idleWithHeldQueue(harness, target); + assert.isUndefined(yield* sendNoticeTo("notice-held-idle", target)); + }).pipe(Effect.provide(makeLifecycleTestLayer(harness))); + }), +); + it.effect("settles a held peer delivery once after resume without alarming", () => Effect.gen(function* () { const harness = yield* makeHarness; diff --git a/apps/server/src/j5/a2a/DeliveryTransport.ts b/apps/server/src/j5/a2a/DeliveryTransport.ts index ae5b734c35f5f..43b495b7c2c80 100644 --- a/apps/server/src/j5/a2a/DeliveryTransport.ts +++ b/apps/server/src/j5/a2a/DeliveryTransport.ts @@ -306,6 +306,34 @@ export const requestedSteeringRun = ( return (mode === "steer" ? turns.supportsActiveSteering || restarts : restarts) ? run : undefined; }; +/** + * Why an idle agent's queue must not be resumed for a delivery. Upstream refuses to resume a thread + * stopped by a usage limit, and holds a message queued after a failed worktree setup + * (`worktreeMissingRun` in Orchestrator.ts), as resuming would run it in the project checkout. + */ +export const idleQueueHold = ( + target: Pick< + OrchestrationV2ThreadProjection, + "thread" | "runs" | "turnItems" | "providerSessions" + >, +) => { + const sessionError = + target.providerSessions + .filter((session) => session.providerInstanceId === target.thread.providerInstanceId) + .toSorted( + (left, right) => + DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt), + )[0]?.lastError ?? null; + const limitedRun = usageLimitBlockedRun(target.runs, target.turnItems, sessionError); + if (limitedRun !== null) return { type: "usage_limit" as const, run: limitedRun }; + const latestRun = latestExecutedRun(target.runs); + return (latestRun?.status === "failed" || latestRun?.status === "interrupted") && + latestRun.workspacePreparation?.type === "worktree" && + target.thread.worktreePath === null + ? { type: "worktree_setup_failed" as const } + : undefined; +}; + export const formatAgentDeliveryEnvelope = ( input: AgentDeliveryInput & { readonly originProjectTitle?: string | undefined; @@ -630,34 +658,14 @@ export const live: Layer.Layer< // queue, so the held messages run first and it joins the back (#580). A retry of an // accepted delivery never resumes again. Upstream refuses to resume a thread stopped by // a usage limit, so that delivery waits unsent, as a held one, until the thread continues. - // So does one whose worktree setup failed, as upstream holds a message queued then - // (`worktreeMissingRun` in Orchestrator.ts): resuming would run it in the project checkout. + // So does one whose worktree setup failed (`idleQueueHold`). const heldQueueRun = target.runs.find( (run) => run.status === "queued" && run.queueHeld === true, ); - const latestRun = latestExecutedRun(target.runs); - const worktreeSetupFailed = - (latestRun?.status === "failed" || latestRun?.status === "interrupted") && - latestRun.workspacePreparation?.type === "worktree" && - target.thread.worktreePath === null; const queueBehindHeld = alreadyAccepted || heldQueueRun === undefined || target.runs.some(isActiveRun) ? Effect.void - : worktreeSetupFailed || - usageLimitBlockedRun( - target.runs, - target.turnItems, - target.providerSessions - .filter( - (session) => - session.providerInstanceId === target.thread.providerInstanceId, - ) - .toSorted( - (left, right) => - DateTime.toEpochMillis(right.updatedAt) - - DateTime.toEpochMillis(left.updatedAt), - )[0]?.lastError ?? null, - ) !== null + : idleQueueHold(target) !== undefined ? Effect.fail( new A2ADeliveryHeldError({ participantId: input.receiverId, diff --git a/apps/server/src/j5/a2a/EnvelopeFormatter.ts b/apps/server/src/j5/a2a/EnvelopeFormatter.ts index 8710a5bd12337..2dc587cf6d39f 100644 --- a/apps/server/src/j5/a2a/EnvelopeFormatter.ts +++ b/apps/server/src/j5/a2a/EnvelopeFormatter.ts @@ -154,3 +154,22 @@ export const formatReceiverBacklogNotice = (input: { waiting: String(input.waiting), fromYou: String(input.fromYou), }); + +/** + * Told to a sender whose message waits on a receiver stopped by a usage limit. `resetAt` is when + * upstream continues it, or null when it waits for a person. + */ +export const formatReceiverLimitNotice = (input: { + readonly receiverId: ParticipantId; + readonly resetAt: string | null; +}): string => + input.resetAt === null + ? render(config.receiverLimitPausedNotice, { receiverId: input.receiverId }) + : render(config.receiverLimitAutoResumeNotice, { + receiverId: input.receiverId, + resetAt: input.resetAt, + }); + +/** Told to a sender whose message waits until a person resumes the receiver's held queue. */ +export const formatReceiverQueueHeldNotice = (input: { readonly receiverId: ParticipantId }) => + render(config.receiverQueueHeldNotice, { receiverId: input.receiverId }); diff --git a/apps/server/src/j5/a2a/contracts.ts b/apps/server/src/j5/a2a/contracts.ts index 588aecc143bfa..81005410b67c6 100644 --- a/apps/server/src/j5/a2a/contracts.ts +++ b/apps/server/src/j5/a2a/contracts.ts @@ -436,7 +436,7 @@ export const SendMessageResult = Schema.Struct({ exchangeState: Schema.Literals(["none", "open", "closing", "closed"]), joinedExistingExchange: Schema.Boolean, durableAtSeq: PositiveInt, - /** Present when the receiver is busy and the message will wait behind its running turn. */ + /** Present when the message will wait: behind the receiver's running turn, or on its held queue or usage limit. */ deliveryNotice: Schema.optional(Schema.String), /** The name of the peer server the receiver lives on; absent for a receiver on this server. */ receiverServer: Schema.optionalKey(Schema.String), diff --git a/apps/server/src/j5/a2a/envelopes.v1.json b/apps/server/src/j5/a2a/envelopes.v1.json index 7c4fa474ec5ff..907539a545847 100644 --- a/apps/server/src/j5/a2a/envelopes.v1.json +++ b/apps/server/src/j5/a2a/envelopes.v1.json @@ -16,5 +16,8 @@ "sendToolDescription": "Send one durable message. To another agent, three uses: a **plain send** when you don't need a reply; an **ask** — set expect_reply=true with a one-line intent, opening an exchange the receiver owes a reply to; a **reply** — include the exchange_id from the ask you are answering, which closes that exchange. To the human, only an ask: a plain send to a person is refused — if nobody needs to act, say it in your own thread instead. Set urgency only when asking the human. Use this tool only for participants already returned by j5_list_participants; when creating a Peer Agent, put any reply expectation in j5_spawn_agent's brief instead of sending a follow-up ask. Returns once the message is committed; delivery continues asynchronously — carry on with your work, and the reply arrives later as an incoming message. An agent that is busy usually handles each message as its own turn after its current one ends, so put related updates in one message rather than sending them one by one; the result's deliveryNotice says when your message will wait behind the receiver's current turn. To interrupt an agent that is busy, set mode: mode=steer puts your message into the turn it is running now, and mode=restart stops that turn and starts it again on your message. Without mode the message is delivered the ordinary way, whatever its text or its intent says: most agents take it after their current turn ends, and Codex GPT 6 agents take it into the turn they are running. intent only labels an ask. Leave mode out for updates and replies. A steer can cancel the tool calls the receiver has in flight, so keep it for a correction the receiver must see now, not for an update. An idle receiver starts a turn on your message whichever mode you set. Attach files for an agent on this server with attachments: pending uploads from t3_attachment_prepare_upload, or files its thread already holds. A provider Subagent is not a participant and is refused. Reuse client_request_id to retry the same send safely.", "listToolDescription": "Your address book, one project at a time: the project's agents, and the human, with the display name to recognize them by, the participant_id to address them with, the project_id and project_title that place them, and what each accepts (messages, exchanges, urgency). Leave project_id out to list your own project; pass another project's id, from t3_project_list, to list that one. People appear in every listing. Results come a page at a time: your own row first, then the people, then agents with the most recently active first. Narrow a listing with name_contains, or with settled=true or settled=false for settled or active agents. If this server is peered with others, each row also carries `server`: the name of the server the participant lives on, and whether it is this one (`local`), and the result names every server in `servers`; pass a peer server's name as server to list that server's agents instead of this one's. When you're told to message someone by name or role, resolve them here first. Your own row is marked self=true and its project_title is the project you work in; it cannot receive messages or open exchanges from you — use schedule_task if you need a future trigger for yourself. Provider Subagents are not participants: they do not appear here and cannot be messaged. Archived agents are hidden by default; set include_archived=true to see them with archived=true. They cannot receive messages or open Exchanges. The roster changes — after you spawn, archive, unarchive, or delete an agent, call this again instead of reusing a stale listing.", "receiverBacklogNotice": "{{receiverId}} is in the middle of a turn, with {{waiting}} message(s) waiting for it ({{fromYou}} from you). It will handle each one as a separate turn after its current turn ends, so put any further updates for it in one message.", + "receiverLimitAutoResumeNotice": "{{receiverId}} hit its provider's usage limit and continues automatically at {{resetAt}}. Your message is saved and will run then, in the order it was sent. Don't send it again.", + "receiverLimitPausedNotice": "{{receiverId}} hit its provider's usage limit and is paused until a person continues it. Your message is saved and will run then, in the order it was sent. Don't send it again.", + "receiverQueueHeldNotice": "{{receiverId}}'s queue is on hold, so your message waits until a person resumes it. It will run then, in the order it was sent. Don't send it again.", "clearOwnAskToolDescription": "Withdraw an ask you sent: closes your open exchange without a reply message. Use when the answer already arrived outside the exchange — for example, the human answered you directly in your thread — so the obligation exits their inbox honestly. Only the exchange's sender may clear it; the closure is recorded as sender-cleared, distinct from an answered exchange. Reuse client_request_id to retry safely." } diff --git a/apps/server/src/j5/a2a/receiverBacklog.ts b/apps/server/src/j5/a2a/receiverBacklog.ts index 38403564bb74e..82c00c3a4da7a 100644 --- a/apps/server/src/j5/a2a/receiverBacklog.ts +++ b/apps/server/src/j5/a2a/receiverBacklog.ts @@ -5,33 +5,53 @@ import * as SqlClient from "effect/sql/SqlClient"; import { OrchestratorV2 } from "../../orchestration-v2/Orchestrator.ts"; import { latestActiveRun } from "../../orchestration-v2/ThreadManagementService.ts"; +import { + latestExecutedRun, + latestRootProviderFailure, +} from "@t3tools/shared/orchestrationV2ThreadError"; + import { gpt6PeerSteeringRun, deliveryMessageId, + idleQueueHold, isDeliveryMessageId, requestedSteeringRun, } from "./DeliveryTransport.ts"; -import { formatReceiverBacklogNotice } from "./EnvelopeFormatter.ts"; +import { + formatReceiverBacklogNotice, + formatReceiverLimitNotice, + formatReceiverQueueHeldNotice, +} from "./EnvelopeFormatter.ts"; import { LedgerMessageId, Participant, type ParticipantId, type SendMode } from "./contracts.ts"; -export interface ReceiverBacklog { - /** Messages that will each start their own turn once the receiver's current turn ends. */ - readonly waiting: number; - /** How many of those the caller sent. */ - readonly fromCaller: number; -} +export type ReceiverBacklog = + | { + readonly type: "behind_turn"; + /** Messages that will each start their own turn once the receiver's current turn ends. */ + readonly waiting: number; + /** How many of those the caller sent. */ + readonly fromCaller: number; + } + | { + readonly type: "usage_limit"; + /** When upstream continues the receiver, or null when it waits for a person. */ + readonly resetAt: string | null; + } + /** Its queue is held, so the message runs only once a person resumes it. */ + | { readonly type: "queue_held" }; const decodeParticipant = Schema.decodeUnknownEffect(Schema.fromJsonString(Participant)); /** * What a just-sent message is waiting behind: the receiver's running turn and the * A2A messages after it, both those already queued as runs and those the delivery - * worker has not handed over yet. Undefined when the message will not wait: the - * receiver is idle, takes it mid-turn (a GPT 6 model, or a steer or restart), holds its queue, is not an agent on - * this server, or the message has already run or will never run. Measured when - * called and never stored, so it is advice to the sender, not a delivery fact. A - * failed read is logged and reads as undefined: the message is already committed, - * and the send must not fail over advice. + * worker has not handed over yet; or a held queue or usage limit, which only a resume + * or a continue lifts (D4). Undefined when the message will not wait: the receiver is + * idle and takes it now, takes it mid-turn (a GPT 6 model, or a steer or restart), is + * not an agent on this server, or the message has already run or will never run. + * Measured when called and never stored, so it is advice to the sender, not a delivery + * fact. A failed read is logged and reads as undefined: the message is already + * committed, and the send must not fail over advice. */ export const readReceiverBacklog = Effect.fn("j5.a2a.readReceiverBacklog")( function* (input: { @@ -69,17 +89,52 @@ export const readReceiverBacklog = Effect.fn("j5.a2a.readReceiverBacklog")( "providerThreads", "providerSessions", ]); - if (target.thread.archivedAt !== null || latestActiveRun(target) === undefined) - return undefined; - // A held queue drains only when someone resumes the thread, so "after its current - // turn ends" would be false. Telling the sender about held receivers is #272. - if (target.runs.some((run) => run.status === "queued" && run.queueHeld === true)) - return undefined; + if (target.thread.archivedAt !== null) return undefined; const runByMessage = new Map(target.runs.map((run) => [run.userMessageId, run])); const sentRun = runByMessage.get(deliveryMessageId(input.sentMessageId)); // Already started or finished (a replay reports the current state, not the first one). if (sentRun !== undefined && sentRun.status !== "queued") return undefined; + const pending = pendingRows.filter( + (row) => !runByMessage.has(deliveryMessageId(LedgerMessageId.make(row.message_id))), + ); + // Neither queued nor pending: cancelled or alarmed, so it is not waiting. + if (sentRun === undefined && !pending.some((row) => row.message_id === input.sentMessageId)) + return undefined; + const heldQueue = target.runs.some((run) => run.status === "queued" && run.queueHeld === true); + + if (latestActiveRun(target) === undefined) { + // An idle receiver takes the message now, resuming a held queue first, unless that + // queue may not be resumed. Upstream holds a message sent after a failed worktree + // setup even without a held queue. + const latestRun = latestExecutedRun(target.runs); + // Only a failed run's errors can name a usage limit. + const { turnItems } = + latestRun?.status !== "failed" + ? { turnItems: [] } + : yield* orchestrator.getThreadRecords(participant.threadId, ["turnItems"], { + turnItemRunIds: [latestRun.id], + turnItemTypes: ["error"], + }); + const hold = idleQueueHold({ ...target, turnItems }); + if (hold?.type === "worktree_setup_failed") return { type: "queue_held" } as const; + // Without a held queue a delivery starts a turn at once, as upstream starts any message + // to an idle thread, but one already queued waits for the continue. + if (hold?.type !== "usage_limit" || (!heldQueue && sentRun === undefined)) return undefined; + // Upstream continues it at the reset only when its recovery is armed for this limit, + // as the thread's usage-limit banner shows. + const recovery = target.thread.limitRecovery; + const resetAt = latestRootProviderFailure(hold.run, turnItems)?.resetAt; + return { + type: "usage_limit", + resetAt: + recovery?.autoResume === true && + recovery.runId === hold.run.id && + recovery.resetAt === resetAt + ? recovery.resetAt + : null, + } satisfies ReceiverBacklog; + } // Not yet handed over, so a running GPT 6 turn, or the turn a steer or restart lands on, // will take it mid-turn. Once queued, it stays queued even if the receiver's turn later // becomes steerable. @@ -91,13 +146,8 @@ export const readReceiverBacklog = Effect.fn("j5.a2a.readReceiverBacklog")( : requestedSteeringRun(target, "peer", mode)) !== undefined ) return undefined; - - const pending = pendingRows.filter( - (row) => !runByMessage.has(deliveryMessageId(LedgerMessageId.make(row.message_id))), - ); - // Neither queued nor pending: cancelled or alarmed, so it is not waiting. - if (sentRun === undefined && !pending.some((row) => row.message_id === input.sentMessageId)) - return undefined; + // A held queue drains only when someone resumes the thread, not when its turn ends. + if (heldQueue) return { type: "queue_held" } as const; const callerId = (yield* sql<{ readonly sender_id: string }>` SELECT sender_id FROM j5_a2a_delivery WHERE message_id = ${input.sentMessageId} LIMIT 1 `)[0]?.sender_id; @@ -112,6 +162,7 @@ export const readReceiverBacklog = Effect.fn("j5.a2a.readReceiverBacklog")( messageIds: queued.map((run) => run.userMessageId), })).messages; return { + type: "behind_turn", waiting: queued.length + pending.length, fromCaller: queuedMessages.filter((message) => message.senderThreadId === input.callerThreadId).length + @@ -129,7 +180,7 @@ export const readReceiverBacklog = Effect.fn("j5.a2a.readReceiverBacklog")( ), ); -/** Adds the backlog notice to a send result when the message will wait behind the receiver's turn. */ +/** Adds a notice to a send result when the message will wait: behind the receiver's turn, or on its hold. */ export const withDeliveryNotice = Effect.fn("j5.a2a.withDeliveryNotice")(function* < R extends { readonly messageId: LedgerMessageId }, >( @@ -141,14 +192,16 @@ export const withDeliveryNotice = Effect.fn("j5.a2a.withDeliveryNotice")(functio }, ) { const backlog = yield* readReceiverBacklog({ ...input, sentMessageId: result.messageId }); - return backlog === undefined - ? result - : { - ...result, - deliveryNotice: formatReceiverBacklogNotice({ + if (backlog === undefined) return result; + const deliveryNotice = + backlog.type === "behind_turn" + ? formatReceiverBacklogNotice({ receiverId: input.receiverId, waiting: backlog.waiting, fromYou: backlog.fromCaller, - }), - }; + }) + : backlog.type === "usage_limit" + ? formatReceiverLimitNotice({ receiverId: input.receiverId, resetAt: backlog.resetAt }) + : formatReceiverQueueHeldNotice({ receiverId: input.receiverId }); + return { ...result, deliveryNotice }; }); diff --git a/docs/j5/product/a2a/agent-tools.md b/docs/j5/product/a2a/agent-tools.md index 8847d950976a2..2ef43089d8873 100644 --- a/docs/j5/product/a2a/agent-tools.md +++ b/docs/j5/product/a2a/agent-tools.md @@ -42,7 +42,7 @@ An agent learns what it can do from its tools, and it reads a tool's description **Attachments.** Each is a pending upload from `t3_attachment_prepare_upload`, or an attachment the receiver's thread already holds. They are claimed into the receiver's thread before the message is committed, and released if the send is refused before anything is committed (an unacceptable sender, receiver or request). A storage failure leaves the claims in place, because nobody knows then whether the message was committed. A person and an agent on a peer server take no attachments. This replaces J5's own version of `t3_thread_send_attachments`, which sent a thinner message through the same ledger: no ask or reply, no retry key, no landing choice. -**Result:** the message id and the Exchange's state. When the receiver is an agent that is mid-turn and will not take the message into that turn, the result also carries a `deliveryNotice` stating how many messages are waiting for it, how many of them are the caller's, and that each will run as its own turn. When the recipient lives on a peer server, the result also names that server. When that server is offline, the result says the message is waiting for the recipient and when the server was last available, and its wording names the server: "Recorded. is on Laptop, which is offline, last available 3 h ago; it receives this when Laptop is next available." A recipient on this server adds nothing; one on an online peer server adds only that server's name. +**Result:** the message id and the Exchange's state. When the receiver is an agent on this server and the message will wait, the result also carries a `deliveryNotice`. Behind a turn the receiver will not take it into, the notice states how many messages are waiting for it, how many of them are the caller's, and that each will run as its own turn. When the message waits on the receiver's held queue or failed worktree setup, or on the usage limit it stopped on, the notice says it runs, in the order it was sent, once a person resumes or continues the receiver, or at the reset time when upstream continues it automatically, and that it should not be sent again. The notice is measured as the message is sent; a sender is not told when a receiver's queue is held later. When the recipient lives on a peer server, the result also names that server. When that server is offline, the result says the message is waiting for the recipient and when the server was last available, and its wording names the server: "Recorded. is on Laptop, which is offline, last available 3 h ago; it receives this when Laptop is next available." A recipient on this server adds nothing; one on an online peer server adds only that server's name. **Rules.** A message to the caller itself is refused. A message addressed to an [outside agent](index.md#participants) is refused for every sender, because nothing can be delivered to one. A send to a person that is not an ask is refused; a person never opens an Exchange, so there is nothing for an agent to reply to. Between agents, a further ask to a peer that already holds an open Exchange from the caller joins it as a follow-up. To a person, a further ask opens a new Exchange and a new inbox item unless it names an open one in `regarding`, in which case it joins that Exchange and is shown beneath the original ask. An ask to a person without an urgency is refused. An outside agent sends a plain message only, so `expect_reply`, `exchange_id`, `intent` and `urgency` are refused from it, and so is a person, who takes only asks. It reaches agents on this server only: an agent on a peer server and an id the server does not know are refused. A thread caller's receiver is held to the caller's permission modes only for `steer` and `restart`. An outside agent's receiver is held to the level the sign-in was approved at on every send, one that asks for no steer or restart included. The level is checked when the message is sent, not when it lands. An outside agent's message is recorded in the receiver's project, and its result carries no `deliveryNotice`. Attachments work the same for every sender. @@ -486,3 +486,4 @@ run; `j5_stop_crew` doesn't, and unarchiving doesn't restart it. - 2026-10-12 — Stop: the next message delivered to a stopped agent resumes its queue and runs after the held messages, where it used to run ahead of them; the `j5_stop_agent` and `j5_stop_crew` descriptions say so (Jackson, [#580](https://github.com/Jacksondr5/j5code/issues/580)). - 2026-10-17 — the advance onto upstream's nightly `v0.1.1-nightly.20261017.3238`: `t3_workflow_stop`, `write_pull_request_guides` and `read_pull_request_guide` join the kept upstream tools as-is, and `delegate_task`'s description takes upstream's sentences on a child's own worktree, a wait that ends at the child's question, and runtime modes (Jackson's decisions of that day; [register of divergences](../upstream.md), D1 and D2). - 2026-10-24 — `j5_spawn_agent` requires a short `title`, as upstream's `t3_thread_launch` does, instead of naming the agent after the start of its brief ([#296](https://github.com/Jacksondr5/j5code/issues/296)). +- 2026-10-24 — `j5_send_message`'s `deliveryNotice` also tells the sender when its message waits on the receiver's held queue, failed worktree setup or usage limit, and that it should not be sent again (Jackson, [#272](https://github.com/Jacksondr5/j5code/issues/272)).