@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/request.ts ADDED
@@ -0,0 +1,513 @@
1
+ import {
2
+ defineTool,
3
+ messageOf,
4
+ type JsonObjectSchema,
5
+ type Tool,
6
+ type ToolContext,
7
+ type ToolDefinition,
8
+ } from "@providerkit/core";
9
+ import { copyData, equalData, immutableCopy, isId, isRecord, isScope } from "./snapshot.ts";
10
+ import { emitEvent, fail, Halt, untilAbort, type ExecutionScope } from "./tree.ts";
11
+ import type {
12
+ Answer,
13
+ Ask,
14
+ AskRecord,
15
+ Decision,
16
+ QuestionAsk,
17
+ Resolution,
18
+ RunOptions,
19
+ ToolRequest,
20
+ StepRequest,
21
+ RequestOrigin,
22
+ } from "./types.ts";
23
+
24
+ const INPUT_REQUIRED = Symbol.for("@providerkit/agents/InputRequired");
25
+ const QUESTION_TOOL = Symbol.for("@providerkit/agents/questionTool");
26
+
27
+ /** @internal Known asking tools cannot be installed in a non-suspending guest program. */
28
+ export function isQuestionTool(tool: Tool): boolean {
29
+ return QUESTION_TOOL in tool;
30
+ }
31
+
32
+ /** A replay-safe pre-effect boundary, not a saved JavaScript stack. The entire tool runs
33
+ * again with context.answers. Never throw this after an external effect, even a read that
34
+ * incurs a charge. An interrupted invocation is still unknown and is never replayed. */
35
+ export class InputRequired extends Error {
36
+ readonly [INPUT_REQUIRED] = true;
37
+ readonly ask: QuestionAsk;
38
+ constructor(
39
+ question: Omit<QuestionAsk, "type">,
40
+ readonly problem?: string,
41
+ ) {
42
+ super(problem ?? question.message);
43
+ this.name = "InputRequired";
44
+ this.ask = immutableCopy({ ...question, type: "question" });
45
+ if (!isAsk(this.ask)) throw new TypeError("Provide a valid question with a stable key.");
46
+ }
47
+ }
48
+
49
+ export function isInputRequired(value: unknown): value is InputRequired {
50
+ return (
51
+ typeof value === "object" &&
52
+ value !== null &&
53
+ INPUT_REQUIRED in value &&
54
+ value[INPUT_REQUIRED] === true &&
55
+ "ask" in value &&
56
+ isAsk(value.ask) &&
57
+ value.ask.type === "question"
58
+ );
59
+ }
60
+
61
+ function keys(value: Record<string, unknown>, allowed: string[]): boolean {
62
+ return Object.keys(value).every((key) => allowed.includes(key));
63
+ }
64
+ function schema(value: unknown): value is JsonObjectSchema {
65
+ return isRecord(value) && value.type === "object";
66
+ }
67
+
68
+ export function isAsk(value: unknown): value is Ask {
69
+ if (!isRecord(value)) return false;
70
+ if (value.type === "approval")
71
+ return (
72
+ keys(value, ["type", "message", "editable", "approveSchema", "denySchema"]) &&
73
+ (value.message === undefined || isId(value.message)) &&
74
+ (value.editable === undefined || typeof value.editable === "boolean") &&
75
+ (value.approveSchema === undefined || schema(value.approveSchema)) &&
76
+ (value.denySchema === undefined || schema(value.denySchema))
77
+ );
78
+ if (value.type === "client")
79
+ return keys(value, ["type", "resultSchema"]) && schema(value.resultSchema);
80
+ return (
81
+ value.type === "question" &&
82
+ keys(value, ["type", "key", "message", "choices", "multiple", "freeText", "schema"]) &&
83
+ isId(value.key) &&
84
+ isId(value.message) &&
85
+ (value.multiple === undefined || typeof value.multiple === "boolean") &&
86
+ (value.freeText === undefined || typeof value.freeText === "boolean") &&
87
+ (value.schema === undefined || schema(value.schema)) &&
88
+ (value.choices === undefined ||
89
+ (Array.isArray(value.choices) &&
90
+ value.choices.length > 0 &&
91
+ value.choices.every(
92
+ (choice) =>
93
+ isRecord(choice) &&
94
+ keys(choice, ["id", "label", "description"]) &&
95
+ isId(choice.id) &&
96
+ isId(choice.label) &&
97
+ (choice.description === undefined || isId(choice.description)),
98
+ ) &&
99
+ new Set(value.choices.map((choice) => choice.id)).size === value.choices.length)) &&
100
+ (!value.multiple || value.choices !== undefined) &&
101
+ !(value.schema !== undefined && value.choices !== undefined)
102
+ );
103
+ }
104
+
105
+ export function isAnswer(value: unknown): value is Answer {
106
+ return (
107
+ isRecord(value) &&
108
+ keys(value, ["choices", "text", "data"]) &&
109
+ (value.text === undefined || isId(value.text)) &&
110
+ (value.choices === undefined || (Array.isArray(value.choices) && value.choices.every(isId)))
111
+ );
112
+ }
113
+
114
+ /** Fit checks adapted from PydanticAI (MIT), ask_user/_types.py, check_response and
115
+ * _check_answer. Forms are checked by the trusted host and the asker's runtime validator. */
116
+ export function checkDecision(ask: Ask, raw: unknown): Decision {
117
+ const invalid = () =>
118
+ new TypeError(
119
+ "The answer does not fit this request. Check its choices, fields and edit policy.",
120
+ );
121
+ if (!isRecord(raw) || (raw.receipt !== undefined && !isId(raw.receipt))) throw invalid();
122
+ const common = ["type", "receipt"];
123
+ if (raw.type === "cancel" || raw.type === "stop") {
124
+ if (!keys(raw, common)) throw invalid();
125
+ return { type: raw.type, ...(raw.receipt ? { receipt: raw.receipt } : {}) };
126
+ }
127
+ if (ask.type === "approval") {
128
+ if (
129
+ raw.type === "approve" &&
130
+ keys(raw, [...common, "arguments", "data"]) &&
131
+ (raw.arguments === undefined || (ask.editable === true && isRecord(raw.arguments))) &&
132
+ (raw.data === undefined || (ask.approveSchema !== undefined && isRecord(raw.data)))
133
+ )
134
+ return copyData({
135
+ type: "approve",
136
+ arguments: raw.arguments,
137
+ data: raw.data,
138
+ receipt: raw.receipt,
139
+ });
140
+ if (
141
+ raw.type === "deny" &&
142
+ keys(raw, [...common, "message", "data"]) &&
143
+ (raw.message === undefined || isId(raw.message)) &&
144
+ (raw.data === undefined || (ask.denySchema !== undefined && isRecord(raw.data)))
145
+ )
146
+ return copyData({ type: "deny", message: raw.message, data: raw.data, receipt: raw.receipt });
147
+ throw invalid();
148
+ }
149
+ if (ask.type === "client") {
150
+ if (raw.type !== "result" || !keys(raw, [...common, "value"]) || raw.value === undefined)
151
+ throw invalid();
152
+ return copyData({ type: "result", value: raw.value, receipt: raw.receipt });
153
+ }
154
+ if (raw.type !== "answer" || !keys(raw, [...common, "answer"]) || !isAnswer(raw.answer))
155
+ throw invalid();
156
+ const answer = raw.answer;
157
+ const choices = answer.choices ?? [];
158
+ if (
159
+ (answer.choices !== undefined && !ask.choices) ||
160
+ choices.some((id) => !ask.choices?.some((choice) => choice.id === id)) ||
161
+ new Set(choices).size !== choices.length ||
162
+ (!ask.multiple && choices.length > 1) ||
163
+ (answer.text !== undefined && !(ask.freeText || (!ask.choices && !ask.schema))) ||
164
+ (answer.data !== undefined && (!ask.schema || !isRecord(answer.data))) ||
165
+ (ask.schema && answer.data === undefined) ||
166
+ (!choices.length && answer.text === undefined && answer.data === undefined)
167
+ )
168
+ throw invalid();
169
+ return copyData({ type: "answer", answer, receipt: raw.receipt });
170
+ }
171
+
172
+ /** Canonical object ordering ported from TanStack AI (MIT), interrupt-serialization.ts.
173
+ * Reuse our JSON check and Web Crypto instead of carrying another SHA-256 implementation. */
174
+ export async function requestHash(value: unknown): Promise<string> {
175
+ function canonical(item: unknown): string {
176
+ if (Array.isArray(item)) return `[${item.map(canonical).join(",")}]`;
177
+ if (isRecord(item))
178
+ return `{${Object.keys(item)
179
+ .filter((key) => item[key] !== undefined)
180
+ .sort()
181
+ .map((key) => `${JSON.stringify(key)}:${canonical(item[key])}`)
182
+ .join(",")}}`;
183
+ return JSON.stringify(item);
184
+ }
185
+ const bytes = new TextEncoder().encode(canonical(copyData(value)));
186
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
187
+ return `sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
188
+ }
189
+
190
+ export interface ClientToolSpec<I, O> {
191
+ name: string;
192
+ description: string;
193
+ inputSchema: JsonObjectSchema;
194
+ /** Pure argument validation, before a client request is exposed. */
195
+ validate: (raw: unknown) => I;
196
+ result: { schema: JsonObjectSchema; validate: (raw: unknown) => O };
197
+ summarize?: (output: O) => string;
198
+ needsApproval?: boolean;
199
+ }
200
+
201
+ /** A host-registered deferred call, never an invokable local tool. */
202
+ export interface ClientTool {
203
+ readonly kind: "client";
204
+ readonly name: string;
205
+ readonly needsApproval: boolean;
206
+ readonly resultSchema: JsonObjectSchema;
207
+ definition(): ToolDefinition;
208
+ validateArguments(raw: unknown): void;
209
+ result(raw: unknown): { output: unknown; summary: string };
210
+ }
211
+
212
+ export function isClientTool(value: { readonly name: string }): value is ClientTool {
213
+ return "kind" in value && value.kind === "client";
214
+ }
215
+
216
+ export function defineClientTool<I, O>(spec: ClientToolSpec<I, O>): ClientTool {
217
+ if (
218
+ !isId(spec.name) ||
219
+ !isId(spec.description) ||
220
+ !schema(spec.inputSchema) ||
221
+ !schema(spec.result?.schema) ||
222
+ typeof spec.validate !== "function" ||
223
+ typeof spec.result.validate !== "function" ||
224
+ (spec.summarize !== undefined && typeof spec.summarize !== "function")
225
+ )
226
+ throw new TypeError("A client tool needs a name, schemas and input and result validators.");
227
+ const definition = immutableCopy({
228
+ name: spec.name,
229
+ description: spec.description,
230
+ inputSchema: spec.inputSchema,
231
+ });
232
+ const validate = spec.validate;
233
+ const validateResult = spec.result.validate;
234
+ const summarize = spec.summarize;
235
+ return Object.freeze({
236
+ kind: "client",
237
+ name: spec.name,
238
+ needsApproval: spec.needsApproval ?? false,
239
+ resultSchema: immutableCopy(spec.result.schema),
240
+ definition: () => copyData(definition),
241
+ validateArguments(raw: unknown) {
242
+ validate(copyData(raw));
243
+ },
244
+ result(raw: unknown) {
245
+ const output = validateResult(copyData(raw));
246
+ const summary = summarize ? summarize(output) : JSON.stringify(output);
247
+ if (typeof summary !== "string") throw new TypeError("A client result summary must be text.");
248
+ return { output, summary };
249
+ },
250
+ });
251
+ }
252
+
253
+ /** Read only SDK-supplied answers; a host context cannot grant itself a decision. */
254
+ export function answerOf(context: ToolContext, key: string): Answer | undefined {
255
+ const answers = context.answers;
256
+ if (!isRecord(answers) || !Object.hasOwn(answers, key)) return undefined;
257
+ const answer = answers[key];
258
+ return isAnswer(answer) ? copyData(answer) : undefined;
259
+ }
260
+
261
+ /** The model can ask for text, one choice or several choices. For typed forms use a
262
+ * host-defined InputRequired question or a coordinator's ask with a runtime validator. */
263
+ export function questionTool(options: { name?: string; description?: string } = {}): Tool {
264
+ const tool = defineTool({
265
+ name: options.name ?? "ask_question",
266
+ description: options.description ?? "Ask the person a question and wait for their answer.",
267
+ inputSchema: {
268
+ type: "object",
269
+ properties: {
270
+ message: { type: "string" },
271
+ choices: {
272
+ type: "array",
273
+ items: {
274
+ type: "object",
275
+ properties: {
276
+ id: { type: "string" },
277
+ label: { type: "string" },
278
+ description: { type: "string" },
279
+ },
280
+ required: ["id", "label"],
281
+ additionalProperties: false,
282
+ },
283
+ },
284
+ multiple: { type: "boolean" },
285
+ freeText: { type: "boolean" },
286
+ },
287
+ required: ["message"],
288
+ additionalProperties: false,
289
+ },
290
+ isReadOnly: true,
291
+ isConcurrencySafe: true,
292
+ validate(raw) {
293
+ if (!isRecord(raw) || !keys(raw, ["message", "choices", "multiple", "freeText"]))
294
+ throw new TypeError("Pass a question and optional choices.");
295
+ const ask = { ...raw, type: "question", key: "answer" };
296
+ if (!isAsk(ask) || ask.type !== "question")
297
+ throw new TypeError("Provide a question with distinct choices.");
298
+ return ask;
299
+ },
300
+ async run(ask, context) {
301
+ const answer = answerOf(context, ask.key);
302
+ if (answer) return answer;
303
+ throw new InputRequired(ask);
304
+ },
305
+ });
306
+ return Object.assign(tool, { [QUESTION_TOOL]: true });
307
+ }
308
+
309
+ /** One call's request receipts. No second store or independent continuation engine. */
310
+ export class RequestJournal<C extends ToolRequest | StepRequest = ToolRequest> {
311
+ constructor(
312
+ readonly execution: { asks?: AskRecord[] },
313
+ readonly call: C,
314
+ private readonly options: RunOptions,
315
+ private readonly scope: ExecutionScope,
316
+ private readonly signal: AbortSignal,
317
+ private readonly identity: () => Promise<string>,
318
+ private readonly validate: (decision: Decision) => void = () => {},
319
+ // Decisions can contain a client result or answer before toolOutput checks it. Keep the
320
+ // authoritative decision in the private journal, never bypass the guard through progress.
321
+ private readonly withholdDecisions = false,
322
+ ) {}
323
+
324
+ latest(ask: Ask): AskRecord | undefined {
325
+ return [...(this.execution.asks ?? [])]
326
+ .reverse()
327
+ .find(
328
+ (record) =>
329
+ !record.closed &&
330
+ record.request.ask.type === ask.type &&
331
+ (ask.type !== "question" ||
332
+ (record.request.ask.type === "question" && record.request.ask.key === ask.key)),
333
+ );
334
+ }
335
+
336
+ async open(ask: Ask, problem?: AskRecord["problem"]): Promise<AskRecord> {
337
+ if (!isAsk(ask)) throw new TypeError("Invalid human request.");
338
+ const prepare = this.options.host?.prepareRequest;
339
+ if (!prepare)
340
+ fail(
341
+ "request_host_missing",
342
+ "Provide host.prepareRequest to ask for input.",
343
+ this.call.operationId,
344
+ );
345
+ const origin: RequestOrigin =
346
+ "workflowId" in this.call ? { step: this.call } : { call: this.call };
347
+ const draft = {
348
+ id: `${this.call.operationId}/ask/${(this.execution.asks?.length ?? 0) + 1}`,
349
+ path: this.scope.path,
350
+ ...origin,
351
+ definitionHash: await this.identity(),
352
+ ask,
353
+ createdAt: Date.now(),
354
+ };
355
+ const prepared = await untilAbort(Promise.resolve(prepare(immutableCopy(draft))), this.signal);
356
+ if (
357
+ !prepared ||
358
+ !isScope(prepared.scope) ||
359
+ prepared.scope.expiresAt <= Date.now() ||
360
+ (prepared.ask !== undefined &&
361
+ (ask.type !== "approval" || !isAsk(prepared.ask) || prepared.ask.type !== "approval"))
362
+ )
363
+ fail(
364
+ "invalid_request_scope",
365
+ "Supply an actor, resource version and future expiry. Only approval policy may be changed.",
366
+ this.call.operationId,
367
+ );
368
+ const record: AskRecord = {
369
+ request: copyData({ ...draft, ask: prepared.ask ?? ask, scope: prepared.scope }),
370
+ ...(problem ? { problem } : {}),
371
+ };
372
+ (this.execution.asks ??= []).push(record);
373
+ await this.scope.tree.save();
374
+ emitEvent(this.options, { type: "request", request: record.request });
375
+ // A replacement needs a fresh answer. Reapplying a standing decision here could leave
376
+ // the caller suspended with no open request after expiry or failed form validation.
377
+ if (!problem) {
378
+ const answer = await untilAbort(
379
+ Promise.resolve(this.options.host?.answerNow?.(immutableCopy(record.request))),
380
+ this.signal,
381
+ );
382
+ if (answer !== undefined) await this.accept(record, answer);
383
+ }
384
+ return record;
385
+ }
386
+
387
+ async accept(record: AskRecord, resolution: Resolution): Promise<void> {
388
+ if (record.closed || record.decision) throw new TypeError("This request is no longer pending.");
389
+ try {
390
+ if (isRecord(resolution) && resolution.type === "pending") {
391
+ if (resolution.problem !== undefined && !isId(resolution.problem))
392
+ throw new TypeError("A request problem must be text.");
393
+ record.problem = {
394
+ code: "refused",
395
+ message:
396
+ resolution.problem ??
397
+ "The host has not accepted this answer. Check access and try again.",
398
+ };
399
+ } else {
400
+ const decision = checkDecision(record.request.ask, resolution);
401
+ this.validate(decision);
402
+ record.decision = decision;
403
+ delete record.problem;
404
+ }
405
+ } catch (error) {
406
+ record.problem = { code: "invalid_answer", message: messageOf(error) };
407
+ }
408
+ await this.scope.tree.save();
409
+ if (record.decision && !this.withholdDecisions)
410
+ emitEvent(this.options, {
411
+ type: "decision",
412
+ requestId: record.request.id,
413
+ decision: record.decision,
414
+ });
415
+ // A later request can stop while an earlier one is still open. Cancel at acceptance,
416
+ // not when execution eventually reaches this call, and only after saving the decision.
417
+ if (record.decision?.type === "stop") {
418
+ this.scope.tree.stop();
419
+ throw new Halt({ status: "cancelled" });
420
+ }
421
+ }
422
+
423
+ async refresh(record: AskRecord): Promise<AskRecord> {
424
+ const stale = record.request.definitionHash !== (await this.identity());
425
+ // Identity checks may await host policy. Measure expiry after that callback, not before it.
426
+ const expired = record.request.scope.expiresAt <= Date.now();
427
+ if (!expired && !stale) return record;
428
+ // Exposing a client request can start an external effect. Expiry or definition drift is
429
+ // not proof that the receiver did nothing, so never issue a replacement automatically.
430
+ if (record.request.ask.type === "client")
431
+ fail(
432
+ "client_result_unknown",
433
+ "The client request expired or changed. Reconcile its result with the host; it will not be sent again.",
434
+ this.call.operationId,
435
+ );
436
+ record.closed = expired ? "expired" : "stale";
437
+ return this.open(record.request.ask, {
438
+ code: record.closed,
439
+ message: expired
440
+ ? "This request expired. Answer the new request."
441
+ : "The tool changed. Review the new request before answering.",
442
+ });
443
+ }
444
+
445
+ async ensure(ask: Ask): Promise<AskRecord> {
446
+ const existing = this.latest(ask);
447
+ if (!existing) return this.open(ask);
448
+ if (ask.type === "question" && !equalData(ask, existing.request.ask)) {
449
+ existing.closed = "stale";
450
+ return this.open(ask, {
451
+ code: "stale",
452
+ message: "The question changed. Answer the new request.",
453
+ });
454
+ }
455
+ return this.refresh(existing);
456
+ }
457
+
458
+ async resolve(record: AskRecord, evidence: unknown): Promise<void> {
459
+ if ((await this.refresh(record)) !== record) return;
460
+ const resolve = this.options.host?.resolveRequest;
461
+ if (!resolve)
462
+ fail(
463
+ "request_host_missing",
464
+ "Provide host.resolveRequest to authenticate and consume answers.",
465
+ );
466
+ const resolution = await untilAbort(
467
+ Promise.resolve(resolve(immutableCopy(record.request), immutableCopy(evidence))),
468
+ this.signal,
469
+ );
470
+ if (record.request.scope.expiresAt <= Date.now()) {
471
+ await this.refresh(record);
472
+ return;
473
+ }
474
+ await this.accept(record, resolution);
475
+ }
476
+
477
+ async assertFresh(): Promise<void> {
478
+ for (const record of this.execution.asks ?? [])
479
+ if (!record.closed && record.decision && (await this.refresh(record)) !== record)
480
+ throw new Halt({ status: "suspended" });
481
+ }
482
+
483
+ async recheck(call: C): Promise<void> {
484
+ const decided = (this.execution.asks ?? []).filter(
485
+ (record) => record.decision && !record.closed,
486
+ );
487
+ const host = this.options.host;
488
+ const isStep = "workflowId" in call;
489
+ if ((isStep || decided.length) && !(isStep ? host?.beforeStep : host?.beforeTool))
490
+ fail(
491
+ "request_host_missing",
492
+ isStep
493
+ ? "Provide host.beforeStep to check ownership before workflow work."
494
+ : "Provide host.beforeTool to recheck access before using an answer.",
495
+ call.operationId,
496
+ );
497
+ const current: ToolRequest | StepRequest = call;
498
+ const before = (record?: AskRecord) => {
499
+ const decision = record?.decision
500
+ ? immutableCopy({ request: record.request, decision: record.decision })
501
+ : undefined;
502
+ return "workflowId" in current
503
+ ? host?.beforeStep?.(immutableCopy(current), decision)
504
+ : host?.beforeTool?.(immutableCopy(current), decision);
505
+ };
506
+ for (const record of decided) {
507
+ if ((await this.refresh(record)) !== record) throw new Halt({ status: "suspended" });
508
+ await untilAbort(Promise.resolve(before(record)), this.signal);
509
+ if ((await this.refresh(record)) !== record) throw new Halt({ status: "suspended" });
510
+ }
511
+ if (!decided.length) await untilAbort(Promise.resolve(before()), this.signal);
512
+ }
513
+ }