@picassohq/cli 1.0.3 → 1.0.5

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 (64) hide show
  1. package/dist/build-info.json +2 -1
  2. package/dist/index.js +1860 -1316
  3. package/package.json +1 -1
  4. package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +4 -7
  5. package/runtime/dsh/picasso-sdk.patch.yml +47 -0
  6. package/runtime/engine-manifest.json +37 -16
  7. package/runtime/packages/picasso-compaction/cordis.patch.yml +4 -0
  8. package/runtime/packages/picasso-compaction/index.js +875 -0
  9. package/runtime/packages/picasso-compaction/package.json +27 -0
  10. package/runtime/packages/picasso-hooks/cordis.patch.yml +4 -0
  11. package/runtime/packages/picasso-hooks/index.js +302 -0
  12. package/runtime/packages/picasso-hooks/lifecycle-events.js +651 -0
  13. package/runtime/packages/picasso-hooks/package.json +29 -0
  14. package/runtime/packages/picasso-lean-context/argument-repair.js +422 -0
  15. package/runtime/packages/picasso-lean-context/glob-walk.js +518 -0
  16. package/runtime/packages/picasso-lean-context/index.js +159 -11
  17. package/runtime/packages/picasso-memory/index.js +66 -24
  18. package/runtime/packages/picasso-model-router/connections.js +213 -10
  19. package/runtime/packages/picasso-model-router/index.js +128 -1
  20. package/runtime/packages/picasso-model-router/package.json +3 -1
  21. package/runtime/packages/picasso-model-router/thinking-default.js +236 -0
  22. package/runtime/packages/picasso-progress-reports/index.js +128 -18
  23. package/runtime/packages/picasso-sdk-server/command-runs.js +37 -0
  24. package/runtime/packages/picasso-sdk-server/ignore-file.js +5 -1
  25. package/runtime/packages/picasso-sdk-server/index.js +11 -3
  26. package/runtime/packages/picasso-sdk-server/package.json +1 -0
  27. package/runtime/packages/picasso-sdk-server/wave2-hooks.js +26 -6
  28. package/runtime/packages/picasso-web-search/backends.js +245 -195
  29. package/runtime/packages/picasso-web-search/config.js +75 -27
  30. package/runtime/packages/picasso-web-search/cordis.patch.yml +2 -1
  31. package/runtime/packages/picasso-web-search/failure.js +7 -1
  32. package/runtime/packages/picasso-web-search/index.js +7 -5
  33. package/runtime/packages/picasso-web-search/package.json +6 -0
  34. package/runtime/packages/picasso-web-search/requests.js +339 -0
  35. package/runtime/packages/picasso-web-search/router.js +17 -12
  36. package/runtime/packages/picasso-x-reader/settings.js +4 -1
  37. package/runtime/plugins/picasso-auto-approve/index.js +21 -8
  38. package/runtime/plugins/picasso-compaction/index.js +875 -0
  39. package/runtime/plugins/picasso-compaction/package.json +27 -0
  40. package/runtime/plugins/picasso-hooks/index.js +302 -0
  41. package/runtime/plugins/picasso-hooks/lifecycle-events.js +651 -0
  42. package/runtime/plugins/picasso-hooks/package.json +29 -0
  43. package/runtime/plugins/picasso-lean-context/argument-repair.js +422 -0
  44. package/runtime/plugins/picasso-lean-context/glob-walk.js +518 -0
  45. package/runtime/plugins/picasso-lean-context/index.js +159 -11
  46. package/runtime/plugins/picasso-memory/index.js +66 -24
  47. package/runtime/plugins/picasso-model-router/connections.js +213 -10
  48. package/runtime/plugins/picasso-model-router/index.js +128 -1
  49. package/runtime/plugins/picasso-model-router/package.json +3 -1
  50. package/runtime/plugins/picasso-model-router/thinking-default.js +236 -0
  51. package/runtime/plugins/picasso-progress-reports/index.js +128 -18
  52. package/runtime/plugins/picasso-provider-models/index.js +236 -4
  53. package/runtime/plugins/picasso-trackers/index.js +12 -2
  54. package/runtime/plugins/picasso-web-search/backends.js +245 -195
  55. package/runtime/plugins/picasso-web-search/config.js +75 -27
  56. package/runtime/plugins/picasso-web-search/failure.js +7 -1
  57. package/runtime/plugins/picasso-web-search/index.js +7 -5
  58. package/runtime/plugins/picasso-web-search/package.json +6 -0
  59. package/runtime/plugins/picasso-web-search/requests.js +339 -0
  60. package/runtime/plugins/picasso-web-search/router.js +17 -12
  61. package/runtime/plugins/picasso-x-reader/settings.js +4 -1
  62. package/runtime/relay/main.mjs +3877 -1989
  63. package/runtime/relay/model-listing.mjs +337 -26
  64. package/runtime/relay/versions-routes.mjs +86 -20
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "@picasso/picasso-hooks-bridge",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "description": "Phase 2 §5: picasso→dsh hooks bridge. Reads the picasso ~/.picasso/hooks.json store (flat hook list) and runs each enabled shell hook at the mapped dsh interception point, fail-open like picasso's createHookRunner.",
6
+ "type": "module",
7
+ "main": "index.js",
8
+ "scripts": {
9
+ "test": "node --import ../../test/setup/hermetic-preload.mjs --test test/*.test.mjs"
10
+ },
11
+ "exports": {
12
+ ".": "./index.js",
13
+ "./cordis.patch.yml": "./cordis.patch.yml",
14
+ "./package.json": "./package.json"
15
+ },
16
+ "dshTarget": "0.2.2-rc.3",
17
+ "dsh": {
18
+ "bundle": {
19
+ "patch": "./cordis.patch.yml"
20
+ }
21
+ },
22
+ "files": [
23
+ "index.js",
24
+ "lifecycle-events.js",
25
+ "cordis.patch.yml",
26
+ "README.md"
27
+ ],
28
+ "license": "UNLICENSED"
29
+ }
@@ -0,0 +1,422 @@
1
+ // Schema-guided tool-argument repair (all tools, both surfaces).
2
+ //
3
+ // Some models write a nested list or object as a JSON *string* (`{"todos":"[{\"content\":…}]"}`), or a number or
4
+ // boolean in quotes. The engine validates arguments strictly, so such a call fails with `"todos" must be an array` and
5
+ // the model often repeats it. Two seams, neither touching Tier 1 (no tool description or schema changes):
6
+ //
7
+ // 1. `llm/stream` (every model call, every route): when a finished tool call's arguments do not fit the tool's own
8
+ // JSON schema only because a value the schema types as array / object / number / integer / boolean arrived as a
9
+ // string that JSON.parse turns into exactly that type, the parsed value is used. The repaired arguments are what
10
+ // the engine logs and runs, so the log and the call agree. Nothing is invented: a string that does not parse, or
11
+ // parses to another type, is left alone and validation reports it.
12
+ // 2. `tools/post-execute`: a call that still fails validation (`INVALID_ARGS`) keeps the engine's error and gains one
13
+ // plain-words line with the expected shape and an example call, so the model can retry once correctly.
14
+ //
15
+ // Repairs are logged at debug, once per tool per session. Off with `argumentRepair: false` in the lean-context config
16
+ // or PICASSO_LEAN_CONTEXT_ARGUMENT_REPAIR=0.
17
+
18
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
19
+
20
+ /** Whether `value` has the JSON-schema `type` (the engine's subset: one type string). */
21
+ function hasType(value, type) {
22
+ switch (type) {
23
+ case "array":
24
+ return Array.isArray(value);
25
+ case "object":
26
+ return isRecord(value);
27
+ case "string":
28
+ return typeof value === "string";
29
+ case "number":
30
+ return typeof value === "number" && Number.isFinite(value);
31
+ case "integer":
32
+ return typeof value === "number" && Number.isInteger(value);
33
+ case "boolean":
34
+ return typeof value === "boolean";
35
+ case "null":
36
+ return value === null;
37
+ default:
38
+ return false;
39
+ }
40
+ }
41
+
42
+ /** The branch types a schema node allows (`type`, or each `oneOf` branch's `type`); empty when untyped. */
43
+ function allowedTypes(schema) {
44
+ if (!isRecord(schema)) return [];
45
+ if (typeof schema.type === "string") return [schema.type];
46
+ if (Array.isArray(schema.oneOf)) return schema.oneOf.flatMap((branch) => (isRecord(branch) && typeof branch.type === "string" ? [branch.type] : []));
47
+ return [];
48
+ }
49
+
50
+ /** The schema node (itself or a `oneOf` branch) that describes `value`'s type, if any. */
51
+ function branchFor(schema, value) {
52
+ if (!isRecord(schema)) return undefined;
53
+ if (typeof schema.type === "string") return hasType(value, schema.type) ? schema : undefined;
54
+ if (Array.isArray(schema.oneOf)) return schema.oneOf.find((branch) => isRecord(branch) && typeof branch.type === "string" && hasType(value, branch.type));
55
+ return undefined;
56
+ }
57
+
58
+ const REPAIRABLE = new Set(["array", "object", "number", "integer", "boolean"]);
59
+
60
+ /** `value` parsed when it is a string the schema wants as a non-string type and JSON.parse yields that type. */
61
+ function decodeString(value, schema) {
62
+ if (typeof value !== "string") return { ok: false };
63
+ const types = allowedTypes(schema);
64
+ if (types.length === 0 || types.includes("string") || !types.some((type) => REPAIRABLE.has(type))) return { ok: false };
65
+ const text = value.trim();
66
+ if (text.length === 0) return { ok: false };
67
+ let parsed;
68
+ try {
69
+ parsed = JSON.parse(text);
70
+ } catch {
71
+ return { ok: false };
72
+ }
73
+ return types.some((type) => REPAIRABLE.has(type) && hasType(parsed, type)) ? { ok: true, value: parsed } : { ok: false };
74
+ }
75
+
76
+ const MAX_DEPTH = 32;
77
+
78
+ function repairNode(value, schema, path, repairs, depth) {
79
+ if (depth > MAX_DEPTH || !isRecord(schema)) return value;
80
+ let current = value;
81
+ const decoded = decodeString(current, schema);
82
+ if (decoded.ok) {
83
+ current = decoded.value;
84
+ repairs.push(path === "" ? "(arguments)" : path);
85
+ }
86
+ const branch = branchFor(schema, current);
87
+ if (branch === undefined) return current;
88
+ if (branch.type === "object" && isRecord(current) && isRecord(branch.properties)) {
89
+ let out = current;
90
+ for (const [key, propSchema] of Object.entries(branch.properties)) {
91
+ if (!Object.hasOwn(current, key)) continue;
92
+ const next = repairNode(current[key], propSchema, path === "" ? key : `${path}.${key}`, repairs, depth + 1);
93
+ if (next !== current[key]) {
94
+ if (out === current) out = { ...current };
95
+ out[key] = next;
96
+ }
97
+ }
98
+ return out;
99
+ }
100
+ if (branch.type === "array" && Array.isArray(current) && isRecord(branch.items)) {
101
+ let out = current;
102
+ current.forEach((item, index) => {
103
+ const next = repairNode(item, branch.items, `${path}[${index}]`, repairs, depth + 1);
104
+ if (next !== item) {
105
+ if (out === current) out = [...current];
106
+ out[index] = next;
107
+ }
108
+ });
109
+ return out;
110
+ }
111
+ return current;
112
+ }
113
+
114
+ /**
115
+ * Repair `args` against the tool's JSON `schema`: every value the schema types as array / object / number / integer /
116
+ * boolean that arrived as a string which JSON.parse turns into exactly that type is replaced by the parsed value
117
+ * (nested values too; the whole arguments object may itself be a JSON string). Anything else is left alone, so an
118
+ * unfixable call still fails validation. Returns the same `args` when nothing changed.
119
+ * @returns {{ args: unknown, repaired: string[] }} the arguments and the paths that were decoded.
120
+ */
121
+ export function repairToolArguments(args, schema) {
122
+ const repaired = [];
123
+ if (!isRecord(schema)) return { args, repaired };
124
+ const out = repairNode(args, schema, "", repaired, 0);
125
+ return { args: out, repaired };
126
+ }
127
+
128
+ /**
129
+ * Repair one finished tool call's raw JSON `argumentsText`. Returns the new JSON text, or undefined when the text is
130
+ * not JSON or nothing needed repair (the call then goes through exactly as the model wrote it).
131
+ */
132
+ export function repairArgumentsText(argumentsText, schema) {
133
+ if (typeof argumentsText !== "string" || argumentsText.trim().length === 0 || !isRecord(schema)) return undefined;
134
+ let parsed;
135
+ try {
136
+ parsed = JSON.parse(argumentsText);
137
+ } catch {
138
+ return undefined;
139
+ }
140
+ const { args, repaired } = repairToolArguments(parsed, schema);
141
+ if (repaired.length === 0) return undefined;
142
+ return { text: JSON.stringify(args), repaired };
143
+ }
144
+
145
+ // ---------------------------------------------------------------------------------------------------------------------
146
+ // Plain-words expected shape
147
+ // ---------------------------------------------------------------------------------------------------------------------
148
+
149
+ const quoteList = (values) => {
150
+ const words = values.map((value) => (typeof value === "string" ? value : JSON.stringify(value)));
151
+ if (words.length <= 1) return words.join("");
152
+ return `${words.slice(0, -1).join(", ")} or ${words[words.length - 1]}`;
153
+ };
154
+
155
+ /** "a list of {content, status} objects", "a string", "true or false", … for one schema node. */
156
+ export function describeSchemaShape(schema, depth = 0) {
157
+ if (!isRecord(schema)) return "any value";
158
+ if (Array.isArray(schema.enum) && schema.enum.length > 0) return `one of ${quoteList(schema.enum)}`;
159
+ if (Object.hasOwn(schema, "const")) return JSON.stringify(schema.const);
160
+ if (Array.isArray(schema.oneOf)) {
161
+ const branches = schema.oneOf.map((branch) => describeSchemaShape(branch, depth + 1));
162
+ return quoteList([...new Set(branches)]);
163
+ }
164
+ switch (schema.type) {
165
+ case "array": {
166
+ const items = isRecord(schema.items) ? schema.items : undefined;
167
+ if (items === undefined) return "a list";
168
+ if (items.type === "object" && isRecord(items.properties)) return `a list of ${objectShape(items)} objects`;
169
+ if (items.type === "string" && !Array.isArray(items.enum)) return "a list of strings";
170
+ if (items.type === "number" || items.type === "integer") return "a list of numbers";
171
+ return depth >= 2 ? "a list" : `a list of (${describeSchemaShape(items, depth + 1)})`;
172
+ }
173
+ case "object":
174
+ return isRecord(schema.properties) && Object.keys(schema.properties).length > 0 ? `an object ${objectShape(schema)}` : "an object";
175
+ case "string":
176
+ return "a string";
177
+ case "integer":
178
+ return "a whole number";
179
+ case "number":
180
+ return "a number";
181
+ case "boolean":
182
+ return "true or false";
183
+ case "null":
184
+ return "null";
185
+ default:
186
+ return "any value";
187
+ }
188
+ }
189
+
190
+ /** `{content, status}` (required fields; every field when none is required), at most 6 names. */
191
+ function objectShape(schema) {
192
+ const props = isRecord(schema.properties) ? Object.keys(schema.properties) : [];
193
+ const required = Array.isArray(schema.required) ? schema.required.filter((key) => props.includes(key)) : [];
194
+ const names = required.length > 0 ? required : props;
195
+ return `{${names.slice(0, 6).join(", ")}${names.length > 6 ? ", …" : ""}}`;
196
+ }
197
+
198
+ /** Enum notes for an object's (or a list item's) fields: `status is one of pending, in_progress or completed`. */
199
+ function enumNotes(schema) {
200
+ const node = isRecord(schema) && schema.type === "array" && isRecord(schema.items) ? schema.items : schema;
201
+ if (!isRecord(node) || !isRecord(node.properties)) return [];
202
+ const notes = [];
203
+ for (const [key, prop] of Object.entries(node.properties)) {
204
+ if (isRecord(prop) && Array.isArray(prop.enum) && prop.enum.length > 0) notes.push(`${key} is one of ${quoteList(prop.enum)}`);
205
+ }
206
+ return notes.slice(0, 3);
207
+ }
208
+
209
+ /** A minimal example value: required fields filled, enums take their first value, strings are "…". */
210
+ export function exampleForSchema(schema, depth = 0) {
211
+ if (!isRecord(schema) || depth > 4) return "…";
212
+ if (Array.isArray(schema.enum) && schema.enum.length > 0) return schema.enum[0];
213
+ if (Object.hasOwn(schema, "const")) return schema.const;
214
+ if (Array.isArray(schema.oneOf) && schema.oneOf.length > 0) return exampleForSchema(schema.oneOf[0], depth + 1);
215
+ switch (schema.type) {
216
+ case "array":
217
+ return [exampleForSchema(isRecord(schema.items) ? schema.items : { type: "string" }, depth + 1)];
218
+ case "object": {
219
+ const out = {};
220
+ const props = isRecord(schema.properties) ? schema.properties : {};
221
+ const required = Array.isArray(schema.required) ? schema.required : [];
222
+ for (const key of required) if (Object.hasOwn(props, key)) out[key] = exampleForSchema(props[key], depth + 1);
223
+ return out;
224
+ }
225
+ case "integer":
226
+ case "number":
227
+ return 1;
228
+ case "boolean":
229
+ return true;
230
+ case "null":
231
+ return null;
232
+ default:
233
+ return "…";
234
+ }
235
+ }
236
+
237
+ /** Whether `value` satisfies `schema` in the engine's subset (type/oneOf/properties/required/additionalProperties/items/enum/const). */
238
+ function fitsSchema(value, schema, depth = 0) {
239
+ if (!isRecord(schema) || depth > MAX_DEPTH) return true;
240
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
241
+ if (Array.isArray(schema.enum) && !schema.enum.some((item) => same(item, value))) return false;
242
+ if (Object.hasOwn(schema, "const") && !same(schema.const, value)) return false;
243
+ if (Array.isArray(schema.oneOf)) return schema.oneOf.some((branch) => fitsSchema(value, branch, depth + 1));
244
+ if (typeof schema.type !== "string") return true;
245
+ if (!hasType(value, schema.type)) return false;
246
+ if (schema.type === "array") return !isRecord(schema.items) || value.every((item) => fitsSchema(item, schema.items, depth + 1));
247
+ if (schema.type === "object") {
248
+ const props = isRecord(schema.properties) ? schema.properties : {};
249
+ const required = Array.isArray(schema.required) ? schema.required : [];
250
+ if (required.some((key) => !Object.hasOwn(value, key) || value[key] === undefined)) return false;
251
+ if (schema.additionalProperties === false && Object.keys(value).some((key) => !Object.hasOwn(props, key))) return false;
252
+ return Object.entries(props).every(([key, prop]) => !Object.hasOwn(value, key) || fitsSchema(value[key], prop, depth + 1));
253
+ }
254
+ return true;
255
+ }
256
+
257
+ const typeWord = (value) => (value === null ? "null" : Array.isArray(value) ? "a list" : typeof value === "string" ? "a string" : typeof value === "object" ? "an object" : `a ${typeof value}`);
258
+
259
+ /**
260
+ * The plain-words correction for a call that failed validation: each wrong or missing top-level field and its expected
261
+ * shape, a note when a list/object was sent as a quoted string, and the call shape. Empty when nothing can be said.
262
+ */
263
+ export function plainArgumentsCorrection(toolName, schema, args) {
264
+ if (!isRecord(schema) || schema.type !== "object" || !isRecord(schema.properties)) return "";
265
+ const provided = isRecord(args) ? args : {};
266
+ const required = Array.isArray(schema.required) ? schema.required : [];
267
+ const lines = [];
268
+ let quoted = false;
269
+ for (const [key, prop] of Object.entries(schema.properties)) {
270
+ const present = Object.hasOwn(provided, key) && provided[key] !== undefined;
271
+ if (!present) {
272
+ if (required.includes(key)) lines.push(`${key} is required and must be ${describeSchemaShape(prop)}`);
273
+ continue;
274
+ }
275
+ const value = provided[key];
276
+ if (fitsSchema(value, prop)) continue;
277
+ const types = allowedTypes(prop);
278
+ const typeOk = types.length === 0 || types.some((type) => hasType(value, type));
279
+ if (typeof value === "string" && types.some((type) => type === "array" || type === "object")) quoted = true;
280
+ const notes = enumNotes(prop);
281
+ // Right type, wrong inside (a list item missing a field, a value outside an enum): describe the shape only.
282
+ lines.push(`${key} must be ${describeSchemaShape(prop)}${notes.length > 0 ? ` (${notes.join("; ")})` : ""}${typeOk ? "" : `, not ${typeWord(value)}`}`);
283
+ }
284
+ if (schema.additionalProperties === false) {
285
+ const unknown = Object.keys(provided).filter((key) => !Object.hasOwn(schema.properties, key));
286
+ if (unknown.length > 0) lines.push(`${unknown.join(", ")} ${unknown.length === 1 ? "is not a field" : "are not fields"} of ${toolName}`);
287
+ }
288
+ if (lines.length === 0) return "";
289
+ const parts = [`${lines.join("; ")}.`];
290
+ if (quoted) parts.push("Send lists and objects as JSON values, not as quoted strings.");
291
+ parts.push(`Call it as ${toolName}(${JSON.stringify(exampleForSchema(schema))}).`);
292
+ return parts.join(" ");
293
+ }
294
+
295
+ // ---------------------------------------------------------------------------------------------------------------------
296
+ // Plugin seams
297
+ // ---------------------------------------------------------------------------------------------------------------------
298
+
299
+ const LOGGED_LIMIT = 2048;
300
+
301
+ /**
302
+ * The `llm/stream` waterfall listener: repairs each finished tool call's arguments against the tool's schema from the
303
+ * request's own `tools`. Chunks pass through untouched unless a repair applies; the request options are never changed.
304
+ */
305
+ export function createArgumentRepairStream({ log } = {}) {
306
+ const logged = new Set();
307
+ const note = (sessionId, toolName, paths) => {
308
+ const key = `${String(sessionId ?? "")}\u0000${toolName}`;
309
+ if (logged.has(key)) return;
310
+ if (logged.size >= LOGGED_LIMIT) logged.clear();
311
+ logged.add(key);
312
+ try {
313
+ log?.(`picasso-lean-context: repaired string-encoded argument(s) ${paths.join(", ")} for ${toolName} (logged once per tool per session)`);
314
+ } catch {
315
+ // logging never fails a model call
316
+ }
317
+ };
318
+ return function argumentRepairStream(options, next) {
319
+ const upstream = typeof next === "function" ? next() : undefined;
320
+ const request = isRecord(options?.request) ? options.request : options;
321
+ const tools = Array.isArray(request?.tools) ? request.tools : [];
322
+ if (upstream == null || tools.length === 0 || typeof upstream[Symbol.asyncIterator] !== "function") return upstream;
323
+ const sessionId = options?.sessionId ?? request?.sessionId;
324
+ const schemaOf = (name) => {
325
+ const tool = tools.find((candidate) => candidate?.name === name);
326
+ return tool?.parameters ?? tool?.inputSchema;
327
+ };
328
+ const repairBlock = (block) => {
329
+ const fixed = repairArgumentsText(block.arguments, schemaOf(block.name));
330
+ if (fixed === undefined) return undefined;
331
+ note(sessionId, block.name, fixed.repaired);
332
+ return { ...block, arguments: fixed.text };
333
+ };
334
+ return (async function* repaired() {
335
+ // Tool calls an adapter streams as deltas only (no block-end) are assembled by the engine; one that needs a
336
+ // repair is closed here with the repaired block just before the finish chunk.
337
+ const open = new Map();
338
+ for await (const chunk of upstream) {
339
+ if (chunk?.type === "tool-call-delta") {
340
+ const entry = open.get(chunk.index) ?? { id: chunk.id, name: undefined, text: "", closed: false };
341
+ if (typeof chunk.name === "string" && chunk.name.length > 0) entry.name = chunk.name;
342
+ entry.id = chunk.id ?? entry.id;
343
+ entry.text += typeof chunk.argumentsDelta === "string" ? chunk.argumentsDelta : "";
344
+ open.set(chunk.index, entry);
345
+ yield chunk;
346
+ continue;
347
+ }
348
+ if (chunk?.type === "block-end" && chunk.block?.type === "tool-call") {
349
+ const entry = open.get(chunk.index);
350
+ if (entry !== undefined) entry.closed = true;
351
+ else open.set(chunk.index, { closed: true });
352
+ const block = repairBlock(chunk.block);
353
+ yield block === undefined ? chunk : { ...chunk, block };
354
+ continue;
355
+ }
356
+ if (chunk?.type === "finish") {
357
+ for (const [index, entry] of open) {
358
+ if (entry.closed || typeof entry.name !== "string") continue;
359
+ const block = repairBlock({ type: "tool-call", id: entry.id, name: entry.name, arguments: entry.text });
360
+ if (block !== undefined) yield { type: "block-end", index, block };
361
+ }
362
+ }
363
+ yield chunk;
364
+ }
365
+ })();
366
+ };
367
+ }
368
+
369
+ const INVALID_ARGS = "INVALID_ARGS";
370
+
371
+ function isInvalidArgsResult(result) {
372
+ if (!isRecord(result) || result.isError !== true) return false;
373
+ const error = isRecord(result.error) ? result.error : {};
374
+ return error.code === INVALID_ARGS || error.name === "ToolArgsError" || error.info?.code === INVALID_ARGS;
375
+ }
376
+
377
+ /**
378
+ * The `tools/post-execute` listener: an `INVALID_ARGS` failure keeps its error identity and text and gains the
379
+ * plain-words correction (`schemaFor(exec)` returns the tool's JSON schema). Other results are untouched.
380
+ */
381
+ export function createArgumentErrorExplainer({ schemaFor } = {}) {
382
+ return async function argumentErrorExplainer(exec, result, next) {
383
+ const downstream = typeof next === "function" ? await next() : { kind: "accept" };
384
+ if (downstream?.kind !== "accept" || downstream.content !== undefined || Object.hasOwn(downstream, "value")) return downstream;
385
+ if (!isInvalidArgsResult(result)) return downstream;
386
+ let schema;
387
+ try {
388
+ schema = schemaFor?.(exec);
389
+ } catch {
390
+ return downstream;
391
+ }
392
+ const correction = plainArgumentsCorrection(String(exec?.name ?? "tool"), schema, exec?.arguments);
393
+ if (correction === "") return downstream;
394
+ const original = Array.isArray(result.content) ? result.content : [];
395
+ return { ...downstream, kind: "accept", content: [...original, { type: "text", text: correction }] };
396
+ };
397
+ }
398
+
399
+ /** Mount both seams. Returns a disposer. */
400
+ export function installArgumentRepair(ctx, { schemaFor, log } = {}) {
401
+ if (typeof ctx?.on !== "function") return () => {};
402
+ const disposers = [];
403
+ const on = (event, listener) => {
404
+ try {
405
+ const dispose = ctx.on(event, listener, { global: true });
406
+ if (typeof dispose === "function") disposers.push(dispose);
407
+ } catch {
408
+ // an inactive fiber registers nothing
409
+ }
410
+ };
411
+ on("llm/stream", createArgumentRepairStream({ log: log ?? ((line) => ctx.logger?.debug?.(line)) }));
412
+ on("tools/post-execute", createArgumentErrorExplainer({ schemaFor }));
413
+ return () => {
414
+ for (const dispose of disposers.splice(0)) {
415
+ try {
416
+ dispose();
417
+ } catch {
418
+ // already gone
419
+ }
420
+ }
421
+ };
422
+ }