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