@providerkit/agents 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/LICENSE-APACHE-2.0 +202 -0
- package/README.md +2328 -2
- package/THIRD_PARTY_NOTICES.md +521 -0
- package/dist/a2a/auth.d.ts +10 -0
- package/dist/a2a/auth.d.ts.map +1 -0
- package/dist/a2a/auth.js +52 -0
- package/dist/a2a/auth.js.map +1 -0
- package/dist/a2a/client.d.ts +74 -0
- package/dist/a2a/client.d.ts.map +1 -0
- package/dist/a2a/client.js +601 -0
- package/dist/a2a/client.js.map +1 -0
- package/dist/a2a/index.d.ts +22 -0
- package/dist/a2a/index.d.ts.map +1 -0
- package/dist/a2a/index.js +11 -0
- package/dist/a2a/index.js.map +1 -0
- package/dist/a2a/memory-runs.d.ts +62 -0
- package/dist/a2a/memory-runs.d.ts.map +1 -0
- package/dist/a2a/memory-runs.js +349 -0
- package/dist/a2a/memory-runs.js.map +1 -0
- package/dist/a2a/policy.d.ts +15 -0
- package/dist/a2a/policy.d.ts.map +1 -0
- package/dist/a2a/policy.js +114 -0
- package/dist/a2a/policy.js.map +1 -0
- package/dist/a2a/push.d.ts +34 -0
- package/dist/a2a/push.d.ts.map +1 -0
- package/dist/a2a/push.js +180 -0
- package/dist/a2a/push.js.map +1 -0
- package/dist/a2a/remote.d.ts +155 -0
- package/dist/a2a/remote.d.ts.map +1 -0
- package/dist/a2a/remote.js +1196 -0
- package/dist/a2a/remote.js.map +1 -0
- package/dist/a2a/server.d.ts +110 -0
- package/dist/a2a/server.d.ts.map +1 -0
- package/dist/a2a/server.js +1139 -0
- package/dist/a2a/server.js.map +1 -0
- package/dist/a2a/signing.d.ts +21 -0
- package/dist/a2a/signing.d.ts.map +1 -0
- package/dist/a2a/signing.js +305 -0
- package/dist/a2a/signing.js.map +1 -0
- package/dist/a2a/tasks.d.ts +88 -0
- package/dist/a2a/tasks.d.ts.map +1 -0
- package/dist/a2a/tasks.js +170 -0
- package/dist/a2a/tasks.js.map +1 -0
- package/dist/a2a/wire.d.ts +267 -0
- package/dist/a2a/wire.d.ts.map +1 -0
- package/dist/a2a/wire.js +1202 -0
- package/dist/a2a/wire.js.map +1 -0
- package/dist/background-types.d.ts +76 -0
- package/dist/background-types.d.ts.map +1 -0
- package/dist/background-types.js +2 -0
- package/dist/background-types.js.map +1 -0
- package/dist/child.d.ts +25 -0
- package/dist/child.d.ts.map +1 -0
- package/dist/child.js +129 -0
- package/dist/child.js.map +1 -0
- package/dist/code-driver.d.ts +40 -0
- package/dist/code-driver.d.ts.map +1 -0
- package/dist/code-driver.js +2 -0
- package/dist/code-driver.js.map +1 -0
- package/dist/code-mode.d.ts +3 -0
- package/dist/code-mode.d.ts.map +1 -0
- package/dist/code-mode.js +2 -0
- package/dist/code-mode.js.map +1 -0
- package/dist/code-script.d.ts +3 -0
- package/dist/code-script.d.ts.map +1 -0
- package/dist/code-script.js +149 -0
- package/dist/code-script.js.map +1 -0
- package/dist/code.d.ts +75 -0
- package/dist/code.d.ts.map +1 -0
- package/dist/code.js +326 -0
- package/dist/code.js.map +1 -0
- package/dist/compaction.d.ts +15 -0
- package/dist/compaction.d.ts.map +1 -0
- package/dist/compaction.js +168 -0
- package/dist/compaction.js.map +1 -0
- package/dist/delegation.d.ts +135 -0
- package/dist/delegation.d.ts.map +1 -0
- package/dist/delegation.js +401 -0
- package/dist/delegation.js.map +1 -0
- package/dist/evals/driver.d.ts +10 -0
- package/dist/evals/driver.d.ts.map +1 -0
- package/dist/evals/driver.js +192 -0
- package/dist/evals/driver.js.map +1 -0
- package/dist/evals/journal.d.ts +26 -0
- package/dist/evals/journal.d.ts.map +1 -0
- package/dist/evals/journal.js +483 -0
- package/dist/evals/journal.js.map +1 -0
- package/dist/evals/judge.d.ts +31 -0
- package/dist/evals/judge.d.ts.map +1 -0
- package/dist/evals/judge.js +142 -0
- package/dist/evals/judge.js.map +1 -0
- package/dist/evals/report.d.ts +38 -0
- package/dist/evals/report.d.ts.map +1 -0
- package/dist/evals/report.js +241 -0
- package/dist/evals/report.js.map +1 -0
- package/dist/evals/runner.d.ts +24 -0
- package/dist/evals/runner.d.ts.map +1 -0
- package/dist/evals/runner.js +655 -0
- package/dist/evals/runner.js.map +1 -0
- package/dist/evals/scorers.d.ts +36 -0
- package/dist/evals/scorers.d.ts.map +1 -0
- package/dist/evals/scorers.js +259 -0
- package/dist/evals/scorers.js.map +1 -0
- package/dist/evals/simulation.d.ts +7 -0
- package/dist/evals/simulation.d.ts.map +1 -0
- package/dist/evals/simulation.js +38 -0
- package/dist/evals/simulation.js.map +1 -0
- package/dist/evals/testing.d.ts +36 -0
- package/dist/evals/testing.d.ts.map +1 -0
- package/dist/evals/testing.js +87 -0
- package/dist/evals/testing.js.map +1 -0
- package/dist/evals/trajectory.d.ts +11 -0
- package/dist/evals/trajectory.d.ts.map +1 -0
- package/dist/evals/trajectory.js +180 -0
- package/dist/evals/trajectory.js.map +1 -0
- package/dist/evals/types.d.ts +431 -0
- package/dist/evals/types.d.ts.map +1 -0
- package/dist/evals/types.js +4 -0
- package/dist/evals/types.js.map +1 -0
- package/dist/evals.d.ts +14 -0
- package/dist/evals.d.ts.map +1 -0
- package/dist/evals.js +9 -0
- package/dist/evals.js.map +1 -0
- package/dist/extensions.d.ts +33 -0
- package/dist/extensions.d.ts.map +1 -0
- package/dist/extensions.js +188 -0
- package/dist/extensions.js.map +1 -0
- package/dist/handoff.d.ts +58 -0
- package/dist/handoff.d.ts.map +1 -0
- package/dist/handoff.js +160 -0
- package/dist/handoff.js.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -0
- package/dist/input.d.ts +42 -0
- package/dist/input.d.ts.map +1 -0
- package/dist/input.js +266 -0
- package/dist/input.js.map +1 -0
- package/dist/mcp.d.ts +77 -0
- package/dist/mcp.d.ts.map +1 -0
- package/dist/mcp.js +505 -0
- package/dist/mcp.js.map +1 -0
- package/dist/memory-store.d.ts +11 -0
- package/dist/memory-store.d.ts.map +1 -0
- package/dist/memory-store.js +272 -0
- package/dist/memory-store.js.map +1 -0
- package/dist/memory.d.ts +212 -0
- package/dist/memory.d.ts.map +1 -0
- package/dist/memory.js +613 -0
- package/dist/memory.js.map +1 -0
- package/dist/otel.d.ts +74 -0
- package/dist/otel.d.ts.map +1 -0
- package/dist/otel.js +427 -0
- package/dist/otel.js.map +1 -0
- package/dist/progress.d.ts +17 -0
- package/dist/progress.d.ts.map +1 -0
- package/dist/progress.js +193 -0
- package/dist/progress.js.map +1 -0
- package/dist/quickjs.d.ts +19 -0
- package/dist/quickjs.d.ts.map +1 -0
- package/dist/quickjs.js +519 -0
- package/dist/quickjs.js.map +1 -0
- package/dist/recovery.d.ts +10 -0
- package/dist/recovery.d.ts.map +1 -0
- package/dist/recovery.js +62 -0
- package/dist/recovery.js.map +1 -0
- package/dist/request.d.ts +88 -0
- package/dist/request.d.ts.map +1 -0
- package/dist/request.js +422 -0
- package/dist/request.js.map +1 -0
- package/dist/run.d.ts +20 -0
- package/dist/run.d.ts.map +1 -0
- package/dist/run.js +2407 -0
- package/dist/run.js.map +1 -0
- package/dist/runs.d.ts +110 -0
- package/dist/runs.d.ts.map +1 -0
- package/dist/runs.js +438 -0
- package/dist/runs.js.map +1 -0
- package/dist/schema-to-ts.d.ts +4 -0
- package/dist/schema-to-ts.d.ts.map +1 -0
- package/dist/schema-to-ts.js +191 -0
- package/dist/schema-to-ts.js.map +1 -0
- package/dist/session.d.ts +23 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +137 -0
- package/dist/session.js.map +1 -0
- package/dist/snapshot.d.ts +75 -0
- package/dist/snapshot.d.ts.map +1 -0
- package/dist/snapshot.js +1607 -0
- package/dist/snapshot.js.map +1 -0
- package/dist/steering.d.ts +75 -0
- package/dist/steering.d.ts.map +1 -0
- package/dist/steering.js +214 -0
- package/dist/steering.js.map +1 -0
- package/dist/subagents.d.ts +141 -0
- package/dist/subagents.d.ts.map +1 -0
- package/dist/subagents.js +746 -0
- package/dist/subagents.js.map +1 -0
- package/dist/tool-retry.d.ts +12 -0
- package/dist/tool-retry.d.ts.map +1 -0
- package/dist/tool-retry.js +53 -0
- package/dist/tool-retry.js.map +1 -0
- package/dist/tree.d.ts +98 -0
- package/dist/tree.d.ts.map +1 -0
- package/dist/tree.js +320 -0
- package/dist/tree.js.map +1 -0
- package/dist/types.d.ts +1007 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/workflow-snapshot.d.ts +8 -0
- package/dist/workflow-snapshot.d.ts.map +1 -0
- package/dist/workflow-snapshot.js +276 -0
- package/dist/workflow-snapshot.js.map +1 -0
- package/dist/workflow-types.d.ts +171 -0
- package/dist/workflow-types.d.ts.map +1 -0
- package/dist/workflow-types.js +2 -0
- package/dist/workflow-types.js.map +1 -0
- package/dist/workflow.d.ts +19 -0
- package/dist/workflow.d.ts.map +1 -0
- package/dist/workflow.js +1053 -0
- package/dist/workflow.js.map +1 -0
- package/examples/a2a-remote.ts +85 -0
- package/examples/a2a-server.ts +100 -0
- package/examples/background.ts +59 -0
- package/examples/basic.ts +44 -0
- package/examples/code-mode.ts +76 -0
- package/examples/conversation.ts +57 -0
- package/examples/evals.ts +79 -0
- package/examples/guardrails.ts +56 -0
- package/examples/handoff.ts +79 -0
- package/examples/memory.ts +44 -0
- package/examples/otel.ts +99 -0
- package/examples/specialists.ts +99 -0
- package/examples/steering.ts +69 -0
- package/examples/structured-handoff.ts +92 -0
- package/examples/subagents.ts +127 -0
- package/examples/workflow.ts +74 -0
- package/package.json +114 -4
- package/src/a2a/auth.ts +62 -0
- package/src/a2a/client.ts +733 -0
- package/src/a2a/index.ts +74 -0
- package/src/a2a/memory-runs.ts +448 -0
- package/src/a2a/policy.ts +148 -0
- package/src/a2a/push.ts +251 -0
- package/src/a2a/remote.ts +1652 -0
- package/src/a2a/server.ts +1390 -0
- package/src/a2a/signing.ts +348 -0
- package/src/a2a/tasks.ts +260 -0
- package/src/a2a/wire.ts +1443 -0
- package/src/background-types.ts +86 -0
- package/src/child.ts +181 -0
- package/src/code-driver.ts +48 -0
- package/src/code-mode.ts +12 -0
- package/src/code-script.ts +149 -0
- package/src/code.ts +424 -0
- package/src/compaction.ts +212 -0
- package/src/delegation.ts +694 -0
- package/src/evals/driver.ts +222 -0
- package/src/evals/journal.ts +605 -0
- package/src/evals/judge.ts +188 -0
- package/src/evals/report.ts +295 -0
- package/src/evals/runner.ts +826 -0
- package/src/evals/scorers.ts +339 -0
- package/src/evals/simulation.ts +46 -0
- package/src/evals/testing.ts +126 -0
- package/src/evals/trajectory.ts +223 -0
- package/src/evals/types.ts +463 -0
- package/src/evals.ts +72 -0
- package/src/extensions.ts +247 -0
- package/src/handoff.ts +214 -0
- package/src/index.ts +62 -0
- package/src/input.ts +319 -0
- package/src/mcp.ts +690 -0
- package/src/memory-store.ts +366 -0
- package/src/memory.ts +893 -0
- package/src/otel.ts +568 -0
- package/src/progress.ts +214 -0
- package/src/quickjs.ts +524 -0
- package/src/recovery.ts +90 -0
- package/src/request.ts +513 -0
- package/src/run.ts +3199 -0
- package/src/runs.ts +696 -0
- package/src/schema-to-ts.ts +194 -0
- package/src/session.ts +178 -0
- package/src/snapshot.ts +2099 -0
- package/src/steering.ts +329 -0
- package/src/subagents.ts +1084 -0
- package/src/tool-retry.ts +86 -0
- package/src/tree.ts +366 -0
- package/src/types.ts +944 -0
- package/src/workflow-snapshot.ts +366 -0
- package/src/workflow-types.ts +213 -0
- package/src/workflow.ts +1316 -0
|
@@ -0,0 +1,1652 @@
|
|
|
1
|
+
/** Stateful A2A specialists use the SDK child and request journals, never a model adapter.
|
|
2
|
+
* Input-required mapping follows Microsoft Agent Framework (MIT); artifact replacement and
|
|
3
|
+
* parent continuation follow Mastra and CrewAI (Apache-2.0/MIT). See THIRD_PARTY_NOTICES.md.
|
|
4
|
+
*/
|
|
5
|
+
import { parseJsonAnswer, sleep } from "@providerkit/core";
|
|
6
|
+
import {
|
|
7
|
+
AGENT_RUNTIME,
|
|
8
|
+
defineDelegation,
|
|
9
|
+
specialistFailures,
|
|
10
|
+
type Delegation,
|
|
11
|
+
type NodeRuntime,
|
|
12
|
+
type SpecialistToolOptions,
|
|
13
|
+
} from "../delegation.ts";
|
|
14
|
+
import { readInput, readContent } from "../input.ts";
|
|
15
|
+
import { RequestJournal, isAsk, requestHash } from "../request.ts";
|
|
16
|
+
import {
|
|
17
|
+
checkOptions,
|
|
18
|
+
checkTree,
|
|
19
|
+
copyData,
|
|
20
|
+
equalData,
|
|
21
|
+
immutableCopy,
|
|
22
|
+
inlineBytes,
|
|
23
|
+
isAskRecord,
|
|
24
|
+
isId,
|
|
25
|
+
isImageMime,
|
|
26
|
+
isRecord,
|
|
27
|
+
isState,
|
|
28
|
+
isTreeInfo,
|
|
29
|
+
isTurnContent,
|
|
30
|
+
readTreeLimits,
|
|
31
|
+
} from "../snapshot.ts";
|
|
32
|
+
import {
|
|
33
|
+
authorizeTree,
|
|
34
|
+
emitEvent,
|
|
35
|
+
ExecutionTree,
|
|
36
|
+
fail,
|
|
37
|
+
Halt,
|
|
38
|
+
openRequests,
|
|
39
|
+
readAnswers,
|
|
40
|
+
snapshots,
|
|
41
|
+
stopRequests,
|
|
42
|
+
treeUsage,
|
|
43
|
+
untilAbort,
|
|
44
|
+
type ExecutionScope,
|
|
45
|
+
} from "../tree.ts";
|
|
46
|
+
import type {
|
|
47
|
+
AgentInput,
|
|
48
|
+
AskRecord,
|
|
49
|
+
Decision,
|
|
50
|
+
PendingRequest,
|
|
51
|
+
QuestionAsk,
|
|
52
|
+
RequestProblem,
|
|
53
|
+
ResultSchema,
|
|
54
|
+
ResumeOptions,
|
|
55
|
+
RunOptions,
|
|
56
|
+
RunSnapshot,
|
|
57
|
+
RunState,
|
|
58
|
+
ToolRequest,
|
|
59
|
+
TreeLimits,
|
|
60
|
+
TreeNode,
|
|
61
|
+
UserContent,
|
|
62
|
+
} from "../types.ts";
|
|
63
|
+
import { createA2AClient, fetchA2AAgentCard, type A2AClientOptions } from "./client.ts";
|
|
64
|
+
import { checkA2ACardEndpoints, selectA2AInterface } from "./policy.ts";
|
|
65
|
+
import {
|
|
66
|
+
A2AError,
|
|
67
|
+
a2aStateClosed,
|
|
68
|
+
decodeA2AAgentCard,
|
|
69
|
+
decodeA2AMessage,
|
|
70
|
+
encodeA2AMessage,
|
|
71
|
+
parseA2AJson,
|
|
72
|
+
type A2AAgentCard,
|
|
73
|
+
type A2AEvent,
|
|
74
|
+
type A2AMessage,
|
|
75
|
+
type A2APart,
|
|
76
|
+
type A2AState,
|
|
77
|
+
} from "./wire.ts";
|
|
78
|
+
|
|
79
|
+
export interface RemoteLimits {
|
|
80
|
+
/** Outbound messages, not model calls. */
|
|
81
|
+
turns: number;
|
|
82
|
+
elapsedMs: number;
|
|
83
|
+
inlineBytes: number;
|
|
84
|
+
resultBytes: number;
|
|
85
|
+
}
|
|
86
|
+
export interface RemoteAgentOptions<T = string> extends Pick<
|
|
87
|
+
A2AClientOptions,
|
|
88
|
+
| "version"
|
|
89
|
+
| "binding"
|
|
90
|
+
| "policy"
|
|
91
|
+
| "headers"
|
|
92
|
+
| "token"
|
|
93
|
+
| "fetch"
|
|
94
|
+
| "extensions"
|
|
95
|
+
| "timeoutMs"
|
|
96
|
+
| "idleMs"
|
|
97
|
+
> {
|
|
98
|
+
id: string;
|
|
99
|
+
/** Change when hidden endpoint/auth policy or output validation changes. */
|
|
100
|
+
agentVersion: string;
|
|
101
|
+
card: string | A2AAgentCard;
|
|
102
|
+
verifyCard?: Parameters<typeof fetchA2AAgentCard>[1]["verifyCard"];
|
|
103
|
+
updates?: "stream" | "poll";
|
|
104
|
+
inputRequired?: "ask" | "parent" | "fail";
|
|
105
|
+
/** Opt in to inline image output. Requires output to validate { content: UserContent }.
|
|
106
|
+
* Return text/image parts from the validator to forward images through asTool.
|
|
107
|
+
* URLs and other files stay labels; no peer URL is fetched. */
|
|
108
|
+
includeImages?: boolean;
|
|
109
|
+
output?: ResultSchema<T>;
|
|
110
|
+
limits?: Partial<RemoteLimits>;
|
|
111
|
+
treeLimits?: Partial<TreeLimits>;
|
|
112
|
+
}
|
|
113
|
+
export interface RemoteInput {
|
|
114
|
+
input: UserContent;
|
|
115
|
+
/** Root-scoped handle from a prior parent-routed question, not a peer task id. */
|
|
116
|
+
continue?: string;
|
|
117
|
+
}
|
|
118
|
+
export interface RemotePending {
|
|
119
|
+
kind: "input_required";
|
|
120
|
+
handle: string;
|
|
121
|
+
/** Untrusted peer question. Never an approval or capability grant. */
|
|
122
|
+
question: string;
|
|
123
|
+
}
|
|
124
|
+
export interface RemoteSend {
|
|
125
|
+
id: string;
|
|
126
|
+
attemptId: string;
|
|
127
|
+
status: "running" | "accepted";
|
|
128
|
+
/** Exact intent, recorded before dispatch. Never replayed, even if delivery is unknown. */
|
|
129
|
+
message: A2AMessage;
|
|
130
|
+
answers: string[];
|
|
131
|
+
asks?: AskRecord[];
|
|
132
|
+
}
|
|
133
|
+
export interface RemoteJournal {
|
|
134
|
+
endpoint: {
|
|
135
|
+
url: string;
|
|
136
|
+
version: A2AClientOptions["version"];
|
|
137
|
+
binding: A2AClientOptions["binding"];
|
|
138
|
+
streaming: boolean;
|
|
139
|
+
tenant?: string;
|
|
140
|
+
};
|
|
141
|
+
taskId?: string;
|
|
142
|
+
contextId?: string;
|
|
143
|
+
sends: RemoteSend[];
|
|
144
|
+
/** Earlier messages in this parent-continuation chain, counted against turns. */
|
|
145
|
+
priorTurns: number;
|
|
146
|
+
/** A bounded read retry, scheduled by the existing host wake/continuation path. */
|
|
147
|
+
wakeAt?: number;
|
|
148
|
+
state?: A2AState;
|
|
149
|
+
/** Allowlisted response parts only. No peer history, metadata or error body. */
|
|
150
|
+
artifacts: { artifactId: string; parts: A2APart[] }[];
|
|
151
|
+
question?: { messageId: string; structured: boolean; asks: QuestionAsk[] };
|
|
152
|
+
fallback: A2APart[];
|
|
153
|
+
cancel?: { id: string; attemptId: string; status: "running" | "accepted"; state?: A2AState };
|
|
154
|
+
}
|
|
155
|
+
export interface RemoteSnapshot {
|
|
156
|
+
kind: "remote";
|
|
157
|
+
format: 3;
|
|
158
|
+
agentId: string;
|
|
159
|
+
version: string;
|
|
160
|
+
runId: string;
|
|
161
|
+
attemptId: string;
|
|
162
|
+
startedAt: number;
|
|
163
|
+
definition: Record<string, unknown>;
|
|
164
|
+
input: RemoteInput;
|
|
165
|
+
limits: RemoteLimits;
|
|
166
|
+
tree: RunSnapshot["tree"];
|
|
167
|
+
remote: RemoteJournal;
|
|
168
|
+
state: RunState;
|
|
169
|
+
}
|
|
170
|
+
export interface RemoteReceipt {
|
|
171
|
+
kind: "remote";
|
|
172
|
+
action: "send" | "cancel";
|
|
173
|
+
id: string;
|
|
174
|
+
attemptId: string;
|
|
175
|
+
status: "running" | "accepted";
|
|
176
|
+
billing: "unknown";
|
|
177
|
+
taskId?: string;
|
|
178
|
+
contextId?: string;
|
|
179
|
+
}
|
|
180
|
+
export type RemoteOutcome<T = string> = {
|
|
181
|
+
runId: string;
|
|
182
|
+
attemptId: string;
|
|
183
|
+
treeUsage: ReturnType<typeof treeUsage>;
|
|
184
|
+
receipts: RemoteReceipt[];
|
|
185
|
+
snapshot: RemoteSnapshot;
|
|
186
|
+
} & (
|
|
187
|
+
| Exclude<RunState, { status: "running" | "completed" | "suspended" }>
|
|
188
|
+
| { status: "completed"; output: T | RemotePending }
|
|
189
|
+
| {
|
|
190
|
+
status: "suspended";
|
|
191
|
+
requests: (PendingRequest & { problem?: RequestProblem })[];
|
|
192
|
+
wakeAt?: number;
|
|
193
|
+
}
|
|
194
|
+
);
|
|
195
|
+
export interface RemoteRuntime<T> extends NodeRuntime<RemoteOutcome<T>> {
|
|
196
|
+
configuration(): Record<string, unknown>;
|
|
197
|
+
prepare(input: unknown): RemoteInput;
|
|
198
|
+
open(input: AgentInput, options: RunOptions, runId: string): Promise<RemoteSnapshot>;
|
|
199
|
+
create(
|
|
200
|
+
input: RemoteInput,
|
|
201
|
+
runId: string,
|
|
202
|
+
tree?: RunSnapshot["tree"],
|
|
203
|
+
options?: RunOptions,
|
|
204
|
+
root?: TreeNode,
|
|
205
|
+
): Promise<RemoteSnapshot>;
|
|
206
|
+
restore(raw: unknown, tree?: RunSnapshot["tree"]): RemoteSnapshot;
|
|
207
|
+
}
|
|
208
|
+
export interface RemoteAgent<T = string> {
|
|
209
|
+
readonly kind: "remote";
|
|
210
|
+
readonly id: string;
|
|
211
|
+
readonly version: string;
|
|
212
|
+
run(input: AgentInput, options?: RunOptions): Promise<RemoteOutcome<T>>;
|
|
213
|
+
resume(snapshot: unknown, options: ResumeOptions): Promise<RemoteOutcome<T>>;
|
|
214
|
+
/** Explicit host command. AbortSignal only detaches local work, never sends CancelTask.
|
|
215
|
+
* Inspect snapshot.remote.cancel.state: acceptance alone does not prove cancellation. */
|
|
216
|
+
cancel(snapshot: unknown, options: ResumeOptions): Promise<RemoteSnapshot>;
|
|
217
|
+
asTool(options: SpecialistToolOptions<T | RemotePending>): Delegation;
|
|
218
|
+
readonly [AGENT_RUNTIME]: RemoteRuntime<T>;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const dialect = { version: "1.0", binding: "JSONRPC" } as const;
|
|
222
|
+
const bytes = (value: unknown) => new TextEncoder().encode(JSON.stringify(value)).byteLength;
|
|
223
|
+
function node(value: TreeNode): RemoteSnapshot {
|
|
224
|
+
if (value.kind !== "remote") throw new TypeError("Expected a remote node.");
|
|
225
|
+
return value;
|
|
226
|
+
}
|
|
227
|
+
function content(input: unknown): UserContent {
|
|
228
|
+
const read = readInput(input, "caller");
|
|
229
|
+
if (read.history.length)
|
|
230
|
+
throw new TypeError(
|
|
231
|
+
"A2A accepts one user message, not local conversation history. Pass only the text or media you intend to share.",
|
|
232
|
+
);
|
|
233
|
+
return read.input;
|
|
234
|
+
}
|
|
235
|
+
function remoteInput(value: unknown): RemoteInput {
|
|
236
|
+
if (
|
|
237
|
+
!isRecord(value) ||
|
|
238
|
+
!isTurnContent(value.input) ||
|
|
239
|
+
Object.keys(value).some((key) => key !== "input" && key !== "continue") ||
|
|
240
|
+
(value.continue !== undefined && !isId(value.continue))
|
|
241
|
+
)
|
|
242
|
+
throw new TypeError("Pass remote input and an optional continuation handle.");
|
|
243
|
+
return copyData({
|
|
244
|
+
input: readContent(value.input, "The remote message"),
|
|
245
|
+
...(value.continue ? { continue: value.continue } : {}),
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
function readLimits(value: Partial<RemoteLimits> = {}): RemoteLimits {
|
|
249
|
+
if (
|
|
250
|
+
Object.keys(value).some(
|
|
251
|
+
(key) => !["turns", "elapsedMs", "inlineBytes", "resultBytes"].includes(key),
|
|
252
|
+
)
|
|
253
|
+
)
|
|
254
|
+
throw new TypeError("Remote limits are turns, elapsedMs, inlineBytes and resultBytes.");
|
|
255
|
+
const limits = {
|
|
256
|
+
turns: 12,
|
|
257
|
+
elapsedMs: 300_000,
|
|
258
|
+
inlineBytes: 5_000_000,
|
|
259
|
+
resultBytes: 1_048_576,
|
|
260
|
+
...value,
|
|
261
|
+
};
|
|
262
|
+
if (
|
|
263
|
+
Object.entries(limits).some(
|
|
264
|
+
([key, n]) => !Number.isSafeInteger(n) || n < (key === "inlineBytes" ? 0 : 1),
|
|
265
|
+
) ||
|
|
266
|
+
limits.elapsedMs > 2_147_483_647
|
|
267
|
+
)
|
|
268
|
+
throw new TypeError("Use bounded whole-number remote limits.");
|
|
269
|
+
return limits;
|
|
270
|
+
}
|
|
271
|
+
function checkRunOptions(options: RunOptions, resume = false): void {
|
|
272
|
+
checkOptions(options, resume ? "resume" : "run");
|
|
273
|
+
if (
|
|
274
|
+
options.session ||
|
|
275
|
+
options.historyLimit !== undefined ||
|
|
276
|
+
options.prepareHistory ||
|
|
277
|
+
options.enabledTools ||
|
|
278
|
+
options.modelSettings ||
|
|
279
|
+
options.memory
|
|
280
|
+
)
|
|
281
|
+
throw new TypeError(
|
|
282
|
+
"Remote agents do not accept local sessions, memory, model settings or tool selection.",
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
function safeParts(parts: A2APart[], includeImages = false): A2APart[] {
|
|
286
|
+
return parts.map((part) => {
|
|
287
|
+
switch (part.kind) {
|
|
288
|
+
case "text":
|
|
289
|
+
return { kind: "text", text: part.text };
|
|
290
|
+
case "data":
|
|
291
|
+
return { kind: "data", data: copyData(part.data) };
|
|
292
|
+
// Inline images require a host output contract. Peer URLs are never fetched.
|
|
293
|
+
case "raw":
|
|
294
|
+
if (includeImages && isImageMime(part.mediaType))
|
|
295
|
+
return {
|
|
296
|
+
kind: "raw",
|
|
297
|
+
raw: part.raw
|
|
298
|
+
.replaceAll("-", "+")
|
|
299
|
+
.replaceAll("_", "/")
|
|
300
|
+
.padEnd(Math.ceil(part.raw.length / 4) * 4, "="),
|
|
301
|
+
mediaType: part.mediaType,
|
|
302
|
+
};
|
|
303
|
+
return { kind: "text", text: `[File: ${part.filename ?? part.mediaType ?? "attachment"}]` };
|
|
304
|
+
case "url":
|
|
305
|
+
return { kind: "text", text: `[File: ${part.filename ?? part.mediaType ?? "attachment"}]` };
|
|
306
|
+
}
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
function imageBytes(parts: A2APart[]): number {
|
|
310
|
+
return inlineBytes(
|
|
311
|
+
[],
|
|
312
|
+
parts.flatMap((part) =>
|
|
313
|
+
part.kind === "raw" && isImageMime(part.mediaType)
|
|
314
|
+
? [{ type: "image" as const, mimeType: part.mediaType, data: part.raw }]
|
|
315
|
+
: [],
|
|
316
|
+
),
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
function text(parts: A2APart[]): string {
|
|
320
|
+
return parts.flatMap((part) => (part.kind === "text" ? [part.text] : [])).join("");
|
|
321
|
+
}
|
|
322
|
+
function resultParts(snapshot: RemoteSnapshot): A2APart[] {
|
|
323
|
+
return snapshot.remote.artifacts.length
|
|
324
|
+
? snapshot.remote.artifacts.flatMap((artifact) => artifact.parts)
|
|
325
|
+
: snapshot.remote.fallback;
|
|
326
|
+
}
|
|
327
|
+
function candidate(snapshot: RemoteSnapshot): unknown {
|
|
328
|
+
if (snapshot.remote.state === "input_required" && snapshot.definition.inputRequired === "parent")
|
|
329
|
+
return {
|
|
330
|
+
kind: "input_required",
|
|
331
|
+
handle: snapshot.runId,
|
|
332
|
+
question:
|
|
333
|
+
snapshot.remote.question?.asks.map((ask) => ask.message).join("\n") ??
|
|
334
|
+
"The remote agent needs an answer.",
|
|
335
|
+
};
|
|
336
|
+
const parts = resultParts(snapshot);
|
|
337
|
+
if (snapshot.definition.includeImages)
|
|
338
|
+
return {
|
|
339
|
+
content: readContent(
|
|
340
|
+
parts.flatMap<unknown>((part) =>
|
|
341
|
+
part.kind === "text"
|
|
342
|
+
? [{ type: "text", text: part.text }]
|
|
343
|
+
: part.kind === "raw"
|
|
344
|
+
? [{ type: "image", mimeType: part.mediaType, data: part.raw }]
|
|
345
|
+
: [],
|
|
346
|
+
),
|
|
347
|
+
"The remote output",
|
|
348
|
+
),
|
|
349
|
+
};
|
|
350
|
+
return snapshot.definition.output
|
|
351
|
+
? (parts.find((part) => part.kind === "data")?.data ?? parseJsonAnswer(text(parts)))
|
|
352
|
+
: text(parts);
|
|
353
|
+
}
|
|
354
|
+
function question(message: A2AMessage | undefined): RemoteJournal["question"] {
|
|
355
|
+
if (!message)
|
|
356
|
+
return {
|
|
357
|
+
messageId: "input",
|
|
358
|
+
structured: false,
|
|
359
|
+
asks: [
|
|
360
|
+
{
|
|
361
|
+
type: "question",
|
|
362
|
+
key: "input",
|
|
363
|
+
message: "The remote agent needs an answer.",
|
|
364
|
+
freeText: true,
|
|
365
|
+
},
|
|
366
|
+
],
|
|
367
|
+
};
|
|
368
|
+
const data = message.parts.find(
|
|
369
|
+
(part) => part.kind === "data" && isRecord(part.data) && Array.isArray(part.data.requests),
|
|
370
|
+
);
|
|
371
|
+
if (data?.kind === "data" && isRecord(data.data) && Array.isArray(data.data.requests)) {
|
|
372
|
+
const asks = data.data.requests.map((request) => {
|
|
373
|
+
if (!isRecord(request) || request.type !== "question" || !isId(request.id))
|
|
374
|
+
fail(
|
|
375
|
+
"remote_request_unsupported",
|
|
376
|
+
"The remote service requested an action this host cannot authorize. Ask its operator to continue it.",
|
|
377
|
+
);
|
|
378
|
+
const ask = {
|
|
379
|
+
type: "question",
|
|
380
|
+
key: request.id,
|
|
381
|
+
message: request.message,
|
|
382
|
+
...(request.choices !== undefined ? { choices: request.choices } : {}),
|
|
383
|
+
...(request.multiple !== undefined ? { multiple: request.multiple } : {}),
|
|
384
|
+
...(request.freeText !== undefined ? { freeText: request.freeText } : {}),
|
|
385
|
+
...(request.schema !== undefined ? { schema: request.schema } : {}),
|
|
386
|
+
};
|
|
387
|
+
if (!isAsk(ask) || ask.type !== "question") throw new A2AError("invalid");
|
|
388
|
+
return ask;
|
|
389
|
+
});
|
|
390
|
+
if (!asks.length || new Set(asks.map((ask) => ask.key)).size !== asks.length)
|
|
391
|
+
throw new A2AError("invalid");
|
|
392
|
+
return { messageId: message.messageId, structured: true, asks };
|
|
393
|
+
}
|
|
394
|
+
return {
|
|
395
|
+
messageId: message.messageId,
|
|
396
|
+
structured: false,
|
|
397
|
+
asks: [
|
|
398
|
+
{
|
|
399
|
+
type: "question",
|
|
400
|
+
key: message.messageId,
|
|
401
|
+
message:
|
|
402
|
+
text(safeParts(message.parts)).slice(0, 4096) || "The remote agent needs an answer.",
|
|
403
|
+
freeText: true,
|
|
404
|
+
},
|
|
405
|
+
],
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function answerParts(records: AskRecord[], structured: boolean): A2APart[] {
|
|
410
|
+
const answers = Object.fromEntries(
|
|
411
|
+
records.map((record) => {
|
|
412
|
+
if (record.decision?.type !== "answer" || record.request.ask.type !== "question")
|
|
413
|
+
throw new TypeError("Expected an authenticated remote answer.");
|
|
414
|
+
return [record.request.ask.key, { type: "answer", answer: record.decision.answer }];
|
|
415
|
+
}),
|
|
416
|
+
);
|
|
417
|
+
const parts: A2APart[] = structured
|
|
418
|
+
? [{ kind: "data", data: parseA2AJson(JSON.stringify({ answers })) }]
|
|
419
|
+
: [];
|
|
420
|
+
const plain = records
|
|
421
|
+
.flatMap((record) =>
|
|
422
|
+
record.decision?.type === "answer" && record.decision.answer.text
|
|
423
|
+
? [record.decision.answer.text]
|
|
424
|
+
: [],
|
|
425
|
+
)
|
|
426
|
+
.join("\n");
|
|
427
|
+
if (plain) parts.unshift({ kind: "text", text: plain });
|
|
428
|
+
return parts;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** Structural checks are not authorization. A host must compare authoritative snapshots. */
|
|
432
|
+
export function isRemoteSnapshot(raw: unknown): raw is RemoteSnapshot {
|
|
433
|
+
if (
|
|
434
|
+
!isRecord(raw) ||
|
|
435
|
+
raw.kind !== "remote" ||
|
|
436
|
+
raw.format !== 3 ||
|
|
437
|
+
![raw.agentId, raw.version, raw.runId, raw.attemptId].every(isId) ||
|
|
438
|
+
typeof raw.startedAt !== "number" ||
|
|
439
|
+
!Number.isSafeInteger(raw.startedAt) ||
|
|
440
|
+
raw.startedAt <= 0 ||
|
|
441
|
+
!isRecord(raw.definition) ||
|
|
442
|
+
!isRecord(raw.limits) ||
|
|
443
|
+
!isTreeInfo(raw.tree) ||
|
|
444
|
+
!isState(raw.state) ||
|
|
445
|
+
!isRecord(raw.remote) ||
|
|
446
|
+
!isRecord(raw.remote.endpoint) ||
|
|
447
|
+
!isId(raw.remote.endpoint.url) ||
|
|
448
|
+
!["1.0", "0.3"].includes(String(raw.remote.endpoint.version)) ||
|
|
449
|
+
!["JSONRPC", "HTTP+JSON"].includes(String(raw.remote.endpoint.binding)) ||
|
|
450
|
+
Object.keys(raw.remote.endpoint).some(
|
|
451
|
+
(key) => !["url", "version", "binding", "streaming", "tenant"].includes(key),
|
|
452
|
+
) ||
|
|
453
|
+
typeof raw.remote.endpoint.streaming !== "boolean" ||
|
|
454
|
+
(raw.remote.endpoint.tenant !== undefined && !isId(raw.remote.endpoint.tenant)) ||
|
|
455
|
+
typeof raw.remote.priorTurns !== "number" ||
|
|
456
|
+
!Number.isSafeInteger(raw.remote.priorTurns) ||
|
|
457
|
+
raw.remote.priorTurns < 0 ||
|
|
458
|
+
(raw.remote.wakeAt !== undefined &&
|
|
459
|
+
(typeof raw.remote.wakeAt !== "number" ||
|
|
460
|
+
!Number.isSafeInteger(raw.remote.wakeAt) ||
|
|
461
|
+
raw.remote.wakeAt < raw.startedAt ||
|
|
462
|
+
!isId(raw.remote.taskId))) ||
|
|
463
|
+
!Array.isArray(raw.remote.sends) ||
|
|
464
|
+
!Array.isArray(raw.remote.artifacts) ||
|
|
465
|
+
!Array.isArray(raw.remote.fallback)
|
|
466
|
+
)
|
|
467
|
+
return false;
|
|
468
|
+
try {
|
|
469
|
+
remoteInput(raw.input);
|
|
470
|
+
const { turns, elapsedMs, inlineBytes, resultBytes } = raw.limits;
|
|
471
|
+
if (
|
|
472
|
+
typeof turns !== "number" ||
|
|
473
|
+
typeof elapsedMs !== "number" ||
|
|
474
|
+
typeof inlineBytes !== "number" ||
|
|
475
|
+
typeof resultBytes !== "number"
|
|
476
|
+
)
|
|
477
|
+
return false;
|
|
478
|
+
readLimits({ turns, elapsedMs, inlineBytes, resultBytes });
|
|
479
|
+
for (const send of raw.remote.sends) {
|
|
480
|
+
if (
|
|
481
|
+
!isRecord(send) ||
|
|
482
|
+
!isId(send.id) ||
|
|
483
|
+
!isId(send.attemptId) ||
|
|
484
|
+
!["running", "accepted"].includes(String(send.status)) ||
|
|
485
|
+
!Array.isArray(send.answers) ||
|
|
486
|
+
!send.answers.every(isId) ||
|
|
487
|
+
new Set(send.answers).size !== send.answers.length ||
|
|
488
|
+
(send.asks !== undefined && (!Array.isArray(send.asks) || !send.asks.every(isAskRecord)))
|
|
489
|
+
)
|
|
490
|
+
return false;
|
|
491
|
+
checkedMessage(send.message);
|
|
492
|
+
}
|
|
493
|
+
const includeImages = raw.definition.includeImages === true;
|
|
494
|
+
const parts = (value: unknown) => {
|
|
495
|
+
if (Array.isArray(value) && !value.length) return true;
|
|
496
|
+
const message = checkedMessage({
|
|
497
|
+
kind: "message",
|
|
498
|
+
messageId: "check",
|
|
499
|
+
role: "agent",
|
|
500
|
+
parts: value,
|
|
501
|
+
});
|
|
502
|
+
return equalData(message.parts, safeParts(message.parts, includeImages));
|
|
503
|
+
};
|
|
504
|
+
if (!parts(raw.remote.fallback)) return false;
|
|
505
|
+
const ids = new Set<string>();
|
|
506
|
+
for (const artifact of raw.remote.artifacts) {
|
|
507
|
+
if (
|
|
508
|
+
!isRecord(artifact) ||
|
|
509
|
+
!isId(artifact.artifactId) ||
|
|
510
|
+
ids.has(artifact.artifactId) ||
|
|
511
|
+
!parts(artifact.parts)
|
|
512
|
+
)
|
|
513
|
+
return false;
|
|
514
|
+
ids.add(artifact.artifactId);
|
|
515
|
+
}
|
|
516
|
+
if (raw.remote.taskId !== undefined && !isId(raw.remote.taskId)) return false;
|
|
517
|
+
if (raw.remote.contextId !== undefined && !isId(raw.remote.contextId)) return false;
|
|
518
|
+
if (
|
|
519
|
+
raw.remote.question !== undefined &&
|
|
520
|
+
(!isRecord(raw.remote.question) ||
|
|
521
|
+
!isId(raw.remote.question.messageId) ||
|
|
522
|
+
typeof raw.remote.question.structured !== "boolean" ||
|
|
523
|
+
!Array.isArray(raw.remote.question.asks) ||
|
|
524
|
+
!raw.remote.question.asks.length ||
|
|
525
|
+
!raw.remote.question.asks.every((ask) => isAsk(ask) && ask.type === "question"))
|
|
526
|
+
)
|
|
527
|
+
return false;
|
|
528
|
+
if (
|
|
529
|
+
raw.remote.cancel !== undefined &&
|
|
530
|
+
(!isRecord(raw.remote.cancel) ||
|
|
531
|
+
!isId(raw.remote.cancel.id) ||
|
|
532
|
+
!isId(raw.remote.cancel.attemptId) ||
|
|
533
|
+
!["running", "accepted"].includes(String(raw.remote.cancel.status)) ||
|
|
534
|
+
(raw.remote.cancel.state !== undefined && !isRemoteState(raw.remote.cancel.state)))
|
|
535
|
+
)
|
|
536
|
+
return false;
|
|
537
|
+
if (raw.remote.state !== undefined && !isRemoteState(raw.remote.state)) return false;
|
|
538
|
+
return true;
|
|
539
|
+
} catch {
|
|
540
|
+
return false;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
function isRemoteState(value: unknown): value is A2AState {
|
|
544
|
+
return [
|
|
545
|
+
"unknown",
|
|
546
|
+
"submitted",
|
|
547
|
+
"working",
|
|
548
|
+
"input_required",
|
|
549
|
+
"auth_required",
|
|
550
|
+
"completed",
|
|
551
|
+
"failed",
|
|
552
|
+
"canceled",
|
|
553
|
+
"rejected",
|
|
554
|
+
].includes(String(value));
|
|
555
|
+
}
|
|
556
|
+
// Canonical messages are rebuilt at a typed trust boundary instead of asserted into wire types.
|
|
557
|
+
function checkedMessage(raw: unknown): A2AMessage {
|
|
558
|
+
if (!isRecord(raw) || !Array.isArray(raw.parts)) throw new TypeError("Invalid remote message.");
|
|
559
|
+
const message = decodeA2AMessage(
|
|
560
|
+
parseA2AJson(
|
|
561
|
+
JSON.stringify({
|
|
562
|
+
...raw,
|
|
563
|
+
role: raw.role === "user" ? "ROLE_USER" : raw.role === "agent" ? "ROLE_AGENT" : raw.role,
|
|
564
|
+
parts: raw.parts.map((part) => {
|
|
565
|
+
if (!isRecord(part)) throw new TypeError("Invalid remote part.");
|
|
566
|
+
const fields = {
|
|
567
|
+
mediaType: part.mediaType,
|
|
568
|
+
filename: part.filename,
|
|
569
|
+
metadata: part.metadata,
|
|
570
|
+
};
|
|
571
|
+
if (part.kind === "text") return { ...fields, text: part.text };
|
|
572
|
+
if (part.kind === "data") return { ...fields, data: part.data };
|
|
573
|
+
if (part.kind === "raw") return { ...fields, raw: part.raw };
|
|
574
|
+
throw new TypeError("Saved remote messages cannot carry peer URLs.");
|
|
575
|
+
}),
|
|
576
|
+
}),
|
|
577
|
+
),
|
|
578
|
+
dialect,
|
|
579
|
+
);
|
|
580
|
+
if (!equalData(raw, message)) throw new TypeError("Invalid canonical remote message.");
|
|
581
|
+
return message;
|
|
582
|
+
}
|
|
583
|
+
export function checkRemoteSnapshot(snapshot: RemoteSnapshot): void {
|
|
584
|
+
if (!isRemoteSnapshot(snapshot)) throw new TypeError("Invalid remote snapshot.");
|
|
585
|
+
const journal = snapshot.remote;
|
|
586
|
+
if (
|
|
587
|
+
(!snapshot.input.continue && journal.priorTurns !== 0) ||
|
|
588
|
+
journal.sends.length + journal.priorTurns > snapshot.limits.turns ||
|
|
589
|
+
inlineBytes([], snapshot.input.input) > snapshot.limits.inlineBytes ||
|
|
590
|
+
bytes([journal.artifacts, journal.fallback, journal.question]) > snapshot.limits.resultBytes ||
|
|
591
|
+
imageBytes([...journal.fallback, ...journal.artifacts.flatMap((artifact) => artifact.parts)]) >
|
|
592
|
+
snapshot.limits.inlineBytes
|
|
593
|
+
)
|
|
594
|
+
throw new TypeError("The remote journal exceeds its limits.");
|
|
595
|
+
if (
|
|
596
|
+
journal.state !== undefined &&
|
|
597
|
+
![
|
|
598
|
+
"unknown",
|
|
599
|
+
"submitted",
|
|
600
|
+
"working",
|
|
601
|
+
"input_required",
|
|
602
|
+
"auth_required",
|
|
603
|
+
"completed",
|
|
604
|
+
"failed",
|
|
605
|
+
"canceled",
|
|
606
|
+
"rejected",
|
|
607
|
+
].includes(journal.state)
|
|
608
|
+
)
|
|
609
|
+
throw new TypeError("Invalid remote state.");
|
|
610
|
+
for (const [index, send] of journal.sends.entries()) {
|
|
611
|
+
if (
|
|
612
|
+
send.id !== `${snapshot.runId}/send/${index + 1}` ||
|
|
613
|
+
send.message.messageId !== `${send.attemptId}/send/${index + 1}` ||
|
|
614
|
+
send.message.role !== "user" ||
|
|
615
|
+
(index > 0 &&
|
|
616
|
+
(send.message.taskId !== journal.taskId || send.message.contextId !== journal.contextId)) ||
|
|
617
|
+
send.message.metadata !== undefined ||
|
|
618
|
+
send.message.extensions !== undefined ||
|
|
619
|
+
send.message.referenceTaskIds !== undefined ||
|
|
620
|
+
(send.message.taskId !== undefined && send.message.taskId !== journal.taskId) ||
|
|
621
|
+
(send.message.contextId !== undefined && send.message.contextId !== journal.contextId) ||
|
|
622
|
+
(index > 0 && journal.sends[index - 1]?.status !== "accepted")
|
|
623
|
+
)
|
|
624
|
+
throw new TypeError("Invalid remote send identity or order.");
|
|
625
|
+
for (const [i, record] of (send.asks ?? []).entries()) {
|
|
626
|
+
const call = record.request.call;
|
|
627
|
+
if (
|
|
628
|
+
!call ||
|
|
629
|
+
record.request.step ||
|
|
630
|
+
record.request.ask.type !== "question" ||
|
|
631
|
+
record.request.id !== `${send.id}/ask/${i + 1}` ||
|
|
632
|
+
call.operationId !== send.id ||
|
|
633
|
+
call.runId !== snapshot.runId ||
|
|
634
|
+
call.agentId !== snapshot.agentId ||
|
|
635
|
+
call.version !== snapshot.version ||
|
|
636
|
+
call.attemptId !== send.attemptId ||
|
|
637
|
+
call.call.name !== "remote_input" ||
|
|
638
|
+
call.call.id !== send.id ||
|
|
639
|
+
record.request.createdAt < snapshot.startedAt
|
|
640
|
+
)
|
|
641
|
+
throw new TypeError("Invalid remote question receipt.");
|
|
642
|
+
}
|
|
643
|
+
if (index === 0 && send.answers.length)
|
|
644
|
+
throw new TypeError("The first remote send cannot answer a local request.");
|
|
645
|
+
if (index > 0) {
|
|
646
|
+
const prior = journal.sends[index - 1]?.asks ?? [];
|
|
647
|
+
const records = send.answers.map((id) => {
|
|
648
|
+
const record = prior.find((ask) => ask.request.id === id);
|
|
649
|
+
if (!record || record.decision?.type !== "answer")
|
|
650
|
+
throw new TypeError("A remote answer has no authenticated request receipt.");
|
|
651
|
+
return record;
|
|
652
|
+
});
|
|
653
|
+
if (
|
|
654
|
+
!records.length ||
|
|
655
|
+
!equalData(
|
|
656
|
+
send.message.parts,
|
|
657
|
+
answerParts(
|
|
658
|
+
records,
|
|
659
|
+
send.message.parts.some((part) => part.kind === "data"),
|
|
660
|
+
),
|
|
661
|
+
) ||
|
|
662
|
+
(send.status === "accepted" &&
|
|
663
|
+
!equalData(
|
|
664
|
+
send.answers,
|
|
665
|
+
prior.filter((record) => !record.closed).map((record) => record.request.id),
|
|
666
|
+
))
|
|
667
|
+
)
|
|
668
|
+
throw new TypeError("The remote message does not match its answer receipts.");
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
if (
|
|
672
|
+
journal.question &&
|
|
673
|
+
(journal.state !== "input_required" ||
|
|
674
|
+
!journal.taskId ||
|
|
675
|
+
new Set(journal.question.asks.map((ask) => ask.key)).size !== journal.question.asks.length)
|
|
676
|
+
)
|
|
677
|
+
throw new TypeError("Invalid remote question state.");
|
|
678
|
+
if (journal.state === "input_required" && !journal.question)
|
|
679
|
+
throw new TypeError("The remote question is missing.");
|
|
680
|
+
if (
|
|
681
|
+
journal.cancel &&
|
|
682
|
+
(journal.cancel.id !== `${snapshot.runId}/cancel` ||
|
|
683
|
+
!journal.taskId ||
|
|
684
|
+
(journal.cancel.status === "accepted" && journal.cancel.state === undefined))
|
|
685
|
+
)
|
|
686
|
+
throw new TypeError("Invalid remote cancellation receipt.");
|
|
687
|
+
if (
|
|
688
|
+
snapshot.state.status === "completed" &&
|
|
689
|
+
(!journal.sends.length ||
|
|
690
|
+
journal.sends.at(-1)?.status !== "accepted" ||
|
|
691
|
+
(journal.state !== "completed" &&
|
|
692
|
+
!(journal.state === "input_required" && snapshot.definition.inputRequired === "parent")) ||
|
|
693
|
+
!equalData(snapshot.state.candidate, candidate(snapshot)))
|
|
694
|
+
)
|
|
695
|
+
throw new TypeError("The remote result does not match its journal.");
|
|
696
|
+
}
|
|
697
|
+
export function checkRemoteProgress(previous: RemoteSnapshot, next: RemoteSnapshot): void {
|
|
698
|
+
if (
|
|
699
|
+
previous.agentId !== next.agentId ||
|
|
700
|
+
previous.remote.priorTurns !== next.remote.priorTurns ||
|
|
701
|
+
!equalData(previous.remote.endpoint, next.remote.endpoint) ||
|
|
702
|
+
(previous.remote.taskId !== undefined && previous.remote.taskId !== next.remote.taskId) ||
|
|
703
|
+
(previous.remote.contextId !== undefined && previous.remote.contextId !== next.remote.contextId)
|
|
704
|
+
)
|
|
705
|
+
throw new TypeError("The host changed a remote endpoint, task or context.");
|
|
706
|
+
for (const [i, send] of previous.remote.sends.entries()) {
|
|
707
|
+
const saved = next.remote.sends[i];
|
|
708
|
+
if (
|
|
709
|
+
!saved ||
|
|
710
|
+
saved.id !== send.id ||
|
|
711
|
+
saved.attemptId !== send.attemptId ||
|
|
712
|
+
!equalData(saved.message, send.message) ||
|
|
713
|
+
!equalData(saved.answers, send.answers) ||
|
|
714
|
+
(send.status === "accepted" && saved.status !== "accepted")
|
|
715
|
+
)
|
|
716
|
+
throw new TypeError("The host erased or replaced a remote send.");
|
|
717
|
+
for (const [j, record] of (send.asks ?? []).entries()) {
|
|
718
|
+
const later = saved.asks?.[j];
|
|
719
|
+
if (
|
|
720
|
+
!later ||
|
|
721
|
+
!equalData(record.request, later.request) ||
|
|
722
|
+
(record.decision && !equalData(record.decision, later.decision)) ||
|
|
723
|
+
(record.closed && record.closed !== later.closed)
|
|
724
|
+
)
|
|
725
|
+
throw new TypeError("The host erased or replaced a remote request.");
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
const cancel = previous.remote.cancel;
|
|
729
|
+
if (
|
|
730
|
+
cancel &&
|
|
731
|
+
(!next.remote.cancel ||
|
|
732
|
+
!equalData(
|
|
733
|
+
{ ...cancel, status: next.remote.cancel.status, state: next.remote.cancel.state },
|
|
734
|
+
next.remote.cancel,
|
|
735
|
+
) ||
|
|
736
|
+
(cancel.status === "accepted" && !equalData(cancel, next.remote.cancel)))
|
|
737
|
+
)
|
|
738
|
+
throw new TypeError("The host erased or replaced a remote cancellation.");
|
|
739
|
+
if (
|
|
740
|
+
previous.state.status === "completed" &&
|
|
741
|
+
!equalData({ ...previous.remote, cancel: next.remote.cancel }, next.remote)
|
|
742
|
+
)
|
|
743
|
+
throw new TypeError("The host changed a completed remote result.");
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
export function defineRemoteAgent<T>(
|
|
747
|
+
options: RemoteAgentOptions<T> & { output: ResultSchema<T> },
|
|
748
|
+
): RemoteAgent<T>;
|
|
749
|
+
export function defineRemoteAgent(
|
|
750
|
+
options: RemoteAgentOptions<string> & { output?: undefined },
|
|
751
|
+
): RemoteAgent<string>;
|
|
752
|
+
export function defineRemoteAgent<T>(config: RemoteAgentOptions<T>): RemoteAgent<T | string> {
|
|
753
|
+
if (
|
|
754
|
+
!isId(config.id) ||
|
|
755
|
+
!isId(config.agentVersion) ||
|
|
756
|
+
typeof config.policy?.allow !== "function" ||
|
|
757
|
+
!["1.0", "0.3"].includes(config.version) ||
|
|
758
|
+
!["JSONRPC", "HTTP+JSON"].includes(config.binding) ||
|
|
759
|
+
(config.inputRequired !== undefined &&
|
|
760
|
+
!["ask", "parent", "fail"].includes(config.inputRequired)) ||
|
|
761
|
+
(config.updates !== undefined && !["stream", "poll"].includes(config.updates))
|
|
762
|
+
)
|
|
763
|
+
throw new TypeError(
|
|
764
|
+
"A remote agent needs host-owned identity, card, dialect and endpoint policy.",
|
|
765
|
+
);
|
|
766
|
+
if (
|
|
767
|
+
Object.keys(config).some(
|
|
768
|
+
(key) =>
|
|
769
|
+
![
|
|
770
|
+
"id",
|
|
771
|
+
"agentVersion",
|
|
772
|
+
"card",
|
|
773
|
+
"version",
|
|
774
|
+
"binding",
|
|
775
|
+
"policy",
|
|
776
|
+
"headers",
|
|
777
|
+
"token",
|
|
778
|
+
"fetch",
|
|
779
|
+
"extensions",
|
|
780
|
+
"timeoutMs",
|
|
781
|
+
"idleMs",
|
|
782
|
+
"verifyCard",
|
|
783
|
+
"updates",
|
|
784
|
+
"inputRequired",
|
|
785
|
+
"output",
|
|
786
|
+
"includeImages",
|
|
787
|
+
"limits",
|
|
788
|
+
"treeLimits",
|
|
789
|
+
].includes(key),
|
|
790
|
+
)
|
|
791
|
+
)
|
|
792
|
+
throw new TypeError(
|
|
793
|
+
"An unsupported remote option was supplied. Remote sends never retry and endpoints must be selected explicitly.",
|
|
794
|
+
);
|
|
795
|
+
if (
|
|
796
|
+
(config.includeImages !== undefined && typeof config.includeImages !== "boolean") ||
|
|
797
|
+
(config.includeImages && !config.output)
|
|
798
|
+
)
|
|
799
|
+
throw new TypeError("Inline images require an explicit output validator.");
|
|
800
|
+
if (
|
|
801
|
+
config.output &&
|
|
802
|
+
(!isRecord(config.output.schema) ||
|
|
803
|
+
config.output.schema.type !== "object" ||
|
|
804
|
+
typeof config.output.validate !== "function")
|
|
805
|
+
)
|
|
806
|
+
throw new TypeError("Remote output needs an object schema and a validator.");
|
|
807
|
+
const { limits: _limits, treeLimits: _treeLimits, ...configuration } = config;
|
|
808
|
+
const options = {
|
|
809
|
+
...configuration,
|
|
810
|
+
policy: { ...config.policy },
|
|
811
|
+
extensions: config.extensions && Object.freeze([...config.extensions]),
|
|
812
|
+
card: typeof config.card === "string" ? config.card : immutableCopy(config.card),
|
|
813
|
+
};
|
|
814
|
+
const id = config.id,
|
|
815
|
+
version = config.agentVersion;
|
|
816
|
+
const limits = readLimits(config.limits),
|
|
817
|
+
treeLimits = readTreeLimits(config.treeLimits);
|
|
818
|
+
const output = config.output && {
|
|
819
|
+
schema: immutableCopy(config.output.schema),
|
|
820
|
+
validate: config.output.validate,
|
|
821
|
+
};
|
|
822
|
+
const definition = immutableCopy({
|
|
823
|
+
id,
|
|
824
|
+
version,
|
|
825
|
+
card: options.card,
|
|
826
|
+
protocol: config.version,
|
|
827
|
+
binding: config.binding,
|
|
828
|
+
inputRequired: config.inputRequired ?? "ask",
|
|
829
|
+
updates: config.updates ?? "poll",
|
|
830
|
+
includeImages: config.includeImages ?? false,
|
|
831
|
+
extensions: config.extensions ?? [],
|
|
832
|
+
output: output?.schema ?? null,
|
|
833
|
+
});
|
|
834
|
+
const validate = (value: unknown) =>
|
|
835
|
+
output
|
|
836
|
+
? output.validate(copyData(value))
|
|
837
|
+
: typeof value === "string"
|
|
838
|
+
? value
|
|
839
|
+
: (() => {
|
|
840
|
+
throw new TypeError("Expected a text remote result.");
|
|
841
|
+
})();
|
|
842
|
+
function client(snapshot: RemoteSnapshot) {
|
|
843
|
+
return createA2AClient({
|
|
844
|
+
...options,
|
|
845
|
+
endpoint: snapshot.remote.endpoint.url,
|
|
846
|
+
...snapshot.remote.endpoint,
|
|
847
|
+
cardUrl: typeof options.card === "string" ? options.card : undefined,
|
|
848
|
+
maxResultBytes: limits.resultBytes,
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
function request(snapshot: RemoteSnapshot, send: RemoteSend, name = "remote_input"): ToolRequest {
|
|
852
|
+
const args =
|
|
853
|
+
name === "remote_send"
|
|
854
|
+
? {
|
|
855
|
+
agentId: id,
|
|
856
|
+
endpoint: snapshot.remote.endpoint.url,
|
|
857
|
+
message: send.message,
|
|
858
|
+
continuation: snapshot.input.continue ?? null,
|
|
859
|
+
}
|
|
860
|
+
: {
|
|
861
|
+
agentId: id,
|
|
862
|
+
taskId: snapshot.remote.taskId ?? null,
|
|
863
|
+
continuation: snapshot.input.continue ?? null,
|
|
864
|
+
};
|
|
865
|
+
return {
|
|
866
|
+
agentId: id,
|
|
867
|
+
version,
|
|
868
|
+
runId: snapshot.runId,
|
|
869
|
+
attemptId: send.attemptId,
|
|
870
|
+
operationId: send.id,
|
|
871
|
+
call: { id: send.id, name, arguments: JSON.stringify(args) },
|
|
872
|
+
arguments: args,
|
|
873
|
+
};
|
|
874
|
+
}
|
|
875
|
+
function journal(
|
|
876
|
+
snapshot: RemoteSnapshot,
|
|
877
|
+
send: RemoteSend,
|
|
878
|
+
opts: RunOptions,
|
|
879
|
+
scope: ExecutionScope,
|
|
880
|
+
signal: AbortSignal,
|
|
881
|
+
) {
|
|
882
|
+
return new RequestJournal(
|
|
883
|
+
send,
|
|
884
|
+
request(snapshot, send),
|
|
885
|
+
{
|
|
886
|
+
...opts,
|
|
887
|
+
host: {
|
|
888
|
+
...opts.host,
|
|
889
|
+
beforeTool: (call, decided) => authority(opts, signal, call, decided),
|
|
890
|
+
},
|
|
891
|
+
},
|
|
892
|
+
scope,
|
|
893
|
+
signal,
|
|
894
|
+
() => requestHash({ id, version, endpoint: snapshot.remote.endpoint }),
|
|
895
|
+
);
|
|
896
|
+
}
|
|
897
|
+
async function authority(
|
|
898
|
+
opts: RunOptions,
|
|
899
|
+
signal: AbortSignal,
|
|
900
|
+
call: ToolRequest,
|
|
901
|
+
decided?: { request: PendingRequest; decision: Decision },
|
|
902
|
+
): Promise<void> {
|
|
903
|
+
if (!opts.host?.beforeTool)
|
|
904
|
+
fail(
|
|
905
|
+
"remote_authority_missing",
|
|
906
|
+
"Provide host.beforeTool to authorize remote messages and cancellation.",
|
|
907
|
+
);
|
|
908
|
+
try {
|
|
909
|
+
await untilAbort(
|
|
910
|
+
Promise.resolve(
|
|
911
|
+
opts.host.beforeTool(immutableCopy(call), decided && immutableCopy(decided)),
|
|
912
|
+
),
|
|
913
|
+
signal,
|
|
914
|
+
);
|
|
915
|
+
} catch {
|
|
916
|
+
signal.throwIfAborted();
|
|
917
|
+
fail(
|
|
918
|
+
"remote_authority_denied",
|
|
919
|
+
"The host did not authorize this remote operation. Check access before continuing.",
|
|
920
|
+
);
|
|
921
|
+
}
|
|
922
|
+
signal.throwIfAborted();
|
|
923
|
+
}
|
|
924
|
+
async function accept(
|
|
925
|
+
snapshot: RemoteSnapshot,
|
|
926
|
+
event: A2AEvent,
|
|
927
|
+
scope: ExecutionScope,
|
|
928
|
+
opts: RunOptions,
|
|
929
|
+
sent = false,
|
|
930
|
+
) {
|
|
931
|
+
const receipt = snapshot.remote;
|
|
932
|
+
const taskId = event.kind === "task" ? event.id : event.taskId;
|
|
933
|
+
if (receipt.taskId !== undefined && taskId !== undefined && receipt.taskId !== taskId)
|
|
934
|
+
throw new A2AError("invalid");
|
|
935
|
+
if (
|
|
936
|
+
receipt.contextId !== undefined &&
|
|
937
|
+
event.contextId !== undefined &&
|
|
938
|
+
receipt.contextId !== event.contextId
|
|
939
|
+
)
|
|
940
|
+
throw new A2AError("invalid");
|
|
941
|
+
if (event.kind === "message" && event.role !== "agent") throw new A2AError("invalid");
|
|
942
|
+
const last = receipt.sends.at(-1);
|
|
943
|
+
const confirmed =
|
|
944
|
+
(receipt.taskId === undefined && taskId !== undefined) ||
|
|
945
|
+
(receipt.contextId === undefined && event.contextId !== undefined) ||
|
|
946
|
+
(last?.status === "running" && sent);
|
|
947
|
+
receipt.taskId ??= taskId;
|
|
948
|
+
receipt.contextId ??= event.contextId;
|
|
949
|
+
if (last && sent) last.status = "accepted";
|
|
950
|
+
// Semantic refusal must not erase an accepted send or the task needed to cancel it.
|
|
951
|
+
if (confirmed) await scope.tree.save();
|
|
952
|
+
const r = copyData(receipt);
|
|
953
|
+
if (event.kind === "task" || event.kind === "status-update") {
|
|
954
|
+
r.state = event.status.state;
|
|
955
|
+
r.fallback = ["completed", "input_required"].includes(r.state)
|
|
956
|
+
? safeParts(event.status.message?.parts ?? [], definition.includeImages)
|
|
957
|
+
: [];
|
|
958
|
+
if (r.state === "input_required") r.question = question(event.status.message);
|
|
959
|
+
else delete r.question;
|
|
960
|
+
if (event.kind === "task")
|
|
961
|
+
r.artifacts = (event.artifacts ?? []).map((a) => ({
|
|
962
|
+
artifactId: a.artifactId,
|
|
963
|
+
parts: safeParts(a.parts, definition.includeImages),
|
|
964
|
+
}));
|
|
965
|
+
} else if (event.kind === "message") {
|
|
966
|
+
r.state = "completed";
|
|
967
|
+
r.fallback = safeParts(event.parts, definition.includeImages);
|
|
968
|
+
delete r.question;
|
|
969
|
+
} else {
|
|
970
|
+
const parts = safeParts(event.artifact.parts, definition.includeImages);
|
|
971
|
+
const prior = r.artifacts.find((a) => a.artifactId === event.artifact.artifactId);
|
|
972
|
+
if (prior) prior.parts = event.append ? [...prior.parts, ...parts] : parts;
|
|
973
|
+
else r.artifacts.push({ artifactId: event.artifact.artifactId, parts });
|
|
974
|
+
}
|
|
975
|
+
if (bytes([r.artifacts, r.fallback, r.question]) > limits.resultBytes)
|
|
976
|
+
fail(
|
|
977
|
+
"remote_result_too_large",
|
|
978
|
+
"The remote response exceeds this agent's byte limit. Ask for a smaller result.",
|
|
979
|
+
);
|
|
980
|
+
if (imageBytes([...r.fallback, ...r.artifacts.flatMap((a) => a.parts)]) > limits.inlineBytes)
|
|
981
|
+
fail(
|
|
982
|
+
"remote_result_too_large",
|
|
983
|
+
"The remote images exceed this agent's byte limit. Ask for smaller images.",
|
|
984
|
+
);
|
|
985
|
+
if (!r.question) delete snapshot.remote.question;
|
|
986
|
+
Object.assign(snapshot.remote, r);
|
|
987
|
+
// Task/context identity is saved before any more observation or follow-up.
|
|
988
|
+
await scope.tree.save();
|
|
989
|
+
emitEvent(opts, {
|
|
990
|
+
type: "remote_status",
|
|
991
|
+
runId: snapshot.runId,
|
|
992
|
+
attemptId: snapshot.attemptId,
|
|
993
|
+
operationId: last?.id ?? snapshot.runId,
|
|
994
|
+
state: r.state ?? "working",
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
async function answerRequests(
|
|
998
|
+
raw: TreeNode,
|
|
999
|
+
opts: RunOptions,
|
|
1000
|
+
scope: ExecutionScope,
|
|
1001
|
+
answers: Readonly<Record<string, unknown>>,
|
|
1002
|
+
signal: AbortSignal,
|
|
1003
|
+
) {
|
|
1004
|
+
const snapshot = node(raw);
|
|
1005
|
+
if (!["running", "suspended"].includes(snapshot.state.status)) return;
|
|
1006
|
+
for (const send of snapshot.remote.sends) {
|
|
1007
|
+
const requests = journal(snapshot, send, opts, scope, signal);
|
|
1008
|
+
for (const record of [...(send.asks ?? [])]) {
|
|
1009
|
+
if (record.closed) continue;
|
|
1010
|
+
if (!record.decision && Object.hasOwn(answers, record.request.id))
|
|
1011
|
+
await requests.resolve(record, answers[record.request.id]);
|
|
1012
|
+
else if (!snapshot.remote.sends.some((later) => later.answers.includes(record.request.id)))
|
|
1013
|
+
await requests.refresh(record);
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
async function partsOf(
|
|
1018
|
+
input: UserContent,
|
|
1019
|
+
snapshot: RemoteSnapshot,
|
|
1020
|
+
opts: RunOptions,
|
|
1021
|
+
signal: AbortSignal,
|
|
1022
|
+
): Promise<A2APart[]> {
|
|
1023
|
+
if (typeof input === "string") return [{ kind: "text", text: input }];
|
|
1024
|
+
const loaded = [];
|
|
1025
|
+
for (const part of input) {
|
|
1026
|
+
if (part.type !== "media") loaded.push(part);
|
|
1027
|
+
else {
|
|
1028
|
+
if (!opts.host?.loadMedia)
|
|
1029
|
+
fail(
|
|
1030
|
+
"media_host_missing",
|
|
1031
|
+
"Provide host.loadMedia to authorize and read this attachment.",
|
|
1032
|
+
);
|
|
1033
|
+
const data = await untilAbort(
|
|
1034
|
+
Promise.resolve(
|
|
1035
|
+
opts.host.loadMedia(immutableCopy(part), { runId: snapshot.runId, signal }),
|
|
1036
|
+
),
|
|
1037
|
+
signal,
|
|
1038
|
+
);
|
|
1039
|
+
const mimeType = part.mimeType;
|
|
1040
|
+
loaded.push(
|
|
1041
|
+
isImageMime(mimeType)
|
|
1042
|
+
? { type: "image" as const, mimeType, data }
|
|
1043
|
+
: { type: "file" as const, mimeType, data },
|
|
1044
|
+
);
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
const checked = readContent(loaded, "The remote message");
|
|
1048
|
+
if (inlineBytes([], checked) > limits.inlineBytes) throw new A2AError("limit");
|
|
1049
|
+
return loaded.map((part) =>
|
|
1050
|
+
part.type === "text"
|
|
1051
|
+
? { kind: "text", text: part.text }
|
|
1052
|
+
: { kind: "raw", raw: part.data, mediaType: part.mimeType },
|
|
1053
|
+
);
|
|
1054
|
+
}
|
|
1055
|
+
async function cancelTask(
|
|
1056
|
+
snapshot: RemoteSnapshot,
|
|
1057
|
+
opts: RunOptions,
|
|
1058
|
+
scope: ExecutionScope,
|
|
1059
|
+
signal: AbortSignal,
|
|
1060
|
+
requests?: RequestJournal,
|
|
1061
|
+
): Promise<void> {
|
|
1062
|
+
const r = snapshot.remote;
|
|
1063
|
+
if (
|
|
1064
|
+
!r.taskId ||
|
|
1065
|
+
(r.state && ["completed", "failed", "canceled", "rejected"].includes(r.state)) ||
|
|
1066
|
+
r.cancel
|
|
1067
|
+
)
|
|
1068
|
+
return;
|
|
1069
|
+
const operation = {
|
|
1070
|
+
id: `${snapshot.runId}/cancel`,
|
|
1071
|
+
attemptId: snapshot.attemptId,
|
|
1072
|
+
status: "running" as const,
|
|
1073
|
+
};
|
|
1074
|
+
const call: ToolRequest = {
|
|
1075
|
+
agentId: id,
|
|
1076
|
+
version,
|
|
1077
|
+
runId: snapshot.runId,
|
|
1078
|
+
attemptId: snapshot.attemptId,
|
|
1079
|
+
operationId: operation.id,
|
|
1080
|
+
call: {
|
|
1081
|
+
id: operation.id,
|
|
1082
|
+
name: "remote_cancel",
|
|
1083
|
+
arguments: JSON.stringify({ taskId: r.taskId }),
|
|
1084
|
+
},
|
|
1085
|
+
arguments: { taskId: r.taskId },
|
|
1086
|
+
};
|
|
1087
|
+
await authority(opts, signal, call);
|
|
1088
|
+
r.cancel = operation;
|
|
1089
|
+
await scope.tree.save();
|
|
1090
|
+
await authority(opts, signal, call);
|
|
1091
|
+
await requests?.recheck(requests.call);
|
|
1092
|
+
await requests?.assertFresh();
|
|
1093
|
+
signal.throwIfAborted();
|
|
1094
|
+
try {
|
|
1095
|
+
const result = await client(snapshot).call("CancelTask", { id: r.taskId }, { signal });
|
|
1096
|
+
if (
|
|
1097
|
+
result.id !== r.taskId ||
|
|
1098
|
+
(r.contextId !== undefined &&
|
|
1099
|
+
result.contextId !== undefined &&
|
|
1100
|
+
result.contextId !== r.contextId)
|
|
1101
|
+
)
|
|
1102
|
+
throw new A2AError("invalid");
|
|
1103
|
+
// A parent-routed question is a completed child result. Keep that historical result
|
|
1104
|
+
// immutable; the separate cancel receipt closes its continuation handle.
|
|
1105
|
+
if (snapshot.state.status !== "completed") await accept(snapshot, result, scope, opts);
|
|
1106
|
+
r.cancel = { ...operation, status: "accepted", state: result.status.state };
|
|
1107
|
+
await scope.tree.save();
|
|
1108
|
+
} catch (error) {
|
|
1109
|
+
if (error instanceof Halt || !(error instanceof A2AError)) throw error;
|
|
1110
|
+
signal.throwIfAborted();
|
|
1111
|
+
// Unknown cancellation stays unknown and is never sent a second time.
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
function hydrate(raw: TreeNode): RemoteOutcome<T | string> {
|
|
1115
|
+
const snapshot = copyData(node(raw));
|
|
1116
|
+
const state = snapshot.state;
|
|
1117
|
+
if (state.status === "running") throw new TypeError("The remote attempt has not settled.");
|
|
1118
|
+
const r = snapshot.remote;
|
|
1119
|
+
const receipts: RemoteReceipt[] = [
|
|
1120
|
+
...r.sends.map((send): RemoteReceipt => ({
|
|
1121
|
+
kind: "remote",
|
|
1122
|
+
action: "send",
|
|
1123
|
+
id: send.id,
|
|
1124
|
+
attemptId: send.attemptId,
|
|
1125
|
+
status: send.status,
|
|
1126
|
+
billing: "unknown",
|
|
1127
|
+
taskId: r.taskId,
|
|
1128
|
+
contextId: r.contextId,
|
|
1129
|
+
})),
|
|
1130
|
+
...(r.cancel
|
|
1131
|
+
? [
|
|
1132
|
+
{
|
|
1133
|
+
kind: "remote" as const,
|
|
1134
|
+
action: "cancel" as const,
|
|
1135
|
+
...r.cancel,
|
|
1136
|
+
billing: "unknown" as const,
|
|
1137
|
+
taskId: r.taskId,
|
|
1138
|
+
contextId: r.contextId,
|
|
1139
|
+
},
|
|
1140
|
+
]
|
|
1141
|
+
: []),
|
|
1142
|
+
];
|
|
1143
|
+
const record = {
|
|
1144
|
+
runId: snapshot.runId,
|
|
1145
|
+
attemptId: snapshot.attemptId,
|
|
1146
|
+
treeUsage: treeUsage(snapshot),
|
|
1147
|
+
receipts,
|
|
1148
|
+
snapshot,
|
|
1149
|
+
};
|
|
1150
|
+
if (state.status === "completed") {
|
|
1151
|
+
const pending = r.state === "input_required" && definition.inputRequired === "parent";
|
|
1152
|
+
const result: RemotePending = {
|
|
1153
|
+
kind: "input_required",
|
|
1154
|
+
handle: snapshot.runId,
|
|
1155
|
+
question:
|
|
1156
|
+
r.question?.asks.map((ask) => ask.message).join("\n") ??
|
|
1157
|
+
"The remote agent needs an answer.",
|
|
1158
|
+
};
|
|
1159
|
+
return {
|
|
1160
|
+
...record,
|
|
1161
|
+
status: "completed",
|
|
1162
|
+
output: pending ? result : validate(state.candidate),
|
|
1163
|
+
};
|
|
1164
|
+
}
|
|
1165
|
+
return state.status === "suspended"
|
|
1166
|
+
? { ...record, ...state, requests: openRequests(snapshot), wakeAt: r.wakeAt }
|
|
1167
|
+
: { ...record, ...state };
|
|
1168
|
+
}
|
|
1169
|
+
async function execute(
|
|
1170
|
+
raw: TreeNode,
|
|
1171
|
+
opts: RunOptions,
|
|
1172
|
+
scope: ExecutionScope,
|
|
1173
|
+
answers?: Readonly<Record<string, unknown>>,
|
|
1174
|
+
): Promise<RemoteOutcome<T | string>> {
|
|
1175
|
+
const snapshot = node(raw),
|
|
1176
|
+
r = snapshot.remote;
|
|
1177
|
+
if (!["running", "suspended"].includes(snapshot.state.status)) return hydrate(snapshot);
|
|
1178
|
+
const timeout = new AbortController();
|
|
1179
|
+
const signal = AbortSignal.any([
|
|
1180
|
+
scope.tree.signal,
|
|
1181
|
+
timeout.signal,
|
|
1182
|
+
...(opts.signal ? [opts.signal] : []),
|
|
1183
|
+
]);
|
|
1184
|
+
const deadline = snapshot.startedAt + limits.elapsedMs;
|
|
1185
|
+
const timer = setTimeout(() => timeout.abort(), Math.max(0, deadline - Date.now()));
|
|
1186
|
+
let release = () => {};
|
|
1187
|
+
function active() {
|
|
1188
|
+
scope.tree.active();
|
|
1189
|
+
if (timeout.signal.aborted || Date.now() >= deadline)
|
|
1190
|
+
throw new Halt({ status: "limited", limit: "elapsedMs" });
|
|
1191
|
+
signal.throwIfAborted();
|
|
1192
|
+
}
|
|
1193
|
+
async function send(parts: A2APart[], answered: string[], prior?: RequestJournal) {
|
|
1194
|
+
active();
|
|
1195
|
+
if (r.sends.length + r.priorTurns >= limits.turns)
|
|
1196
|
+
throw new Halt({ status: "limited", limit: "turns" });
|
|
1197
|
+
const sendId = `${snapshot.runId}/send/${r.sends.length + 1}`;
|
|
1198
|
+
const entry: RemoteSend = {
|
|
1199
|
+
id: sendId,
|
|
1200
|
+
attemptId: snapshot.attemptId,
|
|
1201
|
+
status: "running",
|
|
1202
|
+
answers: answered,
|
|
1203
|
+
// A2A message IDs have a 128-character ceiling; nested logical run paths do not.
|
|
1204
|
+
message: {
|
|
1205
|
+
kind: "message",
|
|
1206
|
+
messageId: `${snapshot.attemptId}/send/${r.sends.length + 1}`,
|
|
1207
|
+
role: "user",
|
|
1208
|
+
parts,
|
|
1209
|
+
...(r.taskId ? { taskId: r.taskId } : {}),
|
|
1210
|
+
...(r.contextId ? { contextId: r.contextId } : {}),
|
|
1211
|
+
},
|
|
1212
|
+
};
|
|
1213
|
+
encodeA2AMessage(entry.message, r.endpoint);
|
|
1214
|
+
await authority(opts, signal, request(snapshot, entry, "remote_send"));
|
|
1215
|
+
await prior?.recheck(prior.call);
|
|
1216
|
+
r.sends.push(entry);
|
|
1217
|
+
delete r.question;
|
|
1218
|
+
r.state = "working";
|
|
1219
|
+
await scope.tree.save();
|
|
1220
|
+
active();
|
|
1221
|
+
await authority(opts, signal, request(snapshot, entry, "remote_send"));
|
|
1222
|
+
await prior?.recheck(prior.call);
|
|
1223
|
+
await prior?.assertFresh();
|
|
1224
|
+
active();
|
|
1225
|
+
try {
|
|
1226
|
+
if (definition.updates === "stream") {
|
|
1227
|
+
for await (const event of client(snapshot).observe(
|
|
1228
|
+
"SendStreamingMessage",
|
|
1229
|
+
{ message: entry.message },
|
|
1230
|
+
{ signal },
|
|
1231
|
+
))
|
|
1232
|
+
await accept(snapshot, event, scope, opts, true);
|
|
1233
|
+
} else {
|
|
1234
|
+
await accept(
|
|
1235
|
+
snapshot,
|
|
1236
|
+
await client(snapshot).call(
|
|
1237
|
+
"SendMessage",
|
|
1238
|
+
{ message: entry.message, configuration: { returnImmediately: true } },
|
|
1239
|
+
{ signal },
|
|
1240
|
+
),
|
|
1241
|
+
scope,
|
|
1242
|
+
opts,
|
|
1243
|
+
true,
|
|
1244
|
+
);
|
|
1245
|
+
}
|
|
1246
|
+
} catch (error) {
|
|
1247
|
+
if (error instanceof Halt || !(error instanceof A2AError)) throw error;
|
|
1248
|
+
active();
|
|
1249
|
+
if (!r.taskId)
|
|
1250
|
+
fail(
|
|
1251
|
+
"remote_unconfirmed",
|
|
1252
|
+
"The remote message may have been delivered. Reconcile it with the remote service; it will not be sent again.",
|
|
1253
|
+
entry.id,
|
|
1254
|
+
);
|
|
1255
|
+
// A task id permits reads, never a second send.
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
try {
|
|
1259
|
+
emitEvent(opts, {
|
|
1260
|
+
type: "execution_start",
|
|
1261
|
+
kind: "remote",
|
|
1262
|
+
nodeId: id,
|
|
1263
|
+
version,
|
|
1264
|
+
runId: snapshot.runId,
|
|
1265
|
+
attemptId: snapshot.attemptId,
|
|
1266
|
+
});
|
|
1267
|
+
active();
|
|
1268
|
+
if (r.wakeAt !== undefined) {
|
|
1269
|
+
if (Date.now() < r.wakeAt) throw new Halt({ status: "suspended" });
|
|
1270
|
+
delete r.wakeAt;
|
|
1271
|
+
}
|
|
1272
|
+
if (scope.depth === 0 && answers)
|
|
1273
|
+
await answerRequests(snapshot, opts, scope, answers, signal);
|
|
1274
|
+
snapshot.state = { status: "running" };
|
|
1275
|
+
await scope.tree.save();
|
|
1276
|
+
release = await scope.tree.gate.acquire(signal);
|
|
1277
|
+
if (!r.sends.length)
|
|
1278
|
+
await send(await partsOf(snapshot.input.input, snapshot, opts, signal), []);
|
|
1279
|
+
else if (!r.taskId && r.sends.at(-1)?.status === "running")
|
|
1280
|
+
fail(
|
|
1281
|
+
"remote_unconfirmed",
|
|
1282
|
+
"The remote message has no confirmed task. Reconcile it; this run cannot resend it.",
|
|
1283
|
+
);
|
|
1284
|
+
let polls = 0,
|
|
1285
|
+
reconnects = 0;
|
|
1286
|
+
for (;;) {
|
|
1287
|
+
active();
|
|
1288
|
+
if (r.state && a2aStateClosed(r.state) && r.sends.at(-1)?.status === "running")
|
|
1289
|
+
fail(
|
|
1290
|
+
"remote_unconfirmed",
|
|
1291
|
+
"The last message may not have reached this task. Reconcile it with the remote service; it will not be sent again.",
|
|
1292
|
+
);
|
|
1293
|
+
if (r.state === "completed") {
|
|
1294
|
+
try {
|
|
1295
|
+
const value = candidate(snapshot);
|
|
1296
|
+
validate(value);
|
|
1297
|
+
snapshot.state = { status: "completed", candidate: value };
|
|
1298
|
+
} catch {
|
|
1299
|
+
fail(
|
|
1300
|
+
"remote_invalid_output",
|
|
1301
|
+
"The remote result does not match the configured output. Check its format before using it.",
|
|
1302
|
+
);
|
|
1303
|
+
}
|
|
1304
|
+
break;
|
|
1305
|
+
}
|
|
1306
|
+
if (r.state === "input_required") {
|
|
1307
|
+
if (!r.taskId) throw new A2AError("invalid");
|
|
1308
|
+
if (definition.inputRequired === "fail")
|
|
1309
|
+
fail(
|
|
1310
|
+
"remote_input_required",
|
|
1311
|
+
"The remote agent needs an answer. Enable request routing to continue.",
|
|
1312
|
+
);
|
|
1313
|
+
if (definition.inputRequired === "parent") {
|
|
1314
|
+
const asks = r.question?.asks ?? [];
|
|
1315
|
+
if (
|
|
1316
|
+
asks.length !== 1 ||
|
|
1317
|
+
asks[0]?.schema ||
|
|
1318
|
+
asks[0]?.choices ||
|
|
1319
|
+
asks[0]?.freeText === false
|
|
1320
|
+
)
|
|
1321
|
+
fail(
|
|
1322
|
+
"remote_request_unsupported",
|
|
1323
|
+
"This remote task needs multiple answers or a form. Use inputRequired: ask to answer each request.",
|
|
1324
|
+
);
|
|
1325
|
+
snapshot.state = { status: "completed", candidate: candidate(snapshot) };
|
|
1326
|
+
break;
|
|
1327
|
+
}
|
|
1328
|
+
const last = r.sends.at(-1);
|
|
1329
|
+
if (!last || !r.question) throw new A2AError("invalid");
|
|
1330
|
+
const requests = journal(snapshot, last, opts, scope, signal);
|
|
1331
|
+
const records: AskRecord[] = [];
|
|
1332
|
+
for (const ask of r.question.asks) records.push(await requests.ensure(ask));
|
|
1333
|
+
await requests.recheck(requests.call);
|
|
1334
|
+
await requests.assertFresh();
|
|
1335
|
+
if (records.some((record) => record.decision?.type === "cancel")) {
|
|
1336
|
+
await cancelTask(snapshot, opts, scope, signal, requests);
|
|
1337
|
+
fail(
|
|
1338
|
+
"remote_cancelled",
|
|
1339
|
+
"This remote question was cancelled. The remote service may still be working.",
|
|
1340
|
+
);
|
|
1341
|
+
}
|
|
1342
|
+
if (records.some((record) => !record.decision)) throw new Halt({ status: "suspended" });
|
|
1343
|
+
await send(
|
|
1344
|
+
answerParts(records, r.question.structured),
|
|
1345
|
+
records.map((record) => record.request.id),
|
|
1346
|
+
requests,
|
|
1347
|
+
);
|
|
1348
|
+
continue;
|
|
1349
|
+
}
|
|
1350
|
+
if (r.state === "auth_required")
|
|
1351
|
+
fail(
|
|
1352
|
+
"remote_auth_required",
|
|
1353
|
+
"The remote service needs sign-in. Sign in through its host, then reconnect to this task.",
|
|
1354
|
+
);
|
|
1355
|
+
if (r.state && ["failed", "rejected", "canceled"].includes(r.state))
|
|
1356
|
+
fail(
|
|
1357
|
+
"remote_failed",
|
|
1358
|
+
"The remote service did not complete this task. Check its status with its operator.",
|
|
1359
|
+
);
|
|
1360
|
+
if (!r.taskId)
|
|
1361
|
+
fail(
|
|
1362
|
+
"remote_unconfirmed",
|
|
1363
|
+
"No task identity was confirmed. Reconcile the remote message; it will not be sent again.",
|
|
1364
|
+
);
|
|
1365
|
+
const subscribing = definition.updates === "stream" && reconnects++ < 5;
|
|
1366
|
+
try {
|
|
1367
|
+
if (subscribing) {
|
|
1368
|
+
for await (const event of client(snapshot).observe(
|
|
1369
|
+
"SubscribeToTask",
|
|
1370
|
+
{ id: r.taskId },
|
|
1371
|
+
{ signal },
|
|
1372
|
+
))
|
|
1373
|
+
await accept(snapshot, event, scope, opts);
|
|
1374
|
+
} else {
|
|
1375
|
+
if (polls++) await sleep(Math.min(1000 * 2 ** Math.min(polls - 2, 4), 15_000), signal);
|
|
1376
|
+
await accept(
|
|
1377
|
+
snapshot,
|
|
1378
|
+
await client(snapshot).call("GetTask", { id: r.taskId }, { signal }),
|
|
1379
|
+
scope,
|
|
1380
|
+
opts,
|
|
1381
|
+
);
|
|
1382
|
+
}
|
|
1383
|
+
} catch (error) {
|
|
1384
|
+
if (error instanceof Halt || !(error instanceof A2AError)) throw error;
|
|
1385
|
+
active();
|
|
1386
|
+
if (subscribing && error.kind === "protocol" && error.code === -32004) {
|
|
1387
|
+
// A peer can finish between observations. Terminal tasks refuse subscriptions,
|
|
1388
|
+
// but GetTask still returns their result. Poll without replaying any message.
|
|
1389
|
+
reconnects = 5;
|
|
1390
|
+
continue;
|
|
1391
|
+
}
|
|
1392
|
+
if (["protocol", "http", "endpoint", "limit", "invalid"].includes(error.kind))
|
|
1393
|
+
throw error;
|
|
1394
|
+
if (polls >= 3) {
|
|
1395
|
+
// Reuse the host's existing due-wake claims. An empty requestless suspension
|
|
1396
|
+
// otherwise cannot be continued by the background binding.
|
|
1397
|
+
r.wakeAt = Date.now() + 15_000;
|
|
1398
|
+
throw new Halt({ status: "suspended" });
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
} catch (error) {
|
|
1403
|
+
let failure = error;
|
|
1404
|
+
try {
|
|
1405
|
+
active();
|
|
1406
|
+
} catch (stopped) {
|
|
1407
|
+
failure = stopped instanceof Halt ? stopped : new Halt({ status: "cancelled" });
|
|
1408
|
+
}
|
|
1409
|
+
snapshot.state =
|
|
1410
|
+
failure instanceof Halt
|
|
1411
|
+
? failure.state
|
|
1412
|
+
: {
|
|
1413
|
+
status: "failed",
|
|
1414
|
+
error: {
|
|
1415
|
+
code: failure instanceof A2AError ? "remote_unconfirmed" : "remote_host_failed",
|
|
1416
|
+
message:
|
|
1417
|
+
"The remote service could not be observed safely. Reconcile its task before starting new work.",
|
|
1418
|
+
},
|
|
1419
|
+
};
|
|
1420
|
+
if (snapshot.state.status === "cancelled") stopRequests(snapshot);
|
|
1421
|
+
} finally {
|
|
1422
|
+
release();
|
|
1423
|
+
clearTimeout(timer);
|
|
1424
|
+
}
|
|
1425
|
+
try {
|
|
1426
|
+
await scope.tree.save();
|
|
1427
|
+
} catch (error) {
|
|
1428
|
+
snapshot.state =
|
|
1429
|
+
error instanceof Halt
|
|
1430
|
+
? error.state
|
|
1431
|
+
: {
|
|
1432
|
+
status: "failed",
|
|
1433
|
+
error: {
|
|
1434
|
+
code: "checkpoint_failed",
|
|
1435
|
+
message:
|
|
1436
|
+
"The remote journal could not be saved. Reconcile stored state before continuing.",
|
|
1437
|
+
},
|
|
1438
|
+
};
|
|
1439
|
+
}
|
|
1440
|
+
emitEvent(opts, {
|
|
1441
|
+
type: "state",
|
|
1442
|
+
runId: snapshot.runId,
|
|
1443
|
+
attemptId: snapshot.attemptId,
|
|
1444
|
+
state: snapshot.state,
|
|
1445
|
+
});
|
|
1446
|
+
await opts.host?.progress?.flush();
|
|
1447
|
+
return hydrate(snapshot);
|
|
1448
|
+
}
|
|
1449
|
+
async function create(
|
|
1450
|
+
input: RemoteInput,
|
|
1451
|
+
runId: string,
|
|
1452
|
+
tree?: RunSnapshot["tree"],
|
|
1453
|
+
opts: RunOptions = {},
|
|
1454
|
+
root?: TreeNode,
|
|
1455
|
+
): Promise<RemoteSnapshot> {
|
|
1456
|
+
const signal = opts.signal ?? new AbortController().signal;
|
|
1457
|
+
let source: RemoteSnapshot | undefined;
|
|
1458
|
+
if (input.continue) {
|
|
1459
|
+
source =
|
|
1460
|
+
root &&
|
|
1461
|
+
[...snapshots(root)].find(
|
|
1462
|
+
(saved): saved is RemoteSnapshot =>
|
|
1463
|
+
saved.kind === "remote" && saved.runId === input.continue,
|
|
1464
|
+
);
|
|
1465
|
+
if (
|
|
1466
|
+
!source ||
|
|
1467
|
+
source.agentId !== id ||
|
|
1468
|
+
source.version !== version ||
|
|
1469
|
+
!equalData(source.definition, definition) ||
|
|
1470
|
+
source.state.status !== "completed" ||
|
|
1471
|
+
source.remote.state !== "input_required" ||
|
|
1472
|
+
source.remote.cancel ||
|
|
1473
|
+
[...snapshots(root!)].some(
|
|
1474
|
+
(saved) =>
|
|
1475
|
+
saved.kind === "remote" &&
|
|
1476
|
+
saved.runId !== runId &&
|
|
1477
|
+
saved.input.continue === input.continue,
|
|
1478
|
+
)
|
|
1479
|
+
)
|
|
1480
|
+
throw new TypeError(
|
|
1481
|
+
"This remote continuation is not open in this root and specialist scope.",
|
|
1482
|
+
);
|
|
1483
|
+
}
|
|
1484
|
+
const card =
|
|
1485
|
+
typeof options.card === "string"
|
|
1486
|
+
? await fetchA2AAgentCard(options.card, { ...options, signal })
|
|
1487
|
+
: decodeA2AAgentCard(options.card.document, options.card.version);
|
|
1488
|
+
if (typeof options.card !== "string") {
|
|
1489
|
+
await untilAbort(
|
|
1490
|
+
Promise.resolve(
|
|
1491
|
+
options.verifyCard?.(immutableCopy(card), {
|
|
1492
|
+
url: card.interfaces[0]?.url ?? "",
|
|
1493
|
+
fetchedAt: Date.now(),
|
|
1494
|
+
}),
|
|
1495
|
+
),
|
|
1496
|
+
signal,
|
|
1497
|
+
);
|
|
1498
|
+
await untilAbort(
|
|
1499
|
+
checkA2ACardEndpoints(card, card.interfaces[0]?.url ?? "", options.policy),
|
|
1500
|
+
signal,
|
|
1501
|
+
);
|
|
1502
|
+
}
|
|
1503
|
+
const selected = selectA2AInterface(card, options.version, options.binding, options.extensions);
|
|
1504
|
+
if (definition.updates === "stream" && !card.capabilities.streaming)
|
|
1505
|
+
throw new TypeError("This card does not support streaming. Select poll updates.");
|
|
1506
|
+
const endpoint = {
|
|
1507
|
+
url: selected.url,
|
|
1508
|
+
version: options.version,
|
|
1509
|
+
binding: options.binding,
|
|
1510
|
+
streaming: card.capabilities.streaming === true,
|
|
1511
|
+
...(selected.tenant ? { tenant: selected.tenant } : {}),
|
|
1512
|
+
};
|
|
1513
|
+
if (source && !equalData(source.remote.endpoint, endpoint))
|
|
1514
|
+
throw new TypeError("The remote endpoint changed. Restore the original specialist version.");
|
|
1515
|
+
if (inlineBytes([], input.input) > limits.inlineBytes)
|
|
1516
|
+
throw new TypeError("The remote input exceeds its inline byte limit.");
|
|
1517
|
+
const startedAt = Date.now();
|
|
1518
|
+
return {
|
|
1519
|
+
kind: "remote",
|
|
1520
|
+
format: 3,
|
|
1521
|
+
agentId: id,
|
|
1522
|
+
version,
|
|
1523
|
+
runId,
|
|
1524
|
+
attemptId: crypto.randomUUID(),
|
|
1525
|
+
startedAt,
|
|
1526
|
+
input: copyData(input),
|
|
1527
|
+
definition: copyData(definition),
|
|
1528
|
+
limits: copyData(limits),
|
|
1529
|
+
tree: tree ? copyData(tree) : { runId, startedAt, limits: copyData(treeLimits) },
|
|
1530
|
+
remote: {
|
|
1531
|
+
endpoint,
|
|
1532
|
+
priorTurns: source ? source.remote.priorTurns + source.remote.sends.length : 0,
|
|
1533
|
+
sends: [],
|
|
1534
|
+
artifacts: [],
|
|
1535
|
+
fallback: [],
|
|
1536
|
+
...(source?.remote.taskId ? { taskId: source.remote.taskId } : {}),
|
|
1537
|
+
...(source?.remote.contextId ? { contextId: source.remote.contextId } : {}),
|
|
1538
|
+
},
|
|
1539
|
+
state: { status: "running" },
|
|
1540
|
+
};
|
|
1541
|
+
}
|
|
1542
|
+
const runtime: RemoteRuntime<T | string> = {
|
|
1543
|
+
create,
|
|
1544
|
+
execute,
|
|
1545
|
+
hydrate,
|
|
1546
|
+
answerRequests,
|
|
1547
|
+
prepare: remoteInput,
|
|
1548
|
+
configuration: () => copyData({ ...definition, limits }),
|
|
1549
|
+
open(input, opts, runId) {
|
|
1550
|
+
checkRunOptions(opts);
|
|
1551
|
+
return create({ input: content(input) }, runId, undefined, opts);
|
|
1552
|
+
},
|
|
1553
|
+
restore(raw, tree) {
|
|
1554
|
+
if (!isRemoteSnapshot(raw)) throw new TypeError("Invalid remote snapshot.");
|
|
1555
|
+
const snapshot = copyData(raw);
|
|
1556
|
+
if (
|
|
1557
|
+
snapshot.agentId !== id ||
|
|
1558
|
+
snapshot.version !== version ||
|
|
1559
|
+
!equalData(snapshot.definition, definition) ||
|
|
1560
|
+
!equalData(snapshot.limits, limits) ||
|
|
1561
|
+
(tree
|
|
1562
|
+
? !equalData(snapshot.tree, tree)
|
|
1563
|
+
: snapshot.tree.runId !== snapshot.runId || !equalData(snapshot.tree.limits, treeLimits))
|
|
1564
|
+
)
|
|
1565
|
+
throw new TypeError("Restore the same remote definition, limits and tree.");
|
|
1566
|
+
checkRemoteSnapshot(snapshot);
|
|
1567
|
+
checkTree(snapshot);
|
|
1568
|
+
if (snapshot.state.status === "completed" && snapshot.remote.state === "completed")
|
|
1569
|
+
validate(snapshot.state.candidate);
|
|
1570
|
+
return snapshot;
|
|
1571
|
+
},
|
|
1572
|
+
};
|
|
1573
|
+
async function root(
|
|
1574
|
+
snapshot: RemoteSnapshot,
|
|
1575
|
+
opts: RunOptions,
|
|
1576
|
+
answers?: Readonly<Record<string, unknown>>,
|
|
1577
|
+
) {
|
|
1578
|
+
const tree = new ExecutionTree(snapshot, opts);
|
|
1579
|
+
try {
|
|
1580
|
+
return await execute(snapshot, opts, { tree, depth: 0, path: [] }, answers);
|
|
1581
|
+
} finally {
|
|
1582
|
+
tree.close();
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
const remote: RemoteAgent<T | string> = Object.freeze({
|
|
1586
|
+
kind: "remote",
|
|
1587
|
+
id,
|
|
1588
|
+
version,
|
|
1589
|
+
[AGENT_RUNTIME]: runtime,
|
|
1590
|
+
async run(input: AgentInput, opts: RunOptions = {}) {
|
|
1591
|
+
return root(await runtime.open(input, opts, opts.runId ?? crypto.randomUUID()), opts);
|
|
1592
|
+
},
|
|
1593
|
+
async resume(raw: unknown, opts: ResumeOptions) {
|
|
1594
|
+
checkRunOptions(opts, true);
|
|
1595
|
+
const snapshot = runtime.restore(raw),
|
|
1596
|
+
answers = readAnswers(snapshot, opts.answers ?? {});
|
|
1597
|
+
await authorizeTree(snapshot, opts.host);
|
|
1598
|
+
snapshot.attemptId = crypto.randomUUID();
|
|
1599
|
+
return root(snapshot, opts, answers);
|
|
1600
|
+
},
|
|
1601
|
+
async cancel(raw: unknown, opts: ResumeOptions) {
|
|
1602
|
+
checkRunOptions(opts, true);
|
|
1603
|
+
if (opts.answers && Object.keys(opts.answers).length)
|
|
1604
|
+
throw new TypeError("Cancellation is not an answer.");
|
|
1605
|
+
const snapshot = runtime.restore(raw);
|
|
1606
|
+
await authorizeTree(snapshot, opts.host);
|
|
1607
|
+
const tree = new ExecutionTree(snapshot, opts);
|
|
1608
|
+
try {
|
|
1609
|
+
await cancelTask(
|
|
1610
|
+
snapshot,
|
|
1611
|
+
opts,
|
|
1612
|
+
{ tree, depth: 0, path: [] },
|
|
1613
|
+
opts.signal ?? new AbortController().signal,
|
|
1614
|
+
);
|
|
1615
|
+
return copyData(snapshot);
|
|
1616
|
+
} finally {
|
|
1617
|
+
tree.close();
|
|
1618
|
+
}
|
|
1619
|
+
},
|
|
1620
|
+
asTool(tool: SpecialistToolOptions<T | string | RemotePending>) {
|
|
1621
|
+
return specialistFailures(
|
|
1622
|
+
defineDelegation({
|
|
1623
|
+
...tool,
|
|
1624
|
+
inputSchema: {
|
|
1625
|
+
type: "object",
|
|
1626
|
+
properties: {
|
|
1627
|
+
input: { type: "string" },
|
|
1628
|
+
...(definition.inputRequired === "parent" ? { continue: { type: "string" } } : {}),
|
|
1629
|
+
},
|
|
1630
|
+
required: ["input"],
|
|
1631
|
+
additionalProperties: false,
|
|
1632
|
+
},
|
|
1633
|
+
specialists: [remote],
|
|
1634
|
+
validate: remoteInput,
|
|
1635
|
+
async run(input, context) {
|
|
1636
|
+
if (input.continue && definition.inputRequired !== "parent")
|
|
1637
|
+
throw new TypeError("This specialist does not route questions through its parent.");
|
|
1638
|
+
const result = await context.child("result", remote, input).join();
|
|
1639
|
+
if (result.status !== "completed") {
|
|
1640
|
+
const state = result.snapshot.state;
|
|
1641
|
+
if (state.status === "running" || state.status === "completed")
|
|
1642
|
+
throw new TypeError("Invalid remote outcome.");
|
|
1643
|
+
throw new Halt(state);
|
|
1644
|
+
}
|
|
1645
|
+
return result.output;
|
|
1646
|
+
},
|
|
1647
|
+
}),
|
|
1648
|
+
);
|
|
1649
|
+
},
|
|
1650
|
+
});
|
|
1651
|
+
return remote;
|
|
1652
|
+
}
|