Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
223 changes: 169 additions & 54 deletions apps/server/src/j5/a2a/DeliveryTransport.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)));
}),
Expand Down Expand Up @@ -3492,45 +3482,56 @@ 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;
yield* Effect.gen(function* () {
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);

Expand All @@ -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;
Expand Down
52 changes: 30 additions & 22 deletions apps/server/src/j5/a2a/DeliveryTransport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down
19 changes: 19 additions & 0 deletions apps/server/src/j5/a2a/EnvelopeFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
2 changes: 1 addition & 1 deletion apps/server/src/j5/a2a/contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Loading
Loading