@soverius-ai/browser-models 0.0.0-stage → 0.1.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 (81) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +23 -2
  3. package/package.json +85 -3
  4. package/src/agent.d.ts +52 -0
  5. package/src/agent.js +128 -0
  6. package/src/agent.js.map +1 -0
  7. package/src/copilotkit.d.ts +20 -0
  8. package/src/copilotkit.js +163 -0
  9. package/src/copilotkit.js.map +1 -0
  10. package/src/engines/opfs-cache.d.ts +11 -0
  11. package/src/engines/opfs-cache.js +43 -0
  12. package/src/engines/opfs-cache.js.map +1 -0
  13. package/src/engines/prompt-api.d.ts +50 -0
  14. package/src/engines/prompt-api.js +124 -0
  15. package/src/engines/prompt-api.js.map +1 -0
  16. package/src/engines/shared-load.d.ts +20 -0
  17. package/src/engines/shared-load.js +67 -0
  18. package/src/engines/shared-load.js.map +1 -0
  19. package/src/engines/transformers.d.ts +45 -0
  20. package/src/engines/transformers.js +209 -0
  21. package/src/engines/transformers.js.map +1 -0
  22. package/src/engines/web-llm-worker.d.ts +10 -0
  23. package/src/engines/web-llm-worker.js +15 -0
  24. package/src/engines/web-llm-worker.js.map +1 -0
  25. package/src/engines/web-llm.d.ts +41 -0
  26. package/src/engines/web-llm.js +135 -0
  27. package/src/engines/web-llm.js.map +1 -0
  28. package/src/index.d.ts +7 -0
  29. package/src/index.js +6 -0
  30. package/src/index.js.map +1 -0
  31. package/src/lib/abort.d.ts +10 -0
  32. package/src/lib/abort.js +24 -0
  33. package/src/lib/abort.js.map +1 -0
  34. package/src/lib/async-queue.d.ts +8 -0
  35. package/src/lib/async-queue.js +35 -0
  36. package/src/lib/async-queue.js.map +1 -0
  37. package/src/lib/engine.d.ts +45 -0
  38. package/src/lib/engine.js +2 -0
  39. package/src/lib/engine.js.map +1 -0
  40. package/src/lib/parser.d.ts +40 -0
  41. package/src/lib/parser.js +124 -0
  42. package/src/lib/parser.js.map +1 -0
  43. package/src/lib/partial-json.d.ts +21 -0
  44. package/src/lib/partial-json.js +88 -0
  45. package/src/lib/partial-json.js.map +1 -0
  46. package/src/lib/prompt.d.ts +9 -0
  47. package/src/lib/prompt.js +82 -0
  48. package/src/lib/prompt.js.map +1 -0
  49. package/src/lib/repair.d.ts +47 -0
  50. package/src/lib/repair.js +217 -0
  51. package/src/lib/repair.js.map +1 -0
  52. package/src/lib/run.d.ts +40 -0
  53. package/src/lib/run.js +434 -0
  54. package/src/lib/run.js.map +1 -0
  55. package/src/lib/schema.d.ts +21 -0
  56. package/src/lib/schema.js +128 -0
  57. package/src/lib/schema.js.map +1 -0
  58. package/src/lib/tools.d.ts +33 -0
  59. package/src/lib/tools.js +20 -0
  60. package/src/lib/tools.js.map +1 -0
  61. package/src/mcp.d.ts +54 -0
  62. package/src/mcp.js +204 -0
  63. package/src/mcp.js.map +1 -0
  64. package/src/model-store.d.ts +72 -0
  65. package/src/model-store.js +139 -0
  66. package/src/model-store.js.map +1 -0
  67. package/src/prompt-api.d.ts +1 -0
  68. package/src/prompt-api.js +3 -0
  69. package/src/prompt-api.js.map +1 -0
  70. package/src/transformers.d.ts +1 -0
  71. package/src/transformers.js +3 -0
  72. package/src/transformers.js.map +1 -0
  73. package/src/web-llm-worker.d.ts +1 -0
  74. package/src/web-llm-worker.js +3 -0
  75. package/src/web-llm-worker.js.map +1 -0
  76. package/src/web-llm.d.ts +1 -0
  77. package/src/web-llm.js +3 -0
  78. package/src/web-llm.js.map +1 -0
  79. package/src/webmcp.d.ts +43 -0
  80. package/src/webmcp.js +58 -0
  81. package/src/webmcp.js.map +1 -0
package/src/lib/run.js ADDED
@@ -0,0 +1,434 @@
1
+ import { EventType, } from '@ag-ui/core';
2
+ import { AsyncQueue } from "./async-queue.js";
3
+ import { OutputParser } from "./parser.js";
4
+ import { buildChatMessages, toolCallBlock, toolResultBlock } from "./prompt.js";
5
+ import { ToolCallRepair } from "./repair.js";
6
+ import { resolveLocalTools, } from "./tools.js";
7
+ /** `activityType` of the model loading events. */
8
+ export const MODEL_ACTIVITY = 'soverius.model';
9
+ const CUT_OFF = 'The tool call was cut off before it was complete. Send the whole call again.';
10
+ /**
11
+ * One AG-UI run against a browser engine. `events()` yields its AG-UI events.
12
+ *
13
+ * - Text is streamed as TEXT_MESSAGE_* events.
14
+ * - A tool call is streamed while the model writes it: TOOL_CALL_START when the name is
15
+ * known, then TOOL_CALL_ARGS deltas.
16
+ * - Every tool call is repaired once it is complete (see ToolCallRepair). AG-UI cannot take
17
+ * back arguments that were sent, so the call stays open until it is repaired. When the
18
+ * repaired call continues what was sent, the rest follows as a delta. If not, a
19
+ * MESSAGES_SNAPSHOT replaces the call (or removes it, when it cannot be repaired). Only then
20
+ * comes TOOL_CALL_END, so at TOOL_CALL_END the client always holds the repaired call.
21
+ * - Local tools run here and the loop continues with their result.
22
+ * - A frontend tool call ends the run: the client runs it and starts a follow-up run.
23
+ */
24
+ export class AgentRun {
25
+ #options;
26
+ #signal;
27
+ /** What this run added to the conversation, with repaired tool calls only. */
28
+ #produced = [];
29
+ #open = new Set();
30
+ constructor(options) {
31
+ this.#options = options;
32
+ this.#signal = options.signal ?? new AbortController().signal;
33
+ }
34
+ /** Runs the run. Call it once. */
35
+ async *events() {
36
+ const { threadId, runId } = this.#options.input;
37
+ yield { type: EventType.RUN_STARTED, threadId, runId };
38
+ try {
39
+ yield* this.#steps();
40
+ yield { type: EventType.RUN_FINISHED, threadId, runId };
41
+ }
42
+ catch (error) {
43
+ // Calls that were never repaired must not stay with the client, or open.
44
+ if (this.#open.size > 0)
45
+ yield this.#snapshot();
46
+ for (const call of this.#open) {
47
+ yield { type: EventType.TOOL_CALL_END, toolCallId: call.id };
48
+ }
49
+ if (this.#signal.aborted) {
50
+ // Same code as @ag-ui/client's HttpAgent.
51
+ yield {
52
+ type: EventType.RUN_ERROR,
53
+ message: 'The run was stopped.',
54
+ code: 'abort',
55
+ };
56
+ }
57
+ else {
58
+ const message = error instanceof Error ? error.message : String(error);
59
+ yield { type: EventType.RUN_ERROR, message };
60
+ }
61
+ }
62
+ }
63
+ async *#steps() {
64
+ const { engine, input } = this.#options;
65
+ const signal = this.#signal;
66
+ // A client tool wins over a local tool of the same name (CopilotKit can also publish its
67
+ // tools to WebMCP, so the same tool may arrive both ways).
68
+ const clientNames = new Set(input.tools.map((tool) => tool.name));
69
+ const resolved = await resolveLocalTools(this.#options.localTools ?? [], signal);
70
+ for (const message of resolved.errors) {
71
+ yield {
72
+ type: EventType.CUSTOM,
73
+ name: 'soverius.tool_source_error',
74
+ value: { message },
75
+ };
76
+ }
77
+ const localTools = resolved.tools.filter((tool) => !clientNames.has(tool.name));
78
+ const tools = [...input.tools, ...localTools];
79
+ const chat = buildChatMessages(input.messages, input.context, tools);
80
+ const repair = new ToolCallRepair(tools, {
81
+ reask: (tool, error, raw) => this.#reask(chat, raw, tool, error),
82
+ ...(this.#options.repairHook ? { hook: this.#options.repairHook } : {}),
83
+ });
84
+ yield* this.#loadModel();
85
+ signal.throwIfAborted();
86
+ for (let step = 0; step < (this.#options.maxSteps ?? 5); step++) {
87
+ const reply = new ReplyStream(repair, this.#open);
88
+ const { message } = reply;
89
+ this.#produced.push(message);
90
+ const parser = new OutputParser();
91
+ for await (const fragment of engine.generate({
92
+ messages: chat,
93
+ signal,
94
+ })) {
95
+ yield* reply.events(parser.push(fragment));
96
+ }
97
+ // Not every engine throws when it is stopped. A stopped call must not be repaired or run.
98
+ signal.throwIfAborted();
99
+ yield* reply.events(parser.end());
100
+ if (message.content) {
101
+ yield { type: EventType.TEXT_MESSAGE_END, messageId: message.id };
102
+ }
103
+ if (reply.calls.length === 0)
104
+ return;
105
+ const assistantTurn = message.content ? [message.content] : [];
106
+ const results = [];
107
+ let frontendCalled = false;
108
+ for (const { raw, streamed, cut } of reply.calls) {
109
+ signal.throwIfAborted();
110
+ // A call that was cut off is not guessed at: half the arguments may be missing.
111
+ const repaired = cut
112
+ ? { ok: false, error: CUT_OFF }
113
+ : await repair.repair(raw);
114
+ // A stopped re-ask counts as failed in ToolCallRepair; stop here instead.
115
+ signal.throwIfAborted();
116
+ if (!repaired.ok) {
117
+ if (streamed) {
118
+ // Take the call back from the client.
119
+ yield this.#snapshot();
120
+ yield { type: EventType.TOOL_CALL_END, toolCallId: streamed.id };
121
+ this.#open.delete(streamed);
122
+ }
123
+ // Tell the model what was wrong and let it try again in the next step.
124
+ assistantTurn.push('```tool_call\n' + raw + '\n```');
125
+ results.push(toolResultBlock('error', repaired.error));
126
+ continue;
127
+ }
128
+ const { call, steps } = repaired;
129
+ const toolCallId = streamed?.id ?? crypto.randomUUID();
130
+ const argumentsJson = JSON.stringify(call.arguments);
131
+ message.toolCalls.push({
132
+ id: toolCallId,
133
+ type: 'function',
134
+ function: { name: call.name, arguments: argumentsJson },
135
+ });
136
+ if (steps.length > 0) {
137
+ yield {
138
+ type: EventType.CUSTOM,
139
+ name: 'soverius.tool_repair',
140
+ value: { toolCallId, raw, steps },
141
+ };
142
+ }
143
+ if (!streamed) {
144
+ // The name was only known with the complete call (for example it came after the
145
+ // arguments, or the repair hook supplied it), so the call starts here.
146
+ yield {
147
+ type: EventType.TOOL_CALL_START,
148
+ toolCallId,
149
+ toolCallName: call.name,
150
+ parentMessageId: message.id,
151
+ };
152
+ }
153
+ const delta = rest(argumentsJson, streamed?.sent ?? '');
154
+ if (streamed && (streamed.name !== call.name || delta === undefined)) {
155
+ // Repair changed what the client already has: replace it.
156
+ yield this.#snapshot();
157
+ }
158
+ else if (delta) {
159
+ yield { type: EventType.TOOL_CALL_ARGS, toolCallId, delta };
160
+ }
161
+ yield { type: EventType.TOOL_CALL_END, toolCallId };
162
+ if (streamed)
163
+ this.#open.delete(streamed);
164
+ assistantTurn.push(toolCallBlock(call.name, argumentsJson));
165
+ const local = localTools.find((tool) => tool.name === call.name);
166
+ if (!local) {
167
+ frontendCalled = true;
168
+ continue;
169
+ }
170
+ signal.throwIfAborted();
171
+ const result = await this.#runLocalTool(local, call.arguments);
172
+ const resultId = crypto.randomUUID();
173
+ this.#produced.push({
174
+ id: resultId,
175
+ role: 'tool',
176
+ toolCallId,
177
+ content: result,
178
+ });
179
+ yield {
180
+ type: EventType.TOOL_CALL_RESULT,
181
+ messageId: resultId,
182
+ toolCallId,
183
+ content: result,
184
+ role: 'tool',
185
+ };
186
+ results.push(toolResultBlock(call.name, result));
187
+ }
188
+ if (frontendCalled)
189
+ return;
190
+ chat.push({ role: 'assistant', content: assistantTurn.join('\n') });
191
+ chat.push({ role: 'user', content: results.join('\n') });
192
+ }
193
+ }
194
+ /**
195
+ * Everything the client should hold now: the messages it sent plus what this run produced.
196
+ * The client replaces its messages with these, which is the only way in AG-UI to change or
197
+ * remove a tool call that was already streamed.
198
+ */
199
+ #snapshot() {
200
+ return {
201
+ type: EventType.MESSAGES_SNAPSHOT,
202
+ // A copy: the client changes the messages it holds.
203
+ messages: structuredClone([
204
+ // The client keeps its activity and reasoning messages when the snapshot has none.
205
+ ...this.#options.input.messages.filter((message) => message.role !== 'activity' && message.role !== 'reasoning'),
206
+ ...this.#produced.filter((message) => message.role !== 'assistant' ||
207
+ message.content ||
208
+ message.toolCalls?.length),
209
+ ]),
210
+ };
211
+ }
212
+ /**
213
+ * Loads the model before the first answer. While the engine reports progress, emits
214
+ * `ACTIVITY_SNAPSHOT` events (`activityType: 'soverius.model'`, content
215
+ * `{ engineId, status: 'loading' | 'ready', progress }`) so any AG-UI client can show it.
216
+ * A model that is already loaded reports nothing, so the run has no extra events.
217
+ */
218
+ async *#loadModel() {
219
+ const { engine } = this.#options;
220
+ const messageId = crypto.randomUUID();
221
+ const progress = new AsyncQueue();
222
+ engine
223
+ .load({
224
+ signal: this.#signal,
225
+ onProgress: (fraction) => progress.push(fraction),
226
+ })
227
+ .then(() => progress.close(), (error) => progress.fail(error));
228
+ let reported = false;
229
+ let lastPercent = -1;
230
+ for await (const fraction of progress) {
231
+ // Engines report progress very often; one event per whole percent is enough.
232
+ const percent = Math.floor(fraction * 100);
233
+ if (percent === lastPercent)
234
+ continue;
235
+ lastPercent = percent;
236
+ reported = true;
237
+ yield {
238
+ type: EventType.ACTIVITY_SNAPSHOT,
239
+ messageId,
240
+ activityType: MODEL_ACTIVITY,
241
+ content: { engineId: engine.id, status: 'loading', progress: fraction },
242
+ };
243
+ }
244
+ if (reported) {
245
+ yield {
246
+ type: EventType.ACTIVITY_SNAPSHOT,
247
+ messageId,
248
+ activityType: MODEL_ACTIVITY,
249
+ content: { engineId: engine.id, status: 'ready', progress: 1 },
250
+ };
251
+ }
252
+ }
253
+ async #runLocalTool(tool, args) {
254
+ try {
255
+ const result = await tool.execute({ ...args }, this.#signal);
256
+ return typeof result === 'string' ? result : JSON.stringify(result);
257
+ }
258
+ catch (error) {
259
+ return JSON.stringify({
260
+ error: error instanceof Error ? error.message : String(error),
261
+ });
262
+ }
263
+ }
264
+ /**
265
+ * Asks the model once for corrected arguments, forcing JSON output when the engine can. The
266
+ * model sees its own call (`raw`) and the tool's schema. It may answer with the arguments or
267
+ * with a whole new tool call.
268
+ */
269
+ async #reask(chat, raw, tool, error) {
270
+ const { engine } = this.#options;
271
+ const schema = JSON.stringify(tool.parameters ?? { type: 'object' });
272
+ const request = {
273
+ role: 'user',
274
+ content: `Your call to the tool "${tool.name}" had invalid arguments: ${error}. The arguments must match this JSON Schema: ${schema}. Reply with only the corrected arguments as one JSON object.`,
275
+ };
276
+ // Same parser as the main loop, so thinking (<think>…</think>) is not part of the answer.
277
+ const parser = new OutputParser();
278
+ let text = '';
279
+ let call;
280
+ const keep = (parts) => {
281
+ for (const part of parts) {
282
+ if (part.kind === 'text')
283
+ text += part.text;
284
+ if (part.kind === 'tool-call')
285
+ call = part.raw;
286
+ }
287
+ };
288
+ for await (const fragment of engine.generate({
289
+ messages: [
290
+ ...chat,
291
+ { role: 'assistant', content: '```tool_call\n' + raw + '\n```' },
292
+ request,
293
+ ],
294
+ signal: this.#signal,
295
+ ...(engine.supportsConstraint && tool.parameters
296
+ ? { constraint: tool.parameters }
297
+ : {}),
298
+ })) {
299
+ keep(parser.push(fragment));
300
+ }
301
+ keep(parser.end());
302
+ return (call ?? text).trim() || undefined;
303
+ }
304
+ }
305
+ /**
306
+ * Turns the parts of one model reply into AG-UI events while the model is still writing:
307
+ * text, thinking, and the start and argument deltas of tool calls. Finished calls are
308
+ * collected in `calls`; AgentRun repairs and ends them.
309
+ */
310
+ class ReplyStream {
311
+ /** The assistant message of this reply, as the client should hold it. */
312
+ message = {
313
+ id: crypto.randomUUID(),
314
+ role: 'assistant',
315
+ content: '',
316
+ toolCalls: [],
317
+ };
318
+ calls = [];
319
+ #repair;
320
+ #open;
321
+ /** The call the model is writing right now, once it was started. */
322
+ #streaming;
323
+ #reasoningId;
324
+ constructor(repair, open) {
325
+ this.#repair = repair;
326
+ this.#open = open;
327
+ }
328
+ *events(parts) {
329
+ const messageId = this.message.id;
330
+ for (const part of parts) {
331
+ switch (part.kind) {
332
+ case 'tool-call-partial':
333
+ yield* this.#streamCall(part.raw);
334
+ break;
335
+ case 'tool-call':
336
+ case 'tool-call-cut':
337
+ this.calls.push({
338
+ raw: part.raw,
339
+ streamed: this.#streaming,
340
+ cut: part.kind === 'tool-call-cut',
341
+ });
342
+ this.#streaming = undefined;
343
+ break;
344
+ case 'reasoning':
345
+ // Skip leading whitespace, for example the empty <think></think> of Qwen3.
346
+ if (!this.#reasoningId && !part.text.trim())
347
+ break;
348
+ if (!this.#reasoningId) {
349
+ this.#reasoningId = crypto.randomUUID();
350
+ yield {
351
+ type: EventType.REASONING_START,
352
+ messageId: this.#reasoningId,
353
+ };
354
+ yield {
355
+ type: EventType.REASONING_MESSAGE_START,
356
+ messageId: this.#reasoningId,
357
+ role: 'reasoning',
358
+ };
359
+ }
360
+ yield {
361
+ type: EventType.REASONING_MESSAGE_CONTENT,
362
+ messageId: this.#reasoningId,
363
+ delta: part.text,
364
+ };
365
+ break;
366
+ case 'reasoning-end':
367
+ if (this.#reasoningId) {
368
+ yield {
369
+ type: EventType.REASONING_MESSAGE_END,
370
+ messageId: this.#reasoningId,
371
+ };
372
+ yield {
373
+ type: EventType.REASONING_END,
374
+ messageId: this.#reasoningId,
375
+ };
376
+ this.#reasoningId = undefined;
377
+ }
378
+ break;
379
+ case 'text': {
380
+ // Drop the whitespace that models put between thinking and the answer.
381
+ const delta = this.message.content
382
+ ? part.text
383
+ : part.text.trimStart();
384
+ if (!delta)
385
+ break;
386
+ if (!this.message.content) {
387
+ yield {
388
+ type: EventType.TEXT_MESSAGE_START,
389
+ messageId,
390
+ role: 'assistant',
391
+ };
392
+ }
393
+ this.message.content += delta;
394
+ yield { type: EventType.TEXT_MESSAGE_CONTENT, messageId, delta };
395
+ break;
396
+ }
397
+ }
398
+ }
399
+ }
400
+ /** Sends what is new in the call the model is writing: its start, then argument deltas. */
401
+ *#streamCall(raw) {
402
+ const partial = this.#repair.readPartial(raw);
403
+ if (!partial)
404
+ return;
405
+ if (!this.#streaming) {
406
+ this.#streaming = {
407
+ id: crypto.randomUUID(),
408
+ name: partial.name,
409
+ sent: '',
410
+ };
411
+ this.#open.add(this.#streaming);
412
+ yield {
413
+ type: EventType.TOOL_CALL_START,
414
+ toolCallId: this.#streaming.id,
415
+ toolCallName: this.#streaming.name,
416
+ parentMessageId: this.message.id,
417
+ };
418
+ }
419
+ const delta = rest(partial.argumentsJson, this.#streaming.sent);
420
+ if (delta) {
421
+ this.#streaming.sent += delta;
422
+ yield {
423
+ type: EventType.TOOL_CALL_ARGS,
424
+ toolCallId: this.#streaming.id,
425
+ delta,
426
+ };
427
+ }
428
+ }
429
+ }
430
+ /** What is left of `full` after `sent`, or undefined when `full` does not start with `sent`. */
431
+ function rest(full, sent) {
432
+ return full.startsWith(sent) ? full.slice(sent.length) : undefined;
433
+ }
434
+ //# sourceMappingURL=run.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run.js","sourceRoot":"","sources":["../../../../../../libs/agent/browser-models/src/lib/run.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,GAKV,MAAM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,CAAC,UAAU,EAAE,CAAC;YACrB,IAAI,CAAC,UAAU,GAAG;gBAChB,EAAE,EAAE,MAAM,CAAC,UAAU,EAAE;gBACvB,IAAI,EAAE,OAAO,CAAC,IAAI;gBAClB,IAAI,EAAE,EAAE;aACT,CAAC;YACF,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YAChC,MAAM;gBACJ,IAAI,EAAE,SAAS,CAAC,eAAe;gBAC/B,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE;gBAC9B,YAAY,EAAE,IAAI,CAAC,UAAU,CAAC,IAAI;gBAClC,eAAe,EAAE,IAAI,CAAC,OAAO,CAAC,EAAE;aACjC,CAAC;QACJ,CAAC;QACD,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;QAChE,IAAI,KAAK,EAAE,CAAC;YACV,IAAI,CAAC,UAAU,CAAC,IAAI,IAAI,KAAK,CAAC;YAC9B,MAAM;gBACJ,IAAI,EAAE,SAAS,CAAC,cAAc;gBAC9B,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE;gBAC9B,KAAK;aACN,CAAC;QACJ,CAAC;IACH,CAAC;CACF;AAED,gGAAgG;AAChG,SAAS,IAAI,CAAC,IAAY,EAAE,IAAY;IACtC,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AACrE,CAAC"}
@@ -0,0 +1,21 @@
1
+ import type { JsonSchema } from './engine.ts';
2
+ export interface SchemaCheck {
3
+ /** The value after safe coercions such as "5" → 5. */
4
+ readonly value: unknown;
5
+ /** Human-readable problems. Empty means the value is valid. */
6
+ readonly errors: readonly string[];
7
+ /** True when coercion changed the value. */
8
+ readonly coerced: boolean;
9
+ }
10
+ /**
11
+ * Checks tool arguments against the tool's JSON Schema with zod (`z.fromJSONSchema`) and
12
+ * fixes the safe mistakes small models make: "5" → 5, "true" → true, 5 → "5", value → [value],
13
+ * wrong enum case, `null` for "not given" and keys the schema does not allow.
14
+ */
15
+ export declare class ArgumentsSchema {
16
+ #private;
17
+ /** The compiled schema, made once per JSON Schema object. */
18
+ static of(json: JsonSchema): ArgumentsSchema;
19
+ constructor(json: JsonSchema);
20
+ check(input: unknown): SchemaCheck;
21
+ }
@@ -0,0 +1,128 @@
1
+ import { z } from 'zod';
2
+ /** How often the mistakes zod reports are fixed before the rest is reported. */
3
+ const MAX_FIXES = 3;
4
+ /** An object or array: something a zod issue path can lead into. */
5
+ const container = z.instanceof(Object);
6
+ const compiled = new WeakMap();
7
+ /**
8
+ * Checks tool arguments against the tool's JSON Schema with zod (`z.fromJSONSchema`) and
9
+ * fixes the safe mistakes small models make: "5" → 5, "true" → true, 5 → "5", value → [value],
10
+ * wrong enum case, `null` for "not given" and keys the schema does not allow.
11
+ */
12
+ export class ArgumentsSchema {
13
+ #schema;
14
+ /** The compiled schema, made once per JSON Schema object. */
15
+ static of(json) {
16
+ let schema = compiled.get(json);
17
+ if (!schema)
18
+ compiled.set(json, (schema = new ArgumentsSchema(json)));
19
+ return schema;
20
+ }
21
+ constructor(json) {
22
+ try {
23
+ this.#schema = z.fromJSONSchema(json);
24
+ }
25
+ catch {
26
+ // JSON Schema that zod cannot read (`not`, `if`/`then`, external `$ref`) must not make
27
+ // the tool unusable: its arguments only have to be an object.
28
+ this.#schema = z.record(z.string(), z.unknown());
29
+ }
30
+ }
31
+ check(input) {
32
+ const value = structuredClone(input);
33
+ let coerced = false;
34
+ for (let pass = 0;; pass++) {
35
+ const result = this.#schema.safeParse(value);
36
+ if (result.success) {
37
+ // zod orders keys as the schema does. Arguments that were already sent to the client
38
+ // must keep their order, so its copy is only used when it has more: the defaults.
39
+ const filled = size(result.data) !== size(value);
40
+ return {
41
+ value: filled ? result.data : value,
42
+ errors: [],
43
+ coerced: coerced || filled,
44
+ };
45
+ }
46
+ const { issues } = result.error;
47
+ const fixed = pass < MAX_FIXES && issues.filter((issue) => fix(value, issue)).length;
48
+ if (!fixed) {
49
+ const errors = issues.map((issue) => describe(value, issue));
50
+ return { value, errors, coerced };
51
+ }
52
+ coerced = true;
53
+ }
54
+ }
55
+ }
56
+ function size(value) {
57
+ return JSON.stringify(value)?.length ?? 0;
58
+ }
59
+ /** Fixes in `root` what `issue` reports. False when there is no safe fix. */
60
+ function fix(root, issue) {
61
+ if (issue.code === 'unrecognized_keys') {
62
+ // Drop keys the schema does not allow instead of failing the whole call.
63
+ const target = container.safeParse(read(root, issue.path)).data;
64
+ return (target !== undefined &&
65
+ issue.keys.every((key) => Reflect.deleteProperty(target, key)));
66
+ }
67
+ const key = issue.path.at(-1);
68
+ const parent = container.safeParse(read(root, issue.path.slice(0, -1))).data;
69
+ if (key === undefined || parent === undefined)
70
+ return false;
71
+ const current = Reflect.get(parent, key);
72
+ // Small models send null for "not given". A required key is reported as missing next.
73
+ if (current === null && typeof key === 'string')
74
+ return Reflect.deleteProperty(parent, key);
75
+ let next = current;
76
+ if (issue.code === 'invalid_type')
77
+ next = retype(current, issue.expected);
78
+ if (issue.code === 'invalid_value' && typeof current === 'string') {
79
+ const wanted = current.toLowerCase();
80
+ next = issue.values.find((option) => typeof option === 'string' && option.toLowerCase() === wanted);
81
+ }
82
+ return (next !== undefined && next !== current && Reflect.set(parent, key, next));
83
+ }
84
+ /** `value` as the type the schema expects, or unchanged when that is not safe. */
85
+ function retype(value, expected) {
86
+ if (value === undefined)
87
+ return value;
88
+ switch (expected) {
89
+ case 'number':
90
+ case 'int':
91
+ return typeof value === 'string' &&
92
+ value.trim() !== '' &&
93
+ !Number.isNaN(Number(value))
94
+ ? Number(value)
95
+ : value;
96
+ case 'boolean':
97
+ return value === 'true' ? true : value === 'false' ? false : value;
98
+ case 'string':
99
+ return typeof value === 'number' || typeof value === 'boolean'
100
+ ? String(value)
101
+ : value;
102
+ case 'array':
103
+ return [value];
104
+ default:
105
+ return value;
106
+ }
107
+ }
108
+ /** The problem for the model's next attempt, for example `arguments.days: expected int`. */
109
+ function describe(root, issue) {
110
+ const path = issue.path.reduce((text, key) => typeof key === 'number' ? `${text}[${key}]` : `${text}.${String(key)}`, 'arguments');
111
+ if (issue.code === 'invalid_type' && read(root, issue.path) === undefined)
112
+ return `${path} is required`;
113
+ if (issue.code === 'invalid_union') {
114
+ // "Invalid input" alone says nothing: name what each alternative expects.
115
+ const options = issue.errors.flatMap((option) => option[0]?.message ?? []);
116
+ if (options.length > 0)
117
+ return `${path}: ${options.join(', or ')}`;
118
+ }
119
+ return `${path}: ${issue.message}`;
120
+ }
121
+ /** The value in `root` that a zod issue path leads to. */
122
+ function read(root, path) {
123
+ return path.reduce((node, key) => {
124
+ const parent = container.safeParse(node).data;
125
+ return parent && Reflect.get(parent, key);
126
+ }, root);
127
+ }
128
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.js","sourceRoot":"","sources":["../../../../../../libs/agent/browser-models/src/lib/schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAcxB,gFAAgF;AAChF,MAAM,SAAS,GAAG,CAAC,CAAC;AACpB,oEAAoE;AACpE,MAAM,SAAS,GAAG,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;AACvC,MAAM,QAAQ,GAAG,IAAI,OAAO,EAA+B,CAAC;AAE5D;;;;GAIG;AACH,MAAM,OAAO,eAAe;IACjB,OAAO,CAAY;IAE5B,6DAA6D;IAC7D,MAAM,CAAC,EAAE,CAAC,IAAgB;QACxB,IAAI,MAAM,GAAG,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAChC,IAAI,CAAC,MAAM;YAAE,QAAQ,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,IAAI,eAAe,CAAC,IAAI,C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AC,OAAO,EAAE,CAAC;AACrC,CAAC;AAED,0DAA0D;AAC1D,SAAS,IAAI,CAAC,IAAa,EAAE,IAA4B;IACvD,OAAO,IAAI,CAAC,MAAM,CAAU,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE;QACxC,MAAM,MAAM,GAAG,SAAS,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC;QAC9C,OAAO,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC5C,CAAC,EAAE,IAAI,CAAC,CAAC;AACX,CAAC"}
@@ -0,0 +1,33 @@
1
+ import type { JsonSchema } from './engine.ts';
2
+ /** What the model needs to know about a tool. */
3
+ export interface ToolSpec {
4
+ readonly name: string;
5
+ readonly description: string;
6
+ /** JSON Schema of the arguments object. */
7
+ readonly parameters?: JsonSchema;
8
+ }
9
+ /**
10
+ * A tool that runs inside the agent, in the browser. Its result goes back to the model.
11
+ * Type the arguments with `const tool: LocalTool<{ city: string }> = { … }`.
12
+ */
13
+ export interface LocalTool<Args = Record<string, unknown>> extends ToolSpec {
14
+ execute(args: Args, signal: AbortSignal): Promise<unknown>;
15
+ }
16
+ /** Supplies local tools at the start of every run, for example the page's WebMCP tools. */
17
+ export interface LocalToolSource {
18
+ /** `signal` aborts when the run is stopped. */
19
+ tools(signal: AbortSignal): Promise<readonly LocalTool[]>;
20
+ }
21
+ /**
22
+ * Resolves a mix of tools and tool sources into one list. A failing source (for example an
23
+ * unreachable MCP server) is skipped and reported in `errors`, so the run can go on.
24
+ */
25
+ export declare function resolveLocalTools(entries: readonly (LocalTool | LocalToolSource)[], signal: AbortSignal): Promise<{
26
+ tools: LocalTool[];
27
+ errors: string[];
28
+ }>;
29
+ /** A tool call after parsing and repair. */
30
+ export interface ToolCall {
31
+ readonly name: string;
32
+ readonly arguments: Readonly<Record<string, unknown>>;
33
+ }