@picassohq/cli 1.0.1 → 1.0.2

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 (28) hide show
  1. package/dist/build-info.json +1 -1
  2. package/dist/index.js +1291 -1257
  3. package/package.json +1 -1
  4. package/runtime/engine-manifest.json +10 -9
  5. package/runtime/packages/picasso-lean-context/index.js +238 -7
  6. package/runtime/packages/picasso-lean-context/read-image-recovery.js +306 -0
  7. package/runtime/packages/picasso-lean-context/timeline.js +4 -3
  8. package/runtime/packages/picasso-model-router/connections.js +17 -0
  9. package/runtime/packages/picasso-model-router/index.js +2 -0
  10. package/runtime/packages/picasso-sdk-server/aside.js +15 -1
  11. package/runtime/packages/picasso-sdk-server/index.js +6 -1
  12. package/runtime/packages/picasso-web-search/backends.js +71 -9
  13. package/runtime/packages/picasso-web-search/failure.js +9 -4
  14. package/runtime/packages/picasso-web-search/format.js +13 -6
  15. package/runtime/packages/picasso-web-search/index.js +9 -4
  16. package/runtime/packages/picasso-web-search/router.js +3 -2
  17. package/runtime/plugins/picasso-lean-context/index.js +238 -7
  18. package/runtime/plugins/picasso-lean-context/read-image-recovery.js +306 -0
  19. package/runtime/plugins/picasso-lean-context/timeline.js +4 -3
  20. package/runtime/plugins/picasso-model-router/connections.js +17 -0
  21. package/runtime/plugins/picasso-model-router/index.js +2 -0
  22. package/runtime/plugins/picasso-web-search/backends.js +71 -9
  23. package/runtime/plugins/picasso-web-search/failure.js +9 -4
  24. package/runtime/plugins/picasso-web-search/format.js +13 -6
  25. package/runtime/plugins/picasso-web-search/index.js +9 -4
  26. package/runtime/plugins/picasso-web-search/router.js +3 -2
  27. package/runtime/relay/main.mjs +2403 -1075
  28. package/runtime/relay/versions-routes.mjs +218 -16
@@ -25,11 +25,18 @@ export function formatBackendMarker(name) {
25
25
  return `${BACKEND_MARKER_PREFIX}${name}${BACKEND_MARKER_SUFFIX}`;
26
26
  }
27
27
 
28
- /** `attempts`: `[{ name, reason }]` in the order tried. An empty list says no backend is configured for this route. */
29
- export function formatUnavailable(attempts) {
30
- const lines =
31
- attempts.length === 0
32
- ? ['- none: this model route has no native web search and no fallback is configured']
33
- : attempts.map((attempt) => `- ${attempt.name}: ${attempt.reason}`);
28
+ /** The line for a route with nothing to try: it names the route and what web search needs there. */
29
+ export function formatNothingConfigured(route) {
30
+ const id = typeof route === 'string' && /^[A-Za-z0-9._-]{1,64}$/u.test(route) ? route : undefined;
31
+ if (id === undefined) return '- none: this model route has no native web search and no fallback is configured';
32
+ return `- none: the ${id} route has no native web search and no fallback is configured (web search needs a fallback in settings.webSearch.fallbacks or PICASSO_WEB_SEARCH_FALLBACKS, e.g. anthropic or openai)`;
33
+ }
34
+
35
+ /**
36
+ * `attempts`: `[{ name, reason }]` in the order tried. An empty list says no backend is configured for this route;
37
+ * `route` (the thread's route id, a config key) is named in that line when given.
38
+ */
39
+ export function formatUnavailable(attempts, { route } = {}) {
40
+ const lines = attempts.length === 0 ? [formatNothingConfigured(route)] : attempts.map((attempt) => `- ${attempt.name}: ${attempt.reason}`);
34
41
  return [UNAVAILABLE_HEADLINE, BACKENDS_TRIED_LABEL, ...lines, UNAVAILABLE_INSTRUCTION].join('\n');
35
42
  }
@@ -8,14 +8,14 @@
8
8
  //
9
9
  // The tool's schema and description belong to the engine's tool-web and are untouched, so the wire tool list (Tier 1)
10
10
  // is byte-identical: `ready` is always true, so the model is never told `unknown tool "web_search"` (see createSearchProvider).
11
- import { createBackends, credentialsFrom } from './backends.js';
11
+ import { createBackends, credentialsFrom, routeProfileFrom } from './backends.js';
12
12
  import { configReader } from './config.js';
13
13
  import { createRouter } from './router.js';
14
14
 
15
15
  export * from './format.js';
16
16
  export * from './failure.js';
17
17
  export * from './config.js';
18
- export { BACKEND_NAMES, DEFAULT_BASE_URLS, DEFAULT_MODELS, KEY_REFS, NATIVE_ROUTES, createBackends, credentialsFrom, parseGeminiSearch, parseMessagesSearch, parseOpenAiSearch } from './backends.js';
18
+ export { BACKEND_NAMES, DEFAULT_BASE_URLS, DEFAULT_MODELS, DEFAULT_PRISM_URL, KEY_REFS, NATIVE_ROUTES, createBackends, credentialsFrom, messagesBase, parseGeminiSearch, parseMessagesSearch, parseOpenAiSearch, routeProfileFrom } from './backends.js';
19
19
  export { DEFAULT_RETRY_DELAY_MS, MAX_RETRY_WAIT_MS, UNAVAILABLE_CODE, createRouter } from './router.js';
20
20
 
21
21
  export const name = 'picasso-web-search';
@@ -29,9 +29,14 @@ const DESCRIPTION = Object.freeze({
29
29
  });
30
30
 
31
31
  /** The search provider over a web seam (`web.registerSearchProvider`), for tests and for `apply`. */
32
- export function createSearchProvider({ ctx, getWeb, fetch: fetchImpl, readConfig, sleep, maxRetryWaitMs } = {}) {
32
+ export function createSearchProvider({ ctx, getWeb, fetch: fetchImpl, readConfig, sleep, maxRetryWaitMs, routeProfile } = {}) {
33
33
  const creds = credentialsFrom(ctx);
34
- const backends = createBackends({ creds, ...(fetchImpl === undefined ? {} : { fetch: fetchImpl }), getWeb: getWeb ?? (() => undefined) });
34
+ const backends = createBackends({
35
+ creds,
36
+ ...(fetchImpl === undefined ? {} : { fetch: fetchImpl }),
37
+ getWeb: getWeb ?? (() => undefined),
38
+ routeProfile: routeProfile ?? routeProfileFrom(ctx),
39
+ });
35
40
  const router = createRouter({ ctx, readConfig: readConfig ?? configReader(), backends, ...(sleep === undefined ? {} : { sleep }), ...(maxRetryWaitMs === undefined ? {} : { maxRetryWaitMs }) });
36
41
  return {
37
42
  id: PROVIDER_ID,
@@ -121,7 +121,8 @@ export function createRouter({ ctx, readConfig, backends, sleep = defaultSleep,
121
121
  continue;
122
122
  }
123
123
  if (step.role === 'native' && !(await backend.configured(call))) {
124
- attempts.push({ name: backend.name, reason: new BackendFailure('credentials').reason });
124
+ const ref = await backend.keyRef?.(call);
125
+ attempts.push({ name: backend.name, reason: new BackendFailure('credentials', { ref }).reason });
125
126
  continue;
126
127
  }
127
128
  try {
@@ -134,7 +135,7 @@ export function createRouter({ ctx, readConfig, backends, sleep = defaultSleep,
134
135
  if (error.permanent) state.dead.set(step.id, error.reason);
135
136
  }
136
137
  }
137
- throw Object.assign(new Error(formatUnavailable(attempts)), { code: UNAVAILABLE_CODE, attempts });
138
+ throw Object.assign(new Error(formatUnavailable(attempts, { route })), { code: UNAVAILABLE_CODE, attempts });
138
139
  },
139
140
 
140
141
  /**
@@ -6,6 +6,7 @@
6
6
  // 3. Automatic MCP server collapsing (mcp__<server>__<tool> -> <server>_call(tool, arguments)) + ~/.picasso/mcp-catalog/<server>.md.
7
7
  // 4. Tier-1 system-prompt/assemble normalizer (byte-identical across TUI/Desktop and plan/default/auto modes).
8
8
  // 5. Tier-1 agent/pre-step normalizer (8 KB instruction cap + SHA-1/@AGENTS.md dedupe, 2 KB skill catalog cap + skill_search overflow, plan-mode history reminder injection, stale-todos nudge).
9
+ // 6. `read_image` recovery for misnamed / HEIC / TIFF images (read-image-recovery.js, a `tools/execute` wrapper).
9
10
  //
10
11
  // Zero external runtime dependencies (Node.js built-ins only).
11
12
 
@@ -25,7 +26,9 @@ import { homedir } from "node:os";
25
26
  import { basename, delimiter, dirname, join, resolve } from "node:path";
26
27
  import { fileURLToPath } from "node:url";
27
28
  import { buildContextTimeline } from "./timeline.js";
29
+ import { installReadImageRecovery } from "./read-image-recovery.js";
28
30
 
31
+ export { createReadImageRecovery, recoverReadImage, sniffImageFormat } from "./read-image-recovery.js";
29
32
  export {
30
33
  CONTEXT_TIMELINE_VERSION,
31
34
  buildContextTimeline,
@@ -221,7 +224,7 @@ export const SKILL_DESC_MAX_CHARS = 200;
221
224
  // registry: { tier1Tools, deferredTools, mcpGateways, mcpServers[], skills },
222
225
  // snapshot: {at, sessionId?, messageCount, instructions:{before,after,capped},
223
226
  // skillCatalog:{before,after,capped,overflowCount},
224
- // dedupe:{removedBlocks,removedNames[]}, injected:{planMode,runtimePolicy,staleTodos}, skillsKnown},
227
+ // dedupe:{removedBlocks,removedNames[]}, injected:{planMode,runtimePolicy,staleTodos,planNudge}, skillsKnown},
225
228
  // counters: {totalSteps, instructionsCapped, skillsOverflowed, dedupeRuns, remindersInjected},
226
229
  // events: [{at, kind, detail}] (newest first, ring-capped),
227
230
  // }.
@@ -415,6 +418,7 @@ export class ContextStats {
415
418
  injected.planMode === true ? "plan-mode" : null,
416
419
  injected.runtimePolicy === true ? "runtime-policy" : null,
417
420
  injected.staleTodos === true ? "stale-todos" : null,
421
+ injected.planNudge === true ? "plan-nudge" : null,
418
422
  ].filter(Boolean);
419
423
 
420
424
  if (instructions.capped === true) {
@@ -465,6 +469,7 @@ export class ContextStats {
465
469
  planMode: injected.planMode === true,
466
470
  runtimePolicy: injected.runtimePolicy === true,
467
471
  staleTodos: injected.staleTodos === true,
472
+ planNudge: injected.planNudge === true,
468
473
  },
469
474
  skillsKnown: Number.isSafeInteger(meta.skillsKnown) ? meta.skillsKnown : this.registry.skills,
470
475
  };
@@ -4345,6 +4350,107 @@ export function staleTodosReminderMessage(todos) {
4345
4350
  });
4346
4351
  }
4347
4352
 
4353
+ // ── Plan nudge (Tier 2) ─────────────────────────────────────────────────────────────────────────────
4354
+ //
4355
+ // Tier 1 already says "for multi-step work add one todo per concrete step"; some models still run a long
4356
+ // task with no list at all, so the UI has no real percent to show (owner 2026-11-16: "convert a task into a
4357
+ // % completion"). When the current turn has made ≥ PLAN_NUDGE_TOOL_CALLS tool calls with no `todo/write`, and
4358
+ // the session holds no unfinished list (that case is the stale-todos nudge's), the next step gets ONE constant
4359
+ // sourced `<system-reminder>` at the tail of its messages. At most once per turn. Tier 1 is never touched and
4360
+ // the text is a constant, so identical history yields identical bytes. State folds from the session's durable
4361
+ // events (`turn/start`, a person's `user/message`, `tool/call`, `todo/write`, this reminder's own message), so
4362
+ // a resumed session keeps it.
4363
+
4364
+ export const PLAN_NUDGE_SOURCE_KIND = "plan-nudge";
4365
+ export const PLAN_NUDGE_TOOL_CALLS = 6;
4366
+ export const PLAN_NUDGE_TEXT =
4367
+ "<system-reminder>\nThis task is taking several steps. For tasks with 3+ steps, keep a short todo list with todo_write and update it as you go, so progress is visible.\n</system-reminder>";
4368
+
4369
+ /** Fresh per-session plan-nudge state. */
4370
+ export function freshPlanNudgeState() {
4371
+ return {
4372
+ scanned: 0,
4373
+ /** Tool calls since the turn (or the person's message) began. */
4374
+ toolCallsThisTurn: 0,
4375
+ /** A `todo/write` happened this turn. */
4376
+ todoWriteThisTurn: false,
4377
+ /** The nudge was already sent this turn. */
4378
+ nudgedThisTurn: false,
4379
+ /** The session's last todo list (any turn). */
4380
+ todos: [],
4381
+ };
4382
+ }
4383
+
4384
+ function resetPlanNudgeTurn(state) {
4385
+ state.toolCallsThisTurn = 0;
4386
+ state.todoWriteThisTurn = false;
4387
+ state.nudgedThisTurn = false;
4388
+ }
4389
+
4390
+ /** Fold one durable session event into the plan-nudge state. */
4391
+ export function foldPlanNudgeEvent(state, event) {
4392
+ if (!isRecord(event)) return state;
4393
+ switch (event.type) {
4394
+ case "turn/start":
4395
+ resetPlanNudgeTurn(state);
4396
+ break;
4397
+ case "todo/write":
4398
+ state.todoWriteThisTurn = true;
4399
+ state.todos = todosFrom(event.data);
4400
+ break;
4401
+ case "tool/call":
4402
+ state.toolCallsThisTurn += 1;
4403
+ break;
4404
+ case "user/message": {
4405
+ const kind = event.data?.source?.kind;
4406
+ if (kind === PLAN_NUDGE_SOURCE_KIND) state.nudgedThisTurn = true;
4407
+ // A person's own message is a new task even when the log carries no `turn/start` for it.
4408
+ else if (kind === undefined || kind === "user") resetPlanNudgeTurn(state);
4409
+ break;
4410
+ }
4411
+ default:
4412
+ break;
4413
+ }
4414
+ return state;
4415
+ }
4416
+
4417
+ /** Bring a session's plan-nudge state up to date with its event log (incremental; restarts if the log shrank). */
4418
+ export function scanPlanNudgeSession(states, session) {
4419
+ let state = states.get(session);
4420
+ const length = Number.isSafeInteger(session?.seq) ? session.seq : 0;
4421
+ if (!state || state.scanned > length) state = freshPlanNudgeState();
4422
+ for (let seq = state.scanned; seq < length; seq += 1) {
4423
+ let event;
4424
+ try {
4425
+ event = session.eventAt(seq);
4426
+ } catch {
4427
+ event = undefined;
4428
+ }
4429
+ foldPlanNudgeEvent(state, event);
4430
+ }
4431
+ state.scanned = length;
4432
+ states.set(session, state);
4433
+ return state;
4434
+ }
4435
+
4436
+ /** Whether the plan nudge is due for this state. */
4437
+ export function planNudgeDue(state) {
4438
+ if (!isRecord(state)) return false;
4439
+ if (state.nudgedThisTurn === true || state.todoWriteThisTurn === true) return false;
4440
+ if (hasUnfinishedTodos(state.todos)) return false;
4441
+ return state.toolCallsThisTurn >= PLAN_NUDGE_TOOL_CALLS;
4442
+ }
4443
+
4444
+ /** A frozen sourced user-role reminder message carrying the plan nudge (constant text). */
4445
+ export function planNudgeReminderMessage() {
4446
+ return Object.freeze({
4447
+ id: randomUUID(),
4448
+ role: "user",
4449
+ content: Object.freeze([Object.freeze({ type: "text", text: PLAN_NUDGE_TEXT })]),
4450
+ source: Object.freeze({ kind: PLAN_NUDGE_SOURCE_KIND, form: "reminder" }),
4451
+ });
4452
+ }
4453
+
4348
4454
  // ---- Restated-fact reminders: sent when first set or changed, not on every step --------------------------------------
4349
4455
  //
4350
4456
  // The live sandbox/approval policy (`runtime-policy`, which names the workspace path) and the CLI's appended
@@ -4401,7 +4507,7 @@ function emptyStepStats() {
4401
4507
  instructions: { before: 0, after: 0, capped: false },
4402
4508
  skillCatalog: { before: 0, after: 0, capped: false, overflowCount: 0 },
4403
4509
  dedupe: { removedBlocks: 0, removedNames: [] },
4404
- injected: { planMode: false, runtimePolicy: false, staleTodos: false },
4510
+ injected: { planMode: false, runtimePolicy: false, staleTodos: false, planNudge: false },
4405
4511
  // UTF-8 bytes of each injected reminder, by reminder name (the context timeline's sizes).
4406
4512
  reminderBytes: {},
4407
4513
  };
@@ -4413,6 +4519,8 @@ function emptyStepStats() {
4413
4519
  * 2. Trims & caps `skill-catalog` at 2,048 B with `skill_search` collapse entry.
4414
4520
  * 3. Appends `plan-mode` reminder message if the agent has active `plan:policy` text.
4415
4521
  * 4. Appends the `stale-todos` nudge at the tail when `options.staleTodos` (the todo list) is passed.
4522
+ * 5. Appends the `plan-nudge` reminder at the tail when `options.planNudge === true` and no stale-todos nudge is
4523
+ * in this step (never both).
4416
4524
  *
4417
4525
  * The returned `stats` field is additive and observational (`/context`): message count, instruction /
4418
4526
  * skill-catalog before-after bytes and cap flags, dedupe drops, and injected reminders.
@@ -4617,6 +4725,17 @@ export function normalizePreStepMessages(messages, options = {}) {
4617
4725
  stats.reminderBytes["stale-todos"] = Buffer.byteLength(extractMessageText(nudge), "utf8");
4618
4726
  }
4619
4727
 
4728
+ // Plan nudge: same placement (tail, Tier 2). One task-list reminder per step: a stale-todos nudge wins.
4729
+ if (
4730
+ options.planNudge === true &&
4731
+ !normalized.some((msg) => msg?.source?.kind === STALE_TODOS_SOURCE_KIND || msg?.source?.kind === PLAN_NUDGE_SOURCE_KIND)
4732
+ ) {
4733
+ const nudge = planNudgeReminderMessage();
4734
+ normalized.push(nudge);
4735
+ stats.injected.planNudge = true;
4736
+ stats.reminderBytes["plan-nudge"] = Buffer.byteLength(extractMessageText(nudge), "utf8");
4737
+ }
4738
+
4620
4739
  stats.messageCount = normalized.length;
4621
4740
  return {
4622
4741
  messages: normalized,
@@ -4635,6 +4754,97 @@ function formatSchemaOnError(toolName, errorMsg, schema) {
4635
4754
  return `${cleanError}${schemaBlock}`;
4636
4755
  }
4637
4756
 
4757
+ /** `queries` -> `query`, `urls` -> `url`, `paths` -> `path`: the singular a model naturally writes for a list field. */
4758
+ function singularOf(key) {
4759
+ if (/ies$/u.test(key)) return `${key.slice(0, -3)}y`;
4760
+ if (/[^s]s$/u.test(key)) return key.slice(0, -1);
4761
+ return undefined;
4762
+ }
4763
+
4764
+ /**
4765
+ * Arguments a model naturally sends for a deferred tool, reshaped to the schema before validation. Models that never
4766
+ * saw the (deferred) schema write the singular: `web_search({query: "…"})` for `{queries: ["…"]}`; six such calls in one
4767
+ * step all failed before the model saw the first error. Only two conservative rewrites, both driven by the schema:
4768
+ * - a required array field that is absent while its undeclared singular is present takes it (a string becomes a
4769
+ * one-item list, a list is used as is), and the singular is dropped;
4770
+ * - a required array field given a single string becomes a one-item list.
4771
+ * Anything else is returned unchanged (the same object), so validation still reports it.
4772
+ */
4773
+ export function normalizeToolArguments(args, schema) {
4774
+ if (!isRecord(args) || !isRecord(schema) || !isRecord(schema.properties)) return args;
4775
+ const required = Array.isArray(schema.required) ? schema.required : [];
4776
+ let out = args;
4777
+ const edit = () => {
4778
+ if (out === args) out = { ...args };
4779
+ return out;
4780
+ };
4781
+ for (const key of required) {
4782
+ const prop = schema.properties[key];
4783
+ if (!isRecord(prop) || prop.type !== "array") continue;
4784
+ const itemType = isRecord(prop.items) ? prop.items.type : undefined;
4785
+ const fits = (value) => itemType === undefined || (itemType === "string" ? typeof value === "string" : true);
4786
+ const value = out[key];
4787
+ if (typeof value === "string" && fits(value)) {
4788
+ edit()[key] = [value];
4789
+ continue;
4790
+ }
4791
+ if (value !== undefined && value !== null) continue;
4792
+ const singular = singularOf(key);
4793
+ if (singular === undefined || Object.hasOwn(schema.properties, singular) || !Object.hasOwn(out, singular)) continue;
4794
+ const given = out[singular];
4795
+ let list;
4796
+ if (Array.isArray(given) && given.every(fits)) list = given;
4797
+ else if (given !== undefined && given !== null && !Array.isArray(given) && fits(given)) list = [given];
4798
+ if (list === undefined) continue;
4799
+ const next = edit();
4800
+ next[key] = list;
4801
+ delete next[singular];
4802
+ }
4803
+ return out;
4804
+ }
4805
+
4806
+ /** A minimal valid-looking value for one schema property (for the "call it as" line of a validation error). */
4807
+ function exampleValueFor(prop) {
4808
+ const type = isRecord(prop) ? prop.type : undefined;
4809
+ if (isRecord(prop) && Array.isArray(prop.enum) && prop.enum.length > 0) return prop.enum[0];
4810
+ switch (type) {
4811
+ case "string":
4812
+ return "…";
4813
+ case "number":
4814
+ case "integer":
4815
+ return 1;
4816
+ case "boolean":
4817
+ return true;
4818
+ case "array":
4819
+ return [exampleValueFor(isRecord(prop.items) ? prop.items : { type: "string" })];
4820
+ case "object":
4821
+ return {};
4822
+ default:
4823
+ return "…";
4824
+ }
4825
+ }
4826
+
4827
+ /**
4828
+ * The one-line correction appended to a validation error: undeclared fields the model sent, and the call shape with
4829
+ * every required field (`tool_call({"name":"web_search","arguments":{"queries":["…"]}})`), so it self-corrects once.
4830
+ */
4831
+ export function expectedArgumentsHint(toolName, schema, args, { gateway = "tool_call" } = {}) {
4832
+ if (!isRecord(schema)) return "";
4833
+ const declared = isRecord(schema.properties) ? schema.properties : {};
4834
+ const required = Array.isArray(schema.required) ? schema.required : [];
4835
+ const example = {};
4836
+ for (const key of required) example[key] = exampleValueFor(declared[key]);
4837
+ const unknown = isRecord(args) && isRecord(schema.properties) ? Object.keys(args).filter((key) => !Object.hasOwn(declared, key)) : [];
4838
+ const parts = [];
4839
+ if (unknown.length > 0) parts.push(`Unrecognized field(s): ${unknown.join(", ")}.`);
4840
+ const call =
4841
+ gateway === "tool_call"
4842
+ ? `tool_call(${JSON.stringify({ name: toolName, arguments: example })})`
4843
+ : `${gateway}(${JSON.stringify({ tool: toolName, arguments: example })})`;
4844
+ parts.push(`Call it as ${call}.`);
4845
+ return parts.join(" ");
4846
+ }
4847
+
4638
4848
  function validateAgainstInputSchema(args, schema) {
4639
4849
  if (!isRecord(schema)) return { valid: true, missing: [], invalidTypes: [] };
4640
4850
  const provided = isRecord(args) ? args : {};
@@ -4760,6 +4970,8 @@ export function apply(ctx, config = {}, deps = {}) {
4760
4970
  const planPolicyByAgent = new WeakMap();
4761
4971
  // Per-session stale-todos fold state (incremental over the durable event log).
4762
4972
  const staleTodosStates = new WeakMap();
4973
+ // Per-session plan-nudge fold state (same durable log).
4974
+ const planNudgeStates = new WeakMap();
4763
4975
  const statedReminderStates = new WeakMap();
4764
4976
  let defaultPlanPolicyText = "";
4765
4977
  // Live sandbox/approval preset text captured at assemble time (AO-006.11):
@@ -5079,16 +5291,18 @@ export function apply(ctx, config = {}, deps = {}) {
5079
5291
  const toolMeta = serverMap?.get(shortName) ?? deferredTools.get(fullMcpName);
5080
5292
  const cachedSchema = toolMeta?.parameters ?? toolMeta?.inputSchema;
5081
5293
 
5294
+ const callArgs = cachedSchema ? normalizeToolArguments(subArgs, cachedSchema) : subArgs;
5082
5295
  if (cachedSchema) {
5083
- const validation = validateAgainstInputSchema(subArgs, cachedSchema);
5296
+ const validation = validateAgainstInputSchema(callArgs, cachedSchema);
5084
5297
  if (!validation.valid) {
5085
5298
  const reasons = [
5086
5299
  ...(validation.missing.length > 0 ? [`missing required field(s): ${validation.missing.join(", ")}`] : []),
5087
5300
  ...(validation.invalidTypes.length > 0 ? [`invalid type(s): ${validation.invalidTypes.join(", ")}`] : []),
5088
5301
  ].join("; ");
5302
+ const hint = expectedArgumentsHint(shortName, cachedSchema, callArgs, { gateway: `${serverName}_call` });
5089
5303
  const errText = formatSchemaOnError(
5090
5304
  `${serverName}.${shortName}`,
5091
- `Invalid arguments for "${serverName}.${shortName}": ${reasons}.`,
5305
+ `Invalid arguments for "${serverName}.${shortName}": ${reasons}.${hint ? ` ${hint}` : ""}`,
5092
5306
  cachedSchema,
5093
5307
  );
5094
5308
  return {
@@ -5102,7 +5316,7 @@ export function apply(ctx, config = {}, deps = {}) {
5102
5316
  }
5103
5317
  }
5104
5318
 
5105
- return executeDeferredByName(fullMcpName, subArgs, exec, cachedSchema);
5319
+ return executeDeferredByName(fullMcpName, callArgs, exec, cachedSchema);
5106
5320
  };
5107
5321
 
5108
5322
  const executeDeferredByName = async (requestedName, rawArgs = {}, exec = {}, overrideSchema) => {
@@ -5177,7 +5391,9 @@ export function apply(ctx, config = {}, deps = {}) {
5177
5391
  };
5178
5392
  }
5179
5393
 
5180
- // Validate required parameters and basic property types before invoking
5394
+ // Reshape what models naturally send (`query` for a required `queries` list), then validate required parameters
5395
+ // and basic property types before invoking.
5396
+ if (cachedSchema) args = normalizeToolArguments(args, cachedSchema);
5181
5397
  if (cachedSchema) {
5182
5398
  const validation = validateAgainstInputSchema(args, cachedSchema);
5183
5399
  if (!validation.valid) {
@@ -5185,9 +5401,10 @@ export function apply(ctx, config = {}, deps = {}) {
5185
5401
  ...(validation.missing.length > 0 ? [`missing required field(s): ${validation.missing.join(", ")}`] : []),
5186
5402
  ...(validation.invalidTypes.length > 0 ? [`invalid type(s): ${validation.invalidTypes.join(", ")}`] : []),
5187
5403
  ].join("; ");
5404
+ const hint = expectedArgumentsHint(targetName, cachedSchema, args);
5188
5405
  const errText = formatSchemaOnError(
5189
5406
  targetName,
5190
- `Invalid arguments for "${targetName}": ${reasons}.`,
5407
+ `Invalid arguments for "${targetName}": ${reasons}.${hint ? ` ${hint}` : ""}`,
5191
5408
  cachedSchema,
5192
5409
  );
5193
5410
  return {
@@ -5782,6 +5999,14 @@ export function apply(ctx, config = {}, deps = {}) {
5782
5999
  };
5783
6000
  ensureDelegationFastPath();
5784
6001
 
6002
+ // `read_image` on a misnamed image (PNG/HEIC saved as .jpg) or a HEIC/TIFF file: the engine trusts the extension and
6003
+ // refuses; this around-dispatch wrapper re-reads by the real format (sips converts what the wire cannot carry). Runs
6004
+ // only after the engine body failed with a format code; Tier 1 is untouched (read-image-recovery.js). Off with
6005
+ // `readImageRecovery: false` or PICASSO_LEAN_CONTEXT_READ_IMAGE_RECOVERY=0.
6006
+ if (config.readImageRecovery !== false && process.env.PICASSO_LEAN_CONTEXT_READ_IMAGE_RECOVERY !== "0") {
6007
+ installReadImageRecovery(ctx, deps.readImageRecovery);
6008
+ }
6009
+
5785
6010
  // Propagate `isError: true` from `tool_call` / `<server>_call` through dsh-tools `tools/post-execute`
5786
6011
  ctx?.on?.(
5787
6012
  "tools/post-execute",
@@ -5965,6 +6190,11 @@ export function apply(ctx, config = {}, deps = {}) {
5965
6190
  const todoState = scanStaleTodosSession(staleTodosStates, session);
5966
6191
  if (staleTodosReminderDue(todoState)) staleTodos = todoState.todos;
5967
6192
  }
6193
+ // Plan nudge: a long turn with no todo list at all; never in the same step as a stale-todos nudge.
6194
+ let planNudge = false;
6195
+ if (staleTodos === undefined && session && typeof session.eventAt === "function" && !payload?.signal?.aborted) {
6196
+ planNudge = planNudgeDue(scanPlanNudgeSession(planNudgeStates, session));
6197
+ }
5968
6198
 
5969
6199
  // What this session's log already states (runtime policy, appended instructions): not repeated per step.
5970
6200
  let statedReminders;
@@ -5981,6 +6211,7 @@ export function apply(ctx, config = {}, deps = {}) {
5981
6211
  planPolicyText: agentPlanPolicy,
5982
6212
  runtimePolicyText: agentRuntimePolicy,
5983
6213
  staleTodos,
6214
+ planNudge,
5984
6215
  });
5985
6216
 
5986
6217
  for (const skill of overflowSkills) {