UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

240 lines (239 loc) • 19.3 kB
import type { AgentTool } from "../internal/harness-types.js"; import { type CredentialEchoSite } from "./credential-echo.js"; import { type PeerSeat } from "./peer-seat.js"; import { type HostFloor } from "./host-floor.js"; import { type A2aRevocationStopCode, type ProtocolRevocationLedger, type RevocationProbe } from "./protocol-revocation.js"; import { type McpFailureFields } from "./mcp-failure.js"; import type { A2aServerSpec, ToolExecuteContext } from "./types.js"; import { type ToolCtxEnricher } from "./tools.js"; import { type TaskRegistry } from "./task-registry.js"; import { type PeerTaskLaneSeat } from "./peer-task-lane.js"; import type { PeerTaskStore } from "./peer-task-store.js"; import { type A2aDeploymentSwitches } from "./a2a-deployment-switches.js"; import type { AskDestination } from "./mcp-server-spec.js"; import type { EngineNotice } from "./engine-notice.js"; /** The hard per-skill description bound (ruled 2026-08-03: ~2KiB), counted in code points — the unit every cut in the description is made in. */ export declare const A2A_SKILL_DESCRIPTION_MAX_CHARS = 2048; /** * The safety axes carried alongside one materialized A2A tool, for `prepare-task` to fold into the SAME * irreversible/egress collections first-party and MCP tools feed. * * Unlike MCP there is no server-hint leg to merge: the protocol has no per-skill annotation vocabulary, * and a remote agent's self-declaration would not be trustworthy if it had one. Every A2A tool therefore * starts at the ruled default (`egress:true`, the effect undeclared — read as `write` everywhere); the one way down is the whole * peer's registration ({@link A2aServerSpec.boundary} `"inside"`, on a deployment that does not isolate its peers), and the caller's * {@link A2aServerSpec.toolAxes} only raises a skill. So an axis carries exactly the values that declaration takes — the type is the * declaration's own (locked below, members and values), not a wider one a value the engine refuses could still be written into. */ export interface A2aToolAxis { /** Namespaced tool name (`a2a__<peer>__<skill>`). */ name: string; /** Present ONLY when the caller's override declares `"always"` (an A2A skill's axes only raise; `"never"` is refused where the * declaration is read, and so cannot be here). */ irreversibility?: "always"; /** `true` by default on a peer's skill the deployment does not relax as inside (an outside peer's, or any peer's on a deployment that * isolates its peers); on an inside peer's skill it is present ONLY when the caller's override marks it (`true`). `false` cannot be * here: it is refused where the declaration is read. */ egress?: true; /** Present ONLY when the caller's override declares it (`"write"`, the only effect a skill may declare); absent is the repeat-unsafe * `write` every reader applies (and the roster names `default` provenance — a default is not a declaration). */ effect?: "write"; } /** design/99 §E9 equivalent for A2A — a per-peer projection of THIS materialization. A2A holds no * connection (every call is its own HTTPS request), so `ready` means "the card was fetched and its * skills were mounted at prepare time", never "the peer is alive right now". * * A `failed` row carries the SAME failure record an MCP server's failed status carries ({@link McpFailureFields}: `errorCode`, one of * `MCP_FAILURE_KINDS`; `delivered`; `authorization` for `unauthorized`), so a consumer keys on one vocabulary for both protocols. The * members are present iff the row records a failure that was thrown. A peer seat that did not furnish a send reads * `credential_unavailable` (`unauthorized` when it answered that the principal is not authorized); an error the A2A client itself raises * for a non-2xx status or a JSON-RPC error carries no structure the classifier reads and reads `unknown` — `error` is the text to show, * never the field to key on. */ export interface A2aPeerStatus extends Partial<McpFailureFields> { name: string; status: "ready" | "failed"; /** The card's self-declared name, neutralized + bounded (it rides consumer-rendered lines). */ agentName?: string; agentDescription?: string; /** The negotiated JSON-RPC endpoint this task will call. */ endpoint?: string; toolNames?: string[]; error?: string; /** The declaration's {@link A2aServerSpec.boundary}: `outside` when the declaration says none. Absent only on a `failed` row whose * declaration, or whose `boundary` word, the engine could not read — such a row says nothing about the side; never read it as either. */ boundary?: "inside" | "outside"; /** The declaration's {@link A2aServerSpec.fingerprint}, when it carries one. */ fingerprint?: string; /** Present on a `failed` row the revocation door stopped at the dial, and only there: `a2a.peer_revoked` (the ledger withdrew the peer) or * `a2a.revocation_unreadable` (an inside peer, and the ledger could not be read for it) — the word a call's refusal carries as * `details.code`. `errorCode` is `revoked` for both (the failure kinds are one set for two protocols and the cause is not one of them). */ code?: A2aRevocationStopCode; /** On a `ready` row of an inside peer whose card and reviewed skills differ ({@link A2aCardDrift}); absent when they agree, and on * every outside peer (its `allowSkills` picks skills, it does not review them). */ cardDrift?: A2aCardDrift; } /** How an inside peer's card differs from its reviewed skills (`A2aServerSpec.allowSkills`), each list sorted: `unreviewed` — skills the * card names that were not reviewed (they are not mounted); `missing` — reviewed skills the card no longer names (nothing mounts for * them). At least one list is non-empty. Each id is spelled as a list entry is in a sentence (`renderListEntry`): a JSON string — * quotes and the usual escapes — with every control, format, separator and space character written `\uXXXX` (`\u{…}` past the BMP; a * lone space stays), cut after 122 characters, quotes included, and marked `…`; one entry per id; the lists are compared before it. */ export interface A2aCardDrift { readonly unreviewed: readonly string[]; readonly missing: readonly string[]; } /** One per-peer entry of {@link MaterializedA2a.refresh}. A `failed` entry whose refresh threw carries the failure record * ({@link A2aPeerStatus}); the entry for a name no peer is declared under (nothing was attempted) carries none. */ export interface A2aRefreshResult extends Partial<McpFailureFields> { peer: string; /** The peer's namespaced-name prefix — the consumer's SPLICE DOMAIN for a wholesale swap (the same * self-healing prefix domain the MCP refresh receipt hands out). Present on every entry. */ prefix: string; /** `revoked`: the revocation ledger answered the peer revoked, so its card was not asked for and its tools stay as they were. */ status: "refreshed" | "failed" | "disposed" | "revoked"; toolCount: number; added: string[]; removed: string[]; tools?: AgentTool[]; axes?: A2aToolAxis[]; /** On a `refreshed` entry whose peer was mounted from its public card although the card offers an extended one: the same warning * {@link MaterializedA2a.warnings} carries at the first mount (`a2a.extended_card_unavailable`). Present only when there is one. */ warnings?: Error[]; error?: string; } /** * Tools materialized from one or more A2A peers. * * Deliberately NARROWER than {@link import("./mcp.js").MaterializedMcp}: A2A has no server-instructions * channel and no intake schema gate, so there is no `serverInstructions`, no `instructionsDelta` and no * `droppedTools` face — an absent face is honest, an empty one that can never fill is a face a consumer * writes code against for nothing. */ export interface MaterializedA2a { tools: AgentTool[]; toolAxes: A2aToolAxis[]; /** One entry per peer that could not be materialized and was SKIPPED (fail-open, design/29): the task * runs with the healthy peers' tools — `code: "a2a.peer_unavailable"`, the refusal as its `cause`. A peer that DID mount adds one * entry when its public card offers an authenticated extended card that could not be used: it is mounted from the public card — * `code: "a2a.extended_card_unavailable"`, `reason` one of `no_credentials` (a send to the endpoint would carry nothing — no seat piece, no principal — or the * seat did not furnish it, so the extended card was not asked for), `http_<status>` (the peer answered that status), `malformed` (it answered 2xx with something * that is not a card: not JSON, not a JSON-RPC response, an error member, a result that is not an object) or `unreachable` (no * answer: a transport failure, the deadline, or a send the hop judge or the endpoint judge did not make), the failure as its * `cause` when there is one. A peer whose card does not offer one has no entry. The Runner forwards these to * `onError(phase:"a2a")`. */ warnings: Error[]; /** One entry per declared peer that was DIALED, in declaration order, ready or failed — the declaration as this materialization read it * once. A run's materialization asks the leg's dial predicate first: a peer it kept from the dial (the run's tool valve leaves nothing of * it) is declared and has no entry. The library entrance {@link materializeA2aTools} passes no dial predicate, so for a library caller this is * one entry per declared peer. */ statuses: A2aPeerStatus[]; /** Re-read one peer's card (or every dialed peer) and re-derive its tools. Unlike the MCP refresh * this dials nothing new — every A2A call is a fresh request anyway — so a peer whose card or network * failed at prepare time can genuinely recover here. The DECLARATION is not re-read: a refresh works * from the copy this materialization took and judged — the members too (`headers`, `allowSkills`, * `toolAxes` are copied, not shared) — so a declaration refused then is refused again and a caller * rewriting its object afterwards, by replacing a member or by editing one in place, changes nothing. * A peer the dial predicate kept from the dial is not contacted by a refresh: the all-peers form leaves it out, and naming it answers * `failed` with the reason and sends nothing (this status vocabulary has no `not_connected`, the word the MCP refresh answers). */ refresh: (peer?: string) => Promise<A2aRefreshResult[]>; /** * Task teardown. There is no socket to close (every call is its own request), so what this owns is the * LIFETIME statement: after it resolves, a tool that somehow still holds a reference fails loudly * instead of talking to a remote agent on behalf of a task that has ended. */ dispose: () => Promise<void>; } /** A JSON-RPC error answered BY the peer (the exchange happened; the peer refused or failed). Carries the * numeric code for `instanceof`-plus-code discrimination — never message-text matching. The peer's message is the peer's words: read * at the mint (credentials withheld, one line, the error's bound) and carried in the fence its results take ({@link fenceResult}); `after` * is the client's own sentence about the refusal, after the fence. */ export declare class A2aRpcError extends Error { readonly code: number; constructor(peer: string, method: string, code: number, message: string, after?: string); } /** * The tool-result code of a skill call whose answer refused it, by what the caller can change ({@link A2ARefusalClass}) — the result's * `details.code`, and so `tool_end.errorCode`. A refusal whose answer says none of the three ({@link refusalClassOf}) carries no code. * The words name the call, not the peer: a status may have been written by something in front of the peer (`details.delivered`). */ export declare const A2A_CALL_REFUSAL_CODES: Readonly<{ readonly not_retryable: "a2a.call_refused_not_retryable"; readonly changeable: "a2a.call_refused_changeable"; readonly retry_later: "a2a.call_refused_retry_later"; }>; /** What ONE call of a peer's tool reaches beyond the peer: the task registry the run's background rows live in, the one completion sink the * call's ctx carries, and whether a completion would come back through it (`admitsBackgroundLaunch` — the admission every background * producer applies, judged at the call). One source for all three: the ctx the leg's builder makes for the call. */ export interface PeerCallReach { readonly registry: TaskRegistry; readonly completionSink: ToolExecuteContext["onTaskNotification"]; readonly admitted: boolean; /** Where the call's row is filed and whose it is, off the same ctx: the run's task (or, for a row that outlives the run, its session) * under the run's working scope (`scopeKeyOf` of the leg's person and isolation scope). Absent when the ctx names no owner. */ readonly access?: { readonly owner: string; readonly scope: string; readonly sessionId?: string; readonly rootSessionIncarnation?: string; }; /** The row outlives the run (`backgroundScope: "session"` on a ctx that names its session). */ readonly sessionScoped: boolean; /** The task that dispatches the row — the ctx's task id, as a background agent's and a workflow run's row names it: a task id that * is only the session's names no task. The row's member key (`TaskRegistry.membersOfTask`). */ readonly dispatchingTaskId?: string; /** The run sees the row's completion: the row outlives it, or the run's ending waits for the frames it is owed (`ctx.oneShot`). */ readonly completionComesBack: boolean; /** `TaskStop` is on the leg: the leg can start a peer task (the mount fact `seat.peerTasks` holds), and its tool selector admits it. */ readonly taskStopMounted: boolean; /** The run's member ledger seat (`ctx.runLedgerBook`), on a run that keeps one: the lane tells it which call dispatched the row. */ readonly ledger?: NonNullable<ToolExecuteContext["runLedgerBook"]>; } /** The reach of one call, computed from the ctx the leg's per-call builder (the one every mounted tool runs with) makes for it — the * builder's answer with the call's own identity stamped over it (`stampCallIdentity`, the stamp every `defineTool` product applies). The * registry is the ctx's (the run's), else the engine's one. The admission is the engine's one (`admitsBackgroundLaunch`) over the ctx's * completion sink, and a ctx that names no owner for the row admits nothing. */ export declare function peerCallReach(enrichCtx: ToolCtxEnricher, toolCallId: string, signal: AbortSignal | undefined): PeerCallReach; /** The means a peer tool carries to compute the reach of one call (`toolCallId`, `signal`): run once, it builds the call's ctx through the leg's * builder and reads the registry, the completion sink and the admission off it. `undefined` ⇒ the tool was minted with no builder. */ export declare function peerToolReachOf(tool: AgentTool): ((toolCallId: string, signal?: AbortSignal) => PeerCallReach) | undefined; /** * Where a call goes, per tool name, for a leg's declared peers (the preparation door's frozen snapshot, the list the leg materializes): * a tool under a peer's prefix answers that peer's {@link AskDestination}, read off its declaration; any other tool answers nothing. The * prefix is the mint's own ({@link mintNamespacePrefix}), so a name the mint folded (`team.lead` mounts under `a2a__team_lead__`) finds * its peer, and the collision gate keeps one peer per prefix. The one reader every ask and park mint of the leg spreads. */ export declare function a2aDestinationReader(declared: readonly A2aServerSpec[] | undefined): (toolName: string) => { destination?: AskDestination; }; /** The operator's notices (`a2a.peer_card_drift`) for the inside peers whose status rows carry a {@link A2aCardDrift}, one per peer: the * lists from the row, the peer's name bounded; the delivery throat tells each once per session per drift. */ export declare function cardDriftNotices(statuses: readonly A2aPeerStatus[], sessionId: string, runId: string): EngineNotice[]; /** * Materialize every declared A2A peer into tools for one task. * * Peers are set up IN PARALLEL and merged in SPEC ORDER, so the tool roster (and therefore the system * prompt's tool list and the prefix cache) is byte-identical regardless of which card answered first. * `allSettled` keeps it fail-open: one unreachable peer is a skipped peer with a warning, never a task * that cannot start. */ export declare function materializeA2aTools(specs: readonly A2aServerSpec[], principal?: string, signal?: AbortSignal, hostFloor?: HostFloor, given?: PeerSeat, onCredentialEchoed?: (peer: string, where: CredentialEchoSite) => void, // once per peer: its card echoed the credentials its sends carried (the runner's notice) revocations?: ProtocolRevocationLedger & { onProbeFailure?: (error: unknown) => void; }): Promise<MaterializedA2a>; /** The runner's materialization of one leg's peers (not index-exported): the seat as the runner received it, and the leg's ONE revocation * probe — the one its MCP materialization asks too (a broken ledger is told once per leg). `dialable` is an engine-internal parameter, NOT a * host seat: today only the Runner passes it, with the leg's one server-level reading of the tool valve (`serverReached`, under the A2A * prefix) — a pure predicate that answers a boolean and does not throw — asked of each declared peer before anything is sent to it. A peer * it answers `false` for stays declared and is not contacted (no card request, no status row, no tool). Absent ⇒ every declared peer is * dialed. It has no guard against a throwing or non-boolean answer (the MCP materialization's `dialable` is host-suppliable and has one); * a form opened to a host needs that guard and a refusal code of its own. `enrichCtx` is the leg's per-call ctx builder, which every tool the * materialization mints (a refresh's included) carries the means to compute its calls' reach with ({@link peerToolReachOf}); absent ⇒ the * tools carry none (the library entrance). */ export declare function materializeLegA2aTools(revocations: RevocationProbe | undefined, specs: readonly A2aServerSpec[], principal: string | undefined, signal: AbortSignal | undefined, hostFloor: HostFloor | undefined, peerSeat: PeerSeat | undefined, onCredentialEchoed: ((peer: string, where: CredentialEchoSite) => void) | undefined, dialable?: (spec: { readonly name: string; }) => boolean, isolatePeers?: boolean, // the deployment's `RunnerDeps.a2a.isolatePeers`: an inside peer's skills keep the egress default ({@link a2aInsideRelaxed}) enrichCtx?: ToolCtxEnricher, // the leg's per-call ctx builder, carried by every minted tool; absent ⇒ a library materialization laneDeps?: { readonly a2a?: A2aDeploymentSwitches | undefined; readonly onError?: PeerTaskLaneSeat["onError"]; readonly peerTaskStore?: PeerTaskStore | undefined; }): Promise<MaterializedA2a>;