@picassohq/cli 0.0.0-stage → 1.0.1

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 (230) hide show
  1. package/agents/browser_agent.yaml +53 -0
  2. package/agents/code_reviewer.yaml +49 -0
  3. package/agents/codebase_investigator.yaml +70 -0
  4. package/agents/design_auditor.yaml +50 -0
  5. package/agents/devex_auditor.yaml +50 -0
  6. package/agents/doc_writer.yaml +54 -0
  7. package/agents/engineering_architect.yaml +51 -0
  8. package/agents/generalist.yaml +55 -0
  9. package/agents/migration_planner.yaml +51 -0
  10. package/agents/product_reviewer.yaml +48 -0
  11. package/agents/qa_operator.yaml +52 -0
  12. package/agents/release_engineer.yaml +50 -0
  13. package/agents/security_auditor.yaml +62 -0
  14. package/agents/test_writer.yaml +52 -0
  15. package/assets/first-light-lockup.png +0 -0
  16. package/assets/first-light-tagline.png +0 -0
  17. package/assets/house/README.md +26 -0
  18. package/assets/house/auraone-banner.png +0 -0
  19. package/assets/house/auraone-logo.png +0 -0
  20. package/assets/house/kiro-prism-banner.png +0 -0
  21. package/assets/house/kiro-prism-logo.png +0 -0
  22. package/assets/house/picasso-banner.png +0 -0
  23. package/assets/house/picasso-logo.png +0 -0
  24. package/assets/wordmark-app.png +0 -0
  25. package/assets/wordmark-tight.png +0 -0
  26. package/assets/wordmark.png +0 -0
  27. package/design/styles.css +1042 -0
  28. package/dist/build-info.json +37 -0
  29. package/dist/index.js +3028 -0
  30. package/goals/cli-hardening.yaml +40 -0
  31. package/goals/repo-maintenance.yaml +40 -0
  32. package/package.json +49 -4
  33. package/runtime/dsh/picasso-ecosystem.community.amendments.yml +24 -0
  34. package/runtime/dsh/picasso-ecosystem.community.json +185 -0
  35. package/runtime/dsh/picasso-ecosystem.community.patch.yml +40 -0
  36. package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +143 -0
  37. package/runtime/dsh/picasso-isolation.patch.yml +25 -0
  38. package/runtime/dsh/picasso-providers.patch.yml +373 -0
  39. package/runtime/dsh/picasso-runtime.cordis.yml +738 -0
  40. package/runtime/dsh/picasso-sdk.patch.yml +204 -0
  41. package/runtime/engine-manifest.json +214 -0
  42. package/runtime/package.json +6 -0
  43. package/runtime/packages/picasso-cache-probe/cordis.patch.yml +5 -0
  44. package/runtime/packages/picasso-cache-probe/index.js +477 -0
  45. package/runtime/packages/picasso-cache-probe/package.json +38 -0
  46. package/runtime/packages/picasso-commands/cordis.patch.yml +4 -0
  47. package/runtime/packages/picasso-commands/fresh-review.js +573 -0
  48. package/runtime/packages/picasso-commands/index.js +497 -0
  49. package/runtime/packages/picasso-commands/package.json +28 -0
  50. package/runtime/packages/picasso-instructions/conflicts.js +115 -0
  51. package/runtime/packages/picasso-instructions/formats.js +145 -0
  52. package/runtime/packages/picasso-instructions/frontmatter.js +175 -0
  53. package/runtime/packages/picasso-instructions/glob.js +114 -0
  54. package/runtime/packages/picasso-instructions/globals.js +90 -0
  55. package/runtime/packages/picasso-instructions/imports.js +123 -0
  56. package/runtime/packages/picasso-instructions/index.js +326 -0
  57. package/runtime/packages/picasso-instructions/modes.js +64 -0
  58. package/runtime/packages/picasso-instructions/package.json +30 -0
  59. package/runtime/packages/picasso-instructions/parse.js +134 -0
  60. package/runtime/packages/picasso-instructions/report.js +161 -0
  61. package/runtime/packages/picasso-instructions/resolve.js +939 -0
  62. package/runtime/packages/picasso-instructions/scan.js +181 -0
  63. package/runtime/packages/picasso-instructions/settings.js +150 -0
  64. package/runtime/packages/picasso-instructions/skills.js +345 -0
  65. package/runtime/packages/picasso-lean-context/cordis.patch.yml +13 -0
  66. package/runtime/packages/picasso-lean-context/index.js +6049 -0
  67. package/runtime/packages/picasso-lean-context/package.json +26 -0
  68. package/runtime/packages/picasso-lean-context/timeline.js +417 -0
  69. package/runtime/packages/picasso-librarian/classify.js +146 -0
  70. package/runtime/packages/picasso-librarian/cordis.patch.yml +10 -0
  71. package/runtime/packages/picasso-librarian/index.js +878 -0
  72. package/runtime/packages/picasso-librarian/notes.js +159 -0
  73. package/runtime/packages/picasso-librarian/package.json +34 -0
  74. package/runtime/packages/picasso-librarian/state.js +478 -0
  75. package/runtime/packages/picasso-memory/index.js +1184 -0
  76. package/runtime/packages/picasso-memory/package.json +21 -0
  77. package/runtime/packages/picasso-model-router/connections.js +895 -0
  78. package/runtime/packages/picasso-model-router/cordis.patch.yml +17 -0
  79. package/runtime/packages/picasso-model-router/index.js +1081 -0
  80. package/runtime/packages/picasso-model-router/package.json +30 -0
  81. package/runtime/packages/picasso-options/cordis.patch.yml +4 -0
  82. package/runtime/packages/picasso-options/index.js +263 -0
  83. package/runtime/packages/picasso-options/package.json +28 -0
  84. package/runtime/packages/picasso-progress-reports/cordis.patch.yml +10 -0
  85. package/runtime/packages/picasso-progress-reports/index.js +267 -0
  86. package/runtime/packages/picasso-progress-reports/package.json +30 -0
  87. package/runtime/packages/picasso-progress-reports/report.js +235 -0
  88. package/runtime/packages/picasso-sdk-server/aside.js +128 -0
  89. package/runtime/packages/picasso-sdk-server/connections.js +38 -0
  90. package/runtime/packages/picasso-sdk-server/context-timeline.js +27 -0
  91. package/runtime/packages/picasso-sdk-server/egress-gate.js +520 -0
  92. package/runtime/packages/picasso-sdk-server/failure-policy.js +246 -0
  93. package/runtime/packages/picasso-sdk-server/file-input.js +169 -0
  94. package/runtime/packages/picasso-sdk-server/goal.js +131 -0
  95. package/runtime/packages/picasso-sdk-server/ignore-file.js +458 -0
  96. package/runtime/packages/picasso-sdk-server/ignore-plugin.js +12 -0
  97. package/runtime/packages/picasso-sdk-server/ignore-sandbox.js +122 -0
  98. package/runtime/packages/picasso-sdk-server/ignore-snapshot.js +131 -0
  99. package/runtime/packages/picasso-sdk-server/image-input.js +44 -0
  100. package/runtime/packages/picasso-sdk-server/index.js +886 -0
  101. package/runtime/packages/picasso-sdk-server/instructions.js +34 -0
  102. package/runtime/packages/picasso-sdk-server/jobs.js +113 -0
  103. package/runtime/packages/picasso-sdk-server/mcp-gate.js +51 -0
  104. package/runtime/packages/picasso-sdk-server/model-selection.js +162 -0
  105. package/runtime/packages/picasso-sdk-server/package.json +50 -0
  106. package/runtime/packages/picasso-sdk-server/picasso-records.js +50 -0
  107. package/runtime/packages/picasso-sdk-server/provider-reload.js +84 -0
  108. package/runtime/packages/picasso-sdk-server/queue.js +322 -0
  109. package/runtime/packages/picasso-sdk-server/requester.js +43 -0
  110. package/runtime/packages/picasso-sdk-server/rewind.js +108 -0
  111. package/runtime/packages/picasso-sdk-server/schedule.js +187 -0
  112. package/runtime/packages/picasso-sdk-server/session-grants.js +35 -0
  113. package/runtime/packages/picasso-sdk-server/session-state.js +118 -0
  114. package/runtime/packages/picasso-sdk-server/shell-paths.js +869 -0
  115. package/runtime/packages/picasso-sdk-server/stream-deltas.js +211 -0
  116. package/runtime/packages/picasso-sdk-server/team-tasks.js +451 -0
  117. package/runtime/packages/picasso-sdk-server/tool-output.js +128 -0
  118. package/runtime/packages/picasso-sdk-server/tools-list.js +51 -0
  119. package/runtime/packages/picasso-sdk-server/wave2-hooks.js +612 -0
  120. package/runtime/packages/picasso-sdk-server/workspace-archive.js +170 -0
  121. package/runtime/packages/picasso-sdk-server/workspace-restore.js +180 -0
  122. package/runtime/packages/picasso-web-search/backends.js +350 -0
  123. package/runtime/packages/picasso-web-search/config.js +121 -0
  124. package/runtime/packages/picasso-web-search/cordis.patch.yml +7 -0
  125. package/runtime/packages/picasso-web-search/failure.js +111 -0
  126. package/runtime/packages/picasso-web-search/format.js +35 -0
  127. package/runtime/packages/picasso-web-search/index.js +66 -0
  128. package/runtime/packages/picasso-web-search/package.json +38 -0
  129. package/runtime/packages/picasso-web-search/router.js +155 -0
  130. package/runtime/packages/picasso-x-reader/circle.js +324 -0
  131. package/runtime/packages/picasso-x-reader/command.js +169 -0
  132. package/runtime/packages/picasso-x-reader/cordis.patch.yml +8 -0
  133. package/runtime/packages/picasso-x-reader/index.js +170 -0
  134. package/runtime/packages/picasso-x-reader/package.json +39 -0
  135. package/runtime/packages/picasso-x-reader/read.js +370 -0
  136. package/runtime/packages/picasso-x-reader/rewrite.js +38 -0
  137. package/runtime/packages/picasso-x-reader/settings.js +131 -0
  138. package/runtime/packages/picasso-x-reader/urls.js +154 -0
  139. package/runtime/packages/picasso-x-reader/xmd.js +512 -0
  140. package/runtime/plugins/picasso-auth-bridge/index.js +380 -0
  141. package/runtime/plugins/picasso-auth-bridge/package.json +28 -0
  142. package/runtime/plugins/picasso-auto-approve/index.js +1003 -0
  143. package/runtime/plugins/picasso-auto-approve/package.json +28 -0
  144. package/runtime/plugins/picasso-browser/index.js +424 -0
  145. package/runtime/plugins/picasso-browser/package.json +28 -0
  146. package/runtime/plugins/picasso-checkpoints/evidence.js +210 -0
  147. package/runtime/plugins/picasso-checkpoints/index.js +885 -0
  148. package/runtime/plugins/picasso-checkpoints/package.json +29 -0
  149. package/runtime/plugins/picasso-commands/fresh-review.js +573 -0
  150. package/runtime/plugins/picasso-commands/index.js +497 -0
  151. package/runtime/plugins/picasso-commands/package.json +28 -0
  152. package/runtime/plugins/picasso-instructions/conflicts.js +115 -0
  153. package/runtime/plugins/picasso-instructions/formats.js +145 -0
  154. package/runtime/plugins/picasso-instructions/frontmatter.js +175 -0
  155. package/runtime/plugins/picasso-instructions/glob.js +114 -0
  156. package/runtime/plugins/picasso-instructions/globals.js +90 -0
  157. package/runtime/plugins/picasso-instructions/imports.js +123 -0
  158. package/runtime/plugins/picasso-instructions/index.js +326 -0
  159. package/runtime/plugins/picasso-instructions/modes.js +64 -0
  160. package/runtime/plugins/picasso-instructions/package.json +30 -0
  161. package/runtime/plugins/picasso-instructions/parse.js +134 -0
  162. package/runtime/plugins/picasso-instructions/report.js +161 -0
  163. package/runtime/plugins/picasso-instructions/resolve.js +939 -0
  164. package/runtime/plugins/picasso-instructions/scan.js +181 -0
  165. package/runtime/plugins/picasso-instructions/settings.js +150 -0
  166. package/runtime/plugins/picasso-instructions/skills.js +345 -0
  167. package/runtime/plugins/picasso-lean-context/index.js +6049 -0
  168. package/runtime/plugins/picasso-lean-context/package.json +26 -0
  169. package/runtime/plugins/picasso-lean-context/timeline.js +417 -0
  170. package/runtime/plugins/picasso-librarian/classify.js +146 -0
  171. package/runtime/plugins/picasso-librarian/index.js +878 -0
  172. package/runtime/plugins/picasso-librarian/notes.js +159 -0
  173. package/runtime/plugins/picasso-librarian/package.json +34 -0
  174. package/runtime/plugins/picasso-librarian/state.js +478 -0
  175. package/runtime/plugins/picasso-lifecycle-hooks/index.js +186 -0
  176. package/runtime/plugins/picasso-lifecycle-hooks/package.json +25 -0
  177. package/runtime/plugins/picasso-mail/inbox.js +207 -0
  178. package/runtime/plugins/picasso-mail/index.js +293 -0
  179. package/runtime/plugins/picasso-mail/package.json +22 -0
  180. package/runtime/plugins/picasso-memory/index.js +1184 -0
  181. package/runtime/plugins/picasso-memory/package.json +21 -0
  182. package/runtime/plugins/picasso-model-router/connections.js +895 -0
  183. package/runtime/plugins/picasso-model-router/index.js +1081 -0
  184. package/runtime/plugins/picasso-model-router/package.json +30 -0
  185. package/runtime/plugins/picasso-options/index.js +263 -0
  186. package/runtime/plugins/picasso-options/package.json +28 -0
  187. package/runtime/plugins/picasso-progress-reports/index.js +267 -0
  188. package/runtime/plugins/picasso-progress-reports/package.json +30 -0
  189. package/runtime/plugins/picasso-progress-reports/report.js +235 -0
  190. package/runtime/plugins/picasso-provider-models/index.js +436 -0
  191. package/runtime/plugins/picasso-provider-models/package.json +28 -0
  192. package/runtime/plugins/picasso-repo-index/index.js +1850 -0
  193. package/runtime/plugins/picasso-repo-index/package.json +28 -0
  194. package/runtime/plugins/picasso-schedule-pause/index.js +344 -0
  195. package/runtime/plugins/picasso-schedule-pause/package.json +28 -0
  196. package/runtime/plugins/picasso-session-lifecycle/index.js +796 -0
  197. package/runtime/plugins/picasso-session-lifecycle/package.json +28 -0
  198. package/runtime/plugins/picasso-trackers/index.js +895 -0
  199. package/runtime/plugins/picasso-trackers/package.json +28 -0
  200. package/runtime/plugins/picasso-web-search/backends.js +350 -0
  201. package/runtime/plugins/picasso-web-search/config.js +121 -0
  202. package/runtime/plugins/picasso-web-search/failure.js +111 -0
  203. package/runtime/plugins/picasso-web-search/format.js +35 -0
  204. package/runtime/plugins/picasso-web-search/index.js +66 -0
  205. package/runtime/plugins/picasso-web-search/package.json +38 -0
  206. package/runtime/plugins/picasso-web-search/router.js +155 -0
  207. package/runtime/plugins/picasso-x-reader/circle.js +324 -0
  208. package/runtime/plugins/picasso-x-reader/command.js +169 -0
  209. package/runtime/plugins/picasso-x-reader/index.js +170 -0
  210. package/runtime/plugins/picasso-x-reader/package.json +39 -0
  211. package/runtime/plugins/picasso-x-reader/read.js +370 -0
  212. package/runtime/plugins/picasso-x-reader/rewrite.js +38 -0
  213. package/runtime/plugins/picasso-x-reader/settings.js +131 -0
  214. package/runtime/plugins/picasso-x-reader/urls.js +154 -0
  215. package/runtime/plugins/picasso-x-reader/xmd.js +512 -0
  216. package/runtime/relay/attachment-text.mjs +737 -0
  217. package/runtime/relay/companion/companion.css +126 -0
  218. package/runtime/relay/companion/companion.js +648 -0
  219. package/runtime/relay/companion/icon.svg +5 -0
  220. package/runtime/relay/companion/index.html +25 -0
  221. package/runtime/relay/companion/manifest.json +13 -0
  222. package/runtime/relay/companion/sw.js +41 -0
  223. package/runtime/relay/main.mjs +37252 -0
  224. package/runtime/relay/model-listing.mjs +614 -0
  225. package/runtime/relay/versions-routes.mjs +1198 -0
  226. package/runtime/verify-plugins.mjs +205 -0
  227. package/runtime-lock/package-lock.json +10779 -0
  228. package/runtime-lock/package.json +7 -0
  229. package/scripts/install-runtime.mjs +400 -0
  230. package/README.md +0 -3
@@ -0,0 +1,612 @@
1
+ // Wave-2 server hooks, extracted from index.js so each guard, steer and
2
+ // adoption is unit-testable in isolation. index.js stays the thin adapter:
3
+ // it wires dsh services (`permissionPresets`, `llm`, `workspaceChanges`,
4
+ // `workingDirectory`), the aside registry, `BlockAssembler`,
5
+ // `createUserMessage`, `setApprovalPolicy` and `ctx.logger` into these
6
+ // factories; the behaviour below is exactly what the inline closures did.
7
+ //
8
+ // adoptAutoPreset T2.2 --permission-mode auto preset adoption
9
+ // createVerifySteer T2.8 PICASSO_VERIFY_CMD post-execute steer-back
10
+ // createAutoCommit T2.16 PICASSO_AUTO_COMMIT=1 per-turn commits
11
+ // createWave2Guards T2.17 env-file / external-directory / doom-loop vetoes
12
+ // createApprovalCritic T2.19 second-model gate on grant auto-approvals
13
+ // createAllowModifiedGuard T4.6 allow-modified preset: deny new-file creation
14
+ import { execFile } from 'node:child_process';
15
+ import { existsSync, mkdtempSync, writeFileSync } from 'node:fs';
16
+ import { tmpdir } from 'node:os';
17
+ import { basename, join, resolve } from 'node:path';
18
+ import process from 'node:process';
19
+ import { toolCallPaths, toolCallReferences } from './ignore-file.js';
20
+ import { tokenizeShell } from './shell-paths.js';
21
+
22
+ // -- Auto permission preset adoption (Picasso auto mode, T2.2) ---------------
23
+ //
24
+ // `--permission-mode auto` sets DSH_PERMISSION_MODE_PICASSO=auto. The ecosystem
25
+ // patch mounts @deepseek-ai/dsh-experimental-auto-review for every launch (it
26
+ // reviews only `auto` sessions, and one that recorded `auto` must stay resumable).
27
+ // The plugin registers the reserved `auto` preset (its name only appears in
28
+ // `presets.names` once its registerAuto integration is live). We adopt the
29
+ // preset per top-level session; when the reviewer is not mounted, "auto" is
30
+ // absent from names and we never apply it; applying it then would mean
31
+ // unreviewed danger-full-access, which is a non-starter.
32
+
33
+ /**
34
+ * Adopt the reserved `auto` preset for one top-level session. `presets` is the
35
+ * already-resolved permission-presets service (or undefined), `applyPolicy`
36
+ * applies a preset policy to the session (dsh's `setApprovalPolicy`).
37
+ */
38
+ export function adoptAutoPreset(session, { wantAutoPreset = false, isAside = () => undefined, presets, applyPolicy, warn } = {}) {
39
+ if (!wantAutoPreset || session === undefined) return;
40
+ if (isAside(session.id) === true) return;
41
+ if (session.header?.origin === 'subagent') return;
42
+ if (presets === undefined || !(presets.names ?? []).includes('auto')) return;
43
+ try {
44
+ if (presets.current(session) === 'auto') return;
45
+ presets.apply(session, 'auto', (policy) => applyPolicy(session, policy));
46
+ } catch (error) {
47
+ warn?.(`Picasso auto preset adoption failed: ${error instanceof Error ? error.message : String(error)}`);
48
+ }
49
+ }
50
+
51
+ // -- Post-execute verification steer-back (T2.8) ------------------------------
52
+ //
53
+ // When PICASSO_VERIFY_CMD names a command (e.g. `pnpm lint`), every
54
+ // successful file-writing tool call runs it in the session workspace; a
55
+ // non-zero exit steers the running turn with the output so the model fixes
56
+ // the breakage. Bounded to two steers per turn so a persistently failing
57
+ // check cannot loop forever.
58
+
59
+ export const VERIFY_WRITE_TOOLS = new Set(['write', 'edit', 'multi_edit', 'str_replace_editor', 'apply_patch', 'patch']);
60
+ export const MAX_VERIFY_STEERS = 2;
61
+ export const VERIFY_OUTPUT_LIMIT = 4_000;
62
+ export const DEFAULT_VERIFY_TIMEOUT_MS = 30_000;
63
+
64
+ /** The verify command timeout: PICASSO_VERIFY_TIMEOUT_MS, defaulting to 30s, never below 1s. */
65
+ export function verifyTimeoutMs(raw) {
66
+ return Math.max(1_000, Number(raw ?? DEFAULT_VERIFY_TIMEOUT_MS) || DEFAULT_VERIFY_TIMEOUT_MS);
67
+ }
68
+
69
+ /**
70
+ * Run `command` through `/bin/sh -c` in `cwd`; resolves to
71
+ * `{ ok, code, output }` where `output` is the last `outputLimit` bytes of
72
+ * combined stdout+stderr and `code` is the numeric exit code when the shell
73
+ * reported one (undefined for signal/timeout kills).
74
+ */
75
+ export function runVerifyCommand(command, cwd, { timeoutMs = DEFAULT_VERIFY_TIMEOUT_MS, outputLimit = VERIFY_OUTPUT_LIMIT, exec = execFile } = {}) {
76
+ return new Promise((resolveVerify) => {
77
+ exec('/bin/sh', ['-c', command], { cwd, timeout: timeoutMs, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => {
78
+ resolveVerify({
79
+ ok: error === null,
80
+ code: typeof error?.code === 'number' ? error.code : undefined,
81
+ output: `${stdout ?? ''}${stderr ?? ''}`.slice(-outputLimit),
82
+ });
83
+ });
84
+ });
85
+ }
86
+
87
+ /** The model-visible steer text for a failed verification run. */
88
+ export function verifySteerText(command, outcome) {
89
+ return (
90
+ `The post-edit verification command \`${command}\` failed${outcome.code === undefined ? '' : ` (exit ${outcome.code})`}:\n` +
91
+ `${outcome.output.trim().length > 0 ? outcome.output : '(no output)'}\n` +
92
+ 'Fix the reported problems before continuing.'
93
+ );
94
+ }
95
+
96
+ /**
97
+ * The verification steer-back pair: `observe` resets the per-turn steer
98
+ * budget on `turn/start`, `postExecute` is the `tools/post-execute` handler.
99
+ * `run` (default: the real shell command) resolves `{ ok, code, output }`
100
+ * for the session cwd; `createUserMessage` is dsh-llm's message factory.
101
+ */
102
+ export function createVerifySteer({ command, cwdOf, createUserMessage, warn, run, timeoutMs = DEFAULT_VERIFY_TIMEOUT_MS, maxSteers = MAX_VERIFY_STEERS } = {}) {
103
+ const steersThisTurn = new Map();
104
+ const runCommand = run ?? ((cwd) => runVerifyCommand(command, cwd, { timeoutMs }));
105
+ return {
106
+ observe(session, event) {
107
+ if (event?.type === 'turn/start') steersThisTurn.set(session.id, 0);
108
+ },
109
+ async postExecute(exec, result, next) {
110
+ const decision = await next();
111
+ if (decision?.kind !== 'accept' || result?.isError === true) return decision;
112
+ if (exec === undefined || !VERIFY_WRITE_TOOLS.has(exec.name)) return decision;
113
+ const session = exec.agent?.session;
114
+ if (session === undefined) return decision;
115
+ const used = steersThisTurn.get(session.id) ?? 0;
116
+ if (used >= maxSteers) return decision;
117
+ const cwd = cwdOf(session);
118
+ const outcome = await runCommand(cwd);
119
+ if (outcome.ok) return decision;
120
+ steersThisTurn.set(session.id, used + 1);
121
+ try {
122
+ exec.agent?.steer(createUserMessage({
123
+ content: [{
124
+ type: 'text',
125
+ text: verifySteerText(command, outcome),
126
+ }],
127
+ source: { kind: 'user' },
128
+ }));
129
+ } catch (error) {
130
+ warn?.(`Picasso verify steer failed: ${error instanceof Error ? error.message : String(error)}`);
131
+ }
132
+ return decision;
133
+ },
134
+ };
135
+ }
136
+
137
+ // -- Auto-commit per turn (T2.16) ---------------------------------------------
138
+ //
139
+ // On `turn/end`, stage exactly the paths the turn changed and commit them
140
+ // with a `Picasso-Thread: <sessionId>` trailer. Skips when the work tree
141
+ // holds dirty paths the turn did not touch so the user's own edits are
142
+ // never swept into a Picasso commit.
143
+
144
+ /** `git` runner: resolves stdout, rejects on non-zero exit; prompts disabled. */
145
+ export function runGit(cwd, args, { exec = execFile, env = process.env } = {}) {
146
+ return new Promise((resolveGit, rejectGit) => {
147
+ exec('git', args, {
148
+ cwd,
149
+ env: { ...env, GIT_TERMINAL_PROMPT: '0', GIT_EDITOR: 'true' },
150
+ timeout: 30_000,
151
+ maxBuffer: 8 * 1024 * 1024,
152
+ }, (error, stdout) => (error === null ? resolveGit(stdout) : rejectGit(error)));
153
+ });
154
+ }
155
+
156
+ /** Paths named by `git status --porcelain` output (rename targets, unquoted). */
157
+ export function porcelainPaths(raw) {
158
+ return raw
159
+ .split('\n')
160
+ .map((line) => line.trimEnd())
161
+ .filter((line) => line.length > 3)
162
+ .map((line) => {
163
+ let path = line.slice(3);
164
+ const rename = path.indexOf(' -> ');
165
+ if (rename >= 0) path = path.slice(rename + 4);
166
+ return path.replace(/^"|"$/gu, '');
167
+ });
168
+ }
169
+
170
+ /**
171
+ * The auto-commit pair: `observe` is the `session/event` handler that commits
172
+ * after each eligible `turn/end` (skipping subagents and asides); `commitTurn`
173
+ * does the staging and commit. `changesSeq`/`getSummary` read the session's
174
+ * latest workspace-changes summary, `git` runs git (tests inject a fake).
175
+ */
176
+ export function createAutoCommit({
177
+ enabled = () => process.env.PICASSO_AUTO_COMMIT === '1',
178
+ changesSeq,
179
+ getSummary,
180
+ cwdOf,
181
+ isAside = () => undefined,
182
+ git = runGit,
183
+ warn,
184
+ info,
185
+ } = {}) {
186
+ const commitTurn = async (session) => {
187
+ const sessionId = session.id;
188
+ const seq = changesSeq(sessionId);
189
+ const summary = seq !== undefined ? getSummary(sessionId, seq) : undefined;
190
+ const cwd = typeof summary?.cwd === 'string' ? summary.cwd : cwdOf(session);
191
+ const turnPaths = (summary?.files ?? [])
192
+ .map((file) => (typeof file?.path === 'string' ? file.path : undefined))
193
+ .filter((path) => path !== undefined);
194
+ if (turnPaths.length === 0) return;
195
+ const dirty = porcelainPaths(await git(cwd, ['status', '--porcelain']));
196
+ const touched = new Set(turnPaths);
197
+ const unrelated = dirty.filter((path) => !touched.has(path));
198
+ if (unrelated.length > 0) {
199
+ warn?.(`Picasso auto-commit skipped for ${sessionId}: ${unrelated.length} unrelated dirty path(s) present.`);
200
+ return;
201
+ }
202
+ await git(cwd, ['add', '-A', '--', ...turnPaths]);
203
+ const staged = await git(cwd, ['diff', '--cached', '--name-only']);
204
+ if (staged.trim().length === 0) return;
205
+ const dir = mkdtempSync(join(tmpdir(), 'picasso-autocommit-'));
206
+ const messageFile = join(dir, 'COMMIT_EDITMSG');
207
+ writeFileSync(
208
+ messageFile,
209
+ `picasso: turn changes\n\nPicasso-Thread: ${sessionId}\n`,
210
+ 'utf8',
211
+ );
212
+ await git(cwd, ['commit', '--quiet', '-F', messageFile]);
213
+ info?.(`Picasso auto-commit recorded for ${sessionId} (${turnPaths.length} path(s)).`);
214
+ };
215
+ return {
216
+ commitTurn,
217
+ observe(session, event) {
218
+ if (event?.type !== 'turn/end' || !enabled()) return;
219
+ if (session?.header?.origin === 'subagent' || isAside(session.id) === true) return;
220
+ void commitTurn(session).catch((error) => {
221
+ warn?.(`Picasso auto-commit failed: ${error instanceof Error ? error.message : String(error)}`);
222
+ });
223
+ },
224
+ };
225
+ }
226
+
227
+ // -- Wave-2 guards (fail-closed vetoes on tools/pre-execute, T2.17) -----------
228
+ //
229
+ // env-file guard: tool calls (fs tools and shell commands alike, via
230
+ // toolCallReferences) that touch a `*.env` path are denied by default;
231
+ // secrets must never enter the agent pipeline. PICASSO_ENV_GUARD=0 opts out.
232
+ // external-directory guard: a call that asks the sandbox for an escalation
233
+ // (`sandbox_permissions`) while referencing paths outside the session
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.
237
+
238
+ export const DOOM_LOOP_LIMIT = 3;
239
+
240
+ /** Whether `path` names a dotenv file (`.env`, `.env.*`, `*.env`). */
241
+ export function isEnvPath(path) {
242
+ const base = basename(path);
243
+ return base === '.env' || base.startsWith('.env.') || base.endsWith('.env');
244
+ }
245
+
246
+ /** Deterministic JSON (sorted keys) backing the doom-loop signature. */
247
+ export function stableJson(value) {
248
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;
249
+ if (typeof value === 'object' && value !== null) {
250
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(',')}}`;
251
+ }
252
+ return JSON.stringify(value);
253
+ }
254
+
255
+ /**
256
+ * The guard pair: `observe` resets doom-loop bookkeeping on `turn/start`,
257
+ * `preExecute` is the `tools/pre-execute` handler. `references` is
258
+ * `toolCallReferences`, `exists` the real-target check, `isIgnored` the
259
+ * `.picassoignore` lookup (kept as a dep so paths the ignore guard already
260
+ * refuses report the ignore reason, not this one).
261
+ */
262
+ export function createWave2Guards({
263
+ envGuard = () => process.env.PICASSO_ENV_GUARD !== '0',
264
+ cwdOf,
265
+ references = toolCallReferences,
266
+ exists = existsSync,
267
+ isIgnored = () => false,
268
+ doomLimit = DOOM_LOOP_LIMIT,
269
+ } = {}) {
270
+ /** sessionId -> { signature, count } for the running turn. */
271
+ const doomLoop = new Map();
272
+ return {
273
+ observe(session, event) {
274
+ if (event?.type === 'turn/start') doomLoop.delete(session.id);
275
+ },
276
+ async preExecute(exec, next) {
277
+ const session = exec?.agent?.session;
278
+ const cwd = session === undefined ? process.cwd() : cwdOf(session);
279
+ const args = exec?.arguments ?? {};
280
+ const refs = references(exec?.name, args, cwd);
281
+ // Same standard as the ignore guard: a ref must name a real target
282
+ // (`always`, or the path exists) — extracted tokens like `ret.env` in
283
+ // `cat $(printf '%s%s' sec ret.env)` are not `.env` reads. Paths
284
+ // .picassoignore already refuses report that reason, not this one.
285
+ if (envGuard() && refs.some((ref) => {
286
+ const raw = ref.path ?? ref;
287
+ if (typeof raw !== 'string' || !isEnvPath(raw)) return false;
288
+ if (ref.always !== true && !exists(raw)) return false;
289
+ return !isIgnored(cwd, raw);
290
+ })) {
291
+ return {
292
+ kind: 'deny',
293
+ reason: `Picasso env-file guard: tool "${exec?.name}" references a *.env path; denied by default (set PICASSO_ENV_GUARD=0 to disable).`,
294
+ };
295
+ }
296
+ const escalates =
297
+ args !== null &&
298
+ typeof args === 'object' &&
299
+ typeof args.sandbox_permissions === 'string' &&
300
+ args.sandbox_permissions.length > 0;
301
+ if (escalates) {
302
+ const outside = refs.some((ref) => {
303
+ const raw = ref.path ?? ref;
304
+ if (typeof raw !== 'string') return false;
305
+ const resolved = resolve(cwd, raw);
306
+ return resolved !== cwd && !resolved.startsWith(`${cwd}/`);
307
+ });
308
+ if (outside) {
309
+ return {
310
+ kind: 'deny',
311
+ reason: `Picasso external-directory guard: tool "${exec?.name}" requests a sandbox escalation for a path outside the session workspace; denied.`,
312
+ };
313
+ }
314
+ }
315
+ if (session !== undefined) {
316
+ const signature = `${exec?.name}:${stableJson(args)}`;
317
+ const entry = doomLoop.get(session.id);
318
+ if (entry !== undefined && entry.signature === signature) {
319
+ entry.count += 1;
320
+ if (entry.count >= doomLimit) {
321
+ return {
322
+ kind: 'deny',
323
+ reason: `Picasso doom-loop guard: tool "${exec?.name}" was called with identical arguments ${entry.count} times in this turn; denied.`,
324
+ };
325
+ }
326
+ } else {
327
+ doomLoop.set(session.id, { signature, count: 1 });
328
+ }
329
+ }
330
+ return next();
331
+ },
332
+ };
333
+ }
334
+
335
+ // -- Second-model critique for grant auto-approvals (T2.19) -------------------
336
+ //
337
+ // Reads like the auto-review plugin's protocol: the session's own route is
338
+ // asked for {"verdict":"allow"|"deny"|"unsure","reason"?}. Only a confident
339
+ // `allow` keeps the grant auto-approve; deny/unsure/parse failure/missing llm
340
+ // all defer to the ordinary ask. Opt out with PICASSO_APPROVAL_CRITIC=0.
341
+
342
+ export const CRITIC_SYSTEM =
343
+ 'You are a critic vetting a tool call an AI agent is about to run; a human earlier ' +
344
+ 'granted session-level approval for this tool name. Answer with exactly one JSON ' +
345
+ 'object: {"verdict":"allow"} when the call is an ordinary, low-risk use of the tool; ' +
346
+ '{"verdict":"deny","reason":"..."} when it is destructive, escapes the workspace, ' +
347
+ 'exfiltrates data or is otherwise unsafe; {"verdict":"unsure","reason":"..."} when ' +
348
+ 'you cannot tell. No other text.';
349
+
350
+ export const CRITIC_ARGS_LIMIT = 2_000;
351
+
352
+ /** The critic's user prompt: tool name plus truncated JSON call arguments. */
353
+ export function criticRequestText(req) {
354
+ let argsText = '';
355
+ try {
356
+ argsText = JSON.stringify(req.arguments ?? {}) ?? '';
357
+ } catch {
358
+ argsText = '';
359
+ }
360
+ return `Tool: ${req.toolName ?? 'unknown'}\nCall arguments (truncated): ${argsText.slice(0, CRITIC_ARGS_LIMIT)}\nVerdict?`;
361
+ }
362
+
363
+ /** Map the critic's final text to a verdict: only a confident `allow` passes. */
364
+ export function criticVerdict(text) {
365
+ const match = /\{[\s\S]*"verdict"[\s\S]*\}/u.exec(text);
366
+ if (match === null) return { allow: false };
367
+ let parsed;
368
+ try {
369
+ parsed = JSON.parse(match[0]);
370
+ } catch {
371
+ return { allow: false };
372
+ }
373
+ if (parsed?.verdict === 'allow') return { allow: true };
374
+ const reason = typeof parsed?.reason === 'string' && parsed.reason.length > 0
375
+ ? `critic: ${parsed.reason}`
376
+ : 'critic did not allow this call';
377
+ return { allow: false, reason };
378
+ }
379
+
380
+ /**
381
+ * Consume `stream` through a fresh assembler (`createAssembler` is a
382
+ * BlockAssembler factory); resolves the final block's text, or undefined
383
+ * when the last block is not text.
384
+ */
385
+ export async function collectCriticText(stream, createAssembler) {
386
+ const assembler = createAssembler();
387
+ let finished = false;
388
+ for await (const chunk of stream) {
389
+ if (finished) break;
390
+ assembler.push(chunk);
391
+ if (chunk.type === 'finish') finished = true;
392
+ }
393
+ const final = assembler.blocks().at(-1);
394
+ return final?.type === 'text' ? final.text : undefined;
395
+ }
396
+
397
+ /**
398
+ * The critique: `llm()` resolves the model registry, `defaults()` the
399
+ * initialized route (`{ provider, model }` used when the session's request
400
+ * header names none). Returns `{ allow: true }` only for a confident allow
401
+ * (or when the critic is disabled); everything else defers to the ask.
402
+ */
403
+ export function createApprovalCritic({
404
+ enabled = () => process.env.PICASSO_APPROVAL_CRITIC !== '0',
405
+ llm = () => undefined,
406
+ defaults = () => ({}),
407
+ createAssembler,
408
+ } = {}) {
409
+ return async (req) => {
410
+ if (!enabled()) return { allow: true };
411
+ const registry = llm();
412
+ if (registry === undefined || typeof registry.stream !== 'function') return { allow: false };
413
+ const header = req.agent?.session?.requestHeader?.()?.config;
414
+ const fallback = defaults() ?? {};
415
+ const provider =
416
+ typeof header?.provider === 'string' && header.provider.length > 0 ? header.provider : fallback.provider;
417
+ const model =
418
+ typeof header?.model === 'string' && header.model.length > 0 ? header.model : fallback.model;
419
+ if (provider === undefined || model === undefined) return { allow: false };
420
+ const userText = criticRequestText(req);
421
+ try {
422
+ const text = await collectCriticText(registry.stream({
423
+ provider,
424
+ model,
425
+ system: CRITIC_SYSTEM,
426
+ messages: [{ role: 'user', content: [{ type: 'text', text: userText }] }],
427
+ temperature: 0,
428
+ signal: req.signal,
429
+ }), createAssembler);
430
+ if (text === undefined) return { allow: false };
431
+ return criticVerdict(text);
432
+ } catch {
433
+ return { allow: false };
434
+ }
435
+ };
436
+ }
437
+
438
+ // -- allow-modified preset guard (T4.6) ---------------------------------------
439
+ //
440
+ // `allow-modified` is `workspace-write` plus one extra rule: a write may only
441
+ // change what already exists — new-file creation (and new-directory mkdir) is
442
+ // refused outright instead of asked. The dsh PresetSpec schema has no such
443
+ // knob, so the preset declares the plain sandbox/approval bundle and this
444
+ // pre-execute guard enforces the extra semantics, keyed off the session's
445
+ // effective preset (the env launch value is the fallback when the
446
+ // permission-presets service is not mounted — fail closed either way).
447
+ //
448
+ // Coverage: every file-writing tool whose target is knowable before dispatch
449
+ // (`write`/`edit`/`str_replace_editor` and their aliases, patch bodies in both
450
+ // `*** Add File:` and unified-diff spelling, `notebook_edit`) plus shell
451
+ // write-targets — redirections, writer-command operands, `dd of=` — that the
452
+ // static shell reading resolves. A write whose target does not exist is a
453
+ // creation and is denied; a write whose target cannot be resolved at all
454
+ // (dynamic shell expansion behind an output redirect, a write-named tool with
455
+ // no path argument) is denied too: the preset means "modify only", never
456
+ // "create something unverifiable". Reads, deletions of existing files, and
457
+ // writes to existing paths pass; the workspace-write sandbox still bounds
458
+ // everything else.
459
+
460
+ /** Tools that exist to create files — denied outright under allow-modified. */
461
+ const CREATE_ONLY_TOOLS = /^(?:create|create_file|new_file|make_file)$/iu;
462
+ /** Write/mutate tools whose target must already exist (str_replace_editor is handled by command). */
463
+ const WRITE_EXISTING_TOOLS = /^(?:write|write_file|edit|edit_file|multiedit|multi_edit|str_replace|str_replace_editor|apply_patch|patch|notebook_edit|insert|append|append_file|replace|replace_file)$/iu;
464
+ /**
465
+ * Wider write-intent match for tools the exact set does not name (MCP file
466
+ * tools and friends): their resolved path arguments must exist when present,
467
+ * but a match with no file target is not provably a file write and passes.
468
+ */
469
+ const LOOSE_WRITE_TOOLS = /(?:^|[^a-z])(?:write|create|edit|patch|append|replace|save|move|copy|rename|mkdir|rmdir|unlink|delete)(?:[^a-z]|$)/iu;
470
+ /** Shell tools (`toolCallReferences` parses their command line; `always` refs are write-targets). */
471
+ const SHELL_TOOL_NAMES = new Set(['bash', 'pwsh', 'terminal_send', 'terminal_open']);
472
+ /** Shell redirections that write (input redirects `<`, `<<`, `<<<`, `<&` never create). */
473
+ const WRITE_REDIRECT_OPS = new Set(['>', '>>', '>|', '&>', '&>>', '<>', '>&']);
474
+ /** Arguments a patch tool may carry its patch body in. */
475
+ const PATCH_TEXT_KEYS = ['patch', 'diff', 'input', 'content', 'text'];
476
+
477
+ /**
478
+ * The file paths one patch body creates vs modifies, in both spellings:
479
+ * apply_patch's `*** Add/Update/Delete File:` and unified `---`/`+++` headers
480
+ * (`--- /dev/null` marks the `+++` target a creation).
481
+ */
482
+ export function patchTargets(text) {
483
+ const creates = [];
484
+ const modifies = [];
485
+ let created = false;
486
+ for (const line of String(text).split(/\r?\n/u)) {
487
+ const directive = /^\*\*\*\s*(Add|Update|Delete|Move)\s+File:\s*(.+?)\s*$/u.exec(line);
488
+ if (directive !== null) {
489
+ if (directive[1] === 'Add') creates.push(directive[2]);
490
+ else modifies.push(directive[2]);
491
+ continue;
492
+ }
493
+ if (line.startsWith('--- ')) {
494
+ created = line.slice(4).trim() === '/dev/null';
495
+ continue;
496
+ }
497
+ if (line.startsWith('+++ ')) {
498
+ const target = line.slice(4).trim();
499
+ if (target === '/dev/null') {
500
+ created = false;
501
+ continue;
502
+ }
503
+ (created ? creates : modifies).push(target.replace(/^[ab]\//u, ''));
504
+ created = false;
505
+ }
506
+ }
507
+ return { creates, modifies };
508
+ }
509
+
510
+ function deny(reason) {
511
+ return { kind: 'deny', reason };
512
+ }
513
+
514
+ /**
515
+ * The allow-modified pre-execute guard. `presetOf(session)` resolves the
516
+ * session's effective preset name (index.js wires `permissionPresets.current`,
517
+ * tolerant of the service being absent or `custom`); `mode()` is the
518
+ * launch-time fallback (default `DSH_PERMISSION_MODE`). `cwdOf`, `exists` and
519
+ * `isIgnored` behave exactly as in `createWave2Guards`.
520
+ */
521
+ export function createAllowModifiedGuard({
522
+ presetOf = () => undefined,
523
+ mode = () => process.env.DSH_PERMISSION_MODE,
524
+ cwdOf,
525
+ references = toolCallReferences,
526
+ paths = toolCallPaths,
527
+ exists = existsSync,
528
+ isIgnored = () => false,
529
+ } = {}) {
530
+ const active = (exec) => {
531
+ const preset = presetOf(exec?.agent?.session);
532
+ if (typeof preset === 'string' && preset.length > 0) return preset === 'allow-modified';
533
+ return mode() === 'allow-modified';
534
+ };
535
+ const reason = (tool, detail) =>
536
+ `Picasso allow-modified guard: tool "${tool}" ${detail}; this preset permits writes only to files that already exist (new-file creation is denied).`;
537
+ /** Deny when a patch body creates a file or updates one that does not exist. */
538
+ const checkPatch = (name, args, cwd) => {
539
+ const text = PATCH_TEXT_KEYS.map((key) => args?.[key]).find((value) => typeof value === 'string' && value.length > 0);
540
+ if (text === undefined) return deny(reason(name, 'carries no patch body the guard can verify'));
541
+ const { creates, modifies } = patchTargets(text);
542
+ if (creates.length > 0) return deny(reason(name, `would create ${creates.map((path) => `"${path}"`).join(', ')}`));
543
+ const missing = modifies.filter((path) => !exists(resolve(cwd, path)));
544
+ if (missing.length > 0) return deny(reason(name, `writes ${missing.map((path) => `"${path}"`).join(', ')}, which does not exist`));
545
+ return undefined;
546
+ };
547
+ return {
548
+ async preExecute(exec, next) {
549
+ if (!active(exec)) return next();
550
+ const name = exec?.name ?? '';
551
+ const args = exec?.arguments;
552
+ const session = exec?.agent?.session;
553
+ const cwd = resolve(session === undefined ? process.cwd() : cwdOf(session));
554
+ if (CREATE_ONLY_TOOLS.test(name)) {
555
+ return deny(reason(name, 'creates a new file'));
556
+ }
557
+ if (name === 'str_replace_editor') {
558
+ const command = typeof args?.command === 'string' ? args.command : '';
559
+ if (command === 'create') return deny(reason(name, 'create writes a new file'));
560
+ if (command === 'view' || command === '') return next();
561
+ }
562
+ if (WRITE_EXISTING_TOOLS.test(name)) {
563
+ if (PATCH_TOOLS_CHECK.test(name)) {
564
+ const refusal = checkPatch(name, args, cwd);
565
+ if (refusal !== undefined) return refusal;
566
+ return next();
567
+ }
568
+ const targets = paths(name, args, cwd).map((path) => resolve(cwd, path));
569
+ if (targets.length === 0) {
570
+ return deny(reason(name, 'names no file target the guard can verify'));
571
+ }
572
+ const missing = targets.filter((target) => !exists(target));
573
+ if (missing.length > 0) {
574
+ return deny(reason(name, `writes ${missing.map((path) => displayTarget(cwd, path)).join(', ')}, which does not exist`));
575
+ }
576
+ return next();
577
+ }
578
+ if (SHELL_TOOL_NAMES.has(name)) {
579
+ // Shell commands: resolved write-targets (redirects, writer-command
580
+ // operands, `dd of=`) that do not exist are creations; an
581
+ // unresolvable expansion behind an output redirect is denied too,
582
+ // since the preset cannot be checked against it.
583
+ const refs = references(name, args, cwd);
584
+ const missing = refs.filter((ref) => ref.opaque !== true && ref.always === true && !isIgnored(cwd, ref.path) && !exists(ref.path));
585
+ if (missing.length > 0) {
586
+ return deny(reason(name, `writes ${missing.map((ref) => displayTarget(cwd, ref.path)).join(', ')}, which does not exist`));
587
+ }
588
+ const commandText = typeof args?.command === 'string' ? args.command : typeof args?.text === 'string' ? args.text : undefined;
589
+ if (
590
+ refs.some((ref) => ref.opaque === true) &&
591
+ commandText !== undefined &&
592
+ tokenizeShell(commandText).some((token) => token.type === 'redirect' && token.target !== undefined && WRITE_REDIRECT_OPS.has(token.op))
593
+ ) {
594
+ return deny(reason(name, 'writes a path resolvable only at run time; the guard cannot verify it exists'));
595
+ }
596
+ return next();
597
+ }
598
+ if (LOOSE_WRITE_TOOLS.test(name)) {
599
+ const missing = paths(name, args, cwd).map((path) => resolve(cwd, path)).filter((target) => !exists(target));
600
+ if (missing.length > 0) {
601
+ return deny(reason(name, `writes ${missing.map((path) => displayTarget(cwd, path)).join(', ')}, which does not exist`));
602
+ }
603
+ }
604
+ return next();
605
+ },
606
+ };
607
+ }
608
+ const PATCH_TOOLS_CHECK = /^(?:apply_patch|patch)$/iu;
609
+
610
+ function displayTarget(cwd, path) {
611
+ return path.startsWith(`${cwd}/`) ? `"${path.slice(cwd.length + 1)}"` : `"${path}"`;
612
+ }