@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,236 @@
1
+ // A request for a model that cannot run with thinking off never leaves without a thinking level.
2
+ //
3
+ // The clients choose a level before they send (the TUI's `launchEffortOption`, the Mac's `ModelReasoning.swift`), but a
4
+ // request can reach the engine with none: a headless `picasso run`, a subagent, a schedule, a thread created by another
5
+ // client. For a model whose provider refuses "no thinking" the adapter then sends thinking disabled and the provider
6
+ // answers 400 (Z.ai code 1210: "This model always engages in thinking and cannot be disabled; please use low, high, or
7
+ // max"). `agent/pre-step` (index.js) therefore fills the step's level in the engine, on both surfaces.
8
+ //
9
+ // The rule is the one both clients follow (`@picasso/shared-home/model-reasoning`, `resolveReasoningLevel`), for the
10
+ // case with no pick in this chat:
11
+ //
12
+ // a model always thinks when the person's shared file lists it (`alwaysThinks`, learned from a provider 400), or
13
+ // its id is a known family (FAMILIES), or the levels the engine reports leave out off
14
+ // its level is the level saved for this model (`efforts["<route>/<model>"]`), else the default for every
15
+ // model (`defaultEffort`), each moved to the nearest level the model offers; else the
16
+ // model's own default; else the lowest level it offers; `high` when nothing is known
17
+ //
18
+ // A model that can run without thinking is left exactly as it was sent (no level stays no level), so this adds nothing
19
+ // to any request that worked before.
20
+ //
21
+ // A level the model does not offer is never sent either (owner 2026-11-17: a level saved for one connection's model,
22
+ // carried onto the managed route's model of the same name, failed every prompt with `does not support reasoning
23
+ // effort "max"`). When the engine reports the model's levels, a level it lacks moves to the nearest one it offers, and
24
+ // a model with no levels at all gets none (`supportedThinkingLevel`). A model the engine cannot describe keeps what
25
+ // was sent. OFF_LEVELS, LEVEL_ORDER and FAMILIES restate
26
+ // `packages/shared-home/src/model-reasoning.json`; test/thinking-default.test.mjs fails when they drift from it.
27
+
28
+ export const OFF_LEVELS = Object.freeze(['off', 'none', 'disabled', 'minimal-off']);
29
+ export const LEVEL_ORDER = Object.freeze(['minimal', 'low', 'medium', 'high', 'xhigh', 'max']);
30
+ export const FAMILIES = Object.freeze([
31
+ Object.freeze({ id: 'zai-glm-5.3', model: '(?:^|[^a-z0-9])glm-5[.p-]3(?![0-9])' }),
32
+ Object.freeze({ id: 'gemini-pro', model: '(?:^|[^a-z0-9])gemini-(?:2\\.5|[3-9](?:\\.[0-9]+)?)-pro(?![a-z0-9])|(?:^|[^a-z0-9])gemini-pro-latest(?![a-z0-9])' }),
33
+ Object.freeze({ id: 'minimax-m3.1-flash', model: '(?:^|[^a-z0-9])minimax-m3[.p]1-flash(?![a-z0-9])' }),
34
+ ]);
35
+
36
+ const familyPatterns = FAMILIES.map((family) => new RegExp(family.model, 'iu'));
37
+ const nonEmpty = (value) => typeof value === 'string' && value.length > 0;
38
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
39
+
40
+ /** Words that mean "no thinking". */
41
+ export const isOffLevel = (level) => nonEmpty(level) && OFF_LEVELS.includes(level.toLowerCase());
42
+
43
+ /**
44
+ * Whether a model must never run with thinking off. `offered`: the levels the engine reports (undefined = unknown,
45
+ * [] = the model has no reasoning); `learned`: the shared file's `alwaysThinks` refs.
46
+ */
47
+ export function modelAlwaysThinks({ provider, model, offered, learned }) {
48
+ if (Array.isArray(learned) && learned.includes(`${provider}/${model}`)) return true;
49
+ if (familyPatterns.some((pattern) => pattern.test(model))) return true;
50
+ return Array.isArray(offered) && offered.length > 0 && !offered.some(isOffLevel);
51
+ }
52
+
53
+ const rank = (level) => LEVEL_ORDER.indexOf(level.toLowerCase());
54
+
55
+ /** The offered thinking level nearest `level` (exact first, then by level order; ties go to the higher one). */
56
+ function nearest(level, offered) {
57
+ if (isOffLevel(level)) return undefined;
58
+ if (offered === undefined) return level;
59
+ const allowed = offered.filter((id) => !isOffLevel(id));
60
+ const exact = allowed.find((id) => id.toLowerCase() === level.toLowerCase());
61
+ if (exact !== undefined) return exact;
62
+ const wanted = rank(level);
63
+ if (wanted < 0) return undefined;
64
+ let best;
65
+ for (const id of allowed) {
66
+ const at = rank(id);
67
+ if (at < 0) continue;
68
+ const distance = Math.abs(at - wanted);
69
+ if (best === undefined || distance < best.distance || (distance === best.distance && at > best.rank)) best = { id, distance, rank: at };
70
+ }
71
+ return best?.id;
72
+ }
73
+
74
+ /**
75
+ * What an explicit `level` becomes on a model that offers `offered` (the engine's levels; undefined = unknown):
76
+ * undefined = send it as it is, a string = send that level instead (the nearest one offered, ties up), null = send no
77
+ * level (the model has no reasoning, or nothing near it). An off word on a model that offers no off word is left to
78
+ * `requiredThinkingLevel` (the model always thinks).
79
+ */
80
+ export function supportedThinkingLevel(level, offered) {
81
+ if (!nonEmpty(level) || !Array.isArray(offered)) return undefined;
82
+ if (offered.length === 0) return null;
83
+ const exact = offered.find((id) => id.toLowerCase() === level.toLowerCase());
84
+ if (exact !== undefined) return exact === level ? undefined : exact;
85
+ if (isOffLevel(level)) return offered.find(isOffLevel);
86
+ return nearest(level, offered) ?? null;
87
+ }
88
+
89
+ /**
90
+ * The level a request with no usable level must carry, or undefined when it needs none (the model can run without
91
+ * thinking, or has no reasoning at all). `settings`: the shared model-connections document (`efforts`, `defaultEffort`,
92
+ * `alwaysThinks`); `catalogueDefault`: the model's own default level as the engine reports it.
93
+ */
94
+ export function requiredThinkingLevel({ provider, model, offered, catalogueDefault, settings }) {
95
+ if (!nonEmpty(provider) || !nonEmpty(model)) return undefined;
96
+ if (Array.isArray(offered) && offered.length === 0) return undefined;
97
+ const saved = isRecord(settings) ? settings : {};
98
+ if (!modelAlwaysThinks({ provider, model, offered, learned: saved.alwaysThinks })) return undefined;
99
+ const perModel = isRecord(saved.efforts) ? saved.efforts[`${provider}/${model}`] : undefined;
100
+ for (const level of [perModel, saved.defaultEffort]) {
101
+ if (!nonEmpty(level)) continue;
102
+ const usable = nearest(level, offered);
103
+ if (usable !== undefined) return usable;
104
+ }
105
+ if (nonEmpty(catalogueDefault) && !isOffLevel(catalogueDefault) && (offered === undefined || offered.includes(catalogueDefault))) return catalogueDefault;
106
+ if (offered !== undefined) return offered.find((id) => !isOffLevel(id));
107
+ return 'high';
108
+ }
109
+
110
+ /**
111
+ * The `agent/pre-step` guard. `deps`: `{ llm: () => registry | undefined, settings: () => document, log }`. The levels
112
+ * a model offers are asked of the engine once per model (`resolveModelInfo`); a model the engine cannot describe is
113
+ * decided by the shared file and the known families alone.
114
+ */
115
+ export function createThinkingGuard({ llm, settings, log = () => {} }) {
116
+ const known = new Map();
117
+ /**
118
+ * The level each session (its agent object) fixed per model the first time it needed one (owner 2026-11-17: each
119
+ * session owns its model and level). A level another session saves later in the shared file reaches new sessions
120
+ * only, never one already running on that model.
121
+ */
122
+ const fixed = new WeakMap();
123
+ /** `<route>/<model>/<level>` corrections already logged (once each, not every step). */
124
+ const corrected = new Set();
125
+
126
+ async function describe(provider, model) {
127
+ const ref = `${provider}/${model}`;
128
+ if (known.has(ref)) return known.get(ref);
129
+ let described;
130
+ try {
131
+ const registry = llm();
132
+ if (registry !== undefined && registry !== null && typeof registry.resolveModelInfo === 'function') {
133
+ const info = await registry.resolveModelInfo(provider, model);
134
+ const efforts = Array.isArray(info?.reasoning?.efforts) ? info.reasoning.efforts.map((effort) => effort?.id).filter(nonEmpty) : [];
135
+ const fallback = info?.reasoning?.defaultEffort;
136
+ described = { offered: efforts, ...(nonEmpty(fallback) ? { catalogueDefault: fallback } : {}) };
137
+ known.set(ref, described);
138
+ }
139
+ } catch {
140
+ described = undefined; // not cached: the engine may be able to describe it on a later step
141
+ }
142
+ return described;
143
+ }
144
+
145
+ return {
146
+ /**
147
+ * The level this step's selection needs and does not have; undefined when it is fine as it is. `owner` (the step's
148
+ * agent): the session, whose first answer per model is kept for its lifetime.
149
+ */
150
+ async levelFor(selection, owner) {
151
+ if (!isRecord(selection) || !nonEmpty(selection.provider) || !nonEmpty(selection.model)) return undefined;
152
+ if (nonEmpty(selection.reasoningEffort) && !isOffLevel(selection.reasoningEffort)) return undefined;
153
+ const ref = `${selection.provider}/${selection.model}`;
154
+ const session = owner !== null && typeof owner === 'object' ? fixed.get(owner) : undefined;
155
+ if (session?.has(ref)) return session.get(ref);
156
+ const level = await this.resolveLevel(selection);
157
+ // "None needed" is not fixed: a model learned later to always think still gets a level.
158
+ if (level !== undefined && owner !== null && typeof owner === 'object') {
159
+ const levels = fixed.get(owner) ?? new Map();
160
+ levels.set(ref, level);
161
+ fixed.set(owner, levels);
162
+ }
163
+ return level;
164
+ },
165
+
166
+ /** The level the shared file and the model's own levels give a selection now (see `requiredThinkingLevel`). */
167
+ async resolveLevel(selection) {
168
+ const described = await describe(selection.provider, selection.model);
169
+ let saved;
170
+ try {
171
+ saved = settings();
172
+ } catch {
173
+ saved = undefined;
174
+ }
175
+ return requiredThinkingLevel({
176
+ provider: selection.provider,
177
+ model: selection.model,
178
+ ...(described === undefined ? {} : { offered: described.offered }),
179
+ ...(described?.catalogueDefault === undefined ? {} : { catalogueDefault: described.catalogueDefault }),
180
+ settings: saved,
181
+ });
182
+ },
183
+
184
+ /**
185
+ * The step's explicit level checked against the levels the engine reports for its model (see
186
+ * `supportedThinkingLevel`); undefined when there is nothing to change.
187
+ */
188
+ async correctionFor(selection) {
189
+ if (!isRecord(selection) || !nonEmpty(selection.provider) || !nonEmpty(selection.model) || !nonEmpty(selection.reasoningEffort)) return undefined;
190
+ const described = await describe(selection.provider, selection.model);
191
+ return supportedThinkingLevel(selection.reasoningEffort, described?.offered);
192
+ },
193
+
194
+ /** Sets the level on the step's own selection object (what the engine sends this step). True when it changed. */
195
+ async apply(selection, owner) {
196
+ const correction = await this.correctionFor(selection);
197
+ if (correction !== undefined) {
198
+ const was = selection.reasoningEffort;
199
+ try {
200
+ if (correction === null) delete selection.reasoningEffort;
201
+ else selection.reasoningEffort = correction;
202
+ } catch (error) {
203
+ log(`picasso-model-router: the thinking level for ${selection.provider}/${selection.model} could not be corrected (${error instanceof Error ? error.message : String(error)}).`);
204
+ return false;
205
+ }
206
+ if (selection.reasoningEffort === was) return false;
207
+ const ref = `${selection.provider}/${selection.model}/${was}`;
208
+ if (!corrected.has(ref)) {
209
+ corrected.add(ref);
210
+ log(`picasso-model-router: ${selection.provider}/${selection.model} does not offer thinking level "${was}"; ${correction === null ? 'sending none' : `sending "${correction}"`}.`);
211
+ }
212
+ // A model that always thinks still gets a level when the correction left it with none.
213
+ if (correction === null) {
214
+ const required = await this.levelFor(selection, owner);
215
+ if (required !== undefined) {
216
+ try {
217
+ selection.reasoningEffort = required;
218
+ } catch {
219
+ // left with none: the model's own default
220
+ }
221
+ }
222
+ }
223
+ return true;
224
+ }
225
+ const level = await this.levelFor(selection, owner);
226
+ if (level === undefined) return false;
227
+ try {
228
+ selection.reasoningEffort = level;
229
+ } catch (error) {
230
+ log(`picasso-model-router: the thinking level for ${selection.provider}/${selection.model} could not be set (${error instanceof Error ? error.message : String(error)}).`);
231
+ return false;
232
+ }
233
+ return selection.reasoningEffort === level;
234
+ },
235
+ };
236
+ }
@@ -28,7 +28,7 @@ import { readFileSync, statSync } from 'node:fs';
28
28
  import { userInfo } from 'node:os';
29
29
  import { join } from 'node:path';
30
30
 
31
- import { isProgressReport } from './report.js';
31
+ import { isProgressReport, parseProgressReport } from './report.js';
32
32
 
33
33
  export { formatReportMarkdown, isProgressReport, parseProgressReport, splitReportItems } from './report.js';
34
34
 
@@ -131,11 +131,24 @@ function freshState() {
131
131
  openerSeen: true,
132
132
  /** A reminder is in history with no report after it yet. */
133
133
  reminderPending: false,
134
+ /** Reminders in history since the newest report (the ones the model has not answered). */
135
+ unanswered: 0,
134
136
  /** The model has reported without being reminded (its own instructions ask for reports). */
135
137
  selfReporting: false,
138
+ /** The last `todo/write` list (`[]` before any). */
139
+ todos: [],
140
+ /** The newest report's percent written after the last `todo/write` (undefined when none since). */
141
+ reportPercentSincePlan: undefined,
142
+ /** A plan-drift nudge is in history since the last `todo/write`. */
143
+ driftNudged: false,
136
144
  };
137
145
  }
138
146
 
147
+ function todosFrom(data) {
148
+ const list = isRecord(data) && Array.isArray(data.todos) ? data.todos : [];
149
+ return list.filter(isRecord).map((todo) => ({ status: typeof todo.status === 'string' ? todo.status : 'pending' }));
150
+ }
151
+
139
152
  /** Fold one durable session event into the timing state. */
140
153
  export function foldEvent(state, event) {
141
154
  if (!isRecord(event)) return state;
@@ -155,16 +168,27 @@ export function foldEvent(state, event) {
155
168
  if (message?.source?.kind === SOURCE_KIND && time !== undefined) {
156
169
  state.lastReminder = time;
157
170
  state.reminderPending = true;
171
+ state.unanswered += 1;
158
172
  }
173
+ if (message?.source?.kind === DRIFT_SOURCE_KIND) state.driftNudged = true;
159
174
  break;
160
175
  }
161
- case 'assistant/message':
162
- if (time !== undefined && isProgressReport(textOf(event.data?.message))) {
176
+ case 'todo/write':
177
+ state.todos = todosFrom(event.data);
178
+ state.reportPercentSincePlan = undefined;
179
+ state.driftNudged = false;
180
+ break;
181
+ case 'assistant/message': {
182
+ const report = parseProgressReport(textOf(event.data?.message));
183
+ if (report !== undefined && report.percent !== undefined) state.reportPercentSincePlan = report.percent;
184
+ if (time !== undefined && report !== undefined) {
163
185
  state.lastReport = time;
164
186
  if (!state.reminderPending) state.selfReporting = true;
165
187
  state.reminderPending = false;
188
+ state.unanswered = 0;
166
189
  }
167
190
  break;
191
+ }
168
192
  default:
169
193
  break;
170
194
  }
@@ -209,12 +233,36 @@ export function reminderDue(state, now, intervalMs, proposed = []) {
209
233
  return now - baseline >= (state.selfReporting ? intervalMs * SELF_REPORT_GRACE : intervalMs);
210
234
  }
211
235
 
212
- /** The reminder's text. `minutes` is the elapsed wall time it reports. */
213
- export function renderReminder(minutes) {
236
+ /** "10 minutes" / "30 seconds" for an interval in ms (the dev/test overrides go below a minute). */
237
+ export function intervalLabel(intervalMs) {
238
+ const ms = Number.isFinite(intervalMs) && intervalMs > 0 ? intervalMs : DEFAULT_INTERVAL_MINUTES * 60_000;
239
+ if (ms < 60_000) {
240
+ const seconds = Math.max(1, Math.round(ms / 1000));
241
+ return `${seconds} second${seconds === 1 ? '' : 's'}`;
242
+ }
243
+ const minutes = Math.round(ms / 60_000);
244
+ return `${minutes} minute${minutes === 1 ? '' : 's'}`;
245
+ }
246
+
247
+ /**
248
+ * The reminder's text. `minutes` is the elapsed wall time it reports; `intervalMs` the configured cadence;
249
+ * `unanswered` how many earlier reminders since the last report got none (from history, so resume-safe).
250
+ *
251
+ * Owner 2026-11-17: on managed Claude Fable 5.1 four reminders in a row (16:55–17:37) reached the model and got no
252
+ * report, because the run's prompt said "No unnecessary progress reports" and the old text read as an optional harness
253
+ * nudge ("In your next reply … do not mention this reminder"). The text now says whose request it is (the user's
254
+ * setting, shown in the status panel), that a general "fewer status messages" instruction does not cover it, and to
255
+ * write it before the next tool call (a Claude-style model reads "reply" as its final answer).
256
+ */
257
+ export function renderReminder(minutes, options = {}) {
214
258
  const elapsed = minutes >= 1 ? `about ${Math.round(minutes)} minute${Math.round(minutes) === 1 ? '' : 's'}` : 'a while';
259
+ const unanswered = Number.isSafeInteger(options.unanswered) && options.unanswered > 0 ? options.unanswered : 0;
215
260
  return [
216
261
  '<system-reminder>',
217
- `Progress check: you have been working for ${elapsed} without a progress report. In your next reply, post a brief progress report as a normal message in exactly this shape, then keep working — do not stop, wait, or ask for confirmation:`,
262
+ `Progress check: you have been working for ${elapsed} without a progress report.`,
263
+ `The user's Picasso settings ask for a progress report every ${intervalLabel(options.intervalMs)} of work; Picasso shows it in the status panel so the user can follow a long run without interrupting it. This is that scheduled report, not an unnecessary update: a general instruction to keep status messages down does not cover it (to stop these, the user switches Progress reports off in Picasso settings).`,
264
+ ...(unanswered > 0 ? [`The last ${unanswered === 1 ? 'progress check' : `${unanswered} progress checks`} got no report.`] : []),
265
+ 'In your next message, before any further tool call, post the report as a normal message in exactly this shape, then keep working — do not stop, wait, or ask for confirmation:',
218
266
  '',
219
267
  '**Progress report** · <overall %> (<how you measured it, e.g. 3 of 7 steps done>)',
220
268
  'Goal: <the original request, one line>',
@@ -223,14 +271,14 @@ export function renderReminder(minutes) {
223
271
  'Next: <the next steps>',
224
272
  'Blockers: <blockers, or none>',
225
273
  '',
226
- 'Keep it under eight short lines, report only what actually happened, and do not mention this reminder.',
274
+ 'Keep it under eight short lines and report only what actually happened. Write it straight to the user, with no preamble about this check.',
227
275
  '</system-reminder>',
228
276
  ].join('\n');
229
277
  }
230
278
 
231
279
  /** A frozen user-role message shaped like dsh-llm's `createUserMessage` output. */
232
- export function reminderMessage(minutes) {
233
- const text = renderReminder(minutes);
280
+ export function reminderMessage(minutes, options = {}) {
281
+ const text = renderReminder(minutes, options);
234
282
  return Object.freeze({
235
283
  role: 'user',
236
284
  content: Object.freeze([Object.freeze({ type: 'text', text })]),
@@ -239,6 +287,60 @@ export function reminderMessage(minutes) {
239
287
  });
240
288
  }
241
289
 
290
+ // ── Plan drift (Tier 2) ───────────────────────────────────────────────────────────────────────────────────────
291
+ //
292
+ // Owner 2026-11-17: the status panel showed a report's "95%" over "Plan 0/6": the model kept reporting but never
293
+ // updated its todo list. When the newest report written since the last `todo/write` claims at least
294
+ // PLAN_DRIFT_POINTS more than the list's own completion (completed steps whole, the step in progress half), the next
295
+ // step gets ONE sourced `<system-reminder>` at the tail of its messages asking it to update the list. Once per
296
+ // `todo/write`; top-level agents only; the text depends only on history (the two percents and counts), so identical
297
+ // history yields identical bytes. Tier 1 is never touched.
298
+
299
+ export const DRIFT_SOURCE_KIND = 'picasso-plan-drift';
300
+ export const PLAN_DRIFT_POINTS = 50;
301
+
302
+ /** The list's completion (0–100): completed steps whole, the step in progress half. */
303
+ export function planCompletion(todos) {
304
+ const list = Array.isArray(todos) ? todos : [];
305
+ if (list.length === 0) return 0;
306
+ const credit = list.reduce((sum, todo) => sum + (todo?.status === 'completed' ? 1 : todo?.status === 'in_progress' ? 0.5 : 0), 0);
307
+ return (credit / list.length) * 100;
308
+ }
309
+
310
+ /**
311
+ * The report percent that makes the drift nudge due, else undefined: a list with steps, a report since its last write
312
+ * (this step's proposed assistant text counts as the newest), ≥ PLAN_DRIFT_POINTS above the list, no nudge yet.
313
+ */
314
+ export function planDriftDue(state, proposed = []) {
315
+ if (!isRecord(state) || state.driftNudged === true || !Array.isArray(state.todos) || state.todos.length === 0) return undefined;
316
+ let reported = state.reportPercentSincePlan;
317
+ for (const message of proposed) {
318
+ if (message?.role !== 'assistant') continue;
319
+ const report = parseProgressReport(textOf(message));
320
+ if (report?.percent !== undefined) reported = report.percent;
321
+ }
322
+ if (reported === undefined) return undefined;
323
+ return reported - planCompletion(state.todos) >= PLAN_DRIFT_POINTS ? reported : undefined;
324
+ }
325
+
326
+ /** The nudge text: the report's percent against the list's, with the list's counts. */
327
+ export function renderPlanDrift(reported, todos) {
328
+ const list = Array.isArray(todos) ? todos : [];
329
+ const done = list.filter((todo) => todo?.status === 'completed').length;
330
+ const plan = Math.round(planCompletion(list));
331
+ return `<system-reminder>\nYour latest progress report says ${reported}% done, but your todo list shows ${plan}% (${done} of ${list.length} step${list.length === 1 ? '' : 's'} completed). Update it with todo_write so the plan matches the work, then keep going.\n</system-reminder>`;
332
+ }
333
+
334
+ /** A frozen sourced user-role reminder carrying the plan-drift nudge. */
335
+ export function planDriftMessage(reported, todos) {
336
+ return Object.freeze({
337
+ role: 'user',
338
+ content: Object.freeze([Object.freeze({ type: 'text', text: renderPlanDrift(reported, todos) })]),
339
+ source: Object.freeze({ kind: DRIFT_SOURCE_KIND, form: 'reminder' }),
340
+ id: randomUUID(),
341
+ });
342
+ }
343
+
242
344
  export function apply(ctx, config = {}, deps = {}) {
243
345
  const readSettings = deps.settings ?? settingsReader(config, deps.env ?? process.env);
244
346
  const clock = deps.now ?? Date.now;
@@ -251,17 +353,25 @@ export function apply(ctx, config = {}, deps = {}) {
251
353
  const agent = args?.agent;
252
354
  const session = agent?.session;
253
355
  if (!session || typeof session.eventAt !== 'function' || isChildAgent(agent)) return decision;
254
- const { enabled, intervalMs } = readSettings();
255
- if (!enabled) return decision;
256
- if (decision.messages.some((message) => message?.source?.kind === SOURCE_KIND)) return decision;
257
356
  const state = scanSession(states, session);
357
+ // The plan-drift nudge reads only history; it is not the timed report reminder, so that setting does not gate it.
358
+ const drift = decision.messages.some((message) => message?.source?.kind === DRIFT_SOURCE_KIND) ? undefined : planDriftDue(state, decision.messages);
359
+ const extra = [];
360
+ if (drift !== undefined) {
361
+ // Recorded now so a step that is rejected downstream cannot send it twice before its event lands.
362
+ state.driftNudged = true;
363
+ extra.push(planDriftMessage(drift, state.todos));
364
+ }
365
+ const { enabled, intervalMs } = readSettings();
258
366
  const now = clock();
259
- if (!reminderDue(state, now, intervalMs, decision.messages)) return decision;
260
- const baseline = Math.max(state.runStart ?? now, state.lastReport ?? 0, state.lastReminder ?? 0);
261
- // Recorded now so a step that is rejected downstream cannot re-arm it before its event lands.
262
- state.lastReminder = now;
263
- state.reminderPending = true;
264
- return { ...decision, messages: [...decision.messages, reminderMessage((now - baseline) / 60_000)] };
367
+ if (enabled && !decision.messages.some((message) => message?.source?.kind === SOURCE_KIND) && reminderDue(state, now, intervalMs, decision.messages)) {
368
+ const baseline = Math.max(state.runStart ?? now, state.lastReport ?? 0, state.lastReminder ?? 0);
369
+ // Recorded now so a step that is rejected downstream cannot re-arm it before its event lands.
370
+ state.lastReminder = now;
371
+ state.reminderPending = true;
372
+ extra.push(reminderMessage((now - baseline) / 60_000, { intervalMs, unanswered: state.unanswered }));
373
+ }
374
+ return extra.length === 0 ? decision : { ...decision, messages: [...decision.messages, ...extra] };
265
375
  });
266
376
  }
267
377
 
@@ -0,0 +1,37 @@
1
+ // Slash commands run through `command/run` (`/compact`, `/review --fresh`, `/init`, …) have no short clock: a command
2
+ // runs until it finishes, the caller's own `timeoutMs` passes, or `session/cancel` stops it. The old fixed 120 s cut off
3
+ // a `/compact` of a long history and a fresh review with several reviewers (owner 2026-11-17).
4
+
5
+ /**
6
+ * Upper bound on one `command/run` when the caller names none (was 120 s). A command normally ends by itself or is
7
+ * stopped by `session/cancel`; this only frees a command that never settles.
8
+ */
9
+ export const COMMAND_RUN_TIMEOUT_MS = 6 * 60 * 60 * 1000;
10
+
11
+ /** Tracks the commands running per session so `session/cancel` can stop them. */
12
+ export function createCommandRuns() {
13
+ /** sessionId → AbortControllers of the commands running in it. */
14
+ const running = new Map();
15
+ return {
16
+ /** Runs `execute(signal)` with a signal that aborts on cancel or after `timeoutMs` (default `COMMAND_RUN_TIMEOUT_MS`). */
17
+ async run(sessionId, timeoutMs, execute) {
18
+ const controller = new AbortController();
19
+ const set = running.get(sessionId) ?? new Set();
20
+ set.add(controller);
21
+ running.set(sessionId, set);
22
+ try {
23
+ return await execute(AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs ?? COMMAND_RUN_TIMEOUT_MS)]));
24
+ } finally {
25
+ set.delete(controller);
26
+ if (set.size === 0) running.delete(sessionId);
27
+ }
28
+ },
29
+ /** Stops every command running in the session. */
30
+ cancel(sessionId) {
31
+ for (const controller of running.get(sessionId) ?? []) controller.abort(new Error('cancelled'));
32
+ },
33
+ size(sessionId) {
34
+ return running.get(sessionId)?.size ?? 0;
35
+ },
36
+ };
37
+ }
@@ -150,7 +150,11 @@ export function findIgnoreFile(cwd) {
150
150
  }
151
151
  }
152
152
 
153
- const SCAN_LIMIT = 100000;
153
+ /**
154
+ * Entries one `.picassoignore` scan walks before it stops (cached per ignore file and mtime). Was 100 000: past it the
155
+ * guard cannot prove a tree is clean and refuses the read, so glob/grep failed in large monorepos with nothing ignored.
156
+ */
157
+ const SCAN_LIMIT = 2_000_000;
154
158
 
155
159
  /**
156
160
  * Ignore lookups for working directories, cached per ignore file and mtime so
@@ -18,6 +18,7 @@
18
18
  // announced the capability the waterfall falls through (fail-closed, as stock).
19
19
  //
20
20
  // Mounted by dsh/picasso-sdk.patch.yml, which disables the stock server entry.
21
+ import { createCommandRuns } from './command-runs.js';
21
22
  import { existsSync, readdirSync, realpathSync } from 'node:fs';
22
23
  import { approvalRequester, requesterFields } from './requester.js';
23
24
  import { homedir, tmpdir } from 'node:os';
@@ -488,6 +489,8 @@ export function apply(ctx, config = {}) {
488
489
  return { answers: answer.answers };
489
490
  });
490
491
 
492
+ /** The slash commands running per session (`session/cancel` stops them). */
493
+ const commandRuns = createCommandRuns();
491
494
  const requireSession = (params) => {
492
495
  if (typeof params?.sessionId !== 'string' || params.sessionId.length === 0) {
493
496
  throw new TypeError('a non-empty sessionId is required');
@@ -710,6 +713,8 @@ export function apply(ctx, config = {}) {
710
713
  async 'session/cancel'(params) {
711
714
  const agent = requireSession(params);
712
715
  agent.cancel({ kind: 'user' }, { keepInbox: params.keepInbox === true });
716
+ // A running slash command (`/compact`, `/review --fresh`, …) stops with the turn: it has no clock of its own.
717
+ commandRuns.cancel(params.sessionId);
713
718
  return {};
714
719
  },
715
720
  async 'session/fork'(params) {
@@ -746,9 +751,12 @@ export function apply(ctx, config = {}) {
746
751
  const line = typeof params.line === 'string'
747
752
  ? params.line
748
753
  : `/${String(params.name ?? '').replace(/^\//u, '')}${params.args ? ` ${params.args}` : ''}`;
749
- const execution = await commands.execute(agent, line, [], AbortSignal.timeout(params.timeoutMs ?? 120000));
750
- if (execution === undefined) throw new Error(`unknown command: ${line.split(/\s/u)[0]}`);
751
- return { commandId: execution.commandId, result: execution.result };
754
+ // No short clock on a command (command-runs.js): it runs until it ends, `timeoutMs` passes or the turn is cancelled.
755
+ return commandRuns.run(params.sessionId, params.timeoutMs, async (signal) => {
756
+ const execution = await commands.execute(agent, line, [], signal);
757
+ if (execution === undefined) throw new Error(`unknown command: ${line.split(/\s/u)[0]}`);
758
+ return { commandId: execution.commandId, result: execution.result };
759
+ });
752
760
  },
753
761
  async 'workspace/changes/get'(params) {
754
762
  requireSession(params);
@@ -11,6 +11,7 @@
11
11
  },
12
12
  "files": [
13
13
  "index.js",
14
+ "command-runs.js",
14
15
  "aside.js",
15
16
  "context-timeline.js",
16
17
  "instructions.js",
@@ -232,14 +232,31 @@ export function createAutoCommit({
232
232
  // external-directory guard: a call that asks the sandbox for an escalation
233
233
  // (`sandbox_permissions`) while referencing paths outside the session
234
234
  // workspace is denied; escapes must go through ordinary approval.
235
- // doom-loop guard: the same tool with identical arguments more than twice in
236
- // a row within one turn is denied.
235
+ // doom-loop guard: the same tool with identical arguments DOOM_LOOP_LIMIT
236
+ // times in a row within one turn is denied. Waiting and polling (a job's
237
+ // output, a subagent, a background check) repeats a call on purpose and is
238
+ // never counted; the engine's repeat-tool reminder already nudges the model
239
+ // at 3, 5 and 8 repeats, so this is only the backstop for a real loop.
237
240
 
238
- export const DOOM_LOOP_LIMIT = 3;
241
+ /** Was 3, which refused the third identical `job_output({wait: true})` or an unchanged `git status` (owner 2026-11-17). */
242
+ export const DOOM_LOOP_LIMIT = 20;
239
243
 
240
- /** Whether `path` names a dotenv file (`.env`, `.env.*`, `*.env`). */
244
+ /** Tools whose whole job is to wait or poll: repeating them with the same arguments is progress, not a loop. */
245
+ const WAIT_TOOLS = new Set(['job_output', 'job_wait', 'wait_agent', 'wait', 'sleep', 'subagent_wait', 'session_wait']);
246
+
247
+ /** Whether a call waits on something (a wait tool, or any call that asks to `wait`/`block`). */
248
+ export function isWaitCall(name, args) {
249
+ if (WAIT_TOOLS.has(String(name ?? ''))) return true;
250
+ return args !== null && typeof args === 'object' && (args.wait === true || args.block === true);
251
+ }
252
+
253
+ /** Dotenv templates hold placeholders, never secrets: `.env.example`, `.env.sample`, `.env.template`, … */
254
+ const ENV_TEMPLATE = /^\.env\.(?:example|sample|template|dist|defaults|schema|tmpl|tpl)$|\.env\.(?:example|sample|template)$/iu;
255
+
256
+ /** Whether `path` names a dotenv file (`.env`, `.env.*`, `*.env`) that can hold secrets (templates excluded). */
241
257
  export function isEnvPath(path) {
242
258
  const base = basename(path);
259
+ if (ENV_TEMPLATE.test(base)) return false;
243
260
  return base === '.env' || base.startsWith('.env.') || base.endsWith('.env');
244
261
  }
245
262
 
@@ -312,7 +329,10 @@ export function createWave2Guards({
312
329
  };
313
330
  }
314
331
  }
315
- if (session !== undefined) {
332
+ if (session !== undefined && isWaitCall(exec?.name, args)) {
333
+ // A wait breaks no streak and starts none.
334
+ doomLoop.delete(session.id);
335
+ } else if (session !== undefined) {
316
336
  const signature = `${exec?.name}:${stableJson(args)}`;
317
337
  const entry = doomLoop.get(session.id);
318
338
  if (entry !== undefined && entry.signature === signature) {
@@ -320,7 +340,7 @@ export function createWave2Guards({
320
340
  if (entry.count >= doomLimit) {
321
341
  return {
322
342
  kind: 'deny',
323
- reason: `Picasso doom-loop guard: tool "${exec?.name}" was called with identical arguments ${entry.count} times in this turn; denied.`,
343
+ reason: `Picasso loop guard: tool "${exec?.name}" was called with identical arguments ${entry.count} times in a row in this turn, with nothing else in between; this call was not run. Change the arguments, try a different approach, or tell the user what is blocking you.`,
324
344
  };
325
345
  }
326
346
  } else {