@sema-agent/core
Version:
Stateless, task-oriented AI agent core
241 lines (240 loc) • 18.7 kB
TypeScript
/**
* The peer task lane: a call to an A2A peer's skill is a background task row (`peer_task`, a `p…` handle) that the engine drives to
* an ending, never a call that waits on the peer for as long as the peer takes.
*
* THE RULES (one each; the slice page of orchestration slice 2-b car 4 lists where each comes from):
* - ADMISSION BEFORE THE SEND. A call is sent only when its completion will come back: the completion sink the call resolves
* (`resolveCompletionSink`) is there, and the deployment declares that its readers read `peer_task` frames
* ({@link peerTaskFramesDeclared}, `RunnerDeps.a2a.peerTaskFrames`). Either arm missing ⇒ the call is refused by name before
* anything is written or sent; the sentence says what to wire. A tool minted with no leg ctx builder (the library entrance) has no
* completion sink, so every call of it is refused.
* - THREE STATES, IN ORDER. The row is written `recorded` (certainly not sent), then `sent_unconfirmed` (from here on not provably
* unsent), then the request is sent — the stored bytes, under the message id minted once — then `accepted` on the peer's first
* answer (a task, or a direct message that settles the row at once).
* - A SHORT WINDOW, THEN THE CALLER GETS CONTROL BACK — where the call's run sees the row's completion (a one-shot run, a
* session-resident row). Inside `shortWaitMs` the lane asks the peer itself: an ending answers the call as the A2A client always has
* (the peer's result in its fence, its failure as the call's error). A task waiting on a person (the caller, or the peer's own
* approver) or the window's end answers with a RECEIPT; the row goes on in the background and every later fact reaches the caller as
* a `peer_task` notification frame. Where the run does not see it, the call waits for the row's ending (or a person's turn, said as
* the client always has) and that answer is the row's last word: no frame, no watch after it.
* - TWO DEADLINES, FIXED AT DISPATCH. `ackBy` and `finalBy` are the dispatch instant plus the entry's terms ({@link peerTaskTermsOf});
* the hard cap is `finalBy + approvalWaitMs`. Nothing else is a clock: the per-call 120-second idle clock and 10-minute ceiling the
* client used to wait under are retired.
* - AT `finalBy` A RUNNING ROW SETTLES `failed`, its code by the peer's side and state ({@link PEER_TASK_FAILURE_CODES}): an outside
* peer — `a2a.external_no_response`; an inside peer waiting on its own approver — `a2a.peer_awaiting_own_approval` (not a fault);
* any other inside peer — `a2a.internal_no_final_response` (a fault, recorded for operations through `onError`). None of the three
* sends a cancel.
* - A ROW SETTLED BY ITS DEADLINE AFTER A RECEIPT KEEPS A READ-ONLY WATCH UNTIL THE HARD CAP (the overdue tail); a row settled any
* other way keeps none.
* A peer ending inside the tail reaches the caller as one `event` frame (an outside peer's carries `noWake`), and the tail closes.
* - OUR STOP is `killed` with who stopped it (the registry's first marker) and, from the run-end sweep, what ended the run; the PEER'S
* OWN CANCEL is `cancelled`; a revocation met while asking is `failed` with `a2a.peer_revoked` and nothing more is sent.
* - A PEER'S ERROR ANSWER ENDS A RUNNING ROW. An ask after the task that the peer answers with a JSON-RPC error settles the row `failed`
* with that error — thrown as the call's failure inside the window, the failed frame's `error` after it — and nothing more is asked
* ({@link PeerWire.answeredByPeer}). An ask that failed without such an answer is asked again; the final deadline bounds the row.
* - `remoteMayContinue` is derived on a settled row: something was sent, the peer did not reach an ending, and no cancel was confirmed.
* - `followUps` is `not_accepted` on every row: no peer declares an extension that takes additions after submission yet, so the lane
* sends no cancel, reminder or addition to any peer, and the receipt says so.
* - AN ANSWER THAT CARRIES THE ROW'S ENDING NAMES IT, as a terminal frame does: whatever the call answers once its window closed with
* the ending (the peer's result, the client's thrown failure, the summary of a stop or a deadline, a person's turn the row ends
* with) closes with one trusted line, `task_id: p… · <status> (this answer is its ending)`, and carries `details.task_id` and
* `details.status`. A returned answer gains the line as a block of its own; a thrown one gains both on the object the client threw
* (its class, name and code stay the caller's). The run's member ledger reads that answer when the call ends (run-ledger.ts
* `callEnded`), told by the lane which call dispatched the row (`PeerTaskDispatch.ledger`).
*
* - A DEPLOYMENT'S PEER TASK STORE (`RunnerDeps.peerTaskStore`), WHEN MOUNTED, HOLDS THE ROW: the row is `put` before anything is
* sent (a store that cannot take it refuses the call: nothing sent), and every later transition is written in the order it happens
* (`updateIf` against the row's previous `rev`). Everything the row says outward — the call's answer, `TaskStop`'s answer, a
* frame — is minted in the very step it reports, from the row that step left, with the words that step
* gives it with no store; with a store it leaves once THAT version's write was answered (taken, refused or thrown: all are
* answers), never waiting on a later write. For the same steps the store changes when it leaves, not what it says; the row may
* have moved on by then, and what followed comes as the row's frames, in order. Without a store the row lives in this process
* only, as it always has.
* - A RESTART ASKS THE PEER NOTHING: a later leg of the session settles each unsettled row of the session's that no lane of this
* process drives, once ({@link settleOrphanedPeerRows}) — a running row `failed` with `a2a.peer_task_outcome_unknown` and one
* frame carrying the engine's own sentence and the task id, never the peer's words; a settled row's open overdue tail closes
* silently. An ending a frame or the call's answer carried was written to the store before it left, so it is never settled twice.
*
* The lane owns the row and its words; the A2A client (a2a.ts) owns the wire and the peer's words ({@link PeerWire},
* {@link PeerObservation}). The receipt says the wait is not kept across a restart, store or not.
*/
import type { AgentToolResult } from "../internal/harness-types.js";
import { type A2AWaitingFor } from "./a2a-task-state.js";
import type { A2aServerSpec, AskDestination } from "./mcp-server-spec.js";
import { type PeerTaskRemoteState, type PeerTaskStore } from "./peer-task-store.js";
import { ProtocolRevokedRefusal } from "./protocol-revocation.js";
import { type SystemInjectionPriority, type TaskNotificationPayload } from "./task-notification.js";
import { type TaskAccess } from "./task-registry-shared.js";
import type { RunLedgerSink } from "./run-ledger.js";
import type { TaskRegistry } from "./task-registry.js";
/** The failure codes a peer task row settles with — open strings on `MemberOutcome.code` and the failed frame's `errorCode`: one per
* arm of the deadline rule, and `peer_task_outcome_unknown` for a row a later leg settled after the process driving it was gone
* ({@link settleOrphanedPeerRows}). A revocation reuses the revocation door's own word (`a2a.peer_revoked`). */
export declare const PEER_TASK_FAILURE_CODES: Readonly<{
readonly internal_no_final_response: "a2a.internal_no_final_response";
readonly external_no_response: "a2a.external_no_response";
readonly peer_awaiting_own_approval: "a2a.peer_awaiting_own_approval";
readonly peer_task_outcome_unknown: "a2a.peer_task_outcome_unknown";
}>;
/**
* The terms a peer's entry gives a call when its `respond` member says nothing of one. Product choices without readings: the window
* and the two acknowledgement defaults are the design's; the final deadline is the ceiling the retired call clock held, so a peer that
* answered within today's ceiling answers within this one; the approval wait is the design's suggested day.
*/
export declare const PEER_TASK_TERMS_DEFAULTS: Readonly<{
shortWaitMs: 20000;
finalWithinMs: 600000;
approvalWaitMs: 86400000;
ackWithinMs: Readonly<{
inside: 120000;
outside: 600000;
}>;
}>;
/** One call's terms, fixed at dispatch. */
export interface PeerTaskTerms {
readonly shortWaitMs: number;
readonly ackWithinMs: number;
readonly finalWithinMs: number;
readonly approvalWaitMs: number;
}
/**
* What a declaration's `A2aServerSpec.respond` cannot be read as, in a sentence's words (the registration judge's refusal names the
* member), or `undefined` when it fits: an object of the four terms and no other member; each a whole number of milliseconds up to what
* one timer holds; a final deadline after the dispatch instant; the window and the acknowledgement deadline not past the final deadline
* in force (the declared one, else {@link PEER_TASK_TERMS_DEFAULTS}). Read on the declaration's frozen plain-data copy.
*/
export declare function a2aRespondProblem(respond: unknown): string | undefined;
/** The entry's terms (`A2aServerSpec.respond`, judged where the declaration is read: {@link a2aRespondProblem}) over {@link PEER_TASK_TERMS_DEFAULTS}.
* No term in force is past the final deadline in force: a written window or ack past it is refused where it is read, and a term the
* entry leaves out is its default or the final deadline in force, whichever is sooner (a shortened final deadline brings both with it). */
export declare function peerTaskTermsOf(respond: A2aServerSpec["respond"], boundary: AskDestination["boundary"]): PeerTaskTerms;
/** What the leg hands the lane: the deployment's declaration (`peerTaskFramesDeclared`, a2a-deployment-switches.ts) and its operator log. */
export interface PeerTaskLaneSeat {
readonly frames: boolean;
readonly onError?: ((err: unknown, context: {
phase: "a2a";
sessionId: string;
classification?: string;
}) => void) | undefined;
/** The deployment's peer task store (`RunnerDeps.peerTaskStore`); absent ⇒ rows live in this process only. */
readonly store?: PeerTaskStore | undefined;
}
/** The scope a peer task row is filed under: the leg's identity (`principal`, `isolationScope` — a call's trusted ctx members, a leg's
* `legIdentityOf(spec)`) as the registry keys it. A call's row (a2a.ts `peerCallReach`) and a leg's restart settle read it here. */
export declare function peerRowScopeOf(identity: {
readonly principal?: string | undefined;
readonly isolationScope?: string | undefined;
}): string;
/** One answer of the peer, read by the A2A client at the wire: the lane reads nothing of the wire itself. */
export interface PeerObservation {
/** The peer's side as the row keeps it (raw ids — sent back to the peer — and the state the table reads). */
readonly remote: PeerTaskRemoteState;
/** Whom a task that is not over waits on (the table's reading); absent ⇔ {@link ending} is present. */
readonly waitingFor?: A2AWaitingFor;
/** How the peer's side ended, when it did (a direct message is `completed`). */
readonly ending?: "completed" | "failed" | "cancelled";
/** The peer's ids and state as a trusted line may show them. */
readonly shown: {
readonly taskId?: string;
readonly contextId?: string;
readonly state?: string;
};
/** The client's result card for this answer (`details`: its state, class, whom it waits on, the peer's keys) — a receipt carries it. */
readonly details: Record<string, unknown>;
/** The peer's words as the model may read them: a person's turn said by the client plus the message in its fence, or the result /
* reason in its fence. */
readonly words: string;
/** The tool result this answer gives a call inside its window — the client's own shapes; throws for a failed ending, as the call did. */
inline(): AgentToolResult<unknown>;
}
/** The wire the lane drives, bound by the A2A client to one peer and one skill. */
export interface PeerWire {
/** Send the stored request bytes (`message/send`); resolves with the peer's answer, rejects with the client's failure. */
send(paramsJson: string, signal: AbortSignal): Promise<PeerObservation>;
/** Ask after a task, read-only (`tasks/get`). */
poll(remoteTaskId: string, signal: AbortSignal): Promise<PeerObservation>;
/** Whether a failure of `poll` is the peer's own answer — a JSON-RPC error it wrote — and not the exchange failing (a transport
* failure, a deadline, a status that is no JSON-RPC response): the client says it, the lane does not read the failure's shape. */
answeredByPeer(err: unknown): boolean;
/** The result a call answers when the revocation door stopped a request: its send (`accepted` absent), or an ask after the task the
* peer accepted (`accepted`: the peer's task id as a line may show it). */
revoked(refusal: ProtocolRevokedRefusal, accepted?: {
readonly taskId: string | undefined;
}): AgentToolResult<unknown>;
/** A failure of the send as a frame carries it: the words the call would have thrown, fenced as the peer's results are. */
failure(err: unknown): string;
/** The A2A client's result card (`details`) with the lane's members laid in: the card is the client's, whoever fills it. */
card(members: Record<string, unknown>): Record<string, unknown>;
}
/** Everything one call hands the lane. */
export interface PeerTaskDispatch {
/** The call's reach (a2a.ts `peerCallReach`); absent for a tool minted with no leg ctx builder. */
readonly reach: {
readonly registry: TaskRegistry;
readonly sink: ((n: TaskNotificationPayload, opts?: {
priority?: SystemInjectionPriority;
}) => unknown) | undefined;
} | undefined;
readonly seat: PeerTaskLaneSeat | undefined;
/** Where the row is filed and whose it is (the call's ctx); `sessionScoped` = it outlives the run (`backgroundScope: "session"`). */
readonly access: Required<Pick<TaskAccess, "owner" | "scope">> & Pick<TaskAccess, "sessionId" | "rootSessionIncarnation">;
readonly sessionScoped: boolean;
/** The task that dispatches the row (a2a.ts `peerCallReach`): written as the row's `parentTaskId`, the member key a background agent's
* and a workflow run's row carries — the row is a member of that task's ledger by the same law. */
readonly dispatchingTaskId?: string;
readonly toolUseId: string;
/** The row's label (the registry's task list shows it): the engine's tool name for the skill. */
readonly description: string;
readonly destination: AskDestination;
readonly skillId: string;
readonly fingerprint?: string;
readonly messageId: string;
readonly paramsJson: string;
readonly terms: PeerTaskTerms;
/** The call's signal: an abort ends the window (the row stays the run's, which its end settles). */
readonly signal?: AbortSignal;
/** The call's run sees the row's completion: its ending waits for the frames it is owed (`ctx.oneShot`), or the row outlives it
* (`sessionScoped`). Otherwise the run ends before a frame could come back, and the call waits for the row's ending itself. */
readonly completionComesBack: boolean;
/** `TaskStop` is on this leg (the mount fact `seat.peerTasks`, and the leg's tool selector admits it): the receipt names it only then. */
readonly taskStopMounted: boolean;
/** The run's member ledger seat (`ToolExecuteContext.runLedgerBook`, on a run that keeps one): told that this call dispatched the row. */
readonly ledger?: RunLedgerSink;
/** The mount's lifetime (the A2A client's dispose aborts it): for a row whose lifetime is the run, its end closes a settled row's watch
* (and a row settled after it keeps none), so nothing of the lane outlives the run's end — a running row is stopped by the run's end
* sweep. A session-resident row (`sessionScoped`) is the session's: its release stops it and its watch. */
readonly mount?: AbortSignal;
readonly wire: PeerWire;
}
/** The refusal of a call whose completion would not come back (no completion sink for it): nothing is written or sent. */
export declare function peerNoCompletionLaneText(peer: string): string;
/** The refusal of a call on a deployment that has not declared that its readers read `peer_task` frames: nothing is written or sent. */
export declare function peerFramesUndeclaredText(peer: string): string;
/**
* Dispatch one call: admission, the row, the send, the window. Resolves with the call's tool result — the peer's answer when it came
* inside the window, else a receipt. Never throws for a refusal; a failure inside the window is thrown as the A2A client threw it.
*/
export declare function dispatchPeerTask(d: PeerTaskDispatch): Promise<AgentToolResult<unknown>>;
/** Where a leg's restart settle looks: the deployment's store, the leg's scope and session, the occupant its rows carry (`rootAnchorOf`,
* the same reading a call's row is stamped with), and the operator log. */
export interface OrphanedPeerRowsSeat {
readonly store: PeerTaskStore;
readonly scope: string;
readonly sessionId: string;
readonly occupant: string | undefined;
readonly onError?: ((err: unknown, context: {
phase: "a2a";
sessionId: string;
classification?: string;
}) => void) | undefined;
}
/**
* A restart asks the peer nothing (the module head's rule): each row of the session (its own anchor — `owner` for a session-scoped
* row, `parentSessionId` for a task-scoped one — under the leg's occupant) that is unsettled in the store and driven by no lane of this
* process is settled once, by a compare-and-set against the row read: a running row `failed` with
* {@link PEER_TASK_FAILURE_CODES}.peer_task_outcome_unknown (`remoteMayContinue`), answered here as one frame for the session — the
* engine's sentence and the task id, never the peer's words; a settled row's open overdue tail closes, no frame. A row another writer
* moved first is left to it. Answers the frames, for the leg to hand its session before its first turn; never throws (a store that
* cannot be read is said on the operator log, and the next leg looks again).
*/
export declare function settleOrphanedPeerRows(seat: OrphanedPeerRowsSeat): Promise<TaskNotificationPayload[]>;