@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/src/input.ts ADDED
@@ -0,0 +1,319 @@
1
+ // A run's input: checked and normalized once, before anything is saved, loaded or sent.
2
+ //
3
+ // Every entry point (run, a background start, a specialist child) turns what it was given into
4
+ // the same frozen pair, the history and the new user turn, and the snapshot keeps that pair
5
+ // for the run's whole life. Nothing here re-reads a session or rebuilds a history later: one
6
+ // earlier byte that changes between requests re-bills the provider's whole prompt cache.
7
+ import {
8
+ repairHistory,
9
+ type ChatMessage,
10
+ type ContentPart,
11
+ type ToolCall,
12
+ } from "@providerkit/core";
13
+ import {
14
+ copyData,
15
+ isAgentMessage,
16
+ isFileMime,
17
+ isId,
18
+ isImageMime,
19
+ isPart,
20
+ isRecord,
21
+ } from "./snapshot.ts";
22
+ import type {
23
+ AgentInput,
24
+ AgentMessage,
25
+ InputPart,
26
+ MediaRef,
27
+ RunSnapshot,
28
+ UserContent,
29
+ } from "./types.ts";
30
+
31
+ /** `caller`: it may come from a browser, so only the fields a model needs are kept.
32
+ * `trusted`: coordinator code wrote it, so provider-owned fields ride along. */
33
+ export type Trust = "caller" | "trusted";
34
+
35
+ function partProblem(part: unknown): string {
36
+ if (!isRecord(part)) return "A content part must be an object with a type.";
37
+ switch (part.type) {
38
+ case "text":
39
+ return "A text part needs its text as a string.";
40
+ case "image":
41
+ return isImageMime(part.mimeType)
42
+ ? "An image needs its bytes as base64 text, padded with = to a multiple of 4."
43
+ : "An image must be image/jpeg, image/png, image/webp or image/gif. Send other files as a file part.";
44
+ case "file":
45
+ return isFileMime(part.mimeType)
46
+ ? "A file needs its bytes as base64 text, padded with = to a multiple of 4."
47
+ : "A file needs an application/, audio/, video/ or text/ media type, with no parameters.";
48
+ case "media":
49
+ return isId(part.id)
50
+ ? "A media reference needs an image type (JPEG, PNG, WebP or GIF) or an application/, audio/, video/ or text/ type."
51
+ : "A media reference needs the id your host stores its bytes under.";
52
+ default:
53
+ return "Use text, image, file or media content parts.";
54
+ }
55
+ }
56
+
57
+ // Use the same field allow-list on input and on browser output. Trusted stores may attach
58
+ // server-only upload metadata to otherwise valid parts.
59
+ function clientPart(part: InputPart): InputPart {
60
+ switch (part.type) {
61
+ case "text":
62
+ return { type: "text", text: part.text };
63
+ case "media":
64
+ return { type: "media", id: part.id, mimeType: part.mimeType };
65
+ case "image":
66
+ return { type: "image", mimeType: part.mimeType, data: part.data };
67
+ case "file":
68
+ return { type: "file", mimeType: part.mimeType, data: part.data };
69
+ }
70
+ }
71
+
72
+ /** A user turn with each part rebuilt from the fields core reads. A blank text part is
73
+ * dropped: providers refuse an empty text block, and a composer often sends one beside an
74
+ * attachment. Nothing left is an error. */
75
+ export function readContent(value: unknown, what: string): UserContent {
76
+ const empty = `${what} needs some text, an image or a file.`;
77
+ if (typeof value === "string") {
78
+ if (!value.trim()) throw new TypeError(empty);
79
+ return value;
80
+ }
81
+ if (!Array.isArray(value))
82
+ throw new TypeError(`${what} must be text or an array of content parts.`);
83
+ const parts: InputPart[] = [];
84
+ for (const part of value) {
85
+ if (!isPart(part)) throw new TypeError(partProblem(part));
86
+ if (part.type !== "text" || part.text.trim()) parts.push(clientPart(part));
87
+ }
88
+ if (parts.length === 0) throw new TypeError(empty);
89
+ return parts;
90
+ }
91
+
92
+ function readMessage(value: unknown, trust: Trust): AgentMessage {
93
+ if (!isRecord(value)) throw new TypeError("Each message must be an object with a role.");
94
+ if (value.role === "system")
95
+ throw new TypeError(
96
+ "A conversation cannot carry a system message. The agent's instructions are its system prompt.",
97
+ );
98
+ if (value.role === "user")
99
+ return { role: "user", content: readContent(value.content, "A user message") };
100
+ if (!isAgentMessage(value))
101
+ throw new TypeError(
102
+ value.role === "assistant"
103
+ ? "An assistant message needs text content, and tool calls with an id, a name and arguments."
104
+ : value.role === "tool"
105
+ ? "A tool message needs the toolCallId and name of the call it answers, and text content."
106
+ : "A message role must be user, assistant or tool.",
107
+ );
108
+ return trust === "trusted" ? copyData(value) : clientCopy(value);
109
+ }
110
+
111
+ /** A tool result in a caller's history must answer an open call of the assistant message before
112
+ * it, the pairing core's repairHistory keeps. Client tool results and approvals never enter
113
+ * through the history, so a result with no call is refused rather than turned into a note. */
114
+ function checkRounds(history: readonly AgentMessage[]): void {
115
+ let open: string[] = [];
116
+ for (const message of history) {
117
+ if (message.role === "assistant") {
118
+ // repairHistory drops a blank message with no calls, so it does not close a round.
119
+ if (!message.toolCalls?.length && !message.content.trim()) continue;
120
+ open = (message.toolCalls ?? []).map((call) => call.id);
121
+ } else if (message.role === "tool") {
122
+ const index = open.indexOf(message.toolCallId);
123
+ if (index === -1)
124
+ throw new TypeError(
125
+ "A tool result in the history must answer a call from the assistant message before it.",
126
+ );
127
+ open.splice(index, 1);
128
+ }
129
+ }
130
+ }
131
+
132
+ /** Turn an AgentInput into the history and the new turn. Throws a TypeError for anything a run
133
+ * cannot use, before any snapshot, checkpoint or session call. */
134
+ export function readInput(
135
+ input: unknown,
136
+ trust: Trust,
137
+ ): { history: AgentMessage[]; input: UserContent } {
138
+ if (typeof input === "string" || Array.isArray(input))
139
+ return { history: [], input: readContent(input, "The new turn") };
140
+ if (
141
+ !isRecord(input) ||
142
+ !Array.isArray(input.messages) ||
143
+ Object.keys(input).some((key) => key !== "messages")
144
+ )
145
+ throw new TypeError("Give the agent text, content parts or { messages }.");
146
+ const messages = input.messages.map((message) => readMessage(message, trust));
147
+ const last = messages.pop();
148
+ if (!last) throw new TypeError("Pass at least one message: the new user turn.");
149
+ if (last.role !== "user")
150
+ throw new TypeError(
151
+ "The last message must be the new user turn. Tool results and approvals never enter through the history.",
152
+ );
153
+ checkRounds(messages);
154
+ return { history: messages, input: last.content };
155
+ }
156
+
157
+ /** Trusted history from a session or prepareHistory, kept as it is: shape checked, system
158
+ * refused. A window may start inside a tool round; repair at creation handles that. */
159
+ export function readStored(value: unknown, source: string): AgentMessage[] {
160
+ if (!Array.isArray(value)) throw new TypeError(`${source} must give an array of messages.`);
161
+ if (value.some((message) => isRecord(message) && message.role === "system"))
162
+ throw new TypeError(
163
+ `${source} gave a system message. A conversation never carries one: the agent's instructions are its system prompt.`,
164
+ );
165
+ if (!value.every(isAgentMessage))
166
+ throw new TypeError(`${source} gave a message that is not a user, assistant or tool message.`);
167
+ return copyData(value);
168
+ }
169
+
170
+ /** A message rebuilt from the fields a model reads, so provider-owned fields and anything
171
+ * unknown stay behind. */
172
+ function clientCopy(message: AgentMessage): AgentMessage {
173
+ if (message.role === "user")
174
+ return {
175
+ role: "user",
176
+ content:
177
+ typeof message.content === "string" ? message.content : message.content.map(clientPart),
178
+ };
179
+ if (message.role === "tool")
180
+ return {
181
+ role: "tool",
182
+ toolCallId: message.toolCallId,
183
+ name: message.name,
184
+ content: message.content,
185
+ ...(message.images
186
+ ? { images: message.images.map(({ type, mimeType, data }) => ({ type, mimeType, data })) }
187
+ : {}),
188
+ };
189
+ const calls = message.toolCalls?.map((call): ToolCall => ({
190
+ id: call.id,
191
+ name: call.name,
192
+ arguments: call.arguments,
193
+ }));
194
+ return {
195
+ role: "assistant",
196
+ content: message.content,
197
+ ...(message.reasoning !== undefined ? { reasoning: message.reasoning } : {}),
198
+ ...(calls ? { toolCalls: calls } : {}),
199
+ };
200
+ }
201
+
202
+ /**
203
+ * Copies of the messages without the fields a provider owns: `reasoningDetails`,
204
+ * `reasoningItems` and each call's `thoughtSignature`. Use it before history reaches a
205
+ * browser. Reasoning text and tool rounds stay: DeepSeek needs the reasoning of a tool-call
206
+ * turn sent back. The run applies the same rule to history a caller passes in, because a
207
+ * browser could forge those fields.
208
+ */
209
+ export function toClientMessages(messages: readonly AgentMessage[]): AgentMessage[] {
210
+ return messages.map(clientCopy);
211
+ }
212
+
213
+ /**
214
+ * Core's repairHistory, run once when a run is created. Core types a user message without
215
+ * media references, so each user message crosses as a stand-in and comes back as itself:
216
+ * repair moves user messages, it never reads or rewrites them. Its orphan-result notes are
217
+ * new user messages with core content, which an AgentMessage can hold as they are.
218
+ */
219
+ export function repairConversation(
220
+ history: readonly AgentMessage[],
221
+ isReadOnly: (name: string) => boolean,
222
+ ): AgentMessage[] {
223
+ const users = new Map<ChatMessage, AgentMessage>();
224
+ const wire = history.map((message): ChatMessage => {
225
+ if (message.role !== "user") return message;
226
+ const stand: ChatMessage = { role: "user", content: "" };
227
+ users.set(stand, message);
228
+ return stand;
229
+ });
230
+ return repairHistory(wire, { isReadOnly }).messages.map((message): AgentMessage => {
231
+ const user = users.get(message);
232
+ if (user) return user;
233
+ if (message.role === "system") throw new TypeError("History repair returned a system message.");
234
+ return message;
235
+ });
236
+ }
237
+
238
+ /** The history, the new turn and whole settled rounds. Never half a tool round: the journal
239
+ * keeps unfinished work, and a provider refuses a call without its result. */
240
+ export function conversationOf(
241
+ snapshot: RunSnapshot,
242
+ beforeModel = snapshot.models.length,
243
+ ): AgentMessage[] {
244
+ const messages: AgentMessage[] = [...snapshot.history, { role: "user", content: snapshot.input }];
245
+ for (let position = 0; position <= beforeModel; position++) {
246
+ // Steering joins only between whole rounds. Its saved position survives attempts and
247
+ // preserves the exact prefix even when the host later offers more input.
248
+ for (const input of snapshot.inputs)
249
+ if (input.beforeModel === position) messages.push({ role: "user", content: input.content });
250
+ const model = position < beforeModel ? snapshot.models[position] : undefined;
251
+ if (
252
+ !model ||
253
+ model.status !== "completed" ||
254
+ model.tools.some((tool) => tool.status !== "completed")
255
+ )
256
+ break;
257
+ messages.push(model.turn.message);
258
+ for (const [index, tool] of model.tools.entries()) {
259
+ const call = model.turn.message.toolCalls?.[index];
260
+ if (call && tool.status === "completed") {
261
+ messages.push({
262
+ role: "tool",
263
+ toolCallId: call.id,
264
+ name: call.name,
265
+ content: tool.result.content,
266
+ ...(tool.result.ok && tool.result.images ? { images: tool.result.images } : {}),
267
+ });
268
+ }
269
+ }
270
+ }
271
+ return copyData(messages);
272
+ }
273
+
274
+ /** A saved run's frozen input in the form child() takes, to admit it again unchanged. */
275
+ export function inputOf(snapshot: RunSnapshot): AgentInput {
276
+ return snapshot.history.length === 0
277
+ ? snapshot.input
278
+ : { messages: [...snapshot.history, { role: "user", content: snapshot.input }] };
279
+ }
280
+
281
+ // Ported from TanStack AI (MIT), packages/ai-harness/src/media.ts: the transcript keeps the
282
+ // reference and only the provider request gets the bytes. Ours fails on a missing file
283
+ // instead of sending a note in its place, so the model never answers about a file it did not
284
+ // see.
285
+ /** The provider request: the system prompt, then the conversation with each media reference
286
+ * swapped for its bytes. Only this copy ever holds them. */
287
+ export async function requestOf(
288
+ instructions: string,
289
+ conversation: readonly AgentMessage[],
290
+ load: (ref: MediaRef) => Promise<string>,
291
+ ): Promise<ChatMessage[]> {
292
+ const request: ChatMessage[] = [{ role: "system", content: instructions }];
293
+ for (const message of conversation) {
294
+ if (message.role !== "user") {
295
+ request.push(message);
296
+ continue;
297
+ }
298
+ if (typeof message.content === "string") {
299
+ request.push({ role: "user", content: message.content });
300
+ continue;
301
+ }
302
+ const content: ContentPart[] = [];
303
+ for (const part of message.content) {
304
+ if (part.type !== "media") {
305
+ content.push(part);
306
+ continue;
307
+ }
308
+ const data = await load(part);
309
+ const mimeType = part.mimeType;
310
+ content.push(
311
+ isImageMime(mimeType)
312
+ ? { type: "image", mimeType, data }
313
+ : { type: "file", mimeType, data },
314
+ );
315
+ }
316
+ request.push({ role: "user", content });
317
+ }
318
+ return request;
319
+ }