@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
@@ -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,302 @@
1
+ // @picasso/hooks — picasso→dsh hooks bridge.
2
+ // Reads the picasso hooks store (`<picassoHome>/hooks.json`, flat hook list with
3
+ // { id, event, command, timeoutMs, enabled }) and runs each enabled shell hook
4
+ // at the mapped dsh interception point, fail-open, via node:child_process
5
+ // (host-side execution — the dsh ctx.shell service is for model tools, not
6
+ // host hooks; picasso's own createHookRunner uses execFileAsync the same way).
7
+ //
8
+ // Two families of events:
9
+ //
10
+ // - engine events (`pre-tool`, `turn/end`, `tools/pre-execute`, …;
11
+ // lifecycle-events.js) fire wherever this plugin is mounted — both the
12
+ // CLI's runtime (ECOSYSTEM_PLUGIN_DIRS) and the Mac relay (PICASSO_PLUGINS);
13
+ // - loop events (`pre-plan`, `pre-act`, `post-act`, `on-error`, `*`) are fired
14
+ // on CLI turns by the CLI's run loop (packages/core/src/dsh/dsh-agent-loop.ts
15
+ // + createHookRunner), so the CLI mounts this plugin without loopEvents and
16
+ // it leaves those names alone (no double firing). With
17
+ // `config.loopEvents: true` (the Mac relay's row, apps/desktop-helper/src/dsh-host.ts)
18
+ // this plugin fires them itself with the same semantics, so a hooks.json
19
+ // entry behaves the same on a Mac turn as on a CLI turn: pre-plan once per
20
+ // top-level turn before its first model step (awaited), pre-act / post-act
21
+ // per tool call and result of that turn, on-error when the turn ends in an
22
+ // error; subagent sessions fire nothing (the CLI projects their tools as
23
+ // subagent progress, not as tool calls). Like the CLI, a hook observes only:
24
+ // it never blocks a tool call or changes a decision.
25
+ //
26
+ // The store is re-read when it changes (checked at each turn start), so a hook
27
+ // added with `picasso hooks add` reaches a long-lived engine on its next turn —
28
+ // the CLI reads the file once per run.
29
+ import { execFile } from 'node:child_process'
30
+ import { readFileSync, statSync } from 'node:fs'
31
+ import { userInfo } from 'node:os'
32
+ import { join } from 'node:path'
33
+ import { isLifecycleEvent, lifecycleEvent, resolveHookPoint } from './lifecycle-events.js'
34
+
35
+ export const name = 'picasso-hooks'
36
+
37
+ /** The CLI run loop's hook events (apps/cli/src/hooks-commands.ts PICASSO_LOOP_HOOK_EVENTS). `*` matches every one. */
38
+ export const LOOP_HOOK_EVENTS = ['pre-plan', 'pre-act', 'post-act', 'on-error', '*']
39
+
40
+ /** The hooks.json schema version this bridge reads (packages/shared-home HOOKS_SPEC.current). */
41
+ export const HOOKS_STORE_VERSION = 1
42
+
43
+ const LOOP_EVENT_SET = new Set(LOOP_HOOK_EVENTS)
44
+ const DEFAULT_TIMEOUT_MS = 15_000
45
+ const MAX_BUFFER = 512 * 1024
46
+
47
+ const nonEmpty = (value) => typeof value === 'string' && value.trim() !== ''
48
+
49
+ /**
50
+ * The store this bridge reads: `config.file`, else `PICASSO_HOOKS_ROOT` (a file path), else
51
+ * `<PICASSO_HOME or the OS account's home/.picasso>/hooks.json` — the file `picasso hooks` edits
52
+ * (packages/shared-home `hooksFile`, which resolves the home the same way).
53
+ */
54
+ export function hooksFilePath(env = process.env, config = {}) {
55
+ if (nonEmpty(config?.file)) return config.file
56
+ if (nonEmpty(env.PICASSO_HOOKS_ROOT)) return env.PICASSO_HOOKS_ROOT
57
+ const home = nonEmpty(env.PICASSO_HOME) ? env.PICASSO_HOME : join(userInfo().homedir, '.picasso')
58
+ return join(home, 'hooks.json')
59
+ }
60
+
61
+ /**
62
+ * Enabled, well-formed hooks from the store (id, event and command strings; `enabled !== false`), the same entries
63
+ * the CLI loader accepts. A missing or unreadable file is no hooks; a file written by a newer Picasso is no hooks
64
+ * plus a warning (the CLI refuses it the same way).
65
+ */
66
+ export function readPicassoHooks(file, warn = () => undefined) {
67
+ let parsed
68
+ try {
69
+ parsed = JSON.parse(readFileSync(file, 'utf8'))
70
+ } catch {
71
+ return []
72
+ }
73
+ if (parsed === null || typeof parsed !== 'object') return []
74
+ if (typeof parsed.version === 'number' && parsed.version > HOOKS_STORE_VERSION) {
75
+ warn(`[picasso-hooks] ${file} is hooks schema ${parsed.version}; this build reads ${HOOKS_STORE_VERSION} — hooks skipped until Picasso is updated`)
76
+ return []
77
+ }
78
+ if (!Array.isArray(parsed.hooks)) return []
79
+ return parsed.hooks.filter(
80
+ (h) =>
81
+ h !== null &&
82
+ typeof h === 'object' &&
83
+ typeof h.id === 'string' &&
84
+ typeof h.command === 'string' &&
85
+ typeof h.event === 'string' &&
86
+ h.enabled !== false,
87
+ )
88
+ }
89
+
90
+ function hookShell() {
91
+ return nonEmpty(process.env.SHELL) ? process.env.SHELL : '/bin/sh'
92
+ }
93
+
94
+ /** Run one hook's command; always resolves (fail-open) with whether it exited 0 and what it printed. */
95
+ export function runHookCommand(hook, { event, cwd, env = {} }) {
96
+ return new Promise((resolve) => {
97
+ try {
98
+ execFile(
99
+ hookShell(),
100
+ ['-lc', hook.command],
101
+ {
102
+ cwd,
103
+ timeout: typeof hook.timeoutMs === 'number' && hook.timeoutMs > 0 ? hook.timeoutMs : DEFAULT_TIMEOUT_MS,
104
+ maxBuffer: MAX_BUFFER,
105
+ env: { ...process.env, PICASSO_HOOK_EVENT: event, PICASSO_HOOK_ID: hook.id, PICASSO_HOOK_TOOL: '', ...env },
106
+ },
107
+ (error, stdout, stderr) => {
108
+ const output = `${stdout ?? ''}${stderr ?? ''}`.trim()
109
+ resolve(error ? { ok: false, output: output || (error instanceof Error ? error.message : String(error)) } : { ok: true, output })
110
+ },
111
+ )
112
+ } catch (error) {
113
+ // A cwd that no longer exists throws synchronously on some platforms: still fail-open.
114
+ resolve({ ok: false, output: error instanceof Error ? error.message : String(error) })
115
+ }
116
+ })
117
+ }
118
+
119
+ /** A subagent child session (delegated work). Forks are ordinary sessions, so `parentSession` alone does not count. */
120
+ function isSubagentSession(session) {
121
+ const header = session?.header
122
+ if (header === null || typeof header !== 'object') return false
123
+ return header.origin === 'subagent' || (Number.isSafeInteger(header.delegationDepth) && header.delegationDepth > 0)
124
+ }
125
+
126
+ /** The session a dispatch is about: a Session itself, or the session of the agent an execution or step carries. */
127
+ function sessionOf(args) {
128
+ const first = args[0]
129
+ if (first?.header !== undefined && typeof first?.id === 'string') return first
130
+ return first?.agent?.session ?? first?.session
131
+ }
132
+
133
+ /** The tool a dispatch names: an execution's `name`, or a session-log record's `data.name`. */
134
+ function toolNameOf(args) {
135
+ const [first, second] = args
136
+ if (typeof first?.name === 'string') return first.name
137
+ if (typeof second?.data?.name === 'string') return second.data.name
138
+ return ''
139
+ }
140
+
141
+ export function apply(ctx, config = {}) {
142
+ const loopEvents = config?.loopEvents === true
143
+ const file = hooksFilePath(process.env, config)
144
+ const warn = (message) => (typeof ctx.logger?.warn === 'function' ? ctx.logger.warn(message) : console.warn(message))
145
+ const report = (hook, event, result) => {
146
+ const line = `[picasso-hooks] hook ${hook.id} (${event}) ${result.ok ? 'ran' : 'failed'}${result.output ? `: ${result.output.slice(0, 160)}` : ''}`
147
+ if (typeof ctx.logger?.info === 'function') ctx.logger.info(line)
148
+ }
149
+
150
+ /** Last-seen working folder per session (`working-directory/change`), else the session header's. */
151
+ const cwdBySession = new WeakMap()
152
+ const cwdOf = (session) => cwdBySession.get(session) ?? (nonEmpty(session?.header?.cwd) ? session.header.cwd : process.cwd())
153
+
154
+ let stamp
155
+ let loopHooks = []
156
+ let engineByPoint = new Map()
157
+
158
+ const run = (hook, event, session, env) =>
159
+ runHookCommand(hook, { event, cwd: cwdOf(session), env }).then((result) => report(hook, event, result))
160
+
161
+ // ── engine events ──────────────────────────────────────────────────────────
162
+ const subscriptions = new Map()
163
+ const engineListener = (point) => (...args) => {
164
+ // Waterfall points hand `next` last: the pipeline decides first and its decision is returned unchanged.
165
+ const next = typeof args[args.length - 1] === 'function' ? args[args.length - 1] : undefined
166
+ const decision = next === undefined ? undefined : next()
167
+ const hooks = engineByPoint.get(point)
168
+ if (hooks !== undefined && hooks.length > 0) {
169
+ const session = sessionOf(args)
170
+ const tool = toolNameOf(args)
171
+ // Off the hot path: the hooks start after the dispatch returns.
172
+ queueMicrotask(() => {
173
+ for (const hook of hooks) void run(hook, hook.event, session, { PICASSO_HOOK_TOOL: tool })
174
+ })
175
+ }
176
+ return decision
177
+ }
178
+ const syncSubscriptions = () => {
179
+ const wanted = new Set([...engineByPoint.keys()].filter((point) => point !== 'session/event'))
180
+ if (loopEvents && loopHooks.some((hook) => hook.event === 'pre-plan' || hook.event === '*')) wanted.add('loop:pre-plan')
181
+ for (const [key, dispose] of subscriptions) {
182
+ if (!wanted.has(key)) {
183
+ dispose?.()
184
+ subscriptions.delete(key)
185
+ }
186
+ }
187
+ for (const key of wanted) {
188
+ if (subscriptions.has(key)) continue
189
+ subscriptions.set(key, key === 'loop:pre-plan' ? ctx.on('agent/pre-step', prePlanListener) : ctx.on(key, engineListener(key)))
190
+ }
191
+ }
192
+
193
+ const refresh = () => {
194
+ let next
195
+ try {
196
+ const stat = statSync(file)
197
+ next = `${stat.mtimeMs}:${stat.size}`
198
+ } catch {
199
+ next = 'missing'
200
+ }
201
+ if (next === stamp) return
202
+ stamp = next
203
+ const loop = []
204
+ const byPoint = new Map()
205
+ for (const hook of readPicassoHooks(file, warn)) {
206
+ if (loopEvents && LOOP_EVENT_SET.has(hook.event)) {
207
+ loop.push(hook)
208
+ continue
209
+ }
210
+ const resolved = resolveHookPoint(hook.event)
211
+ if (resolved === undefined) {
212
+ // Loop names belong to the CLI run loop where this bridge runs without loopEvents.
213
+ if (!LOOP_EVENT_SET.has(hook.event)) {
214
+ warn('[picasso-hooks] no dsh interception point for picasso event ' + hook.event + ' (hook ' + hook.id + '); skipped')
215
+ }
216
+ continue
217
+ }
218
+ const entry = { ...hook, sessionType: resolved.sessionType }
219
+ if (!byPoint.has(resolved.point)) byPoint.set(resolved.point, [])
220
+ byPoint.get(resolved.point).push(entry)
221
+ }
222
+ loopHooks = loop
223
+ engineByPoint = byPoint
224
+ syncSubscriptions()
225
+ }
226
+
227
+ // ── loop events (config.loopEvents) ────────────────────────────────────────
228
+ /** Per top-level session: the open turn's tool-call count (PICASSO_HOOK_STEP) and its call ids → tool names. */
229
+ const turns = new WeakMap()
230
+ const prePlanPending = new WeakSet()
231
+ const fireLoop = async (event, session, { tool = '', step = 0 } = {}) => {
232
+ const matching = loopHooks.filter((hook) => hook.event === event || hook.event === '*')
233
+ // Sequential within one event, like createHookRunner; every hook settles (fail-open).
234
+ for (const hook of matching) {
235
+ await run(hook, event, session, {
236
+ PICASSO_HOOK_WORKSPACE: cwdOf(session),
237
+ PICASSO_HOOK_TOOL: tool,
238
+ PICASSO_HOOK_STEP: String(step),
239
+ })
240
+ }
241
+ }
242
+ async function prePlanListener(payload, next) {
243
+ const session = payload?.agent?.session
244
+ if (session !== undefined && prePlanPending.has(session)) {
245
+ prePlanPending.delete(session)
246
+ // Awaited before the turn's first model step, as the CLI awaits pre-plan before it dispatches the prompt.
247
+ await fireLoop('pre-plan', session)
248
+ }
249
+ return next()
250
+ }
251
+ const observeLoop = (session, event) => {
252
+ const type = event?.type
253
+ const data = event?.data ?? {}
254
+ if (type === 'turn/start') {
255
+ turns.set(session, { steps: 0, calls: new Map() })
256
+ if (loopHooks.some((hook) => hook.event === 'pre-plan' || hook.event === '*')) prePlanPending.add(session)
257
+ return
258
+ }
259
+ const turn = turns.get(session)
260
+ if (turn === undefined) return
261
+ if (type === 'tool/call') {
262
+ const tool = typeof data.name === 'string' ? data.name : 'unknown'
263
+ turn.steps += 1
264
+ if (typeof data.callId === 'string') turn.calls.set(data.callId, tool)
265
+ void fireLoop('pre-act', session, { tool, step: turn.steps })
266
+ } else if (type === 'tool/result') {
267
+ const message = data.message ?? {}
268
+ const callId = typeof message.toolCallId === 'string' ? message.toolCallId : message.source?.callId
269
+ // Only results of this turn's calls: a prune's trimmed copy of an old output is not a tool call.
270
+ if (typeof callId !== 'string' || !turn.calls.has(callId)) return
271
+ void fireLoop('post-act', session, { tool: turn.calls.get(callId), step: turn.steps })
272
+ } else if (type === 'turn/end') {
273
+ prePlanPending.delete(session)
274
+ turns.delete(session)
275
+ if (data.reason?.kind === 'error') void fireLoop('on-error', session, { step: turn.steps })
276
+ }
277
+ }
278
+
279
+ const disposeCore = ctx.on('session/event', (session, event) => {
280
+ const type = event?.type
281
+ if (type === 'turn/start') refresh()
282
+ if (type === 'working-directory/change' && nonEmpty(event?.data?.cwd)) cwdBySession.set(session, event.data.cwd)
283
+ if (loopEvents && loopHooks.length > 0 && !isSubagentSession(session)) observeLoop(session, event)
284
+ // Session-log type hooks: the bound record type only.
285
+ const typed = (engineByPoint.get('session/event') ?? []).filter((hook) => hook.sessionType === type)
286
+ if (typed.length > 0) {
287
+ const tool = typeof event?.data?.name === 'string' ? event.data.name : ''
288
+ queueMicrotask(() => {
289
+ for (const hook of typed) void run(hook, hook.event, session, { PICASSO_HOOK_TOOL: tool })
290
+ })
291
+ }
292
+ })
293
+ refresh()
294
+
295
+ return () => {
296
+ disposeCore?.()
297
+ for (const dispose of subscriptions.values()) dispose?.()
298
+ subscriptions.clear()
299
+ }
300
+ }
301
+
302
+ export { isLifecycleEvent, lifecycleEvent }