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
@@ -22,11 +22,35 @@ export const PROFILES_VERSION = 1;
22
22
  export const PROFILE_EXPORT_KIND = "gentle-pi.agent_model_profile";
23
23
  export const PROFILE_EXPORT_VERSION = 1;
24
24
 
25
+ // The orchestrator workflow a profile opts into (full-delegation-mode S1).
26
+ //
27
+ // This deliberately does NOT live inside a profile's routing map. A profile's
28
+ // value is an `AgentModelConfig` — `Record<string, AgentRoutingEntry>` — and
29
+ // `normalizeModelConfig` drops every key that is not a routing entry, reporting
30
+ // it as a broken role. A nested `workflow` key would therefore be destroyed on
31
+ // the first read of `<configHome>/profiles.json`, so the flag travels in a
32
+ // sibling map keyed by profile name instead: same profile, same file, same
33
+ // live-switch semantics, unchanged routing contract.
34
+ export const ORCHESTRATOR_MODES = ["organic", "full-delegation"] as const;
35
+ export type OrchestratorMode = (typeof ORCHESTRATOR_MODES)[number];
36
+ /** Today's behaviour: the orchestrator may implement inline under the usual rules. */
37
+ export const DEFAULT_ORCHESTRATOR_MODE: OrchestratorMode = "organic";
38
+
39
+ export interface ProfileWorkflow {
40
+ orchestratorMode: OrchestratorMode;
41
+ }
42
+
25
43
  export interface AgentProfilesFile {
26
44
  kind: typeof PROFILES_KIND;
27
45
  version: typeof PROFILES_VERSION;
28
46
  active?: string;
29
47
  profiles: Record<string, AgentModelConfig>;
48
+ /** Per-profile workflow opt-ins; absent means every profile is organic. */
49
+ workflow?: Record<string, ProfileWorkflow>;
50
+ }
51
+
52
+ export function isOrchestratorMode(value: unknown): value is OrchestratorMode {
53
+ return typeof value === "string" && (ORCHESTRATOR_MODES as readonly string[]).includes(value);
30
54
  }
31
55
 
32
56
  export type AgentProfileErrorCode =
@@ -103,6 +127,12 @@ export interface ProfilesParseDrops {
103
127
  droppedAgents: Array<{ profile: string; agent: string }>;
104
128
  /** An `active` marker that did not name a normalized profile, when present. */
105
129
  droppedActive?: string;
130
+ /**
131
+ * Workflow modes that named an unknown profile or an unknown mode, when any.
132
+ * Optional so the existing drops shape stays compatible for callers and tests
133
+ * that assert it without a workflow map.
134
+ */
135
+ droppedWorkflow?: Array<{ profile: string; mode: string }>;
106
136
  }
107
137
 
108
138
  export interface NormalizedProfilesFile {
@@ -165,7 +195,49 @@ export function normalizeProfilesFile(value: unknown): NormalizedProfilesFile |
165
195
  typeof value.active === "string" ? value.active : JSON.stringify(value.active);
166
196
  }
167
197
  }
168
- return { file: { kind: PROFILES_KIND, version: PROFILES_VERSION, active, profiles }, drops };
198
+ const workflow = normalizeWorkflowMap(value.workflow, profiles, drops);
199
+ return {
200
+ file: {
201
+ kind: PROFILES_KIND,
202
+ version: PROFILES_VERSION,
203
+ active,
204
+ profiles,
205
+ ...(workflow === undefined ? {} : { workflow }),
206
+ },
207
+ drops,
208
+ };
209
+ }
210
+
211
+ /**
212
+ * Keeps only workflow opt-ins that name a surviving profile and a declared
213
+ * mode. Anything else is reported through `drops.droppedWorkflow` instead of
214
+ * being honoured or silently erased (full-delegation-mode S6).
215
+ */
216
+ function normalizeWorkflowMap(
217
+ value: unknown,
218
+ profiles: Record<string, AgentModelConfig>,
219
+ drops: ProfilesParseDrops,
220
+ ): Record<string, ProfileWorkflow> | undefined {
221
+ if (value === undefined) return undefined;
222
+ if (!isRecord(value)) return undefined;
223
+ const workflow: Record<string, ProfileWorkflow> = {};
224
+ const dropped: Array<{ profile: string; mode: string }> = [];
225
+ for (const [name, rawEntry] of Object.entries(value)) {
226
+ const rawMode = isRecord(rawEntry) ? rawEntry.orchestratorMode : undefined;
227
+ const described = rawMode === undefined ? JSON.stringify(rawEntry ?? null) : String(rawMode);
228
+ if (!hasOwn(profiles, name) || !isOrchestratorMode(rawMode)) {
229
+ dropped.push({ profile: name, mode: described });
230
+ continue;
231
+ }
232
+ workflow[name] = { orchestratorMode: rawMode };
233
+ }
234
+ if (dropped.length > 0) drops.droppedWorkflow = dropped;
235
+ // An all-organic map carries no information: keep the file identical to the
236
+ // pre-change shape so an opted-out file never grows a `workflow` key.
237
+ const meaningful = Object.fromEntries(
238
+ Object.entries(workflow).filter(([, entry]) => entry.orchestratorMode !== DEFAULT_ORCHESTRATOR_MODE),
239
+ );
240
+ return Object.keys(meaningful).length === 0 ? undefined : meaningful;
169
241
  }
170
242
 
171
243
  export type ProfilesFileParseResult =
@@ -204,9 +276,25 @@ export function serializeProfilesFile(file: AgentProfilesFile): string {
204
276
  profiles: cloneProfiles(file.profiles),
205
277
  };
206
278
  if (file.active !== undefined) payload.active = file.active;
279
+ const workflow = meaningfulWorkflowMap(file.workflow, file.profiles);
280
+ if (workflow !== undefined) payload.workflow = workflow;
207
281
  return `${JSON.stringify(payload, null, 2)}\n`;
208
282
  }
209
283
 
284
+ /** The subset of a workflow map worth persisting: declared profiles, non-default modes. */
285
+ function meaningfulWorkflowMap(
286
+ workflow: Record<string, ProfileWorkflow> | undefined,
287
+ profiles: Record<string, AgentModelConfig>,
288
+ ): Record<string, ProfileWorkflow> | undefined {
289
+ if (workflow === undefined) return undefined;
290
+ const kept = Object.fromEntries(
291
+ Object.entries(workflow)
292
+ .filter(([name, entry]) => hasOwn(profiles, name) && entry.orchestratorMode !== DEFAULT_ORCHESTRATOR_MODE)
293
+ .map(([name, entry]) => [name, { orchestratorMode: entry.orchestratorMode }]),
294
+ );
295
+ return Object.keys(kept).length === 0 ? undefined : kept;
296
+ }
297
+
210
298
  // ---- Store mutations (each returns a new file and never mutates the input) ----
211
299
 
212
300
  export function createProfile(
@@ -246,7 +334,8 @@ export function duplicateProfile(
246
334
  if (hasOwn(file.profiles, to)) {
247
335
  throw new AgentProfileError("duplicate_name", `Profile already exists: ${to}.`);
248
336
  }
249
- return createProfile(file, to, file.profiles[from]);
337
+ const created = createProfile(file, to, file.profiles[from]);
338
+ return setProfileOrchestratorMode(created, to, readProfileWorkflow(file, from).orchestratorMode);
250
339
  }
251
340
 
252
341
  export function renameProfile(
@@ -272,6 +361,9 @@ export function renameProfile(
272
361
  ...file,
273
362
  active: file.active === from ? to : file.active,
274
363
  profiles,
364
+ ...(renamedWorkflow(file.workflow, from, to) === undefined
365
+ ? {}
366
+ : { workflow: renamedWorkflow(file.workflow, from, to) }),
275
367
  };
276
368
  }
277
369
 
@@ -291,6 +383,9 @@ export function deleteProfile(file: AgentProfilesFile, name: string): AgentProfi
291
383
  profiles: Object.fromEntries(
292
384
  Object.entries(file.profiles).filter(([profileName]) => profileName !== name),
293
385
  ),
386
+ ...(workflowWithout(file.workflow, name) === undefined
387
+ ? {}
388
+ : { workflow: workflowWithout(file.workflow, name) }),
294
389
  };
295
390
  }
296
391
 
@@ -302,6 +397,69 @@ export function setActiveProfile(file: AgentProfilesFile, name: string): AgentPr
302
397
  return { ...file, active: name };
303
398
  }
304
399
 
400
+ // ---- Per-profile orchestrator workflow (full-delegation-mode) ----
401
+
402
+ /**
403
+ * The orchestrator mode a profile carries, defaulting to today's behaviour.
404
+ *
405
+ * Unknown names resolve to the default instead of throwing: this is read on
406
+ * every prompt build, and a profile deleted or renamed between reads must not
407
+ * be able to break the orchestrator prompt.
408
+ */
409
+ export function readProfileWorkflow(file: AgentProfilesFile, name: string): ProfileWorkflow {
410
+ const entry = file.workflow !== undefined && hasOwn(file.workflow, name) ? file.workflow[name] : undefined;
411
+ return { orchestratorMode: entry?.orchestratorMode ?? DEFAULT_ORCHESTRATOR_MODE };
412
+ }
413
+
414
+ /**
415
+ * Opts one profile into a mode (S1). Selecting the default removes the entry
416
+ * instead of persisting it, so an all-organic store keeps its pre-change shape.
417
+ */
418
+ export function setProfileOrchestratorMode(
419
+ file: AgentProfilesFile,
420
+ name: string,
421
+ mode: OrchestratorMode,
422
+ ): AgentProfilesFile {
423
+ requireValidName(name);
424
+ if (!hasOwn(file.profiles, name)) {
425
+ throw new AgentProfileError("missing_profile", `Profile does not exist: ${name}.`);
426
+ }
427
+ if (mode === DEFAULT_ORCHESTRATOR_MODE) return { ...file, workflow: workflowWithout(file.workflow, name) };
428
+ return { ...file, workflow: { ...file.workflow, [name]: { orchestratorMode: mode } } };
429
+ }
430
+
431
+ /** The mode the focused profile would get from one key press (panel `d`). */
432
+ export function toggleProfileOrchestratorMode(
433
+ file: AgentProfilesFile,
434
+ name: string,
435
+ ): AgentProfilesFile {
436
+ const current = readProfileWorkflow(file, name).orchestratorMode;
437
+ const next = ORCHESTRATOR_MODES[(ORCHESTRATOR_MODES.indexOf(current) + 1) % ORCHESTRATOR_MODES.length];
438
+ return setProfileOrchestratorMode(file, name, next);
439
+ }
440
+
441
+ /** Drops one profile's workflow entry, and the map itself once it is empty. */
442
+ function workflowWithout(
443
+ workflow: Record<string, ProfileWorkflow> | undefined,
444
+ name: string,
445
+ ): Record<string, ProfileWorkflow> | undefined {
446
+ if (workflow === undefined) return undefined;
447
+ const kept = Object.fromEntries(Object.entries(workflow).filter(([key]) => key !== name));
448
+ return Object.keys(kept).length === 0 ? undefined : kept;
449
+ }
450
+
451
+ function renamedWorkflow(
452
+ workflow: Record<string, ProfileWorkflow> | undefined,
453
+ from: string,
454
+ to: string,
455
+ ): Record<string, ProfileWorkflow> | undefined {
456
+ if (workflow === undefined) return undefined;
457
+ const remapped = Object.fromEntries(
458
+ Object.entries(workflow).map(([key, entry]) => [key === from ? to : key, entry]),
459
+ );
460
+ return Object.keys(remapped).length === 0 ? undefined : remapped;
461
+ }
462
+
305
463
  // ---- Summaries and panel decision helpers ----
306
464
 
307
465
  export interface ProfileModelSummary {
@@ -0,0 +1,105 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import { dirname, join, resolve } from "node:path";
4
+
5
+ export interface AgentStatus {
6
+ schema: "gentle-shell.agent-status/v1";
7
+ agent: "gentle-shell" | "pi";
8
+ session: string;
9
+ pid: number;
10
+ cwd: string;
11
+ state: "working" | "blocked" | "idle";
12
+ task: { title: string } | null;
13
+ updatedAt: string;
14
+ }
15
+ const ORPHAN_AGE_MS = 24 * 60 * 60 * 1000;
16
+ const ORPHAN_MAX_BYTES = 64 * 1024;
17
+ export function agentStatus(input: Omit<AgentStatus, "schema" | "updatedAt">, now: number): AgentStatus {
18
+ return { schema: "gentle-shell.agent-status/v1", ...input, updatedAt: new Date(now).toISOString() };
19
+ }
20
+
21
+ /** Private, best-effort store. No destination file is ever opened for writing. */
22
+ export function createAgentStatusStore(home: string, session: string) {
23
+ const configHome = resolve(home);
24
+ const root = join(configHome, "agent-status");
25
+ const path = join(root, `${createHash("sha256").update(session).digest("hex")}.json`);
26
+ const owned = (stat: fs.Stats) => process.platform === "win32" || stat.uid === process.getuid?.();
27
+ const directory = (create: boolean) => {
28
+ // Validate through the config home only; its ancestors are trusted.
29
+ const ensure = (dir: string): void => {
30
+ try {
31
+ const stat = fs.lstatSync(dir);
32
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw Error("unsafe-directory");
33
+ } catch (error) {
34
+ if (!create || (error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
35
+ if (dir === configHome) fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
36
+ else { ensure(dirname(dir)); fs.mkdirSync(dir, { mode: 0o700 }); }
37
+ }
38
+ if (dir !== configHome) ensureExisting(dirname(dir));
39
+ };
40
+ const ensureExisting = (dir: string): void => {
41
+ const stat = fs.lstatSync(dir);
42
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw Error("unsafe-directory");
43
+ if (dir !== configHome) ensureExisting(dirname(dir));
44
+ };
45
+ // Same trust boundary as orchestrator presence: refuse a foreign-owned or
46
+ // group/other-writable config home, where another account could swap the root.
47
+ const home = () => {
48
+ const parent = fs.lstatSync(dirname(root));
49
+ if (!parent.isDirectory() || parent.isSymbolicLink() || !owned(parent) || (process.platform !== "win32" && (parent.mode & 0o022) !== 0)) throw Error("unsafe-home");
50
+ };
51
+ try { home(); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
52
+ ensure(root); home();
53
+ const stat = fs.lstatSync(root);
54
+ if (!owned(stat) || (process.platform !== "win32" && (stat.mode & 0o077) !== 0)) throw Error("not-private");
55
+ };
56
+ const regular = () => {
57
+ try {
58
+ const stat = fs.lstatSync(path);
59
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || !owned(stat)) throw Error("unsafe-file");
60
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
61
+ };
62
+ // Probe a recorded owner PID: only ESRCH proves it dead; EPERM means alive.
63
+ const gone = (pid: unknown) => {
64
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return false;
65
+ try { process.kill(pid, 0); } catch (error) { return (error as NodeJS.ErrnoException).code === "ESRCH"; }
66
+ return false;
67
+ };
68
+ const orphaned = (value: { pid?: unknown; updatedAt?: unknown }) => {
69
+ const updated = typeof value.updatedAt === "string" ? Date.parse(value.updatedAt) : Number.NaN;
70
+ return (Number.isFinite(updated) && Date.now() - updated > ORPHAN_AGE_MS) || gone(value.pid);
71
+ };
72
+ // A crashed session leaves its file behind; a bounded startup sweep drops proven
73
+ // orphans only. Unreadable, oversized, foreign, linked or unparsable files stay.
74
+ const sweep = () => {
75
+ let entries: string[];
76
+ try { directory(false); entries = fs.readdirSync(root); } catch { return; }
77
+ for (const entry of entries) {
78
+ const candidate = join(root, entry);
79
+ if (!entry.endsWith(".json") || candidate === path) continue;
80
+ try {
81
+ const stat = fs.lstatSync(candidate);
82
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || !owned(stat) || stat.size > ORPHAN_MAX_BYTES) continue;
83
+ const value = JSON.parse(fs.readFileSync(candidate, "utf8")) as { pid?: unknown; updatedAt?: unknown } | null;
84
+ if (typeof value !== "object" || value === null || !orphaned(value)) continue;
85
+ fs.unlinkSync(candidate);
86
+ } catch { /* Never touch what cannot be proven an orphan. */ }
87
+ }
88
+ };
89
+ try { sweep(); } catch { /* The sweep never interrupts a session start. */ }
90
+ return { path, write(value: AgentStatus): boolean {
91
+ let temporary: string | undefined;
92
+ try {
93
+ directory(true); regular();
94
+ const candidate = join(root, `.${randomUUID()}.tmp`);
95
+ const fd = fs.openSync(candidate, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
96
+ temporary = candidate;
97
+ try { fs.writeFileSync(fd, `${JSON.stringify(value)}\n`); } finally { fs.closeSync(fd); }
98
+ directory(false); regular(); fs.renameSync(temporary, path);
99
+ temporary = undefined; return true;
100
+ } catch { return false; }
101
+ finally { if (temporary) { try { fs.unlinkSync(temporary); } catch { /* Best effort. */ } } }
102
+ }, remove(): void {
103
+ try { directory(false); regular(); fs.unlinkSync(path); } catch { /* Missing, unsafe or unavailable. */ }
104
+ } };
105
+ }
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readdirSync, readFileSync } from "node:fs";
2
2
  import { basename, join } from "node:path";
3
+ import type { AgentProfilesFile } from "./agent-profiles.ts";
3
4
  import { THINKING_LEVELS as ROUTING_THINKING_LEVELS, isServiceTier, type AgentModelConfig, type ServiceTier, type ThinkingLevel as RoutingThinkingLevel } from "./model-routing-authority.ts";
4
5
 
5
6
  // Gentle Agents configuration. Agent definitions are markdown files with YAML
@@ -360,6 +361,51 @@ export function unmatchedProfileKeys(
360
361
  .map((key) => ({ key, suggestion: suggestionFor(key) }));
361
362
  }
362
363
 
364
+ // Live routing targets without agent definition files; keep local to avoid a runtime import cycle.
365
+ const RESERVED_ROUTING_KEYS = new Set([...PROVIDER_REVIEW_ROLES, "orchestrator"]);
366
+
367
+ /** Removable keys exclude reserved targets, exact matches, and likely typos in the caller's full agent list. */
368
+ export function staleRoutingKeys(
369
+ config: Record<string, { model?: unknown; thinking?: unknown }>,
370
+ agents: ReadonlyArray<{ name: string }>,
371
+ ): string[] {
372
+ // Matching uses keys only; adapt the three stores without interpreting their values.
373
+ const profiles = Object.fromEntries(
374
+ Object.keys(config).map((key) => [key, { model: undefined, thinking: undefined }]),
375
+ );
376
+ return unmatchedProfileKeys(profiles, agents)
377
+ .filter(({ key, suggestion }) => suggestion === undefined && !RESERVED_ROUTING_KEYS.has(key))
378
+ .map(({ key }) => key)
379
+ .sort();
380
+ }
381
+
382
+ /** Preserve identity on a no-op so callers can skip unnecessary store writes. */
383
+ export function removeRoutingKeys<T extends Record<string, unknown>>(
384
+ config: T,
385
+ keys: ReadonlyArray<string>,
386
+ ): T {
387
+ const present = keys.filter((key) => Object.prototype.hasOwnProperty.call(config, key));
388
+ if (present.length === 0) return config;
389
+ const updated = { ...config };
390
+ for (const key of present) delete updated[key];
391
+ return updated;
392
+ }
393
+
394
+ /** Remove selected routing keys without cloning unaffected profiles or metadata. */
395
+ export function removeRoutingKeysFromProfilesFile(
396
+ file: AgentProfilesFile,
397
+ keys: ReadonlyArray<string>,
398
+ ): AgentProfilesFile {
399
+ let profiles = file.profiles;
400
+ for (const [name, config] of Object.entries(file.profiles)) {
401
+ const updated: AgentModelConfig = removeRoutingKeys(config, keys);
402
+ if (updated === config) continue;
403
+ if (profiles === file.profiles) profiles = { ...file.profiles };
404
+ profiles[name] = updated;
405
+ }
406
+ return profiles === file.profiles ? file : { ...file, profiles };
407
+ }
408
+
363
409
  export function resolveAgentProfile(agent: AgentDefinition, config: AgentsConfig): ResolvedProfile {
364
410
  const profile = config.modelProfiles[agent.name];
365
411
  const [model, modelSource] = pick<ModelRef>([
@@ -1,6 +1,6 @@
1
1
  import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
- import { emptyThread, type TaskRecord, type TaskThread } from "./agents-protocol.ts";
3
+ import { emptyThread, isFinished, type TaskRecord, type TaskThread } from "./agents-protocol.ts";
4
4
 
5
5
  // Gentle Agents history: one JSON file per finished task, written by the
6
6
  // host after the child is gone and read back lazily when the overlay opens
@@ -40,9 +40,28 @@ function parseStored(text: string): StoredTask | undefined {
40
40
  }
41
41
  }
42
42
 
43
- export async function saveTask(dir: string, task: TaskRecord, thread: TaskThread): Promise<void> {
43
+ // Writes to one task file run one after another in call order. Each write
44
+ // renames a fresh temp file over the target, so unordered writes would let a
45
+ // stale launch record land after the terminal one (#1741).
46
+ const pendingWrites = new Map<string, Promise<void>>();
47
+
48
+ export function saveTask(dir: string, task: TaskRecord, thread: TaskThread): Promise<void> {
49
+ let target: string;
50
+ try {
51
+ target = fileFor(dir, task.id);
52
+ } catch (error) {
53
+ return Promise.reject(error);
54
+ }
55
+ const previous = pendingWrites.get(target) ?? Promise.resolve();
56
+ const write = previous.catch(() => {}).then(() => writeTask(dir, target, task, thread));
57
+ const settled = write.catch(() => {});
58
+ pendingWrites.set(target, settled);
59
+ void settled.then(() => { if (pendingWrites.get(target) === settled) pendingWrites.delete(target); });
60
+ return write;
61
+ }
62
+
63
+ async function writeTask(dir: string, target: string, task: TaskRecord, thread: TaskThread): Promise<void> {
44
64
  await mkdir(dir, { recursive: true });
45
- const target = fileFor(dir, task.id);
46
65
  const temp = `${target}.${process.pid}-${Math.random().toString(36).slice(2, 8)}.tmp`;
47
66
  await writeFile(temp, JSON.stringify({ task, thread }), "utf8");
48
67
  await rename(temp, target);
@@ -74,8 +93,8 @@ export async function loadHistory(dir: string): Promise<StoredTask[]> {
74
93
  // Keep the newest `maxTasks` files; the rest go. Returns how many were removed.
75
94
  export async function pruneHistory(dir: string, maxTasks: number): Promise<number> {
76
95
  const stored = await loadHistory(dir);
77
- // Preserve historical remediation payloads without interpreting or replaying their retired ledger.
78
- const extra = stored.filter(({ task }) => task.sddRemediation === undefined).slice(Math.max(0, maxTasks));
96
+ // Preserve historical remediation payloads and any active in-flight tasks.
97
+ const extra = stored.filter(({ task }) => task.sddRemediation === undefined && isFinished(task.status)).slice(Math.max(0, maxTasks));
79
98
  await Promise.all(extra.map((entry) => rm(fileFor(dir, entry.task.id), { force: true })));
80
99
  return extra.length;
81
100
  }
@@ -18,7 +18,16 @@ export interface QueryFrame {
18
18
  message: string;
19
19
  }
20
20
 
21
- export type ChildFrame = NotificationFrame | QueryFrame;
21
+ // The child's own background-job state report. It carries no model text: the
22
+ // runner reads only the bounded JSON state, acks it, and never routes it to the
23
+ // parent model.
24
+ export interface JobFrame {
25
+ id: string;
26
+ kind: "job";
27
+ message: string;
28
+ }
29
+
30
+ export type ChildFrame = NotificationFrame | QueryFrame | JobFrame;
22
31
 
23
32
  interface AckFrame {
24
33
  id: string;
@@ -62,7 +71,7 @@ function boundedText(value: unknown, maxBytes: number): value is string {
62
71
  return typeof value === "string" && wellFormedUnicode(value) && Buffer.byteLength(value, "utf8") <= maxBytes;
63
72
  }
64
73
 
65
- function validCorrelation(value: unknown, prefix: "n" | "q"): value is string {
74
+ function validCorrelation(value: unknown, prefix: "n" | "q" | "j"): value is string {
66
75
  if (typeof value !== "string" || !new RegExp(`^${prefix}[1-9]\\d{0,15}$`).test(value)) return false;
67
76
  const counter = Number(value.slice(1));
68
77
  return Number.isSafeInteger(counter) && counter > 0;
@@ -76,17 +85,50 @@ export function validChildQueryId(value: unknown): value is string {
76
85
  return validCorrelation(value, "q");
77
86
  }
78
87
 
88
+ // Job reports use their own correlation space, so a job frame can never be
89
+ // mistaken for a notification admission or collide with its acknowledgement.
90
+ export function validChildJobId(value: unknown): value is string {
91
+ return validCorrelation(value, "j");
92
+ }
93
+
79
94
  export function validChildMessage(value: unknown): value is string {
80
95
  return boundedText(value, CHILD_MESSAGE_MAX_BYTES);
81
96
  }
82
97
 
98
+ /** Upper bound on the running count a child job frame may report; the child's
99
+ * own registry caps running jobs at 25, so this only rejects nonsense. */
100
+ export const CHILD_JOB_MAX_RUNNING = 1_000_000;
101
+
102
+ /** The bounded state a child reports about its own background jobs. */
103
+ export interface ChildJobState {
104
+ running: number;
105
+ /* True while the child still considers itself pending, even with no running job. */
106
+ pending: boolean;
107
+ }
108
+
109
+ /** Encodes the child-side job report; see `parseChildJobState`. */
110
+ export function formatChildJobState(state: ChildJobState): string {
111
+ return JSON.stringify({ running: state.running, pending: state.pending });
112
+ }
113
+
114
+ /** Decodes a job frame message; undefined for anything that is not the exact shape. */
115
+ export function parseChildJobState(message: string): ChildJobState | undefined {
116
+ let value: unknown;
117
+ try { value = JSON.parse(message); } catch { return undefined; }
118
+ if (!record(value) || !exact(value, ["running", "pending"])) return undefined;
119
+ const { running, pending } = value as { running?: unknown; pending?: unknown };
120
+ if (typeof running !== "number" || !Number.isSafeInteger(running) || running < 0 || running > CHILD_JOB_MAX_RUNNING) return undefined;
121
+ if (typeof pending !== "boolean") return undefined;
122
+ return { running, pending };
123
+ }
124
+
83
125
  export function parseChildFrame(value: unknown): { frame?: ChildFrame; id?: string; error?: string } {
84
126
  if (!record(value)) return { error: "invalid child IPC frame" };
85
- const id = validChildQueryId(value.id) || validChildId(value.id) ? value.id : undefined;
127
+ const id = validChildQueryId(value.id) || validChildId(value.id) || validChildJobId(value.id) ? value.id : undefined;
86
128
  if (!exact(value, ["id", "kind", "message"])) return { ...(id === undefined ? {} : { id }), error: "invalid child IPC frame" };
87
129
  if (id === undefined) return { error: "invalid child IPC correlation" };
88
- if (value.kind !== "notification" && value.kind !== "query") return { id, error: "unsupported child IPC kind" };
89
- if (value.kind === "notification" && !validChildId(id) || value.kind === "query" && !validChildQueryId(id)) return { id, error: "invalid child IPC correlation" };
130
+ if (value.kind !== "notification" && value.kind !== "query" && value.kind !== "job") return { id, error: "unsupported child IPC kind" };
131
+ if (value.kind === "notification" && !validChildId(id) || value.kind === "query" && !validChildQueryId(id) || value.kind === "job" && !validChildJobId(id)) return { id, error: "invalid child IPC correlation" };
90
132
  if (!validChildMessage(value.message)) return { id, error: "invalid child IPC message" };
91
133
  return { frame: { id, kind: value.kind, message: value.message } } as { frame: ChildFrame };
92
134
  }