gentle-pi 4.6.0 → 4.7.0

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 (290) hide show
  1. package/README.md +10 -11
  2. package/assets/agents/gentle-ai-explore.md +1 -0
  3. package/assets/agents/gentle-ai-verify.md +5 -2
  4. package/assets/agents/gentle-ai-worker.md +3 -0
  5. package/assets/agents/jd-fix-agent.md +1 -0
  6. package/assets/agents/jd-judge-a.md +1 -0
  7. package/assets/agents/jd-judge-b.md +1 -0
  8. package/assets/design-canvas/canvas.css +13 -1
  9. package/assets/design-canvas/canvas.js +11 -2
  10. package/assets/install-wizard/wizard.js +1 -0
  11. package/assets/migrations/agent-body-history.json +16 -1
  12. package/assets/orchestrator-delegation-reference.md +4 -4
  13. package/assets/orchestrator-delegation.md +1 -1
  14. package/assets/orchestrator-full-delegation-card.md +65 -0
  15. package/assets/orchestrator-full-delegation.md +34 -0
  16. package/assets/orchestrator-memory.md +3 -3
  17. package/assets/orchestrator-prompts.md +1 -1
  18. package/assets/orchestrator-skills.md +1 -1
  19. package/assets/orchestrator-verification.md +7 -5
  20. package/assets/orchestrator.md +3 -3
  21. package/bin/gentle-shell.mjs +164 -56
  22. package/docs/agent-status.md +61 -0
  23. package/docs/bundled-install.md +7 -5
  24. package/docs/delegated-verification.md +29 -7
  25. package/docs/gentle-agents-activity.md +14 -0
  26. package/docs/gentle-shell.md +54 -16
  27. package/docs/install-wizard.md +1 -1
  28. package/docs/permission-modes.md +9 -4
  29. package/docs/readme-reference.md +75 -30
  30. package/docs/render-cache-performance.md +11 -1
  31. package/docs/review-coordinator.md +33 -0
  32. package/docs/review-request-context.md +19 -0
  33. package/docs/review-windows-acl.md +18 -0
  34. package/docs/voice.md +6 -3
  35. package/docs/yolo-mode.md +5 -5
  36. package/extensions/ask-user-choice.ts +1 -0
  37. package/extensions/ask-user-question.ts +1 -0
  38. package/extensions/child-safety.ts +3 -0
  39. package/extensions/gentle-agent-status.ts +99 -0
  40. package/extensions/gentle-agents.ts +326 -34
  41. package/extensions/gentle-ai.ts +1496 -454
  42. package/extensions/gentle-shell.ts +293 -63
  43. package/extensions/gentle-todo.ts +18 -2
  44. package/extensions/gentle-tps.ts +48 -0
  45. package/extensions/quiet-tools.ts +38 -8
  46. package/extensions/skill-registry.ts +175 -18
  47. package/extensions/startup-banner.ts +30 -3
  48. package/lib/agent-profile-pin.ts +3 -3
  49. package/lib/agent-profiles.ts +160 -2
  50. package/lib/agent-status.ts +105 -0
  51. package/lib/agents-config.ts +46 -0
  52. package/lib/agents-history.ts +24 -5
  53. package/lib/agents-messaging.ts +47 -5
  54. package/lib/agents-runner.ts +183 -12
  55. package/lib/auto-permission-runtime.ts +1 -1
  56. package/lib/bounded-writer-admission.ts +13 -1
  57. package/lib/card-content-policy.ts +8 -6
  58. package/lib/command-palette.ts +133 -17
  59. package/lib/context-backstop.ts +14 -5
  60. package/lib/destructive-command-guard.ts +48 -4
  61. package/lib/execution-surface-guard.ts +20 -0
  62. package/lib/exploration-budget.ts +4 -2
  63. package/lib/gentle-ai-binary.ts +1 -1
  64. package/lib/gentle-design.ts +3 -0
  65. package/lib/gentle-shell-bundled.ts +6 -19
  66. package/lib/gentle-shell-launcher.ts +43 -8
  67. package/lib/herdr-activity.ts +14 -2
  68. package/lib/herdr-busy.ts +45 -0
  69. package/lib/image-attachments.ts +33 -0
  70. package/lib/image-disk-cache.ts +137 -0
  71. package/lib/inprocess-reviewer.ts +270 -140
  72. package/lib/jobs-view.ts +198 -11
  73. package/lib/model-routing-authority.ts +22 -4
  74. package/lib/native-choice-list.ts +20 -2
  75. package/lib/native-review-cli.ts +96 -19
  76. package/lib/orchestrator-mode-policy.ts +105 -0
  77. package/lib/questionnaire/questionnaire-view.ts +105 -12
  78. package/lib/rdd-mode-control.ts +32 -0
  79. package/lib/reply-language-anchor.ts +104 -0
  80. package/lib/review-blocker.ts +92 -0
  81. package/lib/review-candidate-symlink-scan.ts +136 -0
  82. package/lib/review-candidate-view-owner.ts +81 -44
  83. package/lib/review-continuation-registry.ts +99 -0
  84. package/lib/review-coordinator.ts +163 -0
  85. package/lib/review-failure-facts.ts +49 -0
  86. package/lib/review-host-relay.ts +46 -10
  87. package/lib/review-integration-v2.ts +7 -1
  88. package/lib/review-relay-phase-timing.ts +45 -0
  89. package/lib/review-start-context.ts +17 -0
  90. package/lib/session-profile-freeze.ts +4 -2
  91. package/lib/shell-bar.ts +140 -58
  92. package/lib/shell-changes.ts +2 -0
  93. package/lib/shell-panel.ts +17 -3
  94. package/lib/shell-sidebar-layout.ts +112 -40
  95. package/lib/shell-sidebar.ts +7 -0
  96. package/lib/shell-todo.ts +10 -3
  97. package/lib/verifier-admission.ts +1 -1
  98. package/lib/visual-customization-policy.ts +36 -16
  99. package/lib/visual-customize-view.ts +216 -21
  100. package/lib/visual-layout-preview.ts +9 -5
  101. package/lib/visual-profiles.ts +2 -2
  102. package/lib/windows-session-transport.ts +53 -2
  103. package/lib/yolo-session-policy.ts +40 -15
  104. package/package.json +2 -1
  105. package/runtime/gentle-ai-binary.mjs +1 -1
  106. package/runtime/gentle-shell-bundled.mjs +6 -19
  107. package/runtime/gentle-shell-launcher.mjs +42 -7
  108. package/runtime/native-review-cli.mjs +93 -16
  109. package/runtime/review-integration-v2.mjs +7 -1
  110. package/scripts/build-full-delegation-card.mjs +175 -0
  111. package/scripts/bundled-install.mjs +38 -8
  112. package/scripts/download-progress.mjs +68 -0
  113. package/scripts/gentle-ai-installer.mjs +41 -18
  114. package/scripts/gentle-ai-proxy.mjs +294 -0
  115. package/scripts/install-gentle-ai.mjs +14 -1
  116. package/scripts/installer-preflight.mjs +5 -5
  117. package/scripts/installer-runner.mjs +27 -12
  118. package/scripts/installer-server.mjs +8 -7
  119. package/scripts/render-cache-host.mjs +72 -0
  120. package/scripts/render-cache-performance-worker.mjs +5 -4
  121. package/scripts/render-cache-performance.mjs +6 -1
  122. package/scripts/run-test-suite.mjs +40 -28
  123. package/scripts/verify-package-files.mjs +12 -2
  124. package/scripts/voice-worker.cjs +32 -6
  125. package/skills/design/SKILL.md +11 -8
  126. package/skills/gentle-ai/SKILL.md +2 -2
  127. package/skills/gentle-ui-design/SKILL.md +46 -0
  128. package/skills/gentle-ui-design/references/adaptive-interfaces.md +46 -0
  129. package/skills/gentle-ui-design/references/browse-and-compare.md +62 -0
  130. package/skills/gentle-ui-design/references/composition-and-feedback.md +56 -0
  131. package/skills/gentle-ui-design/references/task-and-content.md +60 -0
  132. package/skills/skill-registry/SKILL.md +4 -2
  133. package/skills/work-unit-commits/SKILL.md +6 -7
  134. package/tests/agent-home.test.ts +28 -9
  135. package/tests/agent-profiles-workflow.test.ts +163 -0
  136. package/tests/agent-risk-escalation.test.ts +1 -1
  137. package/tests/agent-status.test.ts +143 -0
  138. package/tests/agents-config.test.ts +96 -0
  139. package/tests/agents-history.test.ts +31 -0
  140. package/tests/agents-jobs-frames.test.ts +93 -0
  141. package/tests/agents-prompt-lifecycle-runtime.test.ts +376 -0
  142. package/tests/agents-runner-drain.test.ts +193 -0
  143. package/tests/agents-runner.test.ts +178 -2
  144. package/tests/append-system-prompt-route.test.ts +4 -1
  145. package/tests/ask-user-choice.test.ts +4 -3
  146. package/tests/ask-user-question.test.ts +97 -0
  147. package/tests/auto-permission-runtime.test.ts +1 -1
  148. package/tests/autonomous-guard.test.ts +346 -10
  149. package/tests/bounded-stop-contract.test.ts +43 -3
  150. package/tests/bridge-cost.test.ts +19 -4
  151. package/tests/bundled-install.test.ts +30 -5
  152. package/tests/card-content-policy.test.ts +3 -3
  153. package/tests/chained-pr-skill.test.ts +8 -6
  154. package/tests/child-safety.test.ts +11 -0
  155. package/tests/codegraph-tools.test.ts +11 -5
  156. package/tests/command-palette.test.ts +284 -1
  157. package/tests/delegate-for-reason-contract.test.ts +3 -3
  158. package/tests/design-canvas-assets.test.ts +185 -2
  159. package/tests/destructive-command-guard.test.ts +52 -0
  160. package/tests/download-progress.test.ts +71 -0
  161. package/tests/execution-surface-guard.test.ts +55 -0
  162. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +9 -5
  163. package/tests/fixtures/proxy-tls/proxy.crt +19 -0
  164. package/tests/fixtures/proxy-tls/proxy.key +28 -0
  165. package/tests/fixtures/session-profile-v1/gentle-ai-reviewer.ts +89 -0
  166. package/tests/fixtures/session-profile-v1/replay.ts +53 -6
  167. package/tests/full-delegation-closure.test.ts +131 -0
  168. package/tests/full-delegation-notices.test.ts +76 -0
  169. package/tests/generic-agent-tools.test.ts +3 -3
  170. package/tests/gentle-agent-status.test.ts +74 -0
  171. package/tests/gentle-agents-child-jobs.test.ts +237 -0
  172. package/tests/gentle-agents.test.ts +1070 -12
  173. package/tests/gentle-ai-binary.test.ts +3 -1
  174. package/tests/gentle-ai-elapsed-store.test.ts +19 -0
  175. package/tests/gentle-ai-exploration-budget.test.ts +18 -2
  176. package/tests/gentle-ai-installer.test.ts +134 -51
  177. package/tests/gentle-ai-proxy.test.ts +434 -0
  178. package/tests/gentle-ai.test.ts +113 -38
  179. package/tests/gentle-design.test.ts +21 -0
  180. package/tests/gentle-herdr-activity.test.ts +9 -6
  181. package/tests/gentle-shell-bin.test.ts +123 -0
  182. package/tests/gentle-shell-bundled.test.ts +207 -31
  183. package/tests/gentle-shell-launcher.test.ts +77 -10
  184. package/tests/gentle-shell.test.ts +899 -59
  185. package/tests/gentle-todo.test.ts +19 -2
  186. package/tests/gentle-tps.test.ts +123 -0
  187. package/tests/gentle-ui-design-skill.test.ts +59 -0
  188. package/tests/herdr-busy.test.ts +59 -0
  189. package/tests/herdr-task-summary-policy.test.ts +8 -4
  190. package/tests/image-disk-cache.test.ts +163 -0
  191. package/tests/independent-recovery-delivery.test.ts +83 -0
  192. package/tests/inprocess-reviewer.test.ts +176 -4
  193. package/tests/installer-posix-bootstrap.test.ts +1 -1
  194. package/tests/installer-preflight.test.ts +5 -4
  195. package/tests/installer-runner.test.ts +79 -44
  196. package/tests/installer-server.test.ts +14 -11
  197. package/tests/jobs-view.test.ts +260 -6
  198. package/tests/modal-mouse-boundaries.test.ts +136 -0
  199. package/tests/model-routing-authority.test.ts +178 -2
  200. package/tests/native-choice-list.test.ts +77 -2
  201. package/tests/native-review-capability-contract.test.ts +7 -1
  202. package/tests/native-review-cli.test.ts +269 -1
  203. package/tests/no-self-pause-contract.test.ts +4 -1
  204. package/tests/odd-routing-canonical-ratchet.test.ts +3 -3
  205. package/tests/orchestrator-budget.test.ts +7 -2
  206. package/tests/orchestrator-delegation-mode.test.ts +153 -0
  207. package/tests/orchestrator-mode-policy.test.ts +175 -0
  208. package/tests/orchestrator-prompt-budget.test.ts +3 -1
  209. package/tests/orchestrator-rdd-ownership.test.ts +2 -2
  210. package/tests/package-manifest.test.ts +11 -9
  211. package/tests/permission-allowlist.test.ts +202 -0
  212. package/tests/pi-update-launcher.test.ts +8 -0
  213. package/tests/pnpm-workspace-config.test.ts +58 -0
  214. package/tests/primary-session-prompt.test.ts +13 -0
  215. package/tests/profile-pin.test.ts +29 -2
  216. package/tests/profile-tier-footer.test.ts +5 -0
  217. package/tests/profiles-panel-delegation-mode.test.ts +422 -0
  218. package/tests/questionnaire-view.test.ts +115 -0
  219. package/tests/quiet-bash-runtime.test.ts +1 -1
  220. package/tests/quiet-tool-rendering.test.ts +48 -0
  221. package/tests/rdd-aware-verification-contract.test.ts +16 -11
  222. package/tests/rdd-customize.test.ts +287 -0
  223. package/tests/rdd-mode-cache.test.ts +450 -0
  224. package/tests/rdd-mode-control.test.ts +407 -0
  225. package/tests/rdd-mode-scope-regression.test.ts +137 -0
  226. package/tests/rdd-off-independent-regression.test.ts +69 -0
  227. package/tests/rdd-status-line.test.ts +18 -0
  228. package/tests/render-cache-performance.test.ts +171 -2
  229. package/tests/reply-language-anchor.test.ts +173 -0
  230. package/tests/review-agent-end-preflight.test.ts +1 -1
  231. package/tests/review-blocker.test.ts +193 -0
  232. package/tests/review-candidate-owner-retry.test.ts +1 -1
  233. package/tests/review-candidate-symlink-scan.test.ts +157 -0
  234. package/tests/review-candidate-view.test.ts +1 -1
  235. package/tests/review-candidate-windows-boundary.test.ts +131 -0
  236. package/tests/review-candidate-windows-probe.test.ts +63 -0
  237. package/tests/review-committed-restart-ack.test.ts +129 -0
  238. package/tests/review-continuation-registry.test.ts +76 -0
  239. package/tests/review-controller-native-routing.test.ts +261 -5
  240. package/tests/review-controller-workspace-root.test.ts +230 -3
  241. package/tests/review-controller.test.ts +96 -11
  242. package/tests/review-coordinator-runtime.test.ts +117 -0
  243. package/tests/review-coordinator.test.ts +195 -0
  244. package/tests/review-failure-facts.test.ts +87 -0
  245. package/tests/review-host-relay-routing.test.ts +258 -4
  246. package/tests/review-host-relay.test.ts +39 -0
  247. package/tests/review-integration-v2.test.ts +46 -3
  248. package/tests/review-json-arguments.test.ts +65 -10
  249. package/tests/review-last-event-closure.test.ts +68 -0
  250. package/tests/review-loadout-rdd-off-sdk.test.ts +65 -31
  251. package/tests/review-owner-identity.test.ts +60 -24
  252. package/tests/review-relay-phase-timing.test.ts +128 -0
  253. package/tests/review-relay-transport-agent.test.ts +12 -2
  254. package/tests/review-reviewer-evidence.test.ts +183 -0
  255. package/tests/review-risk-assessment.test.ts +74 -3
  256. package/tests/review-session-standing-permission-controller.test.ts +21 -1
  257. package/tests/review-start-context.test.ts +19 -0
  258. package/tests/review-tool-prose-budget.test.ts +121 -0
  259. package/tests/run-test-suite.test.ts +122 -1
  260. package/tests/runtime-harness.mjs +4 -1
  261. package/tests/sensitive-path-tools.test.ts +181 -5
  262. package/tests/session-profile-append-controller-pi.test.ts +60 -31
  263. package/tests/session-profile-binding.test.ts +19 -1
  264. package/tests/session-profile-disk-reader-pi.test.ts +58 -16
  265. package/tests/session-profile-v1-compat.test.ts +35 -1
  266. package/tests/shell-bar.test.ts +186 -42
  267. package/tests/shell-panel.test.ts +50 -22
  268. package/tests/shell-sidebar-fullscreen.test.ts +5 -5
  269. package/tests/shell-sidebar-layout.test.ts +294 -23
  270. package/tests/shell-sidebar-scroll-benchmark.test.ts +1 -1
  271. package/tests/shell-surface-transparent.test.ts +89 -0
  272. package/tests/shell-todo.test.ts +12 -0
  273. package/tests/skill-registry.test.ts +838 -5
  274. package/tests/startup-banner.test.ts +152 -1
  275. package/tests/startup-home-repo.test.ts +2 -0
  276. package/tests/support/review-coordinator-runtime.ts +69 -0
  277. package/tests/task-size-routing-contract.test.ts +5 -3
  278. package/tests/verifier-admission.test.ts +49 -0
  279. package/tests/verify-first-launch-contract.test.ts +78 -3
  280. package/tests/visual-customization-policy.test.ts +39 -6
  281. package/tests/visual-customize-view.test.ts +573 -9
  282. package/tests/visual-layout-preview.test.ts +15 -1
  283. package/tests/visual-profiles.test.ts +11 -0
  284. package/tests/voice-worker.test.ts +73 -2
  285. package/tests/windows-session-transport.test.ts +126 -0
  286. package/tests/work-continuity-contract.test.ts +28 -0
  287. package/tests/writer-feature-document-admission.test.ts +92 -0
  288. package/tests/yolo-customize.test.ts +27 -4
  289. package/tests/yolo-mode.test.ts +23 -18
  290. package/tests/yolo-session-policy.test.ts +270 -1
@@ -1,4 +1,5 @@
1
1
  import type { ToolResultEvent, ToolResultEventResult } from "@earendil-works/pi-coding-agent";
2
+ import type { OrchestratorMode } from "./agent-profiles.ts";
2
3
 
3
4
  // Harness roadmap R1: the parent-context backstop was a fixed "~150k tokens" in
4
5
  // prompt text, so the model had to estimate its own context. The runtime now
@@ -48,18 +49,26 @@ export function contextBackstopReached(usage: MeasuredContext | undefined, env:
48
49
 
49
50
  const count = (value: number) => Math.round(value).toLocaleString("en-US");
50
51
 
51
- function contextBackstopNotice(tokens: number, contextWindow: number | null | undefined, threshold: number): string {
52
+ function contextBackstopNotice(tokens: number, contextWindow: number | null | undefined, threshold: number, fullDelegation: boolean): string {
52
53
  const share = positive(contextWindow) ? ` (${Math.round((tokens / contextWindow) * 100)}% of the ${count(contextWindow)}-token context window)` : "";
53
- return `Context backstop: the parent context measures ${count(tokens)} tokens${share}, at or past the ${count(threshold)}-token backstop: delegate the next bounded unit that needs several steps (its reads, edits, and checks) with a short handoff, while single small edits and state checks stay inline.`;
54
+ // In full delegation mode no edit stays with the parent, whatever its size, so the
55
+ // organic carve-out for small edits would contradict the session's own rules.
56
+ const tail = fullDelegation
57
+ ? "delegate the next bounded unit with a short handoff, and keep only state checks in this context."
58
+ : "delegate the next bounded unit that needs several steps (its reads, edits, and checks) with a short handoff, while single small edits and state checks stay inline.";
59
+ return `Context backstop: the parent context measures ${count(tokens)} tokens${share}, at or past the ${count(threshold)}-token backstop: ${tail}`;
54
60
  }
55
61
 
56
62
  /**
57
63
  * One notice per crossing for each session: the first measurement at or past the backstop returns it, and a
58
64
  * measurement below the backstop re-arms it (for example after compaction). Unknown tokens change nothing.
59
65
  */
60
- export function createContextBackstopSignal(env: Env = process.env): (session: unknown, usage: MeasuredContext | undefined) => string | undefined {
66
+ export function createContextBackstopSignal(
67
+ env: Env = process.env,
68
+ ): (session: unknown, usage: MeasuredContext | undefined, mode?: () => OrchestratorMode) => string | undefined {
61
69
  const notified = new Set<unknown>();
62
- return (session, usage) => {
70
+ // `mode` is a thunk: it is read only when a notice is emitted, never on every measurement.
71
+ return (session, usage, mode) => {
63
72
  if (typeof usage?.tokens !== "number") return undefined;
64
73
  const threshold = contextBackstopThreshold(usage.contextWindow, env);
65
74
  if (usage.tokens < threshold) {
@@ -68,7 +77,7 @@ export function createContextBackstopSignal(env: Env = process.env): (session: u
68
77
  }
69
78
  if (notified.has(session)) return undefined;
70
79
  notified.add(session);
71
- return contextBackstopNotice(usage.tokens, usage.contextWindow, threshold);
80
+ return contextBackstopNotice(usage.tokens, usage.contextWindow, threshold, mode?.() === "full-delegation");
72
81
  };
73
82
  }
74
83
 
@@ -96,6 +96,39 @@ const DATA_COMMANDS = new Set([
96
96
  "wc", "sort", "uniq", "cut", "tr", "jq", "diff", "ls", "file", "stat",
97
97
  ]);
98
98
  const INERT_COMMANDS = new Set(["cd", "pwd", "true", "false", "test", "[", "mkdir", "touch"]);
99
+ // gentle-shell#1202: read-only subcommands that neither execute nor re-route
100
+ // text. A segment headed by one of these no longer makes the whole line opaque,
101
+ // provided nothing is piped into it and nothing precedes the head (assignments,
102
+ // wrappers) or follows `git` besides `-C <path>` / `--no-pager`. `push` and
103
+ // `rebase` are the guarded operations themselves: they match lexically on their
104
+ // own text and run only their own literal arguments. Every such segment must be
105
+ // free of `$`: a masked data substitution could smuggle in options such as
106
+ // `--receive-pack=` or `-x`.
107
+ const READ_ONLY_GIT = new Set(["status", "log", "diff", "show", "rev-parse", "rev-list", "ls-files", "describe"]);
108
+ const LITERAL_GIT = new Set(["push", "rebase"]);
109
+ const READ_ONLY_GH = new Map([["pr", ["view", "list", "checks", "diff", "status"]], ["issue", ["view", "list", "status"]], ["run", ["view", "list"]]]);
110
+
111
+ /**
112
+ * True when the segment at `cursor` is a top-level, literal `git` or `gh`
113
+ * command that reads only (or a literal push/rebase the YOLO waiver already
114
+ * judges on its own), so it cannot turn a sibling data argument into an action.
115
+ * Piped-into, nested or `$`-bearing segments are never eligible.
116
+ */
117
+ function readOnlyVcsSegment(segment: readonly Token[], cursor: number, pipedInto: boolean, literal: boolean): boolean {
118
+ if (pipedInto || !literal || cursor !== 0) return false;
119
+ const name = segment[0].value;
120
+ if (name !== "git" && name !== "gh") return false;
121
+ if (segment.some((token) => token.value !== token.raw)) return false;
122
+ if (name === "gh") return READ_ONLY_GH.get(segment[1]?.value)?.includes(segment[2]?.value) ?? false;
123
+ let index = 1;
124
+ while (index < segment.length) {
125
+ if (segment[index].value === "--no-pager") index++;
126
+ else if (segment[index].value === "-C" && index + 1 < segment.length) index += 2;
127
+ else break;
128
+ }
129
+ const subcommand = segment[index]?.value;
130
+ return READ_ONLY_GIT.has(subcommand) || LITERAL_GIT.has(subcommand);
131
+ }
99
132
  const HEREDOC_RE = /<<-?\s*(['"]?)([A-Za-z_]\w*)\1[^\n]*\n[\s\S]*?\n\2(?=\n|$)/g;
100
133
 
101
134
  type Ranges = Array<readonly [number, number]>;
@@ -115,7 +148,7 @@ function maskDataSubstitutions(command: string): { masked: string; ranges: Range
115
148
  const ranges: Ranges = [];
116
149
  let opaque = false;
117
150
  const masked = command.replace(SIMPLE_SUBSTITUTION_RE, (raw: string, body: string, offset: number) => {
118
- const inner = dataRanges(body);
151
+ const inner = dataRanges(body, true);
119
152
  if (inner === undefined) opaque = true;
120
153
  else ranges.push(...inner.map(([from, to]) => [offset + 2 + from, offset + 2 + to] as const));
121
154
  return "_".repeat(raw.length);
@@ -136,8 +169,12 @@ export function dataArgumentRanges(command: string): Ranges {
136
169
  return dataRanges(command) ?? [];
137
170
  }
138
171
 
139
- /** Undefined means opaque; an empty list means only inert commands. */
140
- function dataRanges(original: string): Ranges | undefined {
172
+ /**
173
+ * Undefined means opaque; an empty list means only inert commands. A nested
174
+ * (substitution) body admits data and inert commands only: its output is text
175
+ * that can run, so an ordinary git or gh segment inside it proves nothing.
176
+ */
177
+ function dataRanges(original: string, nested = false): Ranges | undefined {
141
178
  const substitutions = maskDataSubstitutions(original);
142
179
  if (substitutions === undefined) return undefined;
143
180
  const command = substitutions.masked;
@@ -172,7 +209,14 @@ function dataRanges(original: string): Ranges | undefined {
172
209
  if (head === undefined || head.value !== head.raw) return undefined;
173
210
  const name = head.value;
174
211
  if (INERT_COMMANDS.has(name)) continue;
175
- if (!DATA_COMMANDS.has(name)) return undefined;
212
+ if (!DATA_COMMANDS.has(name)) {
213
+ // Output of an earlier segment may be piped into this one, also across
214
+ // blank segments (`|` then newline, `|&`).
215
+ let pipedInto = false;
216
+ for (let back = end - segment.length - 1; back >= 0 && tokens[back].operator; back--) pipedInto ||= tokens[back].raw === "|";
217
+ if (!nested && readOnlyVcsSegment(segment, cursor, pipedInto, !original.slice(segment[0].index, segment.at(-1)!.index + segment.at(-1)!.raw.length).includes("$"))) continue;
218
+ return undefined;
219
+ }
176
220
  ranges.push([head.index + head.raw.length, tokens[end]?.index ?? command.length]);
177
221
  }
178
222
  // A heredoc body belongs to the segment of its `<<` header, which the
@@ -0,0 +1,20 @@
1
+ import type { ToolCallEventResult } from "@earendil-works/pi-coding-agent";
2
+
3
+ // gentle-shell#379: delegated work stays in the current runtime. A tool call
4
+ // that asks to open an external project pane is classified by its own input
5
+ // property, never by the tool name, and is blocked in every mode and in
6
+ // children. A value that is not a boolean fails closed. The reason carries
7
+ // fixed fields only, never input paths or content.
8
+
9
+ export const EXTERNAL_FALLBACK_PROHIBITED = "gentle-ai.execution-surface.external-fallback-prohibited";
10
+
11
+ const PANE_PROPERTY = "openProjectPaneIfMissing";
12
+
13
+ export function evaluateExecutionSurfaceTool(toolName: string, input: unknown): ToolCallEventResult | undefined {
14
+ if (typeof input !== "object" || input === null || !Object.hasOwn(input, PANE_PROPERTY)) return undefined;
15
+ if ((input as Record<string, unknown>)[PANE_PROPERTY] === false) return undefined;
16
+ return {
17
+ block: true,
18
+ reason: `Gentle AI blocked an execution-surface escalation. code=${EXTERNAL_FALLBACK_PROHIBITED} tool=${toolName} property=${PANE_PROPERTY} next=Run the work through subagent_* or the native Agent in the current runtime; if neither is available, stop and tell the user.`,
19
+ };
20
+ }
@@ -1,4 +1,5 @@
1
1
  import type { ToolResultEvent } from "@earendil-works/pi-coding-agent";
2
+ import type { OrchestratorMode } from "./agent-profiles.ts";
2
3
  import { inferOddPhase } from "./odd-phase-inference.ts";
3
4
 
4
5
  // Explicit discovery tools; existing shell inference below is advisory, never authorization.
@@ -32,7 +33,8 @@ export function createExplorationBudget() {
32
33
  const request = requests.get(session);
33
34
  if (request && !request.seen.has(id)) request.pending.set(id, { toolName, parentToolCallId });
34
35
  },
35
- result(session: unknown, event: DiscoveryResult, primary = true, aborted = false): string | undefined {
36
+ // `mode` is a thunk: it is read only when the notice is emitted, never per tool result.
37
+ result(session: unknown, event: DiscoveryResult, primary = true, aborted = false, mode?: () => OrchestratorMode): string | undefined {
36
38
  const request = requests.get(session);
37
39
  const call = request?.pending.get(event.toolCallId);
38
40
  if (!request || !call) return undefined;
@@ -51,7 +53,7 @@ export function createExplorationBudget() {
51
53
  }
52
54
  if (request.notified || (request.lookups <= 3 && request.bytes <= 40_000)) return undefined;
53
55
  request.notified = true;
54
- return `Exploration budget: ${request.lookups.toLocaleString("en-US")} tracked lookups and ${request.bytes.toLocaleString("en-US")} UTF-8 text bytes (an approximate evidence budget). Ongoing discovery needs one configured explorer, even if read-only or initially small. Preparation for an already-understood authorized inline write remains exempt. This is runtime context for the original task, not a new user request. This notice grants no mutation or guard bypass authority.`;
56
+ return `Exploration budget: ${request.lookups.toLocaleString("en-US")} tracked lookups and ${request.bytes.toLocaleString("en-US")} UTF-8 text bytes (an approximate evidence budget). Ongoing discovery needs one configured explorer, even if read-only or initially small. ${mode?.() === "full-delegation" ? "Reading that prepares a writer belongs in that writer's prompt." : "Preparation for an already-understood authorized inline write remains exempt."} This is runtime context for the original task, not a new user request. This notice grants no mutation or guard bypass authority.`;
55
57
  },
56
58
  facts(session: unknown): { lookups: number; textBytes: number } | undefined {
57
59
  const request = requests.get(session);
@@ -382,7 +382,7 @@ function binaryIdentity(path: string): string {
382
382
  return [details.dev, details.ino, details.size, details.mtimeNs, details.ctimeNs].join(":");
383
383
  }
384
384
 
385
- function binaryDigest(path: string, readBinary: (path: string) => Buffer): string {
385
+ export function binaryDigest(path: string, readBinary: (path: string) => Buffer = readFileSync): string {
386
386
  let entries = binaryDigestCache.get(readBinary);
387
387
  if (entries === undefined) binaryDigestCache.set(readBinary, entries = new Map());
388
388
  const identity = binaryIdentity(path);
@@ -10,6 +10,8 @@ import { detectDesignSources, staleDesignSources } from "./design-sources.ts";
10
10
  // open/stop drive, and the comments tool. The extension stays a thin wrapper.
11
11
 
12
12
  export const DESIGN_SKILL_NAME = "gentle-design";
13
+ /** Paired with every design request: gentle-design owns delivery, this skill owns UX quality. */
14
+ export const UI_DESIGN_SKILL_NAME = "gentle-ui-design";
13
15
 
14
16
  export const DESIGN_SUBCOMMANDS = ["open", "stop", "sync", "implement"] as const;
15
17
  export type DesignSubcommand = (typeof DESIGN_SUBCOMMANDS)[number];
@@ -365,6 +367,7 @@ export const DESIGN_TOOL_NAME = "gentle_design";
365
367
  /** Appended to the system prompt while the gentle-design skill is available (S11). */
366
368
  export const DESIGN_PROMPT_HINT = [
367
369
  `Gentle Design: any request for a UI design, mockup, screen, landing page or visual directions uses the ${DESIGN_SKILL_NAME} skill by default; read the skill first when it is not loaded.`,
370
+ `Pair it with the ${UI_DESIGN_SKILL_NAME} skill for UX quality: read that skill and only the references relevant to the brief before choosing directions.`,
368
371
  `Before designing, call the ${DESIGN_TOOL_NAME} tool (action "list"); when the project has design sources but no design/system.md, run the skill's design system sync first.`,
369
372
  `After writing or changing a design, open or refresh it on the canvas with the ${DESIGN_TOOL_NAME} tool (action "open" with the slug), unless the user said not to.`,
370
373
  "Designs stay under design/<slug>/.",
@@ -266,8 +266,8 @@ export function bundledPi(install: BundledInstall, input: { platform: string; fs
266
266
  // given explicitly, and its npm through the home's npmCommand setting), plus
267
267
  // only no Pi override, subagents on the same node and Pi (the subagent runner
268
268
  // splits GENTLE_PI_AGENTS_PI on whitespace, so a spaced path is left to its
269
- // default, the running node and cli.js), and no Pi update check, since Pi only
270
- // updates with Gentle Shell (S5). S9: the prefix (GENTLE_SHELL_PREFIX, from
269
+ // default, the running node and cli.js), and no separate Pi update check, since
270
+ // Shell handles Pi updates. S9: the prefix (GENTLE_SHELL_PREFIX, from
271
271
  // which gentle-pi derives its config folder and gives its own gentle-ai runs
272
272
  // Gentle AI's variables, never set here because the agent's shell would pass
273
273
  // them to a gentle-ai the user runs), and the published Engram as
@@ -275,7 +275,7 @@ export function bundledPi(install: BundledInstall, input: { platform: string; fs
275
275
  // (S2, S6): the startup policy, and ENGRAM_BIN is the Shell-owned guard, so no
276
276
  // provider, whatever loaded it, runs an Engram binary against a store; allowed
277
277
  // memory reaches the shared server through ENGRAM_URL only.
278
- export const ENGRAM_COMPANION_SOURCE = "npm:gentle-engram@0.4.2";
278
+ export const ENGRAM_COMPANION_SOURCE = "npm:gentle-engram";
279
279
  export const ENGRAM_RECOVERY_NOTICE = "Engram memory disabled: Shell could not verify safe server reuse. Matching versions or updating alone do not prove compatibility. Reuse requires a server on 127.0.0.1:7437 with verified /compatibility evidence; Shell never stops or replaces a server already listening there. Back up existing Engram data before manual changes; do not delete it or bypass the safety check. Shell rechecks on every launch and remains usable without memory.";
280
280
  export const ENGRAM_START_FAILED_NOTICE = "Engram memory disabled for this launch: Shell could not start the shared Engram server, or it did not report ready in time. Restart Shell to retry; if another program holds 127.0.0.1:7437, stop it first. Shell remains usable without memory.";
281
281
  export const ENGRAM_NEWER_SCHEMA_NOTICE = "Engram memory disabled: ~/.engram was migrated by a newer Engram than Shell's bundled core, so Shell will not start a server on it. Start that newer Engram's server yourself (engram serve); Shell reuses a running server with verified /compatibility evidence. Back up the store; do not delete or downgrade it. Shell remains usable without memory.";
@@ -613,29 +613,16 @@ export function bundledUpdatePlan(passthrough: string[]): BundledUpdatePlan {
613
613
  return { self: true, ...marked };
614
614
  }
615
615
 
616
- // What `gentle-shell update` does after the redirected upgrade or the
617
- // `--latest` Pi update (`upgradeCode` is undefined when it did not run): with
618
- // nothing left for Pi it exits with that code; otherwise Pi still runs, so
619
- // `update --all` updates the extensions even when that step could not complete.
616
+ // Forward extension updates even when the latest Pi update failed; the caller
617
+ // retains that failure code while Pi handles the remaining arguments.
620
618
  export function bundledUpdateNext(plan: BundledUpdatePlan, upgradeCode: number | undefined): { exitCode: number } | { piArgs: string[]; note?: string } {
621
619
  if (plan.piArgs === undefined) return { exitCode: upgradeCode ?? 0 };
622
620
  if (plan.self && upgradeCode !== undefined && upgradeCode !== 0) {
623
- const step = plan.latest ? "latest Pi update" : "Gentle Shell upgrade";
624
- return { piArgs: plan.piArgs, note: `gentle-shell: the ${step} did not complete; updating the extensions anyway.` };
621
+ return { piArgs: plan.piArgs, note: "gentle-shell: the latest Pi update did not complete; updating the extensions anyway." };
625
622
  }
626
623
  return { piArgs: plan.piArgs };
627
624
  }
628
625
 
629
- export function bundledUpdateNotice(input: { piVersion: string; interactive: boolean }): string[] {
630
- return [
631
- `Pi ships pinned with Gentle Shell (Pi ${input.piVersion}): a newer Pi arrives with a Gentle Shell release.`,
632
- input.interactive
633
- ? "Running 'gentle-shell upgrade'..."
634
- : "Run 'gentle-shell upgrade' to install the latest Gentle Shell release and its Pi.",
635
- "Run 'gentle-shell update --latest' to install the newest published Pi now, without the release's verified lockfile.",
636
- ];
637
- }
638
-
639
626
  export type BundledUpgradeAction = { action: "upgrade" } | { action: "rollback" } | { error: string; usage: boolean };
640
627
 
641
628
  export const BUNDLED_UPGRADE_USAGE = "usage: gentle-shell upgrade [--channel release] | gentle-shell upgrade --rollback";
@@ -222,6 +222,32 @@ export function userPiHome(env: Record<string, string | undefined>, homedir: str
222
222
  return env[USER_PI_HOME_ENV] || linkDir(env, homedir);
223
223
  }
224
224
 
225
+ // Nobody can see or type into an editor git opens from Pi's bash tool, so
226
+ // `git rebase --continue` or a bare `git commit` would wait on it forever.
227
+ // `true` makes git keep the prepared message (or abort an empty one) instead.
228
+ // A value the user already set is kept; on Windows env names ignore case, so a
229
+ // user's `git_editor` counts too.
230
+ export const NON_INTERACTIVE_GIT_ENV = { GIT_EDITOR: "true", GIT_SEQUENCE_EDITOR: "true" } as const;
231
+
232
+ export function nonInteractiveGitEnv(env: Record<string, string | undefined>, platform: string = process.platform): Record<string, string> {
233
+ const isSet = (key: string) => platform === "win32"
234
+ ? Object.entries(env).some(([name, value]) => value !== undefined && name.toUpperCase() === key)
235
+ : env[key] !== undefined;
236
+ return Object.fromEntries(Object.entries(NON_INTERACTIVE_GIT_ENV).filter(([key]) => !isSet(key)));
237
+ }
238
+
239
+ // On Windows, Node keeps only the first of a set of case variants (in sorted
240
+ // order) and then skips it if it is undefined, so `{ GIT_EDITOR: undefined,
241
+ // git_editor: "vim" }` would reach the child with neither. Drop the undefined
242
+ // variants so the defined one is what gets spawned.
243
+ export function dropUndefinedCaseVariants(env: Record<string, string | undefined>, platform: string = process.platform): void {
244
+ if (platform !== "win32") return;
245
+ const defined = new Set(Object.entries(env).filter(([, value]) => value !== undefined).map(([name]) => name.toUpperCase()));
246
+ for (const [name, value] of Object.entries(env)) {
247
+ if (value === undefined && defined.has(name.toUpperCase())) delete env[name];
248
+ }
249
+ }
250
+
225
251
  export function isolatedDir(env: Record<string, string | undefined>, homedir: string): string {
226
252
  return env.GENTLE_SHELL_HOME || join(homedir, ".gentle-shell", "agent");
227
253
  }
@@ -454,11 +480,16 @@ export interface PiRuntime {
454
480
  kind: PiRuntimeKind;
455
481
  command: string;
456
482
  args: string[];
483
+ // Only ever set for kind "bundled": the adjacent peer's and the
484
+ // gentle-shell-managed install's version both come from a package.json
485
+ // already read into memory, so main() can run checkPiVersion(runtime.version)
486
+ // without spawning a process just to print it back (#2096).
487
+ version?: string;
457
488
  }
458
489
 
459
490
  export interface PiRuntimeDeps {
460
491
  env: Record<string, string | undefined>;
461
- resolveBundledCli: () => string | undefined;
492
+ resolveBundledCli: () => { path: string; version: string } | undefined;
462
493
  findOnPath: (name: string) => string | undefined;
463
494
  nodeExecPath: string;
464
495
  }
@@ -467,8 +498,8 @@ export function resolvePiRuntime(deps: PiRuntimeDeps): PiRuntime | undefined {
467
498
  const envOverride = deps.env.GENTLE_SHELL_PI;
468
499
  if (envOverride !== undefined && envOverride.length > 0) return { kind: "env", command: envOverride, args: [] };
469
500
 
470
- const bundledCliPath = deps.resolveBundledCli();
471
- if (bundledCliPath !== undefined) return { kind: "bundled", command: deps.nodeExecPath, args: [bundledCliPath] };
501
+ const bundledCli = deps.resolveBundledCli();
502
+ if (bundledCli !== undefined) return { kind: "bundled", command: deps.nodeExecPath, args: [bundledCli.path], version: bundledCli.version };
472
503
 
473
504
  const onPath = deps.findOnPath("pi");
474
505
  if (onPath !== undefined) return { kind: "path", command: onPath, args: [] };
@@ -988,6 +1019,8 @@ export interface BuildPiInvocationInput {
988
1019
  // gentle-pi extension injection below may precede it.
989
1020
  piSubcommand?: PiSubcommand;
990
1021
  baseEnv: Record<string, string | undefined>;
1022
+ // Defaults to process.platform; decides whether env names ignore case.
1023
+ platform?: string;
991
1024
  // A bundled launch: its gentle-pi keeps its config in the prefix, so Pi gets
992
1025
  // no standalone config marker (standaloneConfigHome).
993
1026
  bundled?: boolean;
@@ -1085,6 +1118,7 @@ export function buildPiInvocation(input: BuildPiInvocationInput): PiInvocation {
1085
1118
 
1086
1119
  const env: Record<string, string | undefined> = {
1087
1120
  ...input.baseEnv,
1121
+ ...nonInteractiveGitEnv(input.baseEnv, input.platform),
1088
1122
  PI_CODING_AGENT_DIR: input.home.dir,
1089
1123
  PI_PROGRAM_STATUS_APP: "gentle-shell",
1090
1124
  GENTLE_PI_AGENT_HOME: input.home.dir,
@@ -1098,6 +1132,7 @@ export function buildPiInvocation(input: BuildPiInvocationInput): PiInvocation {
1098
1132
  else env[GENTLE_SHELL_CONFIG_HOME_ENV] = configHome;
1099
1133
  if (childInjection === undefined) delete env[CHILD_PACKAGE_INJECTION_ENV];
1100
1134
  else env[CHILD_PACKAGE_INJECTION_ENV] = encodeChildPackageInjection(childInjection);
1135
+ dropUndefinedCaseVariants(env, input.platform);
1101
1136
 
1102
1137
  return { command: input.runtime.command, args, env };
1103
1138
  }
@@ -1352,11 +1387,11 @@ export function helpText(): string {
1352
1387
  " gentle-shell install npm:<pkg> Run pi's own 'install' against the resolved home.",
1353
1388
  " gentle-shell remove <source> Run pi's own 'remove' against the resolved home.",
1354
1389
  " gentle-shell list Run pi's own 'list' against the resolved home.",
1355
- " gentle-shell update [target] Run pi's own 'update' against the resolved home.",
1356
- " In a bundled install Pi ships pinned: 'update' without a package",
1357
- " runs 'gentle-shell upgrade' instead of updating Pi.",
1358
- " 'update --latest' installs the newest published Pi instead,",
1359
- " without the release's verified lockfile.",
1390
+ " gentle-shell update [target] Update Pi through its supported owner, or packages in the resolved home.",
1391
+ " In a bundled install 'update' installs the newest stable Pi",
1392
+ " without the release's verified lockfile; --latest is an alias.",
1393
+ " --all also updates extensions; explicit package pins remain pinned.",
1394
+ " --force is not supported for managed Pi self updates.",
1360
1395
  " gentle-shell config Run pi's own 'config' against the resolved home.",
1361
1396
  " gentle-shell auth <command> Run pi's own 'auth' against the resolved home.",
1362
1397
  " gentle-shell mcp <command> Run pi's own 'mcp' (add, list, login, logout) against the",
@@ -66,8 +66,7 @@ function fit(parts: string[], columns: number, bytes: number, characters: number
66
66
  return count;
67
67
  }
68
68
 
69
- /** Only the active Todo title is free text. LF is private framing, not a token. */
70
- export function activitySummary(tasks: unknown, columns = FALLBACK_COLUMNS): string | null {
69
+ function activeTodo(tasks: unknown): { parts: string[]; clipped: boolean } | null {
71
70
  if (!Array.isArray(tasks)) return null;
72
71
  const title: unknown = tasks.find((task) => task?.status === "in_progress")?.title;
73
72
  if (typeof title !== "string") return null;
@@ -82,6 +81,19 @@ export function activitySummary(tasks: unknown, columns = FALLBACK_COLUMNS): str
82
81
  const parts = Array.from(graphemes.segment(clean), ({ segment }) => segment);
83
82
  // The bounded sample may end inside a grapheme; never publish that fragment.
84
83
  if (clipped) parts.pop();
84
+ return { parts, clipped };
85
+ }
86
+
87
+ /** Sanitized active title, without Herdr icons, rows or ellipsis layout. */
88
+ export function activeTodoTitle(tasks: unknown): string | null {
89
+ return activeTodo(tasks)?.parts.join("") || null;
90
+ }
91
+
92
+ /** Only the active Todo title is free text. LF is private framing, not a token. */
93
+ export function activitySummary(tasks: unknown, columns = FALLBACK_COLUMNS): string | null {
94
+ const active = activeTodo(tasks);
95
+ if (!active) return null;
96
+ const { parts, clipped } = active;
85
97
  columns = Number.isFinite(columns) ? Math.max(1, Math.min(512, Math.floor(columns))) : FALLBACK_COLUMNS;
86
98
  if (columns <= 2) return columns === 1 ? "…" : "◐…";
87
99
  // Herdr caps each token at 80 scalars; count our icon/indent before its trim.
@@ -0,0 +1,45 @@
1
+ import { FINISHED_STATUSES } from "./agents-protocol.ts";
2
+
3
+ // gentle-shell#626: the herdr pane must stay busy while owned background
4
+ // subagents run, even after the parent itself settles. This module is the
5
+ // pure, edge-triggered projection the extension feeds on every summary
6
+ // notification; it mirrors pi-subagents' herdr producer exactly: raise once,
7
+ // dedup an unchanged label, relabel as lower-then-raise in one synchronous
8
+ // step, lower once. Labels are content-free and derived from counts only.
9
+
10
+ export const HERDR_BUSY_CHANNEL = "herdr:busy";
11
+
12
+ /** What the extension last emitted on the channel, or nothing yet. */
13
+ export type HerdrBusyEmitted = { active: true; label: string } | { active: false } | undefined;
14
+
15
+ export type HerdrBusyAction =
16
+ | { kind: "none" }
17
+ | { kind: "raise"; label: string }
18
+ | { kind: "lower-then-raise"; label: string }
19
+ | { kind: "lower" };
20
+
21
+ const finishedStatuses: ReadonlySet<string> = new Set<string>(FINISHED_STATUSES);
22
+
23
+ export function herdrBusyLabel(count: number): string {
24
+ return count === 1 ? "1 subagent running" : `${count} subagents running`;
25
+ }
26
+
27
+ // Fails closed: malformed task input is a no-op, and a malformed previously
28
+ // emitted state is simply "not busy". Never throws.
29
+ export function nextHerdrBusyAction(tasks: unknown, emitted: unknown): HerdrBusyAction {
30
+ if (!Array.isArray(tasks)) return { kind: "none" };
31
+ let running = 0;
32
+ for (const task of tasks) {
33
+ if (task === null || typeof task !== "object" || typeof (task as { status?: unknown }).status !== "string") return { kind: "none" };
34
+ if (!finishedStatuses.has((task as { status: string }).status)) running += 1;
35
+ }
36
+ const emittedLabel = typeof emitted === "object" && emitted !== null
37
+ && (emitted as { active?: unknown }).active === true
38
+ && typeof (emitted as { label?: unknown }).label === "string"
39
+ ? (emitted as { label: string }).label
40
+ : undefined;
41
+ if (running === 0) return emittedLabel === undefined ? { kind: "none" } : { kind: "lower" };
42
+ const label = herdrBusyLabel(running);
43
+ if (label === emittedLabel) return { kind: "none" };
44
+ return emittedLabel === undefined ? { kind: "raise", label } : { kind: "lower-then-raise", label };
45
+ }
@@ -1,6 +1,7 @@
1
1
  import type { ImageContent } from "@earendil-works/pi-ai";
2
2
  import { getImageDimensions, type ImageDimensions } from "@earendil-works/pi-tui";
3
3
  import type { ClipboardImage } from "./clipboard-image.ts";
4
+ import type { ImageDiskCache } from "./image-disk-cache.ts";
4
5
 
5
6
  // Pasted images live in the draft as atomic `[Image#N]` chips (gentle-shell#2464).
6
7
  // The bytes stay in memory: a chip deleted from the draft is never sent, and
@@ -20,6 +21,8 @@ export interface ImageAttachment {
20
21
  byteLength: number;
21
22
  base64: string;
22
23
  dimensions?: ImageDimensions;
24
+ /** Present only when a disk cache was supplied; never injected into the prompt. */
25
+ diskPath?: string;
23
26
  }
24
27
 
25
28
  export interface SubmittedImages {
@@ -42,6 +45,35 @@ export class ImageAttachments {
42
45
  // Never reset: Pi's prompt history keeps the raw submitted text, so a
43
46
  // reused id would let a recalled `[Image#1]` bind to a different image.
44
47
  private counter = 0;
48
+ private cache?: ImageDiskCache;
49
+
50
+ /** Attach or drop the disk cache at runtime (session start and shutdown). */
51
+ setCache(cache?: ImageDiskCache): void {
52
+ this.cache = cache;
53
+ }
54
+
55
+ /** Cached files for the chips still in the draft; empty when no cache is active. */
56
+ cachedPaths(draftText?: string): Array<{ token: string; path: string }> {
57
+ const inDraft = draftText === undefined ? undefined : new Set(this.referenced(draftText).map((entry) => entry.id));
58
+ return [...this.entries.values()].flatMap((entry) =>
59
+ entry.diskPath && (inDraft === undefined || inDraft.has(entry.id)) ? [{ token: entry.token, path: entry.diskPath }] : [],
60
+ );
61
+ }
62
+
63
+ /**
64
+ * An optional disk cache. Without one the class behaves exactly as before:
65
+ * bytes stay in memory and no path exists. With one, each added image also
66
+ * gets a private file the agent's tools can read; the path never enters the
67
+ * prompt, the base64 payload stays the source of truth for submission.
68
+ */
69
+ constructor(cache?: ImageDiskCache) {
70
+ this.cache = cache;
71
+ }
72
+
73
+ /** Drop the session's cached files. Safe to call when no cache was given. */
74
+ dispose(): void {
75
+ this.cache?.dispose();
76
+ }
45
77
 
46
78
  get size(): number { return this.entries.size; }
47
79
 
@@ -57,6 +89,7 @@ export class ImageAttachments {
57
89
  byteLength: image.bytes.length,
58
90
  base64,
59
91
  dimensions: getImageDimensions(base64, image.mimeType) ?? undefined,
92
+ diskPath: this.cache?.write(id, image.bytes, image.mimeType),
60
93
  };
61
94
  this.entries.set(id, attachment);
62
95
  return attachment;
@@ -0,0 +1,137 @@
1
+ import { mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { isAbsolute, basename, join } from "node:path";
4
+
5
+ // Pasted images normally live only in memory (see lib/image-attachments.ts).
6
+ // This module is the opt-in disk cache: it gives tools that need a filesystem
7
+ // path somewhere to look, without ever putting a path in the prompt.
8
+ //
9
+ // Privacy contract:
10
+ // - the directory is per session and private (0700), every file is 0600;
11
+ // - the whole session directory is removed on shutdown;
12
+ // - a startup sweep removes session directories left behind by a crash.
13
+ // Nothing here is on by default: the caller decides whether to build a cache.
14
+
15
+ const EXT_BY_MIME: Record<string, string> = {
16
+ "image/png": "png",
17
+ "image/jpeg": "jpg",
18
+ "image/webp": "webp",
19
+ "image/gif": "gif",
20
+ };
21
+
22
+ /** Files this cache owns. The sweep only ever touches directories holding them. */
23
+ const OWN_FILE = /^image-\d+\.(png|jpg|webp|gif)$/;
24
+
25
+ /** `${XDG_CACHE_HOME:-~/.cache}/gentle-shell/images`, where sessions are created. */
26
+ export function defaultCacheRoot(env: NodeJS.ProcessEnv = process.env, home = homedir()): string {
27
+ const xdg = env.XDG_CACHE_HOME;
28
+ // XDG says a relative value must be ignored: a cache path that depends on the
29
+ // working directory cannot be handed to a tool as an absolute file path.
30
+ const base = xdg && xdg.trim() && isAbsolute(xdg) ? xdg : join(home, ".cache");
31
+ return join(base, "gentle-shell", "images");
32
+ }
33
+
34
+ /**
35
+ * Reduce a session id to one path segment. Taking the last segment first means
36
+ * a crafted id such as `../../etc` lands inside the root instead of above it.
37
+ */
38
+ function safeSegment(id: string): string {
39
+ const last = id.split(/[\\/]/).filter((part) => part.length > 0 && part !== "." && part !== "..").pop();
40
+ const cleaned = (last ?? "").replace(/[^A-Za-z0-9._-]/g, "_").replace(/^\.+/, "");
41
+ return cleaned.length > 0 ? cleaned : "session";
42
+ }
43
+
44
+ export interface ImageDiskCacheOptions {
45
+ root?: string;
46
+ sessionId: string;
47
+ }
48
+
49
+ export class ImageDiskCache {
50
+ readonly directory: string;
51
+
52
+ constructor(options: ImageDiskCacheOptions) {
53
+ const root = options.root ?? defaultCacheRoot();
54
+ this.directory = join(root, safeSegment(options.sessionId));
55
+ try {
56
+ mkdirSync(this.directory, { recursive: true, mode: 0o700 });
57
+ } catch {
58
+ // A cache that cannot be created is a cache that does nothing.
59
+ }
60
+ }
61
+
62
+ /** Write one image, returning its path, or undefined when the disk refuses. */
63
+ write(id: number, bytes: Uint8Array, mimeType: string): string | undefined {
64
+ const extension = EXT_BY_MIME[mimeType];
65
+ if (!extension) return undefined;
66
+ try {
67
+ const path = join(this.directory, `image-${id}.${extension}`);
68
+ writeFileSync(path, bytes, { mode: 0o600 });
69
+ return path;
70
+ } catch {
71
+ return undefined;
72
+ }
73
+ }
74
+
75
+ /** Remove this session's directory; other sessions are never touched. */
76
+ dispose(): void {
77
+ try {
78
+ rmSync(this.directory, { recursive: true, force: true });
79
+ } catch {
80
+ // Nothing to do: the next sweep will try again.
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Remove session directories whose own files are all older than `maxAgeMs`.
86
+ * Directories without this cache's files are left alone, so a wrong root
87
+ * cannot delete somebody else's data. Returns how many were removed.
88
+ */
89
+ static sweepStale(root: string, maxAgeMs: number, now = Date.now()): number {
90
+ let entries: string[];
91
+ try {
92
+ entries = readdirSync(root);
93
+ } catch {
94
+ return 0;
95
+ }
96
+
97
+ let removed = 0;
98
+ for (const entry of entries) {
99
+ const directory = join(root, entry);
100
+ let all: string[];
101
+ try {
102
+ if (!statSync(directory).isDirectory()) continue;
103
+ all = readdirSync(directory);
104
+ } catch {
105
+ continue;
106
+ }
107
+ const files = all.filter((file) => OWN_FILE.test(file));
108
+ if (files.length === 0) continue; // not ours
109
+ // A directory holding anything this cache did not write is somebody
110
+ // else's too, so the sweep leaves it alone.
111
+ if (files.length !== all.length) continue;
112
+
113
+ let newest = 0;
114
+ for (const file of files) {
115
+ try {
116
+ newest = Math.max(newest, statSync(join(directory, file)).mtimeMs);
117
+ } catch {
118
+ // a file that vanished cannot keep the directory alive
119
+ }
120
+ }
121
+ if (now - newest <= maxAgeMs) continue;
122
+
123
+ try {
124
+ rmSync(directory, { recursive: true, force: true });
125
+ removed += 1;
126
+ } catch {
127
+ // leave it for the next sweep
128
+ }
129
+ }
130
+ return removed;
131
+ }
132
+ }
133
+
134
+ /** `image-<id>.<ext>`, exported for callers that need to recognise a cached file. */
135
+ export function isCachedImageFile(name: string): boolean {
136
+ return OWN_FILE.test(basename(name));
137
+ }