@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/code.ts ADDED
@@ -0,0 +1,424 @@
1
+ // Code-mode policy follows TanStack AI (MIT), Mastra and Vercel AI SDK (Apache-2.0).
2
+ // Changed: journal-owned dispatch, no VM replay, explicit bindings and bounded JSON receipts.
3
+ // See THIRD_PARTY_NOTICES.md. This entry never imports an engine.
4
+ import type { Tool, ToolDefinition } from "@providerkit/core";
5
+ import type { CodeDriver, CodeJobResult } from "./code-driver.ts";
6
+ import { codeScript } from "./code-script.ts";
7
+ import { isQuestionTool } from "./request.ts";
8
+ import { toolTypings } from "./schema-to-ts.ts";
9
+ import { copyData, immutableCopy, isId, isRecord } from "./snapshot.ts";
10
+ import { untilAbort } from "./tree.ts";
11
+ import type { ProgramCall, ToolResult } from "./types.ts";
12
+
13
+ export type { CodeDriver, CodeJob, CodeJobResult } from "./code-driver.ts";
14
+ export type { ProgramCall } from "./types.ts";
15
+ export { toolTypings } from "./schema-to-ts.ts";
16
+
17
+ export interface CodeLimits {
18
+ calls: number;
19
+ timeoutMs: number;
20
+ cpuMs: number;
21
+ memoryBytes: number;
22
+ stackBytes: number;
23
+ sourceBytes: number;
24
+ resultBytes: number;
25
+ logBytes: number;
26
+ callInputBytes: number;
27
+ callOutputBytes: number;
28
+ }
29
+
30
+ export const CODE_LIMITS: Readonly<CodeLimits> = Object.freeze({
31
+ calls: 32,
32
+ timeoutMs: 30_000,
33
+ cpuMs: 2_000,
34
+ memoryBytes: 32 * 1024 * 1024,
35
+ stackBytes: 256 * 1024,
36
+ sourceBytes: 64 * 1024,
37
+ resultBytes: 32 * 1024,
38
+ logBytes: 8 * 1024,
39
+ callInputBytes: 256 * 1024,
40
+ callOutputBytes: 1024 * 1024,
41
+ });
42
+
43
+ export interface CodeModeOptions {
44
+ name?: string;
45
+ tools: readonly Tool[];
46
+ driver: CodeDriver;
47
+ limits?: Partial<CodeLimits>;
48
+ needsApproval?: boolean;
49
+ /** Receives an async function expression, not a body. No compiler is bundled. */
50
+ transpile?: (source: string) => string | Promise<string>;
51
+ instructions?: string;
52
+ }
53
+
54
+ /** @internal The run owns admission, dispatch and settlement. Never call tools in a driver. */
55
+ export interface ProgramBridge {
56
+ readonly tools: readonly Tool[];
57
+ readonly signal: AbortSignal;
58
+ readonly deadline: number;
59
+ readonly calls: readonly ProgramCall[];
60
+ call(name: string, input: string): Promise<string>;
61
+ toolCallsLeft(): number;
62
+ /** Abort queued/running calls, then await their recorded outcomes. */
63
+ settle(): Promise<void>;
64
+ }
65
+
66
+ export interface ProgramOutcome {
67
+ result: ToolResult;
68
+ }
69
+
70
+ export interface CodeTool {
71
+ readonly kind: "code";
72
+ readonly name: string;
73
+ readonly tools: readonly Tool[];
74
+ readonly limits: Readonly<CodeLimits>;
75
+ readonly isReadOnly: boolean;
76
+ readonly needsApproval: boolean;
77
+ /** The loop supplies only the enabled subset; callers cannot add bindings. */
78
+ definition(enabled?: readonly string[]): ToolDefinition;
79
+ /** Return a new descriptor with the same binding names, driver and limits. No object is mutated. */
80
+ withTools(tools: readonly Tool[]): CodeTool;
81
+ /** @internal Called only with the run's journal bridge. */
82
+ execute(raw: unknown, bridge: ProgramBridge): Promise<ProgramOutcome>;
83
+ /** @internal Close an interrupted program without evaluating its source. */
84
+ close(calls: readonly ProgramCall[]): ToolResult;
85
+ }
86
+
87
+ export function isCodeTool(value: { readonly name: string }): value is CodeTool {
88
+ return "kind" in value && value.kind === "code";
89
+ }
90
+
91
+ export function textBytes(text: string): number {
92
+ return new TextEncoder().encode(text).byteLength;
93
+ }
94
+
95
+ /** Keep whole Unicode characters and count strings as UTF-8, not UTF-16 code units. */
96
+ export function bytePreview(text: string, limit: number): string {
97
+ const bytes = new TextEncoder().encode(text);
98
+ if (bytes.byteLength <= limit) return text;
99
+ let end = limit;
100
+ while (end > 0 && ((bytes[end] ?? 0) & 0xc0) === 0x80) end--;
101
+ return new TextDecoder().decode(bytes.subarray(0, end));
102
+ }
103
+
104
+ /** JSON-only host boundary. JSON.stringify alone silently drops functions and undefined. */
105
+ export function programJson(value: unknown): string {
106
+ const parents = new Set<object>();
107
+ function check(item: unknown): void {
108
+ if (item === undefined)
109
+ throw new TypeError("Return JSON values only. Use null instead of undefined.");
110
+ if (item === null || typeof item !== "object") return;
111
+ if (parents.has(item)) throw new TypeError("Return JSON values without cycles.");
112
+ parents.add(item);
113
+ const array = Array.isArray(item);
114
+ const keys = Reflect.ownKeys(item);
115
+ if (array && keys.length !== item.length + 1)
116
+ throw new TypeError("Return a JSON array without gaps or extra keys.");
117
+ for (const key of keys) {
118
+ if (array && key === "length") continue;
119
+ const field = Object.getOwnPropertyDescriptor(item, key);
120
+ if (
121
+ typeof key !== "string" ||
122
+ !field?.enumerable ||
123
+ !("value" in field) ||
124
+ (array && (!/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= item.length))
125
+ )
126
+ throw new TypeError(
127
+ "Return plain JSON fields, without symbols, getters or extra array keys.",
128
+ );
129
+ check(field.value);
130
+ }
131
+ parents.delete(item);
132
+ }
133
+ // Check before cloning: structuredClone silently drops symbol keys and invokes getters.
134
+ check(value);
135
+ return JSON.stringify(copyData(value));
136
+ }
137
+
138
+ export function programReply(result: ToolResult, outputBytes: number): string {
139
+ if (!result.ok)
140
+ return JSON.stringify({
141
+ ok: false,
142
+ error: { kind: result.kind, message: bytePreview(result.content, 2048) },
143
+ });
144
+ try {
145
+ const value = result.output === undefined ? undefined : programJson(result.output);
146
+ const bytes = value === undefined ? 0 : textBytes(value);
147
+ if (bytes > outputBytes)
148
+ throw new TypeError(
149
+ `The result is ${bytes} bytes; the limit is ${outputBytes}. Ask for less. The call already ran.`,
150
+ );
151
+ return value === undefined ? '{"ok":true}' : `{"ok":true,"value":${value}}`;
152
+ } catch (error) {
153
+ return JSON.stringify({
154
+ ok: false,
155
+ error: {
156
+ kind: "invalid_output",
157
+ message:
158
+ error instanceof Error
159
+ ? error.message
160
+ : "The call ran but did not return JSON. Check its effect before calling it again.",
161
+ },
162
+ });
163
+ }
164
+ }
165
+
166
+ /** Full values reach only the guest and output guard. Saved results/events keep this preview. */
167
+ export function programReceipt(result: ToolResult): { result: ToolResult; bytes: number } {
168
+ const content = bytePreview(result.content, 1024);
169
+ return {
170
+ result: result.ok ? { ok: true, content } : { ok: false, kind: result.kind, content },
171
+ bytes:
172
+ result.ok && result.output !== undefined
173
+ ? textBytes(programJson(result.output))
174
+ : textBytes(result.content),
175
+ };
176
+ }
177
+
178
+ function callNotes(calls: readonly ProgramCall[]) {
179
+ return calls.slice(0, 20).map((call) => ({
180
+ tool: call.name,
181
+ status: !call.started
182
+ ? "not started"
183
+ : call.status !== "completed"
184
+ ? "stopped"
185
+ : call.result.ok
186
+ ? "returned"
187
+ : ["denied", "disabled_tool", "invalid_input"].includes(call.result.kind)
188
+ ? "refused"
189
+ : ["aborted", "cancelled", "interrupted"].includes(call.result.kind)
190
+ ? "stopped"
191
+ : "failed",
192
+ note:
193
+ call.status === "completed"
194
+ ? call.result.content.slice(0, 200)
195
+ : "The call may have partly run. Check its effect before repeating it.",
196
+ }));
197
+ }
198
+
199
+ type ProgramError = { name: string; message: string; line?: number };
200
+ function errorKind(error: ProgramError): Extract<ToolResult, { ok: false }>["kind"] {
201
+ if (["SyntaxError", "InvalidResultError", "InputError"].includes(error.name))
202
+ return "invalid_input";
203
+ if (["TimeoutError", "CpuLimitError"].includes(error.name)) return "timeout";
204
+ if (error.name === "AbortError") return "aborted";
205
+ return "failed";
206
+ }
207
+
208
+ export function codeMode(options: CodeModeOptions): CodeTool {
209
+ options = { ...options };
210
+ const name = options.name ?? "run_code";
211
+ const bound = [...options.tools];
212
+ if (
213
+ !isId(name) ||
214
+ !options.driver ||
215
+ typeof options.driver.run !== "function" ||
216
+ (options.transpile !== undefined && typeof options.transpile !== "function") ||
217
+ (options.needsApproval !== undefined && typeof options.needsApproval !== "boolean") ||
218
+ (options.instructions !== undefined && typeof options.instructions !== "string")
219
+ )
220
+ throw new TypeError("Code mode needs a name, driver and optional transpile function.");
221
+ if (!bound.length || new Set(bound.map((tool) => tool.name)).size !== bound.length)
222
+ throw new TypeError("Code mode needs at least one tool, with a different name for each tool.");
223
+ for (const tool of bound) {
224
+ if (
225
+ !isId(tool.name) ||
226
+ "kind" in tool ||
227
+ typeof tool.invoke !== "function" ||
228
+ typeof tool.call !== "function" ||
229
+ typeof tool.definition !== "function" ||
230
+ tool.needsApproval ||
231
+ tool.isTerminal ||
232
+ isQuestionTool(tool)
233
+ )
234
+ throw new TypeError(
235
+ `Code mode cannot bind ${tool.name}. Bind ordinary tools without approval, questions or terminal actions; keep control tools direct.`,
236
+ );
237
+ }
238
+ const limits = Object.freeze({ ...CODE_LIMITS, ...options.limits });
239
+ if (
240
+ Object.keys(limits).some((key) => !Object.hasOwn(CODE_LIMITS, key)) ||
241
+ Object.values(limits).some((value) => !Number.isSafeInteger(value) || value <= 0) ||
242
+ limits.timeoutMs > 2_147_483_647
243
+ )
244
+ throw new TypeError("Code limits must be positive whole numbers; timeoutMs must fit a timer.");
245
+ const tools = Object.freeze(bound);
246
+ const { driver, transpile } = options;
247
+ const cache = new Map<string, ToolDefinition>();
248
+ function definition(enabled = tools.map((tool) => tool.name)): ToolDefinition {
249
+ const selected = tools.filter((tool) => enabled.includes(tool.name));
250
+ const key = JSON.stringify(selected.map((tool) => tool.name));
251
+ let value = cache.get(key);
252
+ if (!value) {
253
+ value = immutableCopy({
254
+ name,
255
+ description: [
256
+ "Run a loop or combine tool results in code. For questions, approvals and control actions, call a direct tool instead.",
257
+ `Write ${transpile ? "TypeScript or JavaScript" : "JavaScript"} as the body of an async function. Use await tools.name({}) or Promise.all. Use Promise.allSettled when one failed call must not lose the others. Return a small JSON value; only the return and bounded logs reach the model.`,
258
+ "A failed tool throws ToolError with tool and kind. A failed change may have partly run. Check its effect before repeating it. Cancellation does not undo effects.",
259
+ "Each program starts empty. JSON values only. No network, files, process, timers or imports.",
260
+ `Limits: ${Object.entries(limits)
261
+ .map(([key, value]) => `${key}=${value}`)
262
+ .join(
263
+ ", ",
264
+ )}. Inner calls also spend the run's tool budget, except its final reserved call.`,
265
+ options.instructions ?? "",
266
+ toolTypings(selected),
267
+ ]
268
+ .filter(Boolean)
269
+ .join("\n\n"),
270
+ inputSchema: {
271
+ type: "object",
272
+ properties: { code: { type: "string" } },
273
+ required: ["code"],
274
+ additionalProperties: false,
275
+ },
276
+ });
277
+ cache.set(key, value);
278
+ }
279
+ return copyData(value);
280
+ }
281
+ // Freeze the ordinary definition now, not after a tool author mutates a schema.
282
+ definition();
283
+ return Object.freeze({
284
+ kind: "code",
285
+ name,
286
+ tools,
287
+ limits,
288
+ isReadOnly: tools.every((tool) => tool.isReadOnly),
289
+ needsApproval: options.needsApproval ?? false,
290
+ definition,
291
+ withTools(replacements: readonly Tool[]): CodeTool {
292
+ if (
293
+ replacements.length !== tools.length ||
294
+ replacements.some((tool, index) => tool.name !== tools[index]?.name)
295
+ )
296
+ throw new TypeError("Replace code bindings by the same names in the same order.");
297
+ return codeMode({ ...options, name, tools: replacements, limits, driver, transpile });
298
+ },
299
+ async execute(raw: unknown, bridge: ProgramBridge): Promise<ProgramOutcome> {
300
+ let error: ProgramError | undefined;
301
+ let value: unknown;
302
+ let logs = "";
303
+ let droppedLogBytes = 0;
304
+ try {
305
+ if (!isRecord(raw) || typeof raw.code !== "string" || Object.keys(raw).length !== 1)
306
+ throw new TypeError("Pass one code string containing the body of an async function.");
307
+ if (textBytes(raw.code) > limits.sourceBytes)
308
+ throw new TypeError(
309
+ `The code exceeds ${limits.sourceBytes} bytes. Send a shorter program.`,
310
+ );
311
+ let expression = `(async () => {\n${raw.code}\n})`;
312
+ if (transpile)
313
+ expression = await untilAbort(Promise.resolve(transpile(expression)), bridge.signal);
314
+ if (typeof expression !== "string" || textBytes(expression) > limits.sourceBytes + 32)
315
+ throw new TypeError(
316
+ `The compiled code exceeds ${limits.sourceBytes} bytes. Send a shorter program.`,
317
+ );
318
+ const result: CodeJobResult = await driver.run({
319
+ script: codeScript(
320
+ expression,
321
+ bridge.tools.map((tool) => tool.name),
322
+ ),
323
+ call: bridge.call,
324
+ log(text) {
325
+ if (bridge.signal.aborted) return;
326
+ const addition = `${logs ? "\n" : ""}${text}`;
327
+ const kept = bytePreview(addition, limits.logBytes - textBytes(logs));
328
+ logs += kept;
329
+ droppedLogBytes += textBytes(addition) - textBytes(kept);
330
+ },
331
+ ...limits,
332
+ deadline: bridge.deadline,
333
+ signal: bridge.signal,
334
+ });
335
+ if (!result.ok)
336
+ error = { ...result.error, message: bytePreview(result.error.message, 2048) };
337
+ // Error text has its own 2 KiB ceiling; JSON escaping must not turn it into an
338
+ // oversized successful return when the host chooses a tiny resultBytes allowance.
339
+ else if (textBytes(result.envelope) > Math.max(limits.resultBytes + 64, 16 * 1024))
340
+ error = {
341
+ name: "InvalidResultError",
342
+ message: `The returned JSON exceeds ${limits.resultBytes} bytes. Return less data. Completed tool calls are not undone.`,
343
+ };
344
+ else {
345
+ const envelope: unknown = JSON.parse(result.envelope);
346
+ if (!isRecord(envelope) || typeof envelope.ok !== "boolean")
347
+ throw new TypeError("The code driver returned an invalid result envelope.");
348
+ if (envelope.ok) {
349
+ value = envelope.value;
350
+ if (value !== undefined && textBytes(programJson(value)) > limits.resultBytes)
351
+ error = {
352
+ name: "InvalidResultError",
353
+ message: `The returned JSON exceeds ${limits.resultBytes} bytes. Return less data.`,
354
+ };
355
+ } else {
356
+ if (
357
+ !isRecord(envelope.error) ||
358
+ typeof envelope.error.name !== "string" ||
359
+ typeof envelope.error.message !== "string"
360
+ )
361
+ throw new TypeError("The code driver returned an invalid error envelope.");
362
+ error = {
363
+ name:
364
+ envelope.invalidResult === true
365
+ ? "InvalidResultError"
366
+ : envelope.error.name === "SyntaxError"
367
+ ? "SyntaxError"
368
+ : "ProgramError",
369
+ message: bytePreview(envelope.error.message, 2048),
370
+ ...(!transpile &&
371
+ typeof envelope.error.line === "number" &&
372
+ Number.isSafeInteger(envelope.error.line) &&
373
+ envelope.error.line > 0
374
+ ? { line: envelope.error.line }
375
+ : {}),
376
+ };
377
+ }
378
+ }
379
+ } catch (cause) {
380
+ error = {
381
+ name: bridge.signal.aborted ? "AbortError" : "InputError",
382
+ message:
383
+ cause instanceof Error
384
+ ? bytePreview(cause.message, 2048)
385
+ : "The program could not run. Check its code and driver.",
386
+ };
387
+ } finally {
388
+ await bridge.settle();
389
+ }
390
+ if (error?.name === "AbortError" && Date.now() >= bridge.deadline)
391
+ error = {
392
+ name: "TimeoutError",
393
+ message:
394
+ "The program reached its wall-time limit. Check the call receipts before repeating a change.",
395
+ };
396
+ const content = JSON.stringify({
397
+ ...(value !== undefined && !error ? { result: value } : {}),
398
+ logs,
399
+ ...(droppedLogBytes ? { droppedLogBytes } : {}),
400
+ toolCalls: bridge.calls.length,
401
+ toolCallsLeft: bridge.toolCallsLeft(),
402
+ ...(error ? { error, calls: callNotes(bridge.calls) } : {}),
403
+ });
404
+ return {
405
+ result: error ? { ok: false, kind: errorKind(error), content } : { ok: true, content },
406
+ };
407
+ },
408
+ close(calls: readonly ProgramCall[]): ToolResult {
409
+ return {
410
+ ok: false,
411
+ kind: "interrupted",
412
+ content: JSON.stringify({
413
+ error: {
414
+ name: "InterruptedError",
415
+ message:
416
+ "The program stopped before its result was saved. These receipts show which calls ran. Do not repeat them. Calls marked not started did not run.",
417
+ },
418
+ calls: callNotes(calls),
419
+ toolCalls: calls.length,
420
+ }),
421
+ };
422
+ },
423
+ });
424
+ }
@@ -0,0 +1,212 @@
1
+ // Adapted from TanStack AI (MIT), packages/ai-compaction/src/index.ts: a saved model-only
2
+ // view plus an untouched transcript. Copyright (c) 2025 Tanner Linsley.
3
+ // Changed: core owns cutting/pairing; a running summary is never silently called twice.
4
+ import {
5
+ applyCompaction,
6
+ conversationTokens,
7
+ historyBudgetTokens,
8
+ needsCompaction,
9
+ pickCut,
10
+ type ChatMessage,
11
+ } from "@providerkit/core";
12
+ import { conversationOf } from "./input.ts";
13
+ import { copyData, isId, isRecord } from "./snapshot.ts";
14
+ import type {
15
+ AgentMessage,
16
+ CompactionDefinition,
17
+ CompactionExecution,
18
+ CompactionPolicy,
19
+ ModelExecution,
20
+ RunSnapshot,
21
+ } from "./types.ts";
22
+
23
+ const positive = (value: unknown): value is number =>
24
+ typeof value === "number" && Number.isSafeInteger(value) && value > 0;
25
+
26
+ export function isCompactionDefinition(value: unknown): value is CompactionDefinition | null {
27
+ return (
28
+ value === null ||
29
+ (isRecord(value) &&
30
+ isId(value.identity) &&
31
+ positive(value.contextWindow) &&
32
+ positive(value.keepTokens) &&
33
+ (value.summarize === null ||
34
+ (isRecord(value.summarize) &&
35
+ isRecord(value.summarize.provider) &&
36
+ isId(value.summarize.provider.id) &&
37
+ isId(value.summarize.provider.model) &&
38
+ isId(value.summarize.instructions) &&
39
+ positive(value.summarize.maxTokens))))
40
+ );
41
+ }
42
+
43
+ export function compactionDefinition(policy?: CompactionPolicy): CompactionDefinition | null {
44
+ if (policy === undefined) return null;
45
+ const summary = policy.summarize;
46
+ const definition = {
47
+ identity: policy.identity,
48
+ contextWindow: policy.contextWindow,
49
+ keepTokens: policy.keepTokens ?? historyBudgetTokens(policy.contextWindow),
50
+ summarize: summary
51
+ ? {
52
+ provider: { id: summary.provider?.id, model: summary.provider?.model },
53
+ instructions: summary.instructions,
54
+ maxTokens: summary.maxTokens,
55
+ }
56
+ : null,
57
+ };
58
+ if (
59
+ !isCompactionDefinition(definition) ||
60
+ (summary && typeof summary.provider?.createStream !== "function")
61
+ )
62
+ throw new TypeError(
63
+ "Compaction needs an identity, a context window and positive token limits. A summarizer needs a provider, instructions and maxTokens.",
64
+ );
65
+ return copyData(definition);
66
+ }
67
+
68
+ /** Only core's text estimator reads these stand-ins. Media references are not loaded or
69
+ * counted as text; the original user message returns unchanged after core chooses the cut. */
70
+ function wire(messages: readonly AgentMessage[]) {
71
+ const users = new Map<ChatMessage, AgentMessage>();
72
+ const messagesForCore = messages.map((message): ChatMessage => {
73
+ if (message.role !== "user") return message;
74
+ const stand: ChatMessage = {
75
+ role: "user",
76
+ content:
77
+ typeof message.content === "string"
78
+ ? message.content
79
+ : message.content.filter((part) => part.type !== "media"),
80
+ };
81
+ users.set(stand, message);
82
+ return stand;
83
+ });
84
+ return { messages: messagesForCore, users };
85
+ }
86
+
87
+ export function compactMessages(
88
+ messages: readonly AgentMessage[],
89
+ cut: number,
90
+ summary: string,
91
+ ): AgentMessage[] {
92
+ const core = wire(messages);
93
+ return applyCompaction(core.messages, cut, summary).map((message) => {
94
+ if (message.role === "system") throw new TypeError("Compaction cannot replace instructions.");
95
+ return core.users.get(message) ?? message;
96
+ });
97
+ }
98
+
99
+ export function modelConversation(
100
+ snapshot: RunSnapshot,
101
+ messages = conversationOf(snapshot),
102
+ ): AgentMessage[] {
103
+ const last = snapshot.compactions.at(-1);
104
+ return last?.status === "completed"
105
+ ? compactMessages(messages, last.cut, last.summary)
106
+ : messages;
107
+ }
108
+
109
+ function cutFor(
110
+ snapshot: RunSnapshot,
111
+ beforeModel: number,
112
+ view: readonly AgentMessage[],
113
+ previousCut = 0,
114
+ ): number {
115
+ const policy = snapshot.definition.compaction;
116
+ if (!policy) return 0;
117
+ const cut = pickCut(wire(view).messages, policy.keepTokens) + (previousCut ? previousCut - 1 : 0);
118
+ // A not-yet-delivered steer must reach the model verbatim. These are user boundaries
119
+ // between whole rounds, so capping core's cut here cannot split a call from its result.
120
+ const full = conversationOf(snapshot, beforeModel);
121
+ const unread =
122
+ beforeModel === 0
123
+ ? snapshot.history.length
124
+ : full.length - snapshot.inputs.filter((input) => input.beforeModel === beforeModel).length;
125
+ return Math.min(cut, unread);
126
+ }
127
+
128
+ export function compactionPlan(
129
+ snapshot: RunSnapshot,
130
+ ): { cut: number; sourceCount: number; removed: AgentMessage[] } | undefined {
131
+ const policy = snapshot.definition.compaction;
132
+ if (!policy) return;
133
+ const last = snapshot.compactions.at(-1);
134
+ // Once per boundary, including a crash after the summary was saved but before model admission.
135
+ if (last?.beforeModel === snapshot.models.length) return;
136
+ const full = conversationOf(snapshot);
137
+ const view = modelConversation(snapshot, full);
138
+ const core = wire(view).messages;
139
+ const previous = snapshot.models.at(-1);
140
+ const measured = previous?.status === "completed" && previous.billing === "reported";
141
+ // The last call counted its input, not its newly added answer, tools or steers.
142
+ const priorCount = previous ? conversationOf(snapshot, snapshot.models.length - 1).length : 0;
143
+ const count = measured
144
+ ? previous.usage.inputTokens + conversationTokens(wire(full.slice(priorCount)).messages)
145
+ : conversationTokens([{ role: "system", content: snapshot.definition.instructions }, ...core]);
146
+ if (!needsCompaction(count, policy.contextWindow)) return;
147
+ const cut = cutFor(snapshot, snapshot.models.length, view, last?.cut);
148
+ const localCut = cut - (last ? last.cut - 1 : 0);
149
+ if (localCut <= 0 || cut <= (last?.cut ?? 0)) return;
150
+ return { cut, sourceCount: full.length, removed: view.slice(0, localCut) };
151
+ }
152
+
153
+ export function compactionId(runId: string, index: number): string {
154
+ return `${runId}/compaction/${index + 1}`;
155
+ }
156
+
157
+ /** Summary calls participate in the same model admissions, usage and receipts. */
158
+ export function allModels(snapshot: RunSnapshot): ModelExecution[] {
159
+ return [
160
+ ...snapshot.models,
161
+ ...snapshot.compactions.flatMap((entry) => (entry.model ? [entry.model] : [])),
162
+ ];
163
+ }
164
+
165
+ export function checkCompactions(snapshot: RunSnapshot): void {
166
+ let previous: Extract<CompactionExecution, { status: "completed" }> | undefined;
167
+ for (const [index, entry] of snapshot.compactions.entries()) {
168
+ const policy = snapshot.definition.compaction;
169
+ const source = conversationOf(snapshot, entry.beforeModel);
170
+ const full = source.slice(0, entry.sourceCount);
171
+ const minimumSource =
172
+ source.length -
173
+ snapshot.inputs.filter((input) => input.beforeModel === entry.beforeModel).length;
174
+ const view = previous ? compactMessages(full, previous.cut, previous.summary) : full;
175
+ const cut = cutFor(snapshot, entry.beforeModel, view, previous?.cut);
176
+ if (
177
+ !policy ||
178
+ entry.id !== compactionId(snapshot.runId, index) ||
179
+ entry.beforeModel > snapshot.models.length ||
180
+ entry.beforeModel <= (previous?.beforeModel ?? -1) ||
181
+ full.length !== entry.sourceCount ||
182
+ entry.sourceCount < minimumSource ||
183
+ entry.cut !== cut ||
184
+ entry.cut <= (previous?.cut ?? 0) ||
185
+ entry.cut >= full.length ||
186
+ (entry.status === "running" &&
187
+ (index !== snapshot.compactions.length - 1 ||
188
+ entry.beforeModel !== snapshot.models.length ||
189
+ snapshot.state.status === "completed")) ||
190
+ (entry.model && !policy.summarize) ||
191
+ (entry.status === "completed" && !!entry.model !== !!policy.summarize)
192
+ )
193
+ throw new TypeError("Invalid compaction position or definition.");
194
+ if (
195
+ entry.model &&
196
+ (entry.model.id !== entry.id ||
197
+ entry.model.interrupted.length !== 0 ||
198
+ entry.model.status !== entry.status ||
199
+ (entry.model.status === "completed" &&
200
+ (entry.model.tools.length !== 0 ||
201
+ entry.model.turn.message.toolCalls?.length ||
202
+ entry.model.turn.finishReason !== "stop" ||
203
+ !entry.model.turn.message.content.trim() ||
204
+ entry.model.turn.message.hostedCalls?.length ||
205
+ entry.model.turn.message.hostedItems ||
206
+ entry.status !== "completed" ||
207
+ entry.summary !== entry.model.turn.message.content)))
208
+ )
209
+ throw new TypeError("Invalid summary receipt. Summaries cannot replay or dispatch tools.");
210
+ if (entry.status === "completed") previous = entry;
211
+ }
212
+ }