@picassohq/cli 1.0.4 → 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 (40) hide show
  1. package/dist/build-info.json +2 -1
  2. package/dist/index.js +1557 -1353
  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 +20 -10
  7. package/runtime/packages/picasso-compaction/index.js +257 -5
  8. package/runtime/packages/picasso-hooks/cordis.patch.yml +4 -0
  9. package/runtime/packages/picasso-hooks/index.js +302 -0
  10. package/runtime/packages/picasso-hooks/lifecycle-events.js +651 -0
  11. package/runtime/packages/picasso-hooks/package.json +29 -0
  12. package/runtime/packages/picasso-lean-context/glob-walk.js +518 -0
  13. package/runtime/packages/picasso-lean-context/index.js +136 -9
  14. package/runtime/packages/picasso-memory/index.js +66 -24
  15. package/runtime/packages/picasso-model-router/connections.js +164 -7
  16. package/runtime/packages/picasso-model-router/index.js +97 -1
  17. package/runtime/packages/picasso-model-router/thinking-default.js +29 -5
  18. package/runtime/packages/picasso-progress-reports/index.js +128 -18
  19. package/runtime/packages/picasso-sdk-server/command-runs.js +37 -0
  20. package/runtime/packages/picasso-sdk-server/ignore-file.js +5 -1
  21. package/runtime/packages/picasso-sdk-server/index.js +11 -3
  22. package/runtime/packages/picasso-sdk-server/package.json +1 -0
  23. package/runtime/packages/picasso-sdk-server/wave2-hooks.js +26 -6
  24. package/runtime/packages/picasso-x-reader/settings.js +4 -1
  25. package/runtime/plugins/picasso-auto-approve/index.js +21 -8
  26. package/runtime/plugins/picasso-compaction/index.js +257 -5
  27. package/runtime/plugins/picasso-hooks/index.js +302 -0
  28. package/runtime/plugins/picasso-hooks/lifecycle-events.js +651 -0
  29. package/runtime/plugins/picasso-hooks/package.json +29 -0
  30. package/runtime/plugins/picasso-lean-context/glob-walk.js +518 -0
  31. package/runtime/plugins/picasso-lean-context/index.js +136 -9
  32. package/runtime/plugins/picasso-memory/index.js +66 -24
  33. package/runtime/plugins/picasso-model-router/connections.js +164 -7
  34. package/runtime/plugins/picasso-model-router/index.js +97 -1
  35. package/runtime/plugins/picasso-model-router/thinking-default.js +29 -5
  36. package/runtime/plugins/picasso-progress-reports/index.js +128 -18
  37. package/runtime/plugins/picasso-trackers/index.js +12 -2
  38. package/runtime/plugins/picasso-x-reader/settings.js +4 -1
  39. package/runtime/relay/main.mjs +2254 -1648
  40. package/runtime/relay/versions-routes.mjs +24 -20
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@picassohq/cli",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "description": "Picasso command line interface.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -29,13 +29,10 @@
29
29
  # dsh-persona requires a prose prefix; system-prompt covers it.
30
30
  # dsh-experimental-auto-review boots, but only consulted by the Auto preset;
31
31
  # enabled with `--permission-mode auto` (below).
32
- # @picasso/picasso-hooks-bridge workspace package; plugin names resolve from
33
- # the dsh install's node_modules, so it mounts
34
- # only where dsh is bundled with picasso (the
35
- # Mac relay profile), never against a
36
- # user-installed dsh. hooks.json entries fire
37
- # on the picasso loop runner regardless —
38
- # the bridge adds in-runtime interception.
32
+ # @picasso/picasso-hooks-bridge not a row here: mounted by file path in the
33
+ # generated runtime patch (ECOSYSTEM_PLUGIN_DIRS)
34
+ # for the engine events; the picasso loop runner
35
+ # fires the loop events on CLI turns.
39
36
  # Programmatic tool calling (T4.10), strictly opt-in. `PICASSO_DSH_PTC=1` presents `run_code` plus a generated
40
37
  # SDK instead of every native tool schema; unset leaves the native executor mounted (the rows evaluate to the base
41
38
  # defaults, so the model-visible prefix is unchanged). Never combined with the two unconfined permission rungs
@@ -191,6 +191,8 @@
191
191
  # be pinned here; its listing stays on.
192
192
  - id: llm-deepseek
193
193
  config:
194
+ # A thinking model is not cut off after 5 min without a token (the engine's default; a timed-out request restarts).
195
+ streamIdleTimeoutMs: 900000
194
196
  models:
195
197
  - id: deepseek-flash
196
198
  name: DeepSeek-V4.1-Flash
@@ -202,3 +204,48 @@
202
204
  name: DeepSeek-V4-Pro
203
205
  description: Stronger agentic coding, knowledge, and difficult reasoning; suited to complex or quality-critical tasks at higher cost.
204
206
  contextWindow: 1000000
207
+
208
+ # Work is never cut off by an arbitrary internal limit (owner 2026-11-17). These rows raise the engine defaults that
209
+ # stopped normal coding work; a user abort (Esc, session/cancel) still stops any of them at once, and each bound left
210
+ # here only frees a call that never settles. None of these values appears in a tool description, so the
211
+ # tools -> system -> Tier 1 prefix is byte-identical (the cache-probe Tier-1 tests prove it). Limits that already say
212
+ # so and keep the rest reachable stay as they are: read pages (offset/limit), glob/grep caps with the full result
213
+ # saved to a file, the spill of huge results to a file with head/tail and its path (`spill-policy`).
214
+ # A row replaces the base row's whole `config`, so every field the base row sets is restated.
215
+ #
216
+ # Shell: a foreground command runs 10 min (was 60 s) before it moves to a background job (never killed: the engine's
217
+ # promote-on-timeout); a command may ask for up to 2 h (was 10 min) in the foreground.
218
+ - id: bash-sandbox
219
+ config:
220
+ timeoutMs: 600000
221
+ maxTimeoutMs: 7200000
222
+ # glob/grep: 10 min (was 30 s, which gave up on large trees). The result caps and their saved full lists are unchanged.
223
+ - id: tool-fs-search
224
+ config:
225
+ sampleOverCapGlobResults: false
226
+ timeoutMs: 600000
227
+ # web_fetch / web_search: a slow page or a search that falls back across backends is not cut at 30/60 s, and a long
228
+ # page is read whole (1M characters, was 100k/200k): past the inline budget the engine saves the full text to a file
229
+ # and gives the model its head, tail and path (`spill-policy`) instead of truncating it.
230
+ - id: tool-web
231
+ config:
232
+ fetch: true
233
+ fetchTimeoutMs: 300000
234
+ searchTimeoutMs: 300000
235
+ fetchMaxOutputChars: 1000000
236
+ - id: web-fetch-http
237
+ config:
238
+ timeoutMs: 240000
239
+ maxBodyChars: 1000000
240
+ maxResponseBytes: 20000000
241
+ # Compaction: the engine reserved 64k tokens of headroom on top of the model's output, so a 200k-token model compacted
242
+ # at ~70k and a 128k one at ~30k. 16k headroom (the summary itself is capped at 16k, packages/picasso-compaction
243
+ # SUMMARY_MAX_TOKENS) lets the conversation use the window: 200k compacts at ~120k. The pressure ratio (default 0.8) is
244
+ # where trimming old tool outputs starts, then summarizing; at 0.8 a 1M-token conversation was trimmed at 800k (owner
245
+ # 2026-11-17). 0.92 (packages/picasso-compaction PRESSURE_RATIO, which raises a lower ratio on the Mac too): it starts
246
+ # at the lower of 92% of the window and the window less the request's output reservation and this headroom.
247
+ - id: compaction-basic
248
+ config:
249
+ headroomTokens: 16384
250
+ maxTokens: 16384
251
+ thresholdRatio: 0.92
@@ -36,7 +36,7 @@
36
36
  "name": "@picasso/memory-recall",
37
37
  "version": "0.1.0",
38
38
  "files": {
39
- "index.js": "90a0eda004de42d31626883ec32860e99c252761b83738c4a8bafc633f45a59d",
39
+ "index.js": "a34fb487a1d5d0c9172a5fd0a816cf90fe97ffc0d272d36aa26d5efb3f3fa76f",
40
40
  "package.json": "a21aa04702ed2648cda1c6bf6fade2df9e828f13b6f323f07d50ff3996c77cfa"
41
41
  }
42
42
  },
@@ -86,7 +86,7 @@
86
86
  "name": "@picasso/auto-approve",
87
87
  "version": "0.1.0",
88
88
  "files": {
89
- "index.js": "41ef34fa70440ea8879c8fcfa04d82d860d86ebb9d00a9cbeac8db4fe5b2db81",
89
+ "index.js": "a1380566ffb85275fbdb509c1b60d498a9ce7868a297cab9e8f31cef90558da2",
90
90
  "package.json": "21aac7268052b26ffa545ee9cc420c0ddf7466df96b07fbe1bf4701c2cf2532d"
91
91
  }
92
92
  },
@@ -98,6 +98,15 @@
98
98
  "package.json": "54639113ead4d787f6fb9cf16c53cb44e2d50552b0f94d4ecce6dd84c66ca267"
99
99
  }
100
100
  },
101
+ "picasso-hooks": {
102
+ "name": "@picasso/picasso-hooks-bridge",
103
+ "version": "0.1.0",
104
+ "files": {
105
+ "index.js": "66076f6b67563025e456530effc20c8619d1dd014c254e49f99b700d97819d4e",
106
+ "package.json": "54256cce932c5a743a34010a52da4625da2c7ef9e96fb2f7d1bb8b5661a2ff2f",
107
+ "lifecycle-events.js": "8e44b8c455403d2710c8f41032d6a6f1144466eaf9cd301a2a61ae66a16c51f9"
108
+ }
109
+ },
101
110
  "picasso-auth-bridge": {
102
111
  "name": "@picasso/auth-bridge",
103
112
  "version": "0.1.0",
@@ -118,7 +127,7 @@
118
127
  "name": "@picasso/trackers",
119
128
  "version": "0.1.0",
120
129
  "files": {
121
- "index.js": "5dba3a5b263273103e7ce5ef71f56f6d944ac3f42c53673c16a8fa1e47d55f8f",
130
+ "index.js": "884bb9f6d24be045dbc96bbeeb1f08946d93b59244dba2dd0faf1bbc2183e14e",
122
131
  "package.json": "762afca9934265c1efcd5da6508de0bef07cae18ba94dc676db3ec034860881c"
123
132
  }
124
133
  },
@@ -135,19 +144,20 @@
135
144
  "name": "@picasso/model-router",
136
145
  "version": "0.1.0",
137
146
  "files": {
138
- "index.js": "c1291c8f67e53735d583afb7829acf853a002b23bf121b031573138d9e694bd8",
147
+ "index.js": "19713b722a555304ea4899c657bc39d895dfc419b363c274997ec1424921fd40",
139
148
  "package.json": "0f72ba881be43e3e604a483b3289b5c22a8ded83e66ba319416b999ea2025663",
140
- "connections.js": "4ab9dd2801e4d959834213728ad6e542a85fba81f66ebe3a649f93ea9847f01e",
141
- "thinking-default.js": "b393272965348631b653d2fc92f97083a64b1f6611f69ef11cd09927fac72e98"
149
+ "connections.js": "4d4a87dded62ed9521777248e592e49b48c3a1585f4f9e2f5326905e4b901adb",
150
+ "thinking-default.js": "9f65f183a050328d563b21e2aa397c18ad2b33649a8d46bb9364a8a5324221c3"
142
151
  }
143
152
  },
144
153
  "picasso-lean-context": {
145
154
  "name": "@picasso/lean-context",
146
155
  "version": "0.1.0",
147
156
  "files": {
148
- "index.js": "9ff97f0374e7d975812b636e49137497204bf604ed2466a4070769da6ab9821d",
157
+ "index.js": "51bd56ad21293e9fd91fcb60dc63f0139328b9d11f0fc972604e6bbdd6a6afb7",
149
158
  "package.json": "3f48eb73b4a3e92a2b4d6562a235f733db7368c6450ad6bc6323504109110c90",
150
159
  "argument-repair.js": "a300db7fb968401f2120bb0d20cf7b92fca2b47edcfb2a483123390281ccf73b",
160
+ "glob-walk.js": "9f04ef3757fa7a5fa97f6c12273c5635b103e8a8f6c81bcfefb902b2d9735520",
151
161
  "read-image-recovery.js": "536a476dd842f8e647ebcd67fcc24d66c6f3b255a04cc932c07dcbd216ffdb50",
152
162
  "timeline.js": "ddde3cd2cb7dfa90877b9b80250c470983ec773711410200302d08c94e811eeb"
153
163
  }
@@ -156,7 +166,7 @@
156
166
  "name": "@picasso/progress-reports",
157
167
  "version": "0.1.0",
158
168
  "files": {
159
- "index.js": "31c2f2900f7d634b4ba09102e6844b673e11a88bc32991144a44f861f3b7d40b",
169
+ "index.js": "05096be428d65d23d41f2bf3453d559f7a8b0e40c9ae074bbd9efa79ba22e9ff",
160
170
  "package.json": "b023bd7eca1de3c72618750e7ae586f63b1b6c07b4b1735ecd7746c0177e288d",
161
171
  "report.js": "430e3d834789a1d45e1442dcb26939b91f48dfe852d9c6df02223694b6f46728"
162
172
  }
@@ -182,7 +192,7 @@
182
192
  "command.js": "d22cf2c104e1992cf62ae228304d3f87bdab21a8f3fa88ea8fa0380cfe8dcd21",
183
193
  "read.js": "9e2043a2bdac389a17c395a995aaea753699e74c3978980f5623955693332f1a",
184
194
  "rewrite.js": "a042545b301ad5ba0c2ab11c7f273125935ef2a377b53f672217d08bf7f6be43",
185
- "settings.js": "6245d93acc38ffb084499e2d9505ee7d7f36aee4a469410ce94c924d075f6b59",
195
+ "settings.js": "05b2419003b9bcfb1ab245b96b3d1331af91ca4b99c28fa54d26656d006ba281",
186
196
  "urls.js": "73e0c5cba82f63cd80e3ff76889777580f4ebed8084bb70287193a7ce12f9eae",
187
197
  "xmd.js": "ca6fa8516e1a13dc2d687173a2bde5409f207b447c13ec7a15cd633dbc0ed3be"
188
198
  }
@@ -213,7 +223,7 @@
213
223
  "name": "@picasso/compaction",
214
224
  "version": "0.1.0",
215
225
  "files": {
216
- "index.js": "272fd76bb74083fcd7797c93cb913ff805464341f69ea012a9006dd32656fa05",
226
+ "index.js": "5259ba6bd322989fe2931c001054e8e246a23d8a50709a28a70596c0719e908d",
217
227
  "package.json": "33f04b41e913abfdc7fcccc6043bbe27b9660cd45125d62953e1fe8d0f95ee37"
218
228
  }
219
229
  }
@@ -20,6 +20,14 @@
20
20
  // engine would have picked that model anyway. When it does not fit, the history is rendered as plain text, split into
21
21
  // parts that fit, each part is summarized, and the part summaries are merged (in rounds, if even they do not fit).
22
22
  //
23
+ // Two more things, on the same engine backend (`installSummarizer`): the engine's between-step pressure check is
24
+ // skipped while the step runs on another model than the last request (it would price the old model; the engine's
25
+ // switch check prices the model the step really runs on), and every compaction records why, for which model and how
26
+ // big the conversation is (`plugin:picasso/compaction` → `compaction/notice`) just before its summary, which the TUI
27
+ // shows as one line ("Shortened this conversation to fit <model> (321k → 60k tokens): <reason>"). The engine's
28
+ // tool-output trimming (its pruner, which runs first under pressure) records the same notice with scope
29
+ // `tool-outputs`, and shortening starts only near the window (PRESSURE_RATIO, 0.92, not the engine's 0.8).
30
+ //
23
31
  // C1 zero-fallback: the summary is always the model's own text. Nothing is synthesized when no model can produce
24
32
  // one; the compaction fails and the engine records the attempt. Tier 1 is untouched: the summary lands in history
25
33
  // (Tier 2) through the engine's checkpoint message, exactly as before.
@@ -35,6 +43,13 @@ export const FALLBACK_CONTEXT_WINDOW = 65_536;
35
43
  export const SUMMARY_MAX_TOKENS = 16_384;
36
44
  /** The engine's own summary cap when its config names none (`headroomTokens` default). */
37
45
  export const ENGINE_DEFAULT_MAX_TOKENS = 65_536;
46
+ /**
47
+ * The share of a model's window where the engine starts shortening a conversation (first trimming old tool outputs,
48
+ * then summarizing). The engine's default, 0.8, trimmed a 1M-token Claude conversation at 800k (owner 2026-11-17:
49
+ * "nothing chopped off"); the engine still caps it at the window less the request's output reservation and the
50
+ * compaction headroom, so a request always has room to answer. A configured ratio below this is raised to it.
51
+ */
52
+ export const PRESSURE_RATIO = 0.92;
38
53
  /** Other connected models tried after the selected, last-used and configured ones. */
39
54
  export const MAX_FALLBACK_ATTEMPTS = 2;
40
55
  /** Merge rounds before giving up on a history whose part summaries still do not fit. */
@@ -589,8 +604,137 @@ function rawService(service) {
589
604
  }
590
605
  }
591
606
 
592
- /** Installs the summarizer on the engine's compaction backend; returns the undo. */
593
- export function installSummarizer(compaction, llm, log) {
607
+ /** Session-log record type of the compaction notice (`compaction/notice` inside; projected to the transcript line). */
608
+ export const COMPACTION_NOTICE_RECORD = 'plugin:picasso/compaction';
609
+
610
+ const sameRoute = (a, b) => a !== undefined && b !== undefined && a.provider === b.provider && a.model === b.model;
611
+
612
+ /**
613
+ * Whether the engine's between-step pressure check would price the wrong model: the session's last request ran on
614
+ * one model and this step runs on another (a pick, a reopened session on the current selection). The engine prices
615
+ * that check on the last request's model (owner 2026-11-17: a 321k conversation reopened on a 1M managed model was
616
+ * shortened to 60k because the old model, unknown to the new route, was sized at the 200k default). The switch check
617
+ * on the step's own request prices the model the step really runs on, so the stale check is skipped.
618
+ */
619
+ export function stalePressureHeader(agent) {
620
+ const last = lastRequestTarget(agent);
621
+ const selected = selectedTarget(agent);
622
+ return last !== undefined && selected !== undefined && !sameRoute(last, selected);
623
+ }
624
+
625
+ /**
626
+ * The tokens at which the engine starts shortening a conversation on a model (dsh-compaction-basic
627
+ * `resolveCompactSpec`: the lower of `thresholdRatio` of the window and the window less the request's output
628
+ * reservation and the compaction headroom). For the notice only; the engine's own figure decides.
629
+ */
630
+ export function compactionThreshold(config, target, window, reserved = 0) {
631
+ if (!Number.isSafeInteger(window) || window <= 0) return undefined;
632
+ const policy = (Array.isArray(config?.modelPolicies) ? config.modelPolicies : []).find((entry) => sameRoute(entry, target)) ?? {};
633
+ const ratio = policy.thresholdRatio ?? config?.thresholdRatio ?? 0.8;
634
+ const headroom = policy.headroomTokens ?? config?.headroomTokens ?? ENGINE_DEFAULT_MAX_TOKENS;
635
+ const threshold = Math.floor(Math.min(window * ratio, window - reserved - headroom));
636
+ return threshold > 0 ? threshold : undefined;
637
+ }
638
+
639
+ /**
640
+ * The engine's compaction config with its pressure ratio raised to `ratio` (PRESSURE_RATIO) when lower; per-model
641
+ * policies keep theirs. Unchanged (the same object) when already at or above it, or when it names no ratio.
642
+ */
643
+ export function withPressureRatio(config, ratio = PRESSURE_RATIO) {
644
+ if (config === null || typeof config !== 'object') return config;
645
+ const current = config.thresholdRatio;
646
+ if (typeof current !== 'number' || !(current < ratio)) return config;
647
+ return Object.freeze({ ...config, thresholdRatio: ratio });
648
+ }
649
+
650
+ /** Load `appendPluginRecord` from the running engine install (bare specifiers do not resolve from this file). */
651
+ async function engineAppendPluginRecord() {
652
+ const { createRequire } = await import('node:module');
653
+ const { realpathSync } = await import('node:fs');
654
+ const { join } = await import('node:path');
655
+ const { pathToFileURL } = await import('node:url');
656
+ const anchors = [process.argv[1], process.env.PICASSO_DSH_INSTALL_DIR && join(process.env.PICASSO_DSH_INSTALL_DIR, 'package.json')].filter(Boolean);
657
+ for (const anchor of anchors) {
658
+ try {
659
+ const require = createRequire(realpathSync(anchor));
660
+ const mod = await import(pathToFileURL(require.resolve('@deepseek-ai/dsh-session')).href);
661
+ if (typeof mod.appendPluginRecord === 'function') return mod.appendPluginRecord;
662
+ } catch {
663
+ // not an engine install: try the next anchor
664
+ }
665
+ }
666
+ return undefined;
667
+ }
668
+
669
+ /**
670
+ * Why a compaction runs and how big the conversation is, recorded in the session log just before the summary is
671
+ * written (`plugin:picasso/compaction` → `compaction/notice`), so the transcript says it plainly: "Shortened this
672
+ * conversation to fit <model> (321k → 60k tokens): <reason>". Reasons: `model-switch` (the model the conversation
673
+ * moves to has less room), `pressure` (the conversation reached the model's limit), `overflow` (the provider refused
674
+ * the request as too long), `requested` (/compact).
675
+ */
676
+ function createNoticeWriter({ engine, llm, log, appendRecord }) {
677
+ let append = appendRecord;
678
+ let loading;
679
+ const resolveAppend = async () => {
680
+ if (append !== undefined) return append;
681
+ loading ??= engineAppendPluginRecord().catch(() => undefined);
682
+ append = (await loading) ?? null;
683
+ return append;
684
+ };
685
+ return async (agent, reason, extra = {}) => {
686
+ try {
687
+ const write = await resolveAppend();
688
+ if (typeof write !== 'function' || agent?.session === undefined) return;
689
+ const header = reason?.header;
690
+ const route = target(header?.config?.provider, header?.config?.model) ?? selectedTarget(agent) ?? lastRequestTarget(agent);
691
+ // A prune measured the conversation before it trimmed (by now the measure is after).
692
+ let tokensBefore = extra.tokensBefore;
693
+ if (tokensBefore === undefined) {
694
+ try {
695
+ const measured = engine.ctx?.tokenMeter?.measure?.(agent.session, ...(header === undefined ? [] : [header]));
696
+ tokensBefore = Number.isFinite(measured?.totalTokens) ? Math.round(measured.totalTokens) : undefined;
697
+ } catch {
698
+ tokensBefore = undefined;
699
+ }
700
+ }
701
+ let window;
702
+ let reserved = 0;
703
+ if (route !== undefined) {
704
+ try {
705
+ const info = await llm.resolveModelInfo(route.provider, route.model);
706
+ window = Number.isSafeInteger(info?.context?.contextWindow) ? info.context.contextWindow : undefined;
707
+ reserved = header?.config?.maxTokens ?? info?.defaultMaxTokens ?? 0;
708
+ } catch {
709
+ window = undefined;
710
+ }
711
+ }
712
+ const thresholdTokens = reason?.kind === 'pressure' || reason?.kind === 'model-switch'
713
+ ? compactionThreshold(engine.config, route, window, reserved)
714
+ : undefined;
715
+ write(agent.session, COMPACTION_NOTICE_RECORD, {
716
+ event: {
717
+ type: 'compaction/notice',
718
+ reason: reason?.kind ?? 'requested',
719
+ ...(extra.scope === undefined ? {} : { scope: extra.scope }),
720
+ ...(route === undefined ? {} : { provider: route.provider, model: route.model }),
721
+ ...(tokensBefore === undefined ? {} : { tokensBefore }),
722
+ ...(window === undefined ? {} : { contextWindow: window }),
723
+ ...(thresholdTokens === undefined ? {} : { thresholdTokens }),
724
+ },
725
+ });
726
+ } catch (error) {
727
+ // The notice explains a compaction; it never stops one.
728
+ log(`compaction: the notice was not recorded (${firstLine(error)})`);
729
+ }
730
+ };
731
+ }
732
+
733
+ /**
734
+ * Installs the summarizer on the engine's compaction backend, the stale-pressure guard, and the compaction notice;
735
+ * returns the undo. `deps.appendRecord` replaces the engine's `appendPluginRecord` (tests).
736
+ */
737
+ export function installSummarizer(compaction, llm, log = () => undefined, deps = {}) {
594
738
  const engine = rawService(compaction);
595
739
  if (engine === undefined || typeof engine.summarize !== 'function') return () => undefined;
596
740
  const stockSummarize = engine.summarize;
@@ -600,12 +744,120 @@ export function installSummarizer(compaction, llm, log) {
600
744
  engineConfig: () => engine.config,
601
745
  log,
602
746
  });
603
- const override = function summarize(input, agent, signal) {
747
+ /** agent → why the compaction now running started (set by the engine entry points below). */
748
+ const reasons = new WeakMap();
749
+ /** session → the agent compacting it (the engine's tool-output pruner is handed the session only). */
750
+ const sessionAgents = new WeakMap();
751
+ const notice = createNoticeWriter({ engine, llm, log, appendRecord: deps.appendRecord });
752
+ const override = async function summarize(input, agent, signal) {
753
+ await notice(agent, reasons.get(agent));
604
754
  return summarizer.summarize(input, agent, signal);
605
755
  };
606
- engine.summarize = override;
756
+ const installed = { summarize: override };
757
+ // Shortening starts near the window, not at 80% of it (PRESSURE_RATIO). The engine reads its config at every check.
758
+ const stockConfig = engine.config;
759
+ const raisedConfig = withPressureRatio(stockConfig);
760
+ if (raisedConfig !== stockConfig) {
761
+ try {
762
+ engine.config = raisedConfig;
763
+ } catch (error) {
764
+ log(`compaction: the pressure ratio was not raised (${firstLine(error)})`);
765
+ }
766
+ }
767
+ // The engine's tool-output pruner (dsh-compaction-tool-result-pruner) trims old outputs before any summary; each
768
+ // pass that trims something records the same notice with scope `tool-outputs`, so the transcript's one trimmed line
769
+ // says why ("Shortened 14 old tool outputs to fit <model> (39k tokens saved): <reason>").
770
+ let prunerUndo;
771
+ const wrapPruner = () => {
772
+ if (prunerUndo !== undefined) return;
773
+ let pruner;
774
+ try {
775
+ pruner = rawService(deps.pruner ?? engine.ctx?.get?.('toolResultPruner') ?? engine.ctx?.toolResultPruner);
776
+ } catch {
777
+ pruner = undefined;
778
+ }
779
+ if (pruner === undefined || typeof pruner.pruneSession !== 'function') return;
780
+ const original = pruner.pruneSession;
781
+ const wrapped = function pruneSession(session, ...rest) {
782
+ const agent = sessionAgents.get(session);
783
+ const reason = agent === undefined ? undefined : reasons.get(agent);
784
+ let tokensBefore;
785
+ if (agent !== undefined) {
786
+ try {
787
+ const header = reason?.header;
788
+ const measured = engine.ctx?.tokenMeter?.measure?.(session, ...(header === undefined ? [] : [header]));
789
+ tokensBefore = Number.isFinite(measured?.totalTokens) ? Math.round(measured.totalTokens) : undefined;
790
+ } catch {
791
+ tokensBefore = undefined;
792
+ }
793
+ }
794
+ const result = original.call(this, session, ...rest);
795
+ if (agent !== undefined && Array.isArray(result?.pruned) && result.pruned.length > 0) {
796
+ void notice(agent, reason, { scope: 'tool-outputs', ...(tokensBefore === undefined ? {} : { tokensBefore }) });
797
+ }
798
+ return result;
799
+ };
800
+ pruner.pruneSession = wrapped;
801
+ prunerUndo = () => {
802
+ if (pruner.pruneSession === wrapped) {
803
+ if (Object.getPrototypeOf(pruner)?.pruneSession === original) delete pruner.pruneSession;
804
+ else pruner.pruneSession = original;
805
+ }
806
+ };
807
+ };
808
+ const withReason = (agent, reason, run) => {
809
+ if (agent === undefined || agent === null || typeof agent !== 'object') return run();
810
+ wrapPruner();
811
+ const previous = reasons.get(agent);
812
+ reasons.set(agent, reason);
813
+ const session = agent.session;
814
+ const previousAgent = session !== null && typeof session === 'object' ? sessionAgents.get(session) : undefined;
815
+ if (session !== null && typeof session === 'object') sessionAgents.set(session, agent);
816
+ const restore = () => {
817
+ if (previous === undefined) reasons.delete(agent);
818
+ else reasons.set(agent, previous);
819
+ if (session !== null && typeof session === 'object') {
820
+ if (previousAgent === undefined) sessionAgents.delete(session);
821
+ else sessionAgents.set(session, previousAgent);
822
+ }
823
+ };
824
+ let pending;
825
+ try {
826
+ pending = run();
827
+ } catch (error) {
828
+ restore();
829
+ throw error;
830
+ }
831
+ return Promise.resolve(pending).finally(restore);
832
+ };
833
+ if (typeof engine.compactIfNeeded === 'function') {
834
+ const original = engine.compactIfNeeded;
835
+ installed.compactIfNeeded = function compactIfNeeded(agent, trigger, signal) {
836
+ if (trigger === 'pressure' && stalePressureHeader(agent)) return Promise.resolve(null);
837
+ if (trigger === 'context-overflow') return withReason(agent, { kind: 'overflow' }, () => original.call(engine, agent, trigger, signal));
838
+ return original.call(engine, agent, trigger, signal);
839
+ };
840
+ }
841
+ if (typeof engine.compactPressure === 'function') {
842
+ const original = engine.compactPressure;
843
+ installed.compactPressure = function compactPressure(agent, header, signal, requireBelowThreshold) {
844
+ const kind = requireBelowThreshold === true ? 'model-switch' : 'pressure';
845
+ return withReason(agent, { kind, header }, () => original.call(engine, agent, header, signal, requireBelowThreshold));
846
+ };
847
+ }
848
+ if (typeof engine.compactNow === 'function') {
849
+ const original = engine.compactNow;
850
+ installed.compactNow = function compactNow(agent, signal, sourceCommandId) {
851
+ return withReason(agent, { kind: 'requested' }, () => original.call(engine, agent, signal, sourceCommandId));
852
+ };
853
+ }
854
+ for (const [key, value] of Object.entries(installed)) engine[key] = value;
607
855
  return () => {
608
- if (engine.summarize === override) delete engine.summarize;
856
+ for (const [key, value] of Object.entries(installed)) {
857
+ if (engine[key] === value) delete engine[key];
858
+ }
859
+ if (raisedConfig !== stockConfig && engine.config === raisedConfig) engine.config = stockConfig;
860
+ prunerUndo?.();
609
861
  };
610
862
  }
611
863
 
@@ -0,0 +1,4 @@
1
+ # Picasso hooks bridge — one bundle patch layer row (loader insert).
2
+ - insert:
3
+ - id: picasso-hooks
4
+ name: '@picasso/picasso-hooks-bridge'