@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.
Files changed (296) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/README.md +2328 -2
  4. package/THIRD_PARTY_NOTICES.md +521 -0
  5. package/dist/a2a/auth.d.ts +10 -0
  6. package/dist/a2a/auth.d.ts.map +1 -0
  7. package/dist/a2a/auth.js +52 -0
  8. package/dist/a2a/auth.js.map +1 -0
  9. package/dist/a2a/client.d.ts +74 -0
  10. package/dist/a2a/client.d.ts.map +1 -0
  11. package/dist/a2a/client.js +601 -0
  12. package/dist/a2a/client.js.map +1 -0
  13. package/dist/a2a/index.d.ts +22 -0
  14. package/dist/a2a/index.d.ts.map +1 -0
  15. package/dist/a2a/index.js +11 -0
  16. package/dist/a2a/index.js.map +1 -0
  17. package/dist/a2a/memory-runs.d.ts +62 -0
  18. package/dist/a2a/memory-runs.d.ts.map +1 -0
  19. package/dist/a2a/memory-runs.js +349 -0
  20. package/dist/a2a/memory-runs.js.map +1 -0
  21. package/dist/a2a/policy.d.ts +15 -0
  22. package/dist/a2a/policy.d.ts.map +1 -0
  23. package/dist/a2a/policy.js +114 -0
  24. package/dist/a2a/policy.js.map +1 -0
  25. package/dist/a2a/push.d.ts +34 -0
  26. package/dist/a2a/push.d.ts.map +1 -0
  27. package/dist/a2a/push.js +180 -0
  28. package/dist/a2a/push.js.map +1 -0
  29. package/dist/a2a/remote.d.ts +155 -0
  30. package/dist/a2a/remote.d.ts.map +1 -0
  31. package/dist/a2a/remote.js +1196 -0
  32. package/dist/a2a/remote.js.map +1 -0
  33. package/dist/a2a/server.d.ts +110 -0
  34. package/dist/a2a/server.d.ts.map +1 -0
  35. package/dist/a2a/server.js +1139 -0
  36. package/dist/a2a/server.js.map +1 -0
  37. package/dist/a2a/signing.d.ts +21 -0
  38. package/dist/a2a/signing.d.ts.map +1 -0
  39. package/dist/a2a/signing.js +305 -0
  40. package/dist/a2a/signing.js.map +1 -0
  41. package/dist/a2a/tasks.d.ts +88 -0
  42. package/dist/a2a/tasks.d.ts.map +1 -0
  43. package/dist/a2a/tasks.js +170 -0
  44. package/dist/a2a/tasks.js.map +1 -0
  45. package/dist/a2a/wire.d.ts +267 -0
  46. package/dist/a2a/wire.d.ts.map +1 -0
  47. package/dist/a2a/wire.js +1202 -0
  48. package/dist/a2a/wire.js.map +1 -0
  49. package/dist/background-types.d.ts +76 -0
  50. package/dist/background-types.d.ts.map +1 -0
  51. package/dist/background-types.js +2 -0
  52. package/dist/background-types.js.map +1 -0
  53. package/dist/child.d.ts +25 -0
  54. package/dist/child.d.ts.map +1 -0
  55. package/dist/child.js +129 -0
  56. package/dist/child.js.map +1 -0
  57. package/dist/code-driver.d.ts +40 -0
  58. package/dist/code-driver.d.ts.map +1 -0
  59. package/dist/code-driver.js +2 -0
  60. package/dist/code-driver.js.map +1 -0
  61. package/dist/code-mode.d.ts +3 -0
  62. package/dist/code-mode.d.ts.map +1 -0
  63. package/dist/code-mode.js +2 -0
  64. package/dist/code-mode.js.map +1 -0
  65. package/dist/code-script.d.ts +3 -0
  66. package/dist/code-script.d.ts.map +1 -0
  67. package/dist/code-script.js +149 -0
  68. package/dist/code-script.js.map +1 -0
  69. package/dist/code.d.ts +75 -0
  70. package/dist/code.d.ts.map +1 -0
  71. package/dist/code.js +326 -0
  72. package/dist/code.js.map +1 -0
  73. package/dist/compaction.d.ts +15 -0
  74. package/dist/compaction.d.ts.map +1 -0
  75. package/dist/compaction.js +168 -0
  76. package/dist/compaction.js.map +1 -0
  77. package/dist/delegation.d.ts +135 -0
  78. package/dist/delegation.d.ts.map +1 -0
  79. package/dist/delegation.js +401 -0
  80. package/dist/delegation.js.map +1 -0
  81. package/dist/evals/driver.d.ts +10 -0
  82. package/dist/evals/driver.d.ts.map +1 -0
  83. package/dist/evals/driver.js +192 -0
  84. package/dist/evals/driver.js.map +1 -0
  85. package/dist/evals/journal.d.ts +26 -0
  86. package/dist/evals/journal.d.ts.map +1 -0
  87. package/dist/evals/journal.js +483 -0
  88. package/dist/evals/journal.js.map +1 -0
  89. package/dist/evals/judge.d.ts +31 -0
  90. package/dist/evals/judge.d.ts.map +1 -0
  91. package/dist/evals/judge.js +142 -0
  92. package/dist/evals/judge.js.map +1 -0
  93. package/dist/evals/report.d.ts +38 -0
  94. package/dist/evals/report.d.ts.map +1 -0
  95. package/dist/evals/report.js +241 -0
  96. package/dist/evals/report.js.map +1 -0
  97. package/dist/evals/runner.d.ts +24 -0
  98. package/dist/evals/runner.d.ts.map +1 -0
  99. package/dist/evals/runner.js +655 -0
  100. package/dist/evals/runner.js.map +1 -0
  101. package/dist/evals/scorers.d.ts +36 -0
  102. package/dist/evals/scorers.d.ts.map +1 -0
  103. package/dist/evals/scorers.js +259 -0
  104. package/dist/evals/scorers.js.map +1 -0
  105. package/dist/evals/simulation.d.ts +7 -0
  106. package/dist/evals/simulation.d.ts.map +1 -0
  107. package/dist/evals/simulation.js +38 -0
  108. package/dist/evals/simulation.js.map +1 -0
  109. package/dist/evals/testing.d.ts +36 -0
  110. package/dist/evals/testing.d.ts.map +1 -0
  111. package/dist/evals/testing.js +87 -0
  112. package/dist/evals/testing.js.map +1 -0
  113. package/dist/evals/trajectory.d.ts +11 -0
  114. package/dist/evals/trajectory.d.ts.map +1 -0
  115. package/dist/evals/trajectory.js +180 -0
  116. package/dist/evals/trajectory.js.map +1 -0
  117. package/dist/evals/types.d.ts +431 -0
  118. package/dist/evals/types.d.ts.map +1 -0
  119. package/dist/evals/types.js +4 -0
  120. package/dist/evals/types.js.map +1 -0
  121. package/dist/evals.d.ts +14 -0
  122. package/dist/evals.d.ts.map +1 -0
  123. package/dist/evals.js +9 -0
  124. package/dist/evals.js.map +1 -0
  125. package/dist/extensions.d.ts +33 -0
  126. package/dist/extensions.d.ts.map +1 -0
  127. package/dist/extensions.js +188 -0
  128. package/dist/extensions.js.map +1 -0
  129. package/dist/handoff.d.ts +58 -0
  130. package/dist/handoff.d.ts.map +1 -0
  131. package/dist/handoff.js +160 -0
  132. package/dist/handoff.js.map +1 -0
  133. package/dist/index.d.ts +19 -0
  134. package/dist/index.d.ts.map +1 -0
  135. package/dist/index.js +11 -0
  136. package/dist/index.js.map +1 -0
  137. package/dist/input.d.ts +42 -0
  138. package/dist/input.d.ts.map +1 -0
  139. package/dist/input.js +266 -0
  140. package/dist/input.js.map +1 -0
  141. package/dist/mcp.d.ts +77 -0
  142. package/dist/mcp.d.ts.map +1 -0
  143. package/dist/mcp.js +505 -0
  144. package/dist/mcp.js.map +1 -0
  145. package/dist/memory-store.d.ts +11 -0
  146. package/dist/memory-store.d.ts.map +1 -0
  147. package/dist/memory-store.js +272 -0
  148. package/dist/memory-store.js.map +1 -0
  149. package/dist/memory.d.ts +212 -0
  150. package/dist/memory.d.ts.map +1 -0
  151. package/dist/memory.js +613 -0
  152. package/dist/memory.js.map +1 -0
  153. package/dist/otel.d.ts +74 -0
  154. package/dist/otel.d.ts.map +1 -0
  155. package/dist/otel.js +427 -0
  156. package/dist/otel.js.map +1 -0
  157. package/dist/progress.d.ts +17 -0
  158. package/dist/progress.d.ts.map +1 -0
  159. package/dist/progress.js +193 -0
  160. package/dist/progress.js.map +1 -0
  161. package/dist/quickjs.d.ts +19 -0
  162. package/dist/quickjs.d.ts.map +1 -0
  163. package/dist/quickjs.js +519 -0
  164. package/dist/quickjs.js.map +1 -0
  165. package/dist/recovery.d.ts +10 -0
  166. package/dist/recovery.d.ts.map +1 -0
  167. package/dist/recovery.js +62 -0
  168. package/dist/recovery.js.map +1 -0
  169. package/dist/request.d.ts +88 -0
  170. package/dist/request.d.ts.map +1 -0
  171. package/dist/request.js +422 -0
  172. package/dist/request.js.map +1 -0
  173. package/dist/run.d.ts +20 -0
  174. package/dist/run.d.ts.map +1 -0
  175. package/dist/run.js +2407 -0
  176. package/dist/run.js.map +1 -0
  177. package/dist/runs.d.ts +110 -0
  178. package/dist/runs.d.ts.map +1 -0
  179. package/dist/runs.js +438 -0
  180. package/dist/runs.js.map +1 -0
  181. package/dist/schema-to-ts.d.ts +4 -0
  182. package/dist/schema-to-ts.d.ts.map +1 -0
  183. package/dist/schema-to-ts.js +191 -0
  184. package/dist/schema-to-ts.js.map +1 -0
  185. package/dist/session.d.ts +23 -0
  186. package/dist/session.d.ts.map +1 -0
  187. package/dist/session.js +137 -0
  188. package/dist/session.js.map +1 -0
  189. package/dist/snapshot.d.ts +75 -0
  190. package/dist/snapshot.d.ts.map +1 -0
  191. package/dist/snapshot.js +1607 -0
  192. package/dist/snapshot.js.map +1 -0
  193. package/dist/steering.d.ts +75 -0
  194. package/dist/steering.d.ts.map +1 -0
  195. package/dist/steering.js +214 -0
  196. package/dist/steering.js.map +1 -0
  197. package/dist/subagents.d.ts +141 -0
  198. package/dist/subagents.d.ts.map +1 -0
  199. package/dist/subagents.js +746 -0
  200. package/dist/subagents.js.map +1 -0
  201. package/dist/tool-retry.d.ts +12 -0
  202. package/dist/tool-retry.d.ts.map +1 -0
  203. package/dist/tool-retry.js +53 -0
  204. package/dist/tool-retry.js.map +1 -0
  205. package/dist/tree.d.ts +98 -0
  206. package/dist/tree.d.ts.map +1 -0
  207. package/dist/tree.js +320 -0
  208. package/dist/tree.js.map +1 -0
  209. package/dist/types.d.ts +1007 -0
  210. package/dist/types.d.ts.map +1 -0
  211. package/dist/types.js +2 -0
  212. package/dist/types.js.map +1 -0
  213. package/dist/workflow-snapshot.d.ts +8 -0
  214. package/dist/workflow-snapshot.d.ts.map +1 -0
  215. package/dist/workflow-snapshot.js +276 -0
  216. package/dist/workflow-snapshot.js.map +1 -0
  217. package/dist/workflow-types.d.ts +171 -0
  218. package/dist/workflow-types.d.ts.map +1 -0
  219. package/dist/workflow-types.js +2 -0
  220. package/dist/workflow-types.js.map +1 -0
  221. package/dist/workflow.d.ts +19 -0
  222. package/dist/workflow.d.ts.map +1 -0
  223. package/dist/workflow.js +1053 -0
  224. package/dist/workflow.js.map +1 -0
  225. package/examples/a2a-remote.ts +85 -0
  226. package/examples/a2a-server.ts +100 -0
  227. package/examples/background.ts +59 -0
  228. package/examples/basic.ts +44 -0
  229. package/examples/code-mode.ts +76 -0
  230. package/examples/conversation.ts +57 -0
  231. package/examples/evals.ts +79 -0
  232. package/examples/guardrails.ts +56 -0
  233. package/examples/handoff.ts +79 -0
  234. package/examples/memory.ts +44 -0
  235. package/examples/otel.ts +99 -0
  236. package/examples/specialists.ts +99 -0
  237. package/examples/steering.ts +69 -0
  238. package/examples/structured-handoff.ts +92 -0
  239. package/examples/subagents.ts +127 -0
  240. package/examples/workflow.ts +74 -0
  241. package/package.json +114 -4
  242. package/src/a2a/auth.ts +62 -0
  243. package/src/a2a/client.ts +733 -0
  244. package/src/a2a/index.ts +74 -0
  245. package/src/a2a/memory-runs.ts +448 -0
  246. package/src/a2a/policy.ts +148 -0
  247. package/src/a2a/push.ts +251 -0
  248. package/src/a2a/remote.ts +1652 -0
  249. package/src/a2a/server.ts +1390 -0
  250. package/src/a2a/signing.ts +348 -0
  251. package/src/a2a/tasks.ts +260 -0
  252. package/src/a2a/wire.ts +1443 -0
  253. package/src/background-types.ts +86 -0
  254. package/src/child.ts +181 -0
  255. package/src/code-driver.ts +48 -0
  256. package/src/code-mode.ts +12 -0
  257. package/src/code-script.ts +149 -0
  258. package/src/code.ts +424 -0
  259. package/src/compaction.ts +212 -0
  260. package/src/delegation.ts +694 -0
  261. package/src/evals/driver.ts +222 -0
  262. package/src/evals/journal.ts +605 -0
  263. package/src/evals/judge.ts +188 -0
  264. package/src/evals/report.ts +295 -0
  265. package/src/evals/runner.ts +826 -0
  266. package/src/evals/scorers.ts +339 -0
  267. package/src/evals/simulation.ts +46 -0
  268. package/src/evals/testing.ts +126 -0
  269. package/src/evals/trajectory.ts +223 -0
  270. package/src/evals/types.ts +463 -0
  271. package/src/evals.ts +72 -0
  272. package/src/extensions.ts +247 -0
  273. package/src/handoff.ts +214 -0
  274. package/src/index.ts +62 -0
  275. package/src/input.ts +319 -0
  276. package/src/mcp.ts +690 -0
  277. package/src/memory-store.ts +366 -0
  278. package/src/memory.ts +893 -0
  279. package/src/otel.ts +568 -0
  280. package/src/progress.ts +214 -0
  281. package/src/quickjs.ts +524 -0
  282. package/src/recovery.ts +90 -0
  283. package/src/request.ts +513 -0
  284. package/src/run.ts +3199 -0
  285. package/src/runs.ts +696 -0
  286. package/src/schema-to-ts.ts +194 -0
  287. package/src/session.ts +178 -0
  288. package/src/snapshot.ts +2099 -0
  289. package/src/steering.ts +329 -0
  290. package/src/subagents.ts +1084 -0
  291. package/src/tool-retry.ts +86 -0
  292. package/src/tree.ts +366 -0
  293. package/src/types.ts +944 -0
  294. package/src/workflow-snapshot.ts +366 -0
  295. package/src/workflow-types.ts +213 -0
  296. package/src/workflow.ts +1316 -0
package/src/types.ts ADDED
@@ -0,0 +1,944 @@
1
+ import type {
2
+ ChatMessage,
3
+ ContentPart,
4
+ FileMimeType,
5
+ ImageMimeType,
6
+ ImagePart,
7
+ JsonObjectSchema,
8
+ Provider,
9
+ ProviderChunk,
10
+ StreamOptions,
11
+ TokenUsage,
12
+ Tool,
13
+ ToolCall,
14
+ ToolContext,
15
+ ToolDefinition,
16
+ ToolFailure,
17
+ Turn,
18
+ } from "@providerkit/core";
19
+
20
+ import type {
21
+ AgentMemory,
22
+ MemoryBinding,
23
+ MemoryPolicy,
24
+ MemoryRecall,
25
+ MemoryScopes,
26
+ } from "./memory.ts";
27
+ import type { ClientTool } from "./request.ts";
28
+ import type { CodeTool, CodeLimits } from "./code.ts";
29
+ import type { WorkflowSnapshot, StepRequest, StepKind, StepError } from "./workflow-types.ts";
30
+ export type { WorkflowSnapshot, StepRequest, StepKind, StepError } from "./workflow-types.ts";
31
+ import type { RemoteSnapshot, RemoteReceipt } from "./a2a/remote.ts";
32
+ export type TreeNode = RunSnapshot | WorkflowSnapshot | RemoteSnapshot;
33
+ import type { SubagentRecord } from "./subagents.ts";
34
+ import type { InputInbox, InputReceipt, RunInput } from "./steering.ts";
35
+ import type { Handoff } from "./handoff.ts";
36
+ import type {
37
+ AGENT_RUNTIME,
38
+ AgentRuntime,
39
+ Delegation,
40
+ SpecialistToolOptions,
41
+ } from "./delegation.ts";
42
+
43
+ /** Tree limits count the root too, except maxChildren and maxDepth (root depth is zero). */
44
+ export interface TreeLimits {
45
+ maxParallel: number;
46
+ maxChildren: number;
47
+ maxDepth: number;
48
+ /** SDK admissions only. Provider-internal retries stay in core. */
49
+ modelCalls: number;
50
+ /** Includes queueing and waiting for approval, across resumed attempts. */
51
+ elapsedMs: number;
52
+ }
53
+
54
+ /** Limits for one run, not a whole tree of delegated runs. Cancellation is cooperative:
55
+ * an admitted call can still finish or incur a charge after the signal aborts. */
56
+ export interface RunLimits {
57
+ /** Tool-capable model turns. Text agents may make one final tool-free call, still counted
58
+ * against the tree's model-call budget. Checked-output agents keep the hard cap. */
59
+ turns: number;
60
+ toolCalls: number;
61
+ /** Wall time, including time spent waiting for approval. */
62
+ elapsedMs: number;
63
+ parallelTools: number;
64
+ /** Decoded bytes of the images and files sent inline, history and new turn together. The
65
+ * snapshot holds them, and every checkpoint writes the whole snapshot again, so large files
66
+ * belong behind a MediaRef. Zero accepts media references only. */
67
+ inlineBytes: number;
68
+ }
69
+
70
+ /** Bytes the host keeps under an id. The SDK stores only the reference and asks
71
+ * `host.loadMedia` for the bytes right before each model call. The bytes behind an id must
72
+ * never change: an earlier byte that changes re-bills the provider's whole prompt cache. */
73
+ export interface MediaRef {
74
+ type: "media";
75
+ id: string;
76
+ mimeType: ImageMimeType | FileMimeType;
77
+ }
78
+
79
+ /** Core's text, image and file parts, plus media the host keeps. */
80
+ export type InputPart = ContentPart | MediaRef;
81
+
82
+ /** One user turn: text, or parts with images and files. */
83
+ export type UserContent = string | InputPart[];
84
+
85
+ /** Core's messages without the system prompt, which stays the agent's. A user message may
86
+ * hold media references. */
87
+ export type AgentMessage =
88
+ | { role: "user"; content: UserContent }
89
+ | Extract<ChatMessage, { role: "assistant" | "tool" }>;
90
+
91
+ /** A new turn, or a whole conversation whose last message is the new user turn. */
92
+ export type AgentInput =
93
+ | string
94
+ | readonly InputPart[]
95
+ | { readonly messages: readonly AgentMessage[] };
96
+
97
+ /** What a run asks its session to append once it settles. */
98
+ export interface SessionTurn {
99
+ /** The logical run id, which is the idempotency key. Repeating the same turn (same runId,
100
+ * after and messages) must succeed without writing; the same runId with anything else must
101
+ * throw SessionConflictError. */
102
+ runId: string;
103
+ /** The revision the history was loaded at, or null when the session was empty. */
104
+ after: string | null;
105
+ /** The new user turn and the run's settled rounds, never the system prompt. */
106
+ messages: AgentMessage[];
107
+ }
108
+
109
+ /** A trusted, server-side conversation store. Every method is required. */
110
+ export interface Session {
111
+ readonly id: string;
112
+ /** The newest `limit` messages, or all of them, oldest first, with the revision they belong
113
+ * to. A window may start inside a tool round; the run repairs it before sending. */
114
+ load(options: {
115
+ limit?: number;
116
+ signal: AbortSignal;
117
+ }): Promise<{ messages: AgentMessage[]; revision: string | null }>;
118
+ /** Atomic. Throw SessionConflictError when `after` is not the current revision, or when
119
+ * `runId` already appended a different turn. Write nothing when you throw. */
120
+ append(turn: SessionTurn, options: { signal: AbortSignal }): Promise<{ revision: string }>;
121
+ }
122
+
123
+ /** Whether the session has this run's turn. `pending`: not appended yet, because the run is
124
+ * waiting, its last checkpoint failed, or it was resumed without its session. */
125
+ export type SessionStatus = { id: string } & (
126
+ | { status: "saved"; revision: string }
127
+ | { status: "pending" }
128
+ | { status: "unsaved"; error: RunFailure }
129
+ );
130
+
131
+ export interface ResultSchema<T> {
132
+ schema: JsonObjectSchema;
133
+ /** Pure runtime validation. Throw to reject; also used when restoring a result. */
134
+ validate: (value: unknown) => T;
135
+ }
136
+
137
+ /** Core's call settings. Cancellation, conversation identity and checked output stay with
138
+ * the loop. Provider defaults apply first, then agent settings, then run settings. */
139
+ export type ModelSettings = Omit<StreamOptions, "signal" | "sessionId" | "json">;
140
+
141
+ /** Observers do not change the request and cannot be saved as JSON. */
142
+ export type RecordedModelSettings = Omit<ModelSettings, "onActivity" | "onRateLimit">;
143
+
144
+ /** Available while resolving a new run, never reconstructed from a snapshot. The history
145
+ * and input are frozen copies. context keeps host services by reference, like tool context. */
146
+ export interface RunContext {
147
+ readonly agentId: string;
148
+ readonly version: string;
149
+ readonly runId: string;
150
+ readonly history: readonly AgentMessage[];
151
+ readonly input: UserContent;
152
+ readonly context: ToolContext;
153
+ readonly signal: AbortSignal;
154
+ }
155
+
156
+ /** Dynamic instruction shape adapted from OpenAI Agents JS (MIT), agent.ts. */
157
+ export type AgentInstructions = string | ((run: RunContext) => string | Promise<string>);
158
+
159
+ /** Names from this agent's fixed tool list. Resolved once, not on every model turn. */
160
+ export type EnabledTools =
161
+ | readonly string[]
162
+ | ((run: RunContext) => readonly string[] | Promise<readonly string[]>);
163
+
164
+ /** Trusted host assertions, never inferred from model output or an idempotency key. */
165
+ export interface RecoveryPolicy {
166
+ /** Change when hidden provider defaults, hosted capabilities or tool implementations change. */
167
+ identity: string;
168
+ /** Total attempts per operation, including the first. Tree and local limits still apply. */
169
+ maxAttempts: number;
170
+ /** Assert that this provider profile performs inference only, with no hosted effects. */
171
+ inferenceOnly?: boolean;
172
+ /** Explicit allow-list of ordinary isReadOnly tools. Calls with human requests cannot replay. */
173
+ readOnlyTools?: readonly string[];
174
+ }
175
+
176
+ export interface RecoveryDefinition {
177
+ policy: RecoveryPolicy;
178
+ provider: { id: string; model: string };
179
+ /** Definitions advertised to the model, including the output schema. */
180
+ modelToolsHash: string;
181
+ toolHashes: Record<string, string>;
182
+ }
183
+
184
+ /** Callback context is host-only. Hidden calls inside callbacks do not use SDK tree budgets. */
185
+ export interface LifecycleContext {
186
+ readonly agentId: string;
187
+ readonly version: string;
188
+ readonly runId: string;
189
+ readonly attemptId: string;
190
+ readonly context: ToolContext;
191
+ readonly signal: AbortSignal;
192
+ }
193
+
194
+ export interface ModelProviderScope {
195
+ readonly run: LifecycleContext;
196
+ readonly operationId: string;
197
+ readonly operationAttemptId: string;
198
+ readonly purpose: "turn" | "compaction";
199
+ }
200
+
201
+ /** Synchronous instrumentation binding at the final dispatch boundary. Never starts a call,
202
+ * changes routing or grants permission. A failure before dispatch leaves the provider unchanged. */
203
+ export type ModelProviderBinding = (provider: Provider, scope: ModelProviderScope) => Provider;
204
+
205
+ export interface ModelInput {
206
+ messages: ChatMessage[];
207
+ tools: ToolDefinition[];
208
+ settings: RecordedModelSettings;
209
+ }
210
+
211
+ /** Blocking checks, adapted from OpenAI Agents JS (MIT), guardrail.ts. No parallel tripwire:
212
+ * an input must pass before dispatch, and an output before ordinary progress or history. */
213
+ export interface GuardInputs {
214
+ modelInput: ModelInput;
215
+ modelOutput: Turn;
216
+ toolInput: ToolRequest;
217
+ toolOutput: { request: ToolRequest; result: ToolResult };
218
+ }
219
+ export type GuardStage = keyof GuardInputs;
220
+ export type GuardVerdict = { allow: true } | { allow: false };
221
+ export type Guardrail<K extends GuardStage> = (
222
+ input: GuardInputs[K],
223
+ context: LifecycleContext,
224
+ ) => GuardVerdict | Promise<GuardVerdict>;
225
+
226
+ /** Model-only history trimming. The full journal and session turn are never shortened. */
227
+ export interface CompactionPolicy {
228
+ /** Change when the summary prompt or hidden provider configuration changes. */
229
+ identity: string;
230
+ /** Supply the actual window for the configured model. No model-name guessing. */
231
+ contextWindow: number;
232
+ /** Recent tokens to keep. Core's historyBudgetTokens(contextWindow) is the default. */
233
+ keepTokens?: number;
234
+ /** Omit to trim without a paid call. This provider must do inference only. The SDK sends
235
+ * no tools, allows one attempt, counts usage and refuses interrupted summarization. */
236
+ summarize?: { provider: Provider; instructions: string; maxTokens: number };
237
+ }
238
+ export interface CompactionDefinition {
239
+ identity: string;
240
+ contextWindow: number;
241
+ keepTokens: number;
242
+ summarize: {
243
+ provider: { id: string; model: string };
244
+ instructions: string;
245
+ maxTokens: number;
246
+ } | null;
247
+ }
248
+ export type CompactionExecution = {
249
+ id: string;
250
+ beforeModel: number;
251
+ /** Count and cut in the full conversation, not in the shortened model view. */
252
+ sourceCount: number;
253
+ cut: number;
254
+ model?: ModelExecution;
255
+ } & ({ status: "running" } | { status: "completed"; summary: string });
256
+
257
+ /** Per-operation budgets adapted from PydanticAI's tool_manager.py (MIT). No retries by
258
+ * default. These retry settled failures only; crash recovery remains a separate policy. */
259
+ export interface ToolRetryPolicy {
260
+ identity: string;
261
+ tools: Record<
262
+ string,
263
+ {
264
+ /** Includes the first attempt and any crash recovery attempts. */
265
+ maxAttempts: number;
266
+ /** read-only also requires isReadOnly; reconcile requires host.reconcileToolRetry. */
267
+ replay: "read-only" | "reconcile";
268
+ }
269
+ >;
270
+ }
271
+ export interface ToolRetryDefinition {
272
+ policy: ToolRetryPolicy;
273
+ toolHashes: Record<string, string>;
274
+ }
275
+ export interface RetriedToolAttempt {
276
+ attemptId: string;
277
+ arguments: Record<string, unknown>;
278
+ result: Extract<ToolResult, { ok: false }>;
279
+ /** Host receipt proving this attempt did not run, not an unenforced idempotency key. */
280
+ reconciliation?: string;
281
+ }
282
+
283
+ /** Node-local policy. Configure each specialist/target separately. Callbacks cannot edit data,
284
+ * grant tool access or replace request decisions. Change identity when policy code changes. */
285
+ export type Guardrails = { [K in GuardStage]?: Guardrail<K> } & {
286
+ identity: string;
287
+ /** UTF-8 JSON bytes across model chunks, or in one tool result. Default 1,000,000.
288
+ * Guarded model streams also stop at 4,096 chunks. No protected delta is sent before allow. */
289
+ maxOutputBytes?: number;
290
+ };
291
+ export interface GuardDefinition {
292
+ identity: string;
293
+ stages: GuardStage[];
294
+ maxOutputBytes: number;
295
+ }
296
+ export interface GuardRecord {
297
+ stage: GuardStage;
298
+ operationId: string;
299
+ attemptId: string;
300
+ /** Hash of the checked value; no rejected content or callback exception is saved here. */
301
+ inputHash: string;
302
+ status: "running" | "allowed" | "rejected" | "failed";
303
+ }
304
+
305
+ /** Privileged host inspection, NOT safe display output. End hooks see raw output before its
306
+ * guard. Hooks are ordered and awaited, but exceptions/return values never authorize or block.
307
+ * They may repeat after a crash. Use guards for policy and onEvent for checked progress. */
308
+ export type LifecycleEvent =
309
+ | { type: "run_start" }
310
+ | { type: "run_end"; state: RunState }
311
+ | { type: "model_start"; operationId: string; attemptId: string; input: ModelInput }
312
+ | { type: "model_end"; operationId: string; attemptId: string; turn: Turn }
313
+ | { type: "model_error"; operationId: string; attemptId: string }
314
+ | { type: "tool_start"; request: ToolRequest }
315
+ | { type: "tool_end"; request: ToolRequest; result: ToolResult }
316
+ | { type: "tool_error"; request: ToolRequest };
317
+ export type LifecycleHook = (
318
+ event: LifecycleEvent,
319
+ context: LifecycleContext,
320
+ ) => void | Promise<void>;
321
+
322
+ /** The resolved definition used for every turn, including after a restart. No host context
323
+ * or callbacks: they can contain credentials and process-local services. */
324
+ /** Data needed to validate stored program calls. It contains no driver, tool body or authority. */
325
+ export interface RecordedCodeTool {
326
+ name: string;
327
+ limits: CodeLimits;
328
+ tools: { name: string; isReadOnly: boolean }[];
329
+ }
330
+
331
+ export interface RunDefinition {
332
+ instructions: string;
333
+ modelSettings: RecordedModelSettings;
334
+ enabledTools: string[];
335
+ stopAtTools: string[];
336
+ /** Present for registered code tools, including ones disabled for this run. */
337
+ codeTools?: Record<string, RecordedCodeTool>;
338
+ /** Null refuses interrupted effects. Recorded policy and identities must match on recovery. */
339
+ recovery: RecoveryDefinition | null;
340
+ guardrails: GuardDefinition | null;
341
+ compaction: CompactionDefinition | null;
342
+ toolRetries: ToolRetryDefinition | null;
343
+ /** Recall policy only. Memory tools are explicit registered tools, never implicit grants. */
344
+ memory?: MemoryPolicy;
345
+ }
346
+
347
+ export interface AgentConfig<H = unknown> {
348
+ id: string;
349
+ /** Change this when instructions, tools or output contracts change. */
350
+ version: string;
351
+ /** A function runs once when the run is created; resume uses the recorded text. */
352
+ instructions: AgentInstructions;
353
+ /** Already composed with whatever routing, retries and watchdog the caller needs. */
354
+ provider: Provider;
355
+ modelSettings?: ModelSettings;
356
+ /** Opt in before starting a run. Never retries a settled failure or an unknown write. */
357
+ recovery?: RecoveryPolicy;
358
+ guardrails?: Guardrails;
359
+ compaction?: CompactionPolicy;
360
+ toolRetries?: ToolRetryPolicy;
361
+ /** Bounded recall, recorded before the first model call. Requires host-supplied memory. */
362
+ memory?: AgentMemory | true;
363
+ /** Host-only observer. Runs before RunOptions.onLifecycle at each boundary. */
364
+ onLifecycle?: LifecycleHook;
365
+ /** Core tools, client tools, code tools, delegations or handoffs. Terminal tools and handoffs
366
+ * must be called alone. H is the union of the registered targets' output types. */
367
+ tools?: readonly (Tool | Delegation | ClientTool | CodeTool | Handoff<H>)[];
368
+ /** A host policy or allow-list. A run may narrow this list, never widen it. The reserved
369
+ * submit_result tool stays available when there is an output contract. */
370
+ enabledTools?: EnabledTools;
371
+ /** End on the first successful result from these tools, in model call order, after the
372
+ * whole batch settles. Text agents return its summary; checked agents validate its raw
373
+ * output. A failed or invalid result goes back to the model. */
374
+ stopAtTools?: readonly string[];
375
+ limits?: Partial<RunLimits>;
376
+ /** Applies when this agent is the root. Descendants share the root's limits. */
377
+ treeLimits?: Partial<TreeLimits>;
378
+ }
379
+
380
+ /** T is this agent's output. H is its handoff targets' output, never checked as T. */
381
+ export type AgentDefinition<T = string, H = never> = AgentConfig<H> & { output?: ResultSchema<T> };
382
+
383
+ /** T is every possible completed output, including registered handoff chains. */
384
+ export interface Agent<T = string> {
385
+ readonly kind: "agent";
386
+ readonly id: string;
387
+ readonly version: string;
388
+ /** Invalid input throws a TypeError before anything is saved or loaded. */
389
+ run(input: AgentInput, options?: RunOptions): Promise<RunOutcome<T>>;
390
+ /** Structural validation is not authorization. A host must authorize every resume. */
391
+ resume(snapshot: unknown, options: ResumeOptions): Promise<RunOutcome<T>>;
392
+ asTool(options: SpecialistToolOptions<T>): Delegation;
393
+ /** @internal Execution is scoped explicitly, never through global current-run state. */
394
+ readonly [AGENT_RUNTIME]: AgentRuntime<T>;
395
+ }
396
+
397
+ export interface ToolRequest {
398
+ /** Private model-written name, for host policy only. Never a public label or permission. */
399
+ subagent?: string;
400
+ agentId: string;
401
+ version: string;
402
+ runId: string;
403
+ attemptId: string;
404
+ operationId: string;
405
+ /** Present only for a call made by a code program. Never a permission grant. */
406
+ parentOperationId?: string;
407
+ call: ToolCall;
408
+ arguments: Record<string, unknown>;
409
+ }
410
+
411
+ export interface RequestScope {
412
+ actorId: string;
413
+ resource: { id: string; version: string };
414
+ expiresAt: number;
415
+ }
416
+
417
+ export interface Choice {
418
+ id: string;
419
+ label: string;
420
+ description?: string;
421
+ }
422
+
423
+ export interface ApprovalAsk {
424
+ type: "approval";
425
+ message?: string;
426
+ /** Full argument replacement, only when trusted host policy allows it. */
427
+ editable?: boolean;
428
+ approveSchema?: JsonObjectSchema;
429
+ denySchema?: JsonObjectSchema;
430
+ }
431
+
432
+ export interface QuestionAsk {
433
+ type: "question";
434
+ /** Stable within this call. Coordination replays match by key, not call position. */
435
+ key: string;
436
+ message: string;
437
+ choices?: readonly Choice[];
438
+ multiple?: boolean;
439
+ freeText?: boolean;
440
+ /** Describes form data. The host and asker must validate it at runtime. */
441
+ schema?: JsonObjectSchema;
442
+ }
443
+
444
+ export interface ClientAsk {
445
+ type: "client";
446
+ resultSchema: JsonObjectSchema;
447
+ }
448
+
449
+ export type Ask = ApprovalAsk | QuestionAsk | ClientAsk;
450
+
451
+ export type RequestOrigin =
452
+ | { call: ToolRequest; step?: never }
453
+ | { step: StepRequest; call?: never };
454
+
455
+ export type PendingRequest = RequestOrigin & {
456
+ id: string;
457
+ /** Absolute path from the logical root, derived by the SDK, never supplied by the client. */
458
+ path: ChildPathStep[];
459
+ definitionHash: string;
460
+ ask: Ask;
461
+ scope: RequestScope;
462
+ createdAt: number;
463
+ };
464
+
465
+ export interface Answer {
466
+ choices?: string[];
467
+ text?: string;
468
+ data?: unknown;
469
+ }
470
+
471
+ export type Decision =
472
+ | { type: "approve"; arguments?: Record<string, unknown>; data?: unknown; receipt?: string }
473
+ | { type: "deny"; message?: string; data?: unknown; receipt?: string }
474
+ | { type: "answer"; answer: Answer; receipt?: string }
475
+ | { type: "result"; value: unknown; receipt?: string }
476
+ | { type: "cancel"; receipt?: string }
477
+ | { type: "stop"; receipt?: string };
478
+
479
+ export type Resolution = Decision | { type: "pending"; problem?: string };
480
+
481
+ export interface RequestProblem {
482
+ code: "expired" | "stale" | "invalid_answer" | "refused";
483
+ message: string;
484
+ }
485
+
486
+ export interface AskRecord {
487
+ request: PendingRequest;
488
+ /** Written once before any effect. A stored decision is data, not permission. */
489
+ decision?: Decision;
490
+ closed?: "expired" | "stale" | "invalid" | "stopped";
491
+ problem?: RequestProblem;
492
+ }
493
+
494
+ export interface ChildPathStep {
495
+ operationId: string;
496
+ key: string;
497
+ runId: string;
498
+ }
499
+
500
+ export interface ChildEnvelope {
501
+ snapshot: TreeNode;
502
+ /** An opaque host execution segment, not an independently owned SDK run. */
503
+ reference?: string;
504
+ }
505
+
506
+ export interface ChildRequest extends ChildEnvelope {
507
+ key: string;
508
+ parentRunId: string;
509
+ operationId: string;
510
+ /** A stored SDK child needs resuming, not replay of a successful host segment. */
511
+ resume: boolean;
512
+ }
513
+
514
+ /** Host callbacks are trusted code, never functions reconstructed from a client snapshot.
515
+ * Data passed to callbacks is a frozen copy, not the loop's live state. Without checkpoint,
516
+ * execution is in-memory only. Checkpoints are not leases or exactly-once effect guarantees. */
517
+ export interface AgentHost {
518
+ /** New user messages for the root's active conversation owner, never every specialist.
519
+ * A durable host must supply durable authenticated storage. Does not answer human requests. */
520
+ inbox?: InputInbox;
521
+ /** Required progress storage, separate from best-effort onEvent. push synchronously accepts
522
+ * a frozen event into a bounded buffer; flush must report any write failure, not hide it.
523
+ * The loop awaits flush before every checkpoint and final outcome, including children. */
524
+ progress?: {
525
+ push(event: AgentEvent): void;
526
+ flush(): Promise<void>;
527
+ };
528
+ /** Persist the whole snapshot before returning. Writes are serialized within this attempt. */
529
+ checkpoint?: (snapshot: TreeNode) => void | Promise<void>;
530
+ /** Load/compare authoritative state and check ownership and freshness, or throw.
531
+ * The host must also exclude concurrent attempts; this loop does not take a lease. */
532
+ authorizeResume?: (snapshot: TreeNode) => void | Promise<void>;
533
+ /** May require approval for an unmarked tool, never waive a tool's needsApproval. */
534
+ needsApproval?: (call: ToolRequest) => boolean | Promise<boolean>;
535
+ /** Required to open a request. Supplies trusted actor, resource version and expiry.
536
+ * Only an approval's presentation/edit policy may be overridden. */
537
+ prepareRequest?: (
538
+ draft: RequestOrigin & Omit<PendingRequest, "scope" | "call" | "step">,
539
+ ) =>
540
+ | { scope: RequestScope; ask?: ApprovalAsk }
541
+ | Promise<{ scope: RequestScope; ask?: ApprovalAsk }>;
542
+ /** Optional standing host policy. undefined leaves the request pending. */
543
+ answerNow?: (request: PendingRequest) => Decision | undefined | Promise<Decision | undefined>;
544
+ /** Authenticate evidence, validate form data and consume it for this exact request. Recovery
545
+ * of the same host claim must return the same decision; another claim must be refused. */
546
+ resolveRequest?: (request: PendingRequest, evidence: unknown) => Resolution | Promise<Resolution>;
547
+ /** Recheck current access and resource version, with the arguments that will run. Required
548
+ * for every invocation carrying a decision, and before exposing a client-tool request. */
549
+ beforeTool?: (
550
+ call: ToolRequest,
551
+ decided?: { request: PendingRequest; decision: Decision },
552
+ ) => void | Promise<void>;
553
+ /** Authoritatively query the external service for this exact failed attempt. Return not_run
554
+ * only when it cannot still complete. An error string or literal key is not proof. Never
555
+ * dispatch from this callback. Requests and control tools cannot use this retry path. */
556
+ reconcileToolRetry?: (
557
+ attempt: { request: ToolRequest; result: Extract<ToolResult, { ok: false }> },
558
+ context: LifecycleContext,
559
+ ) =>
560
+ | { outcome: "not_run"; receipt: string }
561
+ | { outcome: "unknown" }
562
+ | Promise<{ outcome: "not_run"; receipt: string } | { outcome: "unknown" }>;
563
+ /** Required before every workflow effect or use of an answer. Check current ownership and lease. */
564
+ beforeStep?: (
565
+ step: StepRequest,
566
+ decided?: { request: PendingRequest; decision: Decision },
567
+ ) => void | Promise<void>;
568
+ reconcileStep?: (
569
+ step: StepRequest,
570
+ attempt: { attemptId: string; error?: StepError },
571
+ signal: AbortSignal,
572
+ ) =>
573
+ | { outcome: "not_run"; receipt: string }
574
+ | { outcome: "unknown" }
575
+ | Promise<{ outcome: "not_run"; receipt: string } | { outcome: "unknown" }>;
576
+ /** Both this callback and the tool's isConcurrencySafe flag must allow batching. */
577
+ canRunConcurrently?: (request: ToolRequest) => boolean;
578
+ /** Optional in-process child binding under this root's lease and cancellation.
579
+ * A host may return a saved envelope. To resume a suspended SDK child it must call
580
+ * execute in a new/resumable segment, not treat a cached suspension as completion.
581
+ * execute may be called once, and must settle before the hook returns. */
582
+ child?: (request: ChildRequest, execute: () => Promise<ChildEnvelope>) => Promise<ChildEnvelope>;
583
+ /** Check that this run's owner may read the media, then return its bytes as base64. Called
584
+ * once per id per attempt, before the model call that needs it. An id is not permission. */
585
+ loadMedia?: (
586
+ ref: MediaRef,
587
+ run: { runId: string; signal: AbortSignal },
588
+ ) => string | Promise<string>;
589
+ }
590
+
591
+ export interface RunOptions {
592
+ runId?: string;
593
+ signal?: AbortSignal;
594
+ /** Overrides agent settings for this run. Recorded settings cannot change on resume. */
595
+ modelSettings?: ModelSettings;
596
+ /** Narrows the agent's enabled tools for this run. Resolved once, before saving. */
597
+ enabledTools?: EnabledTools;
598
+ /** Passed to tools with reserved runId, attemptId, operationId, callId and signal supplied by the loop. */
599
+ context?: ToolContext;
600
+ /** Trusted binding from authentication. Never select a scope from model arguments. */
601
+ memory?: MemoryBinding;
602
+ host?: AgentHost;
603
+ /** Best-effort progress from the one stream reader. Observer errors do not stop work. */
604
+ onEvent?: (event: AgentEvent) => void | Promise<void>;
605
+ /** Privileged observer, inherited by children. Return values and failures are ignored. */
606
+ onLifecycle?: LifecycleHook;
607
+ /** Per-dispatch provider instrumentation. Inherited by children, never saved in checkpoints.
608
+ * Does not wrap tool execution or install an ambient async context manager. */
609
+ bindModelProvider?: ModelProviderBinding;
610
+ /** Loads the history once, before the run is saved, and appends the turn once the run
611
+ * settles. The input must then be the new turn only, not `{ messages }`. Never passed to
612
+ * specialists. */
613
+ session?: Session;
614
+ /** How many of the session's newest messages to load. Needs `session`. */
615
+ historyLimit?: number;
616
+ /** Runs once on the loaded or supplied history, before the run is saved, to trim or
617
+ * summarize it. Its result is frozen in the snapshot; resume never calls it again. */
618
+ prepareHistory?: (history: AgentMessage[]) => AgentMessage[] | Promise<AgentMessage[]>;
619
+ }
620
+
621
+ export interface ResumeOptions extends Omit<
622
+ RunOptions,
623
+ "runId" | "session" | "historyLimit" | "prepareHistory" | "modelSettings" | "enabledTools"
624
+ > {
625
+ host: AgentHost & { authorizeResume: NonNullable<AgentHost["authorizeResume"]> };
626
+ /** The run's own session, so the turn is appended once the run settles. Resume never loads
627
+ * it again: the history stays the one the snapshot froze. Another session is refused. */
628
+ session?: Session;
629
+ /** Untrusted JSON evidence by request id. Unknown, closed and already-decided ids are refused. */
630
+ answers?: Readonly<Record<string, unknown>>;
631
+ }
632
+
633
+ export interface RunFailure {
634
+ code: string;
635
+ message: string;
636
+ operationId?: string;
637
+ }
638
+
639
+ export type LimitReason =
640
+ | "turns"
641
+ | "toolCalls"
642
+ | "elapsedMs"
643
+ | "outputTokens"
644
+ | "maxChildren"
645
+ | "maxDepth"
646
+ | "modelCalls"
647
+ | "steps"
648
+ | "treeElapsedMs";
649
+
650
+ export type RunState =
651
+ | { status: "running" }
652
+ /** Saves the original result input, not a validator's potentially non-JSON return value.
653
+ * After a handoff this is the active target's candidate, validated only by that target. */
654
+ | { status: "completed"; candidate: unknown }
655
+ | { status: "suspended" }
656
+ | { status: "cancelled" }
657
+ | { status: "limited"; limit: LimitReason }
658
+ | { status: "failed"; error: RunFailure };
659
+
660
+ export type ToolResult =
661
+ /** final keeps the raw stopping-tool output (or summary for text agents), not the
662
+ * validator's possibly non-JSON return value. Restoring can validate without replay. */
663
+ | {
664
+ ok: true;
665
+ content: string;
666
+ /** Core image parts, forwarded with the text in the next tool message. */
667
+ images?: ImagePart[];
668
+ /** JSON output for trusted host inspection. Not a browser display policy. Rich part
669
+ * arrays use content/images instead so inline bytes are not stored twice. */
670
+ output?: unknown;
671
+ final?: { candidate: unknown };
672
+ }
673
+ | {
674
+ ok: false;
675
+ content: string;
676
+ kind:
677
+ | ToolFailure
678
+ | "denied"
679
+ | "cancelled"
680
+ | "unknown_tool"
681
+ | "disabled_tool"
682
+ | "invalid_output"
683
+ | "interrupted";
684
+ };
685
+
686
+ export interface InterruptedAttempt {
687
+ attemptId: string;
688
+ }
689
+
690
+ /** Last measured usage, not a final bill. An interrupted call may have cost more. */
691
+ export interface InterruptedModelAttempt extends InterruptedAttempt {
692
+ usage: TokenUsage;
693
+ }
694
+
695
+ /** Private inner-call journal. IDs increase across program restarts; old calls never replay. */
696
+ export type ProgramCall = {
697
+ id: string;
698
+ attemptId: string;
699
+ /** The outer program attempt which admitted this call. */
700
+ programAttemptId: string;
701
+ name: string;
702
+ arguments: Record<string, unknown>;
703
+ /** False means dispatch never started, even if this receipt is now completed. */
704
+ started: boolean;
705
+ asks?: AskRecord[];
706
+ interrupted: InterruptedAttempt[];
707
+ retries: RetriedToolAttempt[];
708
+ /** Current attempt's JSON output size, or failure text size. Result content is at most 1 KiB. */
709
+ bytes?: number;
710
+ } & (
711
+ | { status: "pending"; previousAttemptId?: string }
712
+ | { status: "running" }
713
+ | { status: "completed"; result: ToolResult }
714
+ );
715
+
716
+ export type ToolExecution = {
717
+ asks?: AskRecord[];
718
+ /** Code tools only. Kept across a read-only program restart. */
719
+ calls?: ProgramCall[];
720
+ interrupted: InterruptedAttempt[];
721
+ retries: RetriedToolAttempt[];
722
+ } & (
723
+ | {
724
+ id: string;
725
+ status: "pending";
726
+ /** Failed or interrupted attempt being replaced. Saved before replacement admission. */
727
+ previousAttemptId?: string;
728
+ }
729
+ | { id: string; status: "running"; attemptId: string }
730
+ /** Pure coordination can replay. Its children keep their own effect journals. */
731
+ | { id: string; status: "delegating"; attemptId: string }
732
+ | { id: string; status: "completed"; attemptId: string; result: ToolResult }
733
+ );
734
+
735
+ export type ModelExecution = {
736
+ interrupted: InterruptedModelAttempt[];
737
+ billing: "unknown" | "reported";
738
+ } & (
739
+ | { id: string; attemptId: string; status: "running"; usage: TokenUsage }
740
+ | {
741
+ id: string;
742
+ attemptId: string;
743
+ status: "completed";
744
+ usage: TokenUsage;
745
+ turn: Turn;
746
+ tools: ToolExecution[];
747
+ }
748
+ );
749
+
750
+ export interface AgentRef {
751
+ id: string;
752
+ version: string;
753
+ }
754
+
755
+ /** A server-side receipt. The note is model-written context, never authority. */
756
+ export interface HandoffReceipt {
757
+ operationId: string;
758
+ runId: string;
759
+ childRunId: string;
760
+ from: AgentRef;
761
+ to: AgentRef;
762
+ note?: string;
763
+ }
764
+
765
+ export type DelegationExecution = {
766
+ operationId: string;
767
+ /** Admission order is the deterministic join/request order. Receipts are never removed. */
768
+ children: (ChildEnvelope & { key: string })[];
769
+ } & ({ kind: "delegation" } | { kind: "handoff"; target: AgentRef; note?: string });
770
+
771
+ /** JSON-serializable execution journal. Contains private prompts, arguments and results;
772
+ * the host owns storage, access and retention. Never accept it as proof of permission, and
773
+ * never send it to a browser. */
774
+ export interface RunSnapshot {
775
+ kind: "agent";
776
+ format: 3;
777
+ agentId: string;
778
+ version: string;
779
+ runId: string;
780
+ attemptId: string;
781
+ startedAt: number;
782
+ /** Resolved once before the first checkpoint. Resume never reruns definition callbacks. */
783
+ definition: RunDefinition;
784
+ /** Present only for model-created helpers. Private definition and frozen host capabilities. */
785
+ subagent?: SubagentRecord;
786
+ /** Private model-input data, recorded once. Never part of the session transcript. */
787
+ recall?: MemoryRecall;
788
+ /** The conversation before the new turn, repaired once when the run was created and never
789
+ * read again, so every request starts with the same bytes. Never a system message. */
790
+ history: AgentMessage[];
791
+ /** The new user turn. */
792
+ input: UserContent;
793
+ /** Accepted user messages, in order at safe model boundaries. Never replaces frozen input. */
794
+ inputs: RunInput[];
795
+ /** Guard checks are journaled before callbacks and before releasing their checked output. */
796
+ guards: GuardRecord[];
797
+ /** Completed model-view cuts and any in-flight paid summary. Never session edits. */
798
+ compactions: CompactionExecution[];
799
+ /** The session the history came from, and the revision a settled run appends after. */
800
+ session?: { id: string; revision: string | null };
801
+ limits: RunLimits;
802
+ models: ModelExecution[];
803
+ delegations: DelegationExecution[];
804
+ /** Identical in every node. Admissions are counted from the journals, including running work. */
805
+ tree: { runId: string; startedAt: number; limits: TreeLimits; memory?: MemoryScopes };
806
+ state: RunState;
807
+ }
808
+
809
+ /** Stable operation identity; an attempt changes on resume, an operation does not.
810
+ * A model receipt's usage may be partial if the stream failed. */
811
+ export type OperationReceipt =
812
+ | RemoteReceipt
813
+ | {
814
+ kind: "model";
815
+ purpose?: "compaction";
816
+ id: string;
817
+ attemptId: string;
818
+ status: "running" | "completed" | "interrupted";
819
+ /** reported means a stream with usage ended, not that the SDK verified the vendor's bill. */
820
+ billing: "unknown" | "reported";
821
+ usage: TokenUsage;
822
+ source?: Turn["source"];
823
+ }
824
+ | {
825
+ kind: "tool" | "delegation" | "handoff";
826
+ id: string;
827
+ parentOperationId?: string;
828
+ callId: string;
829
+ attemptId: string;
830
+ status: "running" | "completed" | "interrupted";
831
+ result?: ToolResult;
832
+ };
833
+
834
+ interface RunRecord {
835
+ runId: string;
836
+ attemptId: string;
837
+ usage: TokenUsage;
838
+ /** This run and all descendants, deduplicated by stable model receipt IDs. */
839
+ treeUsage: TokenUsage;
840
+ /** The last admitted agent on this run's handoff chain. Delegated specialists do not change
841
+ * their parent's conversation owner. Route the next turn by both id and version. */
842
+ activeAgent: AgentRef;
843
+ handoffs: HandoffReceipt[];
844
+ /** The active agent's settled conversation, without its system prompt. May contain an
845
+ * SDK-written transfer note, not a person's message. Server-only, not a display transcript. */
846
+ history: AgentMessage[];
847
+ /** The original new turn and settled rounds along its handoff chain. Excludes transferred
848
+ * history and synthetic transfer inputs, so session append never duplicates earlier turns. */
849
+ newMessages: AgentMessage[];
850
+ receipts: OperationReceipt[];
851
+ /** Input delivery receipts. Queued messages still held by the host are not in the journal. */
852
+ inputs: InputReceipt[];
853
+ snapshot: RunSnapshot;
854
+ /** Present when the run has a session. An append that failed never changes the run's own
855
+ * status. */
856
+ session?: SessionStatus;
857
+ }
858
+
859
+ export type RunOutcome<T = string> = RunRecord &
860
+ (
861
+ | { status: "completed"; output: T }
862
+ | {
863
+ status: "suspended";
864
+ requests: (PendingRequest & { problem?: RequestProblem })[];
865
+ wakeAt?: number;
866
+ }
867
+ | { status: "cancelled" }
868
+ | { status: "limited"; limit: LimitReason }
869
+ | { status: "failed"; error: RunFailure }
870
+ );
871
+
872
+ export type AgentEvent =
873
+ /** Portable start identity for nodes without agent lifecycle hooks. No host context or
874
+ * signal is serialized. Cached terminal nodes do not emit a new execution start. */
875
+ | {
876
+ type: "execution_start";
877
+ kind: "workflow" | "remote";
878
+ nodeId: string;
879
+ version: string;
880
+ runId: string;
881
+ attemptId: string;
882
+ }
883
+ | {
884
+ type: "remote_status";
885
+ runId: string;
886
+ attemptId: string;
887
+ operationId: string;
888
+ state: import("./a2a/wire.ts").A2AState;
889
+ }
890
+ | ({ runId: string; attemptId: string; operationId: string; key: string } & (
891
+ | { type: "step_start"; kind: StepKind; attempt: number }
892
+ | { type: "step_progress"; data: unknown }
893
+ | {
894
+ type: "step_result";
895
+ kind: StepKind;
896
+ status: "completed" | "retrying" | "failed";
897
+ error?: StepError;
898
+ }
899
+ ))
900
+ /** Best-effort delivery update without the input's content. The snapshot is authoritative. */
901
+ | { type: "input"; receipt: InputReceipt }
902
+ /** Sent before the target's progress, also on resume. Upsert by operationId. Raw events
903
+ * remain server-only; project only the identities and labels your viewer may see. */
904
+ | ({ type: "handoff"; attemptId: string } & HandoffReceipt)
905
+ /** Replace the interrupted attempt's partial display, do not append to it. Saved attempts
906
+ * are authoritative if this best-effort event is missed. */
907
+ | {
908
+ type: "operation_restart";
909
+ kind: "model" | "tool";
910
+ runId: string;
911
+ operationId: string;
912
+ previousAttemptId: string;
913
+ attemptId: string;
914
+ parentOperationId?: string;
915
+ }
916
+ | {
917
+ type: "model_chunk";
918
+ runId: string;
919
+ attemptId: string;
920
+ operationId: string;
921
+ chunk: ProviderChunk;
922
+ }
923
+ | { type: "request"; request: PendingRequest }
924
+ | { type: "decision"; requestId: string; decision: Decision }
925
+ | { type: "tool_start"; request: ToolRequest }
926
+ | { type: "tool_result"; request: ToolRequest; result: ToolResult }
927
+ | { type: "state"; runId: string; attemptId: string; state: RunState }
928
+ /** Names the specialist run a delegation is starting or resuming, before that run reports
929
+ * anything, so an observer can file the run's events under its parent without reading ID
930
+ * formats. Best-effort progress like every other event: it can be missed, and it carries no
931
+ * status (the child's own state event and the snapshot do). A child resumed after an approval
932
+ * or an interruption sends it again with the same identity, so upsert by runId. Only a child
933
+ * that runs here sends it: a settled child that is reused, or one the host serves from a
934
+ * saved copy, stays silent. */
935
+ | ({
936
+ type: "child";
937
+ /** A model-created helper. Its private name, instructions and task are not display data. */
938
+ subagent?: true;
939
+ parentRunId: string;
940
+ operationId: string;
941
+ key: string;
942
+ runId: string;
943
+ version: string;
944
+ } & ({ kind: "agent" | "remote"; agentId: string } | { kind: "workflow"; workflowId: string }));