@picassohq/cli 1.0.3 → 1.0.4
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.
- package/dist/build-info.json +1 -1
- package/dist/index.js +1591 -1251
- package/package.json +1 -1
- package/runtime/engine-manifest.json +22 -11
- package/runtime/packages/picasso-compaction/cordis.patch.yml +4 -0
- package/runtime/packages/picasso-compaction/index.js +623 -0
- package/runtime/packages/picasso-compaction/package.json +27 -0
- package/runtime/packages/picasso-lean-context/argument-repair.js +422 -0
- package/runtime/packages/picasso-lean-context/index.js +23 -2
- package/runtime/packages/picasso-model-router/connections.js +49 -3
- package/runtime/packages/picasso-model-router/index.js +32 -1
- package/runtime/packages/picasso-model-router/package.json +3 -1
- package/runtime/packages/picasso-model-router/thinking-default.js +212 -0
- package/runtime/packages/picasso-web-search/backends.js +245 -195
- package/runtime/packages/picasso-web-search/config.js +75 -27
- package/runtime/packages/picasso-web-search/cordis.patch.yml +2 -1
- package/runtime/packages/picasso-web-search/failure.js +7 -1
- package/runtime/packages/picasso-web-search/index.js +7 -5
- package/runtime/packages/picasso-web-search/package.json +6 -0
- package/runtime/packages/picasso-web-search/requests.js +339 -0
- package/runtime/packages/picasso-web-search/router.js +17 -12
- package/runtime/plugins/picasso-compaction/index.js +623 -0
- package/runtime/plugins/picasso-compaction/package.json +27 -0
- package/runtime/plugins/picasso-lean-context/argument-repair.js +422 -0
- package/runtime/plugins/picasso-lean-context/index.js +23 -2
- package/runtime/plugins/picasso-model-router/connections.js +49 -3
- package/runtime/plugins/picasso-model-router/index.js +32 -1
- package/runtime/plugins/picasso-model-router/package.json +3 -1
- package/runtime/plugins/picasso-model-router/thinking-default.js +212 -0
- package/runtime/plugins/picasso-provider-models/index.js +236 -4
- package/runtime/plugins/picasso-web-search/backends.js +245 -195
- package/runtime/plugins/picasso-web-search/config.js +75 -27
- package/runtime/plugins/picasso-web-search/failure.js +7 -1
- package/runtime/plugins/picasso-web-search/index.js +7 -5
- package/runtime/plugins/picasso-web-search/package.json +6 -0
- package/runtime/plugins/picasso-web-search/requests.js +339 -0
- package/runtime/plugins/picasso-web-search/router.js +17 -12
- package/runtime/relay/main.mjs +2776 -1494
- package/runtime/relay/model-listing.mjs +337 -26
- package/runtime/relay/versions-routes.mjs +65 -3
|
@@ -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
|
+
}
|
|
@@ -27,8 +27,16 @@ import { basename, delimiter, dirname, join, resolve } from "node:path";
|
|
|
27
27
|
import { fileURLToPath } from "node:url";
|
|
28
28
|
import { buildContextTimeline } from "./timeline.js";
|
|
29
29
|
import { installReadImageRecovery } from "./read-image-recovery.js";
|
|
30
|
+
import { installArgumentRepair, repairToolArguments } from "./argument-repair.js";
|
|
30
31
|
|
|
31
32
|
export { createReadImageRecovery, recoverReadImage, sniffImageFormat } from "./read-image-recovery.js";
|
|
33
|
+
export {
|
|
34
|
+
createArgumentErrorExplainer,
|
|
35
|
+
createArgumentRepairStream,
|
|
36
|
+
plainArgumentsCorrection,
|
|
37
|
+
repairArgumentsText,
|
|
38
|
+
repairToolArguments,
|
|
39
|
+
} from "./argument-repair.js";
|
|
32
40
|
export {
|
|
33
41
|
CONTEXT_TIMELINE_VERSION,
|
|
34
42
|
buildContextTimeline,
|
|
@@ -5317,7 +5325,7 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
5317
5325
|
const toolMeta = serverMap?.get(shortName) ?? deferredTools.get(fullMcpName);
|
|
5318
5326
|
const cachedSchema = toolMeta?.parameters ?? toolMeta?.inputSchema;
|
|
5319
5327
|
|
|
5320
|
-
const callArgs = cachedSchema ? normalizeToolArguments(subArgs, cachedSchema) : subArgs;
|
|
5328
|
+
const callArgs = cachedSchema ? normalizeToolArguments(repairToolArguments(subArgs, cachedSchema).args, cachedSchema) : subArgs;
|
|
5321
5329
|
if (cachedSchema) {
|
|
5322
5330
|
const validation = validateAgainstInputSchema(callArgs, cachedSchema);
|
|
5323
5331
|
if (!validation.valid) {
|
|
@@ -5419,7 +5427,7 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
5419
5427
|
|
|
5420
5428
|
// Reshape what models naturally send (`query` for a required `queries` list), then validate required parameters
|
|
5421
5429
|
// and basic property types before invoking.
|
|
5422
|
-
if (cachedSchema) args = normalizeToolArguments(args, cachedSchema);
|
|
5430
|
+
if (cachedSchema) args = normalizeToolArguments(repairToolArguments(args, cachedSchema).args, cachedSchema);
|
|
5423
5431
|
if (cachedSchema) {
|
|
5424
5432
|
const validation = validateAgainstInputSchema(args, cachedSchema);
|
|
5425
5433
|
if (!validation.valid) {
|
|
@@ -6051,6 +6059,19 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
6051
6059
|
installReadImageRecovery(ctx, deps.readImageRecovery);
|
|
6052
6060
|
}
|
|
6053
6061
|
|
|
6062
|
+
// A nested list/object/number/boolean the model sent as a JSON string is decoded against the tool's own schema
|
|
6063
|
+
// before the engine logs and validates the call; a call that still fails gets a plain-words expected shape
|
|
6064
|
+
// (argument-repair.js). Tier 1 is untouched. Off with `argumentRepair: false` or PICASSO_LEAN_CONTEXT_ARGUMENT_REPAIR=0.
|
|
6065
|
+
if (config.argumentRepair !== false && process.env.PICASSO_LEAN_CONTEXT_ARGUMENT_REPAIR !== "0") {
|
|
6066
|
+
installArgumentRepair(ctx, {
|
|
6067
|
+
schemaFor: (exec) => {
|
|
6068
|
+
const tool = toolsServiceOf(ctx)?.get?.(exec?.name, exec?.agent, exec?.toolSet);
|
|
6069
|
+
return tool?.parameters ?? tool?.inputSchema;
|
|
6070
|
+
},
|
|
6071
|
+
...(deps.argumentRepairLog === undefined ? {} : { log: deps.argumentRepairLog }),
|
|
6072
|
+
});
|
|
6073
|
+
}
|
|
6074
|
+
|
|
6054
6075
|
// Propagate `isError: true` from `tool_call` / `<server>_call` through dsh-tools `tools/post-execute`
|
|
6055
6076
|
ctx?.on?.(
|
|
6056
6077
|
"tools/post-execute",
|
|
@@ -328,13 +328,29 @@ export function reasonPhrase(label, classified) {
|
|
|
328
328
|
return `${subject} ${classified.reason}`;
|
|
329
329
|
}
|
|
330
330
|
|
|
331
|
+
/** A provider's own wording for a key it does not recognise ("Invalid API Key", `invalid_key`, "Incorrect API key"). */
|
|
332
|
+
const INVALID_KEY_WORDING = /\b(?:invalid|incorrect|unrecogni[sz]ed|malformed)[\s_-]*(?:api[\s_-]*)?key\b|\binvalid_api_key\b|\bapi[\s_-]*key[\s_-]*(?:is[\s_-]*)?(?:invalid|not[\s_-]*valid|incorrect)\b/iu;
|
|
333
|
+
|
|
334
|
+
/** The HTTP status of a failure: its `status`, else the one the adapter's message starts with ("401: {…}"). */
|
|
335
|
+
export function failureStatus(failure) {
|
|
336
|
+
if (Number.isInteger(failure?.status)) return failure.status;
|
|
337
|
+
const lead = Number(/^\s*([1-5]\d{2})\s*:/u.exec(typeof failure?.message === 'string' ? failure.message : '')?.[1]);
|
|
338
|
+
return Number.isInteger(lead) ? lead : undefined;
|
|
339
|
+
}
|
|
340
|
+
|
|
331
341
|
/** A short human reason for a probe failure ("Rate limited (429)"). */
|
|
332
342
|
export function probeReason(classified, failure) {
|
|
333
|
-
|
|
343
|
+
// The engine's adapter reports a provider refusal as `{code: 'AUTH', message: '401: {…}'}` with no `status` field.
|
|
344
|
+
const message = typeof failure?.message === 'string' ? failure.message : '';
|
|
345
|
+
const code = failureStatus(failure);
|
|
346
|
+
const status = code === undefined ? '' : ` (${code})`;
|
|
334
347
|
switch (classified.kind) {
|
|
335
348
|
case 'quota': return `Hit its usage limit${status}`;
|
|
336
349
|
case 'billing': return `Out of credit${status}`;
|
|
337
|
-
case 'auth':
|
|
350
|
+
case 'auth':
|
|
351
|
+
if (failure?.code === 'MISSING_CREDENTIAL') return 'No key configured';
|
|
352
|
+
// The provider said the key itself is wrong (not expired, not a plan limit): say so, it is the user's to fix.
|
|
353
|
+
return INVALID_KEY_WORDING.test(message) ? `The provider rejected this key as invalid${status}` : `Key expired or not allowed${status}`;
|
|
338
354
|
case 'rate-limit': return `Rate limited${status}`;
|
|
339
355
|
case 'outage': return `Provider unavailable${status}`;
|
|
340
356
|
default: return (typeof failure?.message === 'string' && failure.message ? failure.message.slice(0, 160) : 'Request failed') + status;
|
|
@@ -411,6 +427,18 @@ export function normalizeSettings(raw) {
|
|
|
411
427
|
// The models each connection shows in the pickers (`{"<route>": ["<model>", …]}`; @picasso/shared-home
|
|
412
428
|
// active-models.ts writes it, both surfaces read it). Kept through every save, never interpreted here.
|
|
413
429
|
const active = normalizeActive(value.active);
|
|
430
|
+
// Routes the person disconnected (`picasso provider disconnect`, the Mac's Disconnect): their key still resolves (often
|
|
431
|
+
// from the shell environment other tools need), but they are never a connection, so never a fallback.
|
|
432
|
+
const routeIds = (raw) => {
|
|
433
|
+
const out = [];
|
|
434
|
+
for (const id of Array.isArray(raw) ? raw : []) {
|
|
435
|
+
if (nonEmpty(id) && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(id.trim()) && !out.includes(id.trim())) out.push(id.trim());
|
|
436
|
+
}
|
|
437
|
+
return out;
|
|
438
|
+
};
|
|
439
|
+
const disconnected = routeIds(value.disconnected);
|
|
440
|
+
// Routes whose environment-only key the person connected on purpose (kept through every save).
|
|
441
|
+
const connected = routeIds(value.connected);
|
|
414
442
|
return {
|
|
415
443
|
version: 1,
|
|
416
444
|
policy,
|
|
@@ -421,6 +449,8 @@ export function normalizeSettings(raw) {
|
|
|
421
449
|
...(defaultEffort === undefined ? {} : { defaultEffort }),
|
|
422
450
|
...(modelPickScope === undefined ? {} : { modelPickScope }),
|
|
423
451
|
...(active === undefined ? {} : { active }),
|
|
452
|
+
...(disconnected.length === 0 ? {} : { disconnected }),
|
|
453
|
+
...(connected.length === 0 ? {} : { connected }),
|
|
424
454
|
};
|
|
425
455
|
}
|
|
426
456
|
|
|
@@ -509,6 +539,8 @@ export function moveId(order, id, where) {
|
|
|
509
539
|
* @param {() => {policy, order, equivalents?}} deps.settings - live settings.
|
|
510
540
|
* @param {() => Promise<{id: string, name?: string}[]>} deps.providers - the engine's provider routes.
|
|
511
541
|
* @param {(id: string) => Promise<string[]>} deps.models - model ids a route serves (empty = not configured).
|
|
542
|
+
* @param {(id: string) => Promise<boolean>|boolean} [deps.envOnly] - whether a route's key comes only from the process
|
|
543
|
+
* environment (such a route is a connection only once the person connects it: settings `connected`).
|
|
512
544
|
* @param {(id: string) => Promise<string|undefined>|string|undefined} [deps.identity] - endpoint + key fingerprint of
|
|
513
545
|
* a route; routes with the same fingerprint are one connection.
|
|
514
546
|
* @param {(agent, selection, options?: {immediate?: boolean}) => Promise<object|undefined>} deps.install - install
|
|
@@ -548,9 +580,23 @@ export class ConnectionFallback {
|
|
|
548
580
|
async list() {
|
|
549
581
|
const settings = this.deps.settings();
|
|
550
582
|
const providers = await this.deps.providers();
|
|
583
|
+
const disconnected = new Set(Array.isArray(settings.disconnected) ? settings.disconnected : []);
|
|
584
|
+
const connected = new Set(Array.isArray(settings.connected) ? settings.connected : []);
|
|
551
585
|
const rows = [];
|
|
552
586
|
for (const provider of providers) {
|
|
553
587
|
if (!nonEmpty(provider?.id)) continue;
|
|
588
|
+
// A disconnected route is not a connection: never listed, never a fallback. Nor is a route whose key was only
|
|
589
|
+
// found in the environment until the person connects it (`connected`).
|
|
590
|
+
if (disconnected.has(provider.id)) continue;
|
|
591
|
+
if (!connected.has(provider.id) && typeof this.deps.envOnly === 'function') {
|
|
592
|
+
let envOnly = false;
|
|
593
|
+
try {
|
|
594
|
+
envOnly = (await this.deps.envOnly(provider.id)) === true;
|
|
595
|
+
} catch {
|
|
596
|
+
envOnly = false;
|
|
597
|
+
}
|
|
598
|
+
if (envOnly) continue;
|
|
599
|
+
}
|
|
554
600
|
let models = [];
|
|
555
601
|
try {
|
|
556
602
|
models = await this.deps.models(provider.id);
|
|
@@ -858,7 +904,7 @@ export class ConnectionFallback {
|
|
|
858
904
|
reason: probeReason(classified, failure),
|
|
859
905
|
kind: classified.kind,
|
|
860
906
|
...(nonEmpty(failure.code) ? { code: failure.code } : {}),
|
|
861
|
-
...(
|
|
907
|
+
...(failureStatus(failure) === undefined ? {} : { status: failureStatus(failure) }),
|
|
862
908
|
latencyMs,
|
|
863
909
|
};
|
|
864
910
|
}
|
|
@@ -57,7 +57,10 @@ import {
|
|
|
57
57
|
writeSettings as writeConnectionSettings,
|
|
58
58
|
} from './connections.js';
|
|
59
59
|
|
|
60
|
+
import { createThinkingGuard } from './thinking-default.js';
|
|
61
|
+
|
|
60
62
|
export * from './connections.js';
|
|
63
|
+
export * from './thinking-default.js';
|
|
61
64
|
|
|
62
65
|
export const name = 'picasso-model-router';
|
|
63
66
|
export const dshTarget = '0.2.2-rc.3';
|
|
@@ -876,6 +879,7 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
876
879
|
const connectionInstalls = new Map();
|
|
877
880
|
/** agent → the route object its current step was prepared with (`agent/pre-step` `modelSelection`). */
|
|
878
881
|
const stepSelections = new WeakMap();
|
|
882
|
+
const thinkingGuard = createThinkingGuard({ llm: llmRegistry, settings: readConnections, log });
|
|
879
883
|
/** session id → the last request route seen (`request/context`), the current-route backstop. */
|
|
880
884
|
const lastRequestRoute = new Map();
|
|
881
885
|
const appendRecord = deps.appendPluginRecord ?? (() => {
|
|
@@ -990,8 +994,26 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
990
994
|
return routeIdentity(profile, (ref) => process.env[ref] || storedCredentialRefs()[ref]);
|
|
991
995
|
});
|
|
992
996
|
|
|
997
|
+
/**
|
|
998
|
+
* Whether a route's key comes only from this process's environment (not the engine home's stored credentials): such
|
|
999
|
+
* a route serves only once the person connects it (`connected` in the shared settings; owner 2026-11-17).
|
|
1000
|
+
*/
|
|
1001
|
+
const AMBIENT_ENVS = { 'amazon-bedrock': [['AWS_BEARER_TOKEN_BEDROCK'], ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY'], ['AWS_PROFILE']], 'google-vertex': [['GOOGLE_CLOUD_API_KEY'], ['GOOGLE_APPLICATION_CREDENTIALS']] };
|
|
1002
|
+
const routeEnvOnlyOf = deps.routeEnvOnly ?? ((id) => {
|
|
1003
|
+
const stored = storedCredentialRefs();
|
|
1004
|
+
const fromEnv = (names) => names.length > 0 && names.every((ref) => Boolean(process.env[ref]));
|
|
1005
|
+
const fromStore = (names) => names.length > 0 && names.every((ref) => Boolean(stored[ref]));
|
|
1006
|
+
const providers = llmPiAiProviders(ctx);
|
|
1007
|
+
const profile = isRecord(providers) ? providers[id] : undefined;
|
|
1008
|
+
const ref = isRecord(profile) && typeof profile.apiKeyEnv === 'string' && profile.apiKeyEnv ? profile.apiKeyEnv : undefined;
|
|
1009
|
+
if (ref !== undefined) return fromEnv([ref]) && !fromStore([ref]);
|
|
1010
|
+
const ambient = AMBIENT_ENVS[id];
|
|
1011
|
+
return ambient !== undefined && ambient.some(fromEnv) && !ambient.some(fromStore);
|
|
1012
|
+
});
|
|
1013
|
+
|
|
993
1014
|
const fallback = deps.connectionFallback ?? new ConnectionFallback({
|
|
994
1015
|
settings: readConnections,
|
|
1016
|
+
envOnly: routeEnvOnlyOf,
|
|
995
1017
|
identity: routeIdentityOf,
|
|
996
1018
|
providers: async () => {
|
|
997
1019
|
const registry = llmRegistry();
|
|
@@ -1065,7 +1087,16 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
1065
1087
|
} catch (error) {
|
|
1066
1088
|
log(`${name}: moving back to the earlier connection skipped (${error instanceof Error ? error.message : String(error)}).`);
|
|
1067
1089
|
}
|
|
1068
|
-
|
|
1090
|
+
// After routing has fixed this step's model: a model that cannot run with thinking off gets a level
|
|
1091
|
+
// (thinking-default.js), whatever sent the request.
|
|
1092
|
+
return router.preStep(args, async () => {
|
|
1093
|
+
try {
|
|
1094
|
+
await thinkingGuard.apply(args?.modelSelection);
|
|
1095
|
+
} catch (error) {
|
|
1096
|
+
log(`${name}: the default thinking level was skipped (${error instanceof Error ? error.message : String(error)}).`);
|
|
1097
|
+
}
|
|
1098
|
+
return next();
|
|
1099
|
+
});
|
|
1069
1100
|
}),
|
|
1070
1101
|
ctx.on('agent/request-error', (payload, next) => fallback.onRequestError(payload, next)),
|
|
1071
1102
|
ctx.on('session/disposed', (session) => {
|
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
".": "./index.js",
|
|
10
10
|
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
11
11
|
"./package.json": "./package.json",
|
|
12
|
-
"./connections.js": "./connections.js"
|
|
12
|
+
"./connections.js": "./connections.js",
|
|
13
|
+
"./thinking-default.js": "./thinking-default.js"
|
|
13
14
|
},
|
|
14
15
|
"dshTarget": "0.2.2-rc.3",
|
|
15
16
|
"dsh": {
|
|
@@ -23,6 +24,7 @@
|
|
|
23
24
|
"files": [
|
|
24
25
|
"index.js",
|
|
25
26
|
"connections.js",
|
|
27
|
+
"thinking-default.js",
|
|
26
28
|
"cordis.patch.yml",
|
|
27
29
|
"README.md"
|
|
28
30
|
],
|