gentle-pi 4.5.0 → 4.6.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 (243) hide show
  1. package/README.md +9 -6
  2. package/assets/agents/gentle-ai-verify.md +4 -0
  3. package/assets/agents/gentle-ai-worker.md +1 -0
  4. package/assets/migrations/agent-body-history.json +147 -0
  5. package/assets/orchestrator-delegation-reference.md +3 -3
  6. package/assets/orchestrator-delegation.md +2 -2
  7. package/assets/orchestrator-verification.md +10 -6
  8. package/assets/orchestrator.md +8 -8
  9. package/bin/gentle-shell.mjs +61 -26
  10. package/docs/ci-performance.md +11 -0
  11. package/docs/delegated-verification.md +6 -0
  12. package/docs/fast-mode.md +15 -0
  13. package/docs/gentle-agents-activity.md +8 -0
  14. package/docs/gentle-music.md +6 -3
  15. package/docs/gentle-shell.md +70 -20
  16. package/docs/install-wizard.md +1 -1
  17. package/docs/mcp-status.md +52 -0
  18. package/docs/prompt-budget.md +28 -0
  19. package/docs/readme-reference.md +82 -21
  20. package/docs/session-profile-format.md +20 -5
  21. package/docs/sound-notifications.md +1 -1
  22. package/docs/star-prompt.md +32 -0
  23. package/docs/work-continuity.md +46 -0
  24. package/extensions/ask-user-question.ts +1 -0
  25. package/extensions/codegraph-tools.ts +38 -4
  26. package/extensions/gentle-agents.ts +477 -50
  27. package/extensions/gentle-ai.ts +1046 -191
  28. package/extensions/gentle-fast.ts +61 -0
  29. package/extensions/gentle-guide.ts +174 -0
  30. package/extensions/gentle-herdr-activity.ts +21 -1
  31. package/extensions/gentle-herdr-agent.ts +144 -0
  32. package/extensions/gentle-music.ts +10 -0
  33. package/extensions/gentle-program-identity.ts +61 -0
  34. package/extensions/gentle-shell.ts +642 -97
  35. package/extensions/gentle-star-prompt.ts +334 -0
  36. package/extensions/gentle-stats.ts +5 -5
  37. package/extensions/gentle-todo.ts +42 -22
  38. package/extensions/history/store.ts +18 -12
  39. package/extensions/skill-registry.ts +35 -3
  40. package/extensions/startup-banner.ts +39 -7
  41. package/lib/agent-assets.ts +74 -17
  42. package/lib/agent-profiles.ts +1 -1
  43. package/lib/agents-config.ts +12 -3
  44. package/lib/agents-keys.ts +8 -16
  45. package/lib/agents-protocol.ts +80 -4
  46. package/lib/agents-runner.ts +105 -4
  47. package/lib/agents-view.ts +6 -1
  48. package/lib/agents-widget.ts +132 -9
  49. package/lib/bridge-cost.ts +28 -0
  50. package/lib/codemode-renderer.ts +16 -0
  51. package/lib/command-palette-catalog.ts +1 -0
  52. package/lib/command-palette.ts +21 -8
  53. package/lib/exploration-budget.ts +62 -0
  54. package/lib/gentle-guide.ts +201 -0
  55. package/lib/gentle-shell-launcher.ts +4 -0
  56. package/lib/herdr-activity.ts +9 -3
  57. package/lib/herdr-task-summary-policy.ts +85 -0
  58. package/lib/inprocess-reviewer.ts +33 -13
  59. package/lib/jobs-sidebar-state.ts +5 -6
  60. package/lib/jobs-widget.ts +16 -52
  61. package/lib/keymaps-customize.ts +81 -0
  62. package/lib/keymaps.ts +291 -0
  63. package/lib/model-fallback-notice.ts +61 -0
  64. package/lib/model-fallback-policy.ts +141 -0
  65. package/lib/model-fallback-store.ts +143 -0
  66. package/lib/model-routing-authority.ts +10 -2
  67. package/lib/nan-provider.ts +3 -2
  68. package/lib/native-review-cli.ts +7 -2
  69. package/lib/notification-customize.ts +48 -51
  70. package/lib/openai-fast-tier.ts +22 -0
  71. package/lib/orchestrator-discovery.ts +5 -1
  72. package/lib/orchestrator-fallback.ts +75 -0
  73. package/lib/pasted-image-paths.ts +113 -0
  74. package/lib/questionnaire/questionnaire-view.ts +121 -7
  75. package/lib/review-candidate-view-owner.ts +4 -0
  76. package/lib/review-candidate-view.ts +10 -7
  77. package/lib/review-host-relay.ts +5 -1
  78. package/lib/review-integration-v2.ts +22 -7
  79. package/lib/review-repository.ts +5 -0
  80. package/lib/session-profile-append-controller.ts +21 -6
  81. package/lib/session-profile-authority.ts +119 -0
  82. package/lib/session-profile-binding.ts +54 -5
  83. package/lib/session-profile-freeze.ts +105 -9
  84. package/lib/session-profile-integration.ts +313 -0
  85. package/lib/session-profile-persistence.ts +63 -9
  86. package/lib/shell-bar.ts +171 -56
  87. package/lib/shell-card.ts +26 -6
  88. package/lib/shell-page.ts +120 -0
  89. package/lib/shell-panel.ts +149 -0
  90. package/lib/shell-prompt.ts +53 -1
  91. package/lib/shell-sidebar-layout.ts +98 -25
  92. package/lib/shell-sidebar.ts +54 -1
  93. package/lib/shell-stats.ts +123 -0
  94. package/lib/shell-todo.ts +71 -0
  95. package/lib/shell-usage.ts +12 -2
  96. package/lib/star-prompt.ts +197 -0
  97. package/lib/verifier-admission.ts +18 -8
  98. package/lib/verifier-settle-reminder.ts +64 -0
  99. package/lib/vim-editor-adapter.ts +6 -1
  100. package/lib/visual-customization-policy.ts +41 -6
  101. package/lib/visual-customize-view.ts +164 -26
  102. package/lib/visual-layout-preview.ts +43 -0
  103. package/lib/yolo-session-policy.ts +28 -1
  104. package/package.json +1 -1
  105. package/runtime/gentle-shell-launcher.mjs +4 -0
  106. package/runtime/native-review-cli.mjs +7 -2
  107. package/runtime/review-integration-v2.mjs +22 -7
  108. package/runtime/windows-session-transport.ps1 +60 -3
  109. package/scripts/bootstrap.sh +4 -1
  110. package/scripts/installer-preflight.mjs +1 -1
  111. package/scripts/pi-update.mjs +113 -3
  112. package/scripts/run-test-suite.mjs +17 -1
  113. package/scripts/shell-snapshot.mjs +340 -0
  114. package/scripts/test-packed-runner.mjs +1 -1
  115. package/scripts/update-agent-body-history.mjs +41 -0
  116. package/scripts/verify-installer-tap.mjs +45 -0
  117. package/scripts/verify-package-files.mjs +2 -0
  118. package/skills/gentle-ai/SKILL.md +2 -2
  119. package/skills/tui-design/NOTICE.md +5 -0
  120. package/skills/tui-design/SKILL.md +56 -0
  121. package/skills/tui-design/references/commands.md +75 -0
  122. package/skills/tui-design/references/critique.md +48 -0
  123. package/skills/tui-design/references/design-doc.md +44 -0
  124. package/skills/tui-design/references/terminal-craft.md +64 -0
  125. package/skills/tui-design/references/visual-loop.md +32 -0
  126. package/tests/agents-protocol.test.ts +53 -1
  127. package/tests/agents-runner.test.ts +168 -3
  128. package/tests/agents-view.test.ts +27 -0
  129. package/tests/agents-widget.test.ts +312 -10
  130. package/tests/bounded-scan-contract.test.ts +39 -0
  131. package/tests/bridge-cost.test.ts +32 -0
  132. package/tests/bundled-install.test.ts +6 -4
  133. package/tests/ci-concurrency.test.ts +11 -0
  134. package/tests/ci-merge-base-identity.test.ts +114 -0
  135. package/tests/codegraph-tools.test.ts +69 -0
  136. package/tests/codemode-rendering.test.ts +22 -2
  137. package/tests/command-palette.test.ts +16 -2
  138. package/tests/commit-slice-signal.test.ts +11 -9
  139. package/tests/delegate-for-reason-contract.test.ts +5 -4
  140. package/tests/design-canvas-server.test.ts +6 -2
  141. package/tests/exploration-budget.test.ts +128 -0
  142. package/tests/fixtures/agent-assets/gentle-ai-worker.strict-tdd-era.md +122 -0
  143. package/tests/fixtures/measure-orchestrator-prompt.mjs +2 -1
  144. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +18 -10
  145. package/tests/fixtures/session-profile-v1/replay.ts +125 -0
  146. package/tests/fixtures/session-profile-v1/session-profile-authority.ts +113 -0
  147. package/tests/fixtures/session-profile-v1/session-profile-binding.ts +83 -0
  148. package/tests/fixtures/session-profile-v1/session-profile-disk-reader.ts +182 -0
  149. package/tests/fixtures/session-profile-v1/session-profile-freeze.ts +290 -0
  150. package/tests/fixtures/session-profile-v1/session-profile-persistence.ts +195 -0
  151. package/tests/fixtures/session-profile-v1/v1-inputs.ts +16 -0
  152. package/tests/fixtures/windows-pipe-availability.ps1 +26 -0
  153. package/tests/fixtures/windows-session-bootstrap.ps1 +6 -2
  154. package/tests/gentle-agents.test.ts +416 -21
  155. package/tests/gentle-ai-exploration-budget.test.ts +135 -0
  156. package/tests/gentle-ai.test.ts +1011 -37
  157. package/tests/gentle-fast.test.ts +73 -0
  158. package/tests/gentle-guide.test.ts +208 -0
  159. package/tests/gentle-herdr-activity.test.ts +76 -2
  160. package/tests/gentle-herdr-agent.test.ts +111 -0
  161. package/tests/gentle-music.test.ts +36 -1
  162. package/tests/gentle-program-identity.test.ts +197 -0
  163. package/tests/gentle-shell-bin.test.ts +49 -26
  164. package/tests/gentle-shell-launcher.test.ts +18 -2
  165. package/tests/gentle-shell.test.ts +1068 -37
  166. package/tests/gentle-stats.test.ts +15 -2
  167. package/tests/gentle-todo.test.ts +50 -4
  168. package/tests/herdr-task-summary-policy.test.ts +128 -0
  169. package/tests/history-store-private-mode.test.ts +40 -0
  170. package/tests/image-paste-chips.test.ts +42 -0
  171. package/tests/inprocess-reviewer.test.ts +122 -0
  172. package/tests/installer-posix-bootstrap.test.ts +67 -5
  173. package/tests/installer-server.test.ts +2 -2
  174. package/tests/installer-windows-diagnostics.test.ts +4 -5
  175. package/tests/isolated-config-home.ts +28 -0
  176. package/tests/jobs-widget.test.ts +25 -37
  177. package/tests/keymaps-customize.test.ts +114 -0
  178. package/tests/keymaps.test.ts +103 -0
  179. package/tests/maintainer/mcp-status.maintest.ts +88 -0
  180. package/tests/maintainer/pi-update-source.maintest.ts +116 -0
  181. package/tests/model-fallback-notice.test.ts +45 -0
  182. package/tests/model-fallback-policy.test.ts +83 -0
  183. package/tests/model-fallback-store.test.ts +111 -0
  184. package/tests/nan-provider.test.ts +4 -4
  185. package/tests/no-self-pause-contract.test.ts +19 -0
  186. package/tests/notification-customize.test.ts +58 -34
  187. package/tests/odd-routing-canonical-ratchet.test.ts +3 -3
  188. package/tests/odd-routing-contract.test.ts +1 -1
  189. package/tests/orchestrator-fallback.test.ts +82 -0
  190. package/tests/orchestrator-prompt-budget.test.ts +131 -0
  191. package/tests/package-manifest.test.ts +160 -7
  192. package/tests/pasted-image-paths.test.ts +118 -0
  193. package/tests/persona-reply-language.test.ts +61 -0
  194. package/tests/pi-update-launcher.test.ts +32 -8
  195. package/tests/pi-update-source.test.ts +162 -0
  196. package/tests/profile-fast-tier.test.ts +311 -0
  197. package/tests/profile-tier-footer.test.ts +79 -0
  198. package/tests/questionnaire-view.test.ts +150 -0
  199. package/tests/review-candidate-owner-sweep.test.ts +93 -0
  200. package/tests/review-candidate-view.test.ts +51 -0
  201. package/tests/review-controller-native-routing.test.ts +120 -6
  202. package/tests/review-gate.test.ts +24 -0
  203. package/tests/review-inspect-preflight.test.ts +197 -0
  204. package/tests/review-integration-v2-forward.test.ts +59 -0
  205. package/tests/review-repository.test.ts +52 -1
  206. package/tests/review-sidebar-state.test.ts +5 -5
  207. package/tests/run-test-suite.test.ts +61 -5
  208. package/tests/sensitive-path-tools.test.ts +74 -0
  209. package/tests/session-profile-append-controller.test.ts +63 -0
  210. package/tests/session-profile-authority.test.ts +259 -0
  211. package/tests/session-profile-binding.test.ts +15 -0
  212. package/tests/session-profile-extension.test.ts +615 -0
  213. package/tests/session-profile-freeze.test.ts +110 -2
  214. package/tests/session-profile-integration.test.ts +857 -0
  215. package/tests/session-profile-persistence.test.ts +57 -0
  216. package/tests/session-profile-v1-compat.test.ts +221 -0
  217. package/tests/shell-bar.test.ts +113 -55
  218. package/tests/shell-card.test.ts +13 -1
  219. package/tests/shell-page.test.ts +108 -0
  220. package/tests/shell-panel.test.ts +332 -0
  221. package/tests/shell-prompt.test.ts +54 -0
  222. package/tests/shell-render-cache.test.ts +5 -0
  223. package/tests/shell-sidebar-fullscreen.test.ts +12 -0
  224. package/tests/shell-sidebar-layout.test.ts +159 -27
  225. package/tests/shell-stats.test.ts +90 -0
  226. package/tests/shell-usage.test.ts +14 -0
  227. package/tests/skill-registry.test.ts +68 -1
  228. package/tests/star-prompt.test.ts +470 -0
  229. package/tests/startup-banner.test.ts +57 -1
  230. package/tests/task-size-routing-contract.test.ts +45 -1
  231. package/tests/verifier-settle-reminder.test.ts +281 -0
  232. package/tests/verify-first-launch-contract.test.ts +56 -5
  233. package/tests/verify-installer-tap.test.ts +57 -0
  234. package/tests/vim-editor-adapter.test.ts +2 -2
  235. package/tests/visual-customization-policy.test.ts +61 -7
  236. package/tests/visual-customize-view.test.ts +253 -8
  237. package/tests/visual-layout-preview.test.ts +28 -0
  238. package/tests/windows-session-bootstrap.test.ts +105 -2
  239. package/tests/work-continuity-contract.test.ts +86 -0
  240. package/tests/writer-surfaces.test.ts +12 -10
  241. package/tests/yolo-customize.test.ts +30 -11
  242. package/tests/yolo-mode-runtime.test.ts +4 -2
  243. package/tests/yolo-mode.test.ts +16 -2
@@ -1,4 +1,10 @@
1
+ import { fallbackNotice, MODEL_FALLBACK_ENTRY, profileFallbackChain, type FallbackChange } from "../lib/model-fallback-notice.ts";
2
+ import { sharedCooldown } from "../lib/model-fallback-policy.ts";
3
+ import { createOrchestratorFallback } from "../lib/orchestrator-fallback.ts";
4
+ import type { ThinkingLevel } from "../lib/model-routing-authority.ts";
1
5
  import { agentsViewKey, agentsCollapseKey, agentsStopKey } from "../lib/agents-keys.ts";
6
+ import { loadKeymaps } from "../lib/keymaps.ts";
7
+ import { CHILD_TIER_ENV } from "../lib/openai-fast-tier.ts";
2
8
  import { spawn } from "node:child_process";
3
9
  import { Type } from "typebox";
4
10
  import { recordReviewMutation } from "../lib/review-reminder-receipt.ts";
@@ -21,16 +27,17 @@ import { createMonitorController, mergeMonitorBatches, type MonitorNotice } from
21
27
  import { JobsView } from "../lib/jobs-view.ts";
22
28
  import { JOBS_FINISHED_TTL_MS } from "../lib/jobs-widget.ts";
23
29
  import { JOBS_SIDEBAR_EVENT, JOBS_STATUS_KEY } from "../lib/jobs-sidebar-state.ts";
24
- import { Text, type Component, type TUI } from "@earendil-works/pi-tui";
30
+ import { Text, truncateToWidth, type Component, type TUI } from "@earendil-works/pi-tui";
25
31
  import { invalidateSidebar } from "../lib/shell-sidebar-layout.ts";
26
- import { sidebarPart, VISUAL_SETTINGS_CHANGED } from "../lib/shell-sidebar.ts";
32
+ import { releaseSidebarHover, setSidebarHover, sidebarPart, VISUAL_SETTINGS_CHANGED } from "../lib/shell-sidebar.ts";
27
33
  import { NativePointerRegion } from "../lib/native-pointer-region.ts";
28
34
  import { resolveVisualSettings } from "../lib/visual-customization-policy.ts";
29
35
  import { createCompletionQueue } from "../lib/agents-completion-delivery.ts";
30
36
  import { createAgentMessageQueue, type PendingAgentMessage } from "../lib/agents-message-delivery.ts";
31
- import { AGENT_MODE, PROFILE_SOURCE, discoverAgents, formatModelRef, loadAgentsConfig, resolveAgentProfile, unmatchedProfileKeys, withPinnedModelProfiles, type AgentDefinition, type AgentMode, type ProfileSource } from "../lib/agents-config.ts";
37
+ import { parseModelRef, AGENT_MODE, PROFILE_SOURCE, PROVIDER_REVIEW_ROLES, discoverAgents, formatModelRef, loadAgentsConfig, resolveAgentProfile, unmatchedProfileKeys, withPinnedModelProfiles, type AgentDefinition, type AgentMode, type ProfileSource } from "../lib/agents-config.ts";
32
38
  import { freezeSessionProfileAtStartup, inheritedProfileDriftNotice, resolveSessionProfile, sessionProfileRoutingAt, type InheritedProfileOptions, type SessionProfileResolution } from "../lib/session-profile-freeze.ts";
33
39
  import { resolveProfilePin, resolveUnversionedProjectProfile } from "../lib/agent-profile-pin.ts";
40
+ import { requireSessionProfileAuthority } from "../lib/session-profile-authority.ts";
34
41
  import { resolveBackgroundSubagentsPolicy } from "../lib/background-subagents-policy.ts";
35
42
  import { installBackgroundCacheWarming } from "../lib/background-cache-warming.ts";
36
43
  import { isFinished, MISSING_TOOLS_NOTE_PREFIX, TASK_EVENT, TASK_STATUS, TaskStore, type AskRequest, type TaskRecord } from "../lib/agents-protocol.ts";
@@ -60,8 +67,8 @@ import { OrchestratorScopeCache, type RepositoryFact } from "../lib/orchestrator
60
67
  import { createRpcActivityPublisher, type RpcActivityPublisher } from "../lib/agents-rpc-publisher.ts";
61
68
  import { isInteractiveRpcHost } from "../lib/rpc-host.ts";
62
69
  import { createNativeFullscreenInteraction } from "../lib/native-fullscreen-interaction.ts";
63
- import { AGENTS_GLYPH, agentsCardTone, renderAgentsCard, widgetExpiryMs, widgetRows } from "../lib/agents-widget.ts";
64
- import { CARD_TONE, panelHeaderRow, renderCard } from "../lib/shell-card.ts";
70
+ import { AGENTS_GLYPH, agentsCardTone, agentsSpend, agentsSummary, renderAgentsAlert, renderAgentsCard, renderAgentsSection, widgetExpiryMs, widgetRows } from "../lib/agents-widget.ts";
71
+ import { CARD_TONE, cardAwaitingResult, cardBodyRows, cardBottom, cardInnerWidth, cardRunningLine, cardTop, floatRows, headingFits, markCardResult, panelHeaderRow, panelInnerWidth, renderCard, type CardRowContext, type CardTheme, type CardTone } from "../lib/shell-card.ts";
65
72
  import { openInExternalEditor } from "./gentle-shell.ts";
66
73
  import { gentlePiConfigHome } from "../lib/agent-home.ts";
67
74
  import { resolveAgentHomeDirectory } from "../lib/agent-model-resolution.ts";
@@ -100,6 +107,8 @@ const CLOCK_TICK_MS = 1000;
100
107
  const TOOL_PREFIX = "subagent_";
101
108
  // Wakes an idle parent after child content was stored as a custom message.
102
109
  // It names itself as automated so the model never attributes it to the human.
110
+ // Persisted Bridge identities embed this exact text, so changing it would
111
+ // unhide the wakes of existing sessions.
103
112
  const PARENT_WAKE_TEXT = "[System-generated Gentle Agents notification, not written by the user] Subagent output was delivered to this session above. Review it and continue.";
104
113
  const PARENT_WAKE_TYPE = "gentle-agents.wake";
105
114
  const BRIDGE_WAKE_IDENTITY_TYPE = "gentle-agents.wake-identity";
@@ -109,7 +118,10 @@ interface BridgeWakeIdentity {
109
118
  text: string;
110
119
  }
111
120
  const bridgeWakeText = (nonce: string): string => `${PARENT_WAKE_TEXT} [gentle-agents wake: ${nonce}]`;
112
- const NATIVE_PARENT_WAKE_TEXT = "Review the delivered subagent output and continue.";
121
+ // Pi gives the hidden native wake to the model with the user role, so an
122
+ // unlabeled English wake read as an English human turn and switched the reply
123
+ // language. It disowns authorship and pins the human's language.
124
+ const NATIVE_PARENT_WAKE_TEXT = `${PARENT_WAKE_TEXT} Reply in the language of the human's own last message, not the language of this notification or of the subagent output.`;
113
125
  // How long a dispatched wake may take to start a parent run before a later
114
126
  // delivery may send another one.
115
127
  export const PARENT_WAKE_GRACE_MS = 30_000;
@@ -235,15 +247,15 @@ export function agentRuntimePaths(home: string, agentHome = join(home, ".pi", "a
235
247
 
236
248
  const workDescriptorSchema = {
237
249
  type: "object", additionalProperties: false,
238
- description: "Explicit non-authoritative classification, not child context. Topic requires area; limits are UTF-8 bytes. No nested tasks.",
250
+ description: "Non-authoritative, not child context; topic requires area; UTF-8 byte limits. No nested tasks.",
239
251
  properties: {
240
252
  area: { type: "string", maxLength: 64 }, topic: { type: "string", maxLength: 64 },
241
253
  tags: { type: "array", maxItems: 8, uniqueItems: true, items: { type: "string", maxLength: 64 } },
242
254
  refs: { type: "array", maxItems: 8, uniqueItems: true, items: {
243
255
  type: "object", additionalProperties: false, required: ["kind", "repository", "id"], properties: {
244
256
  kind: { type: "string", enum: ["issue", "pr", "task"] },
245
- repository: { type: "string", maxLength: 256, description: "Explicit public host/owner/repo; not a URL or inferred identity." },
246
- id: { type: "string", maxLength: 256, description: "Canonical positive decimal issue/PR ID or opaque historical task ID; never a peer route." },
257
+ repository: { type: "string", maxLength: 256, description: "Explicit public host/owner/repo, not URL or inferred identity." },
258
+ id: { type: "string", maxLength: 256, description: "Issue/PR: canonical positive decimal; task: opaque historical ID. Never a peer route." },
247
259
  },
248
260
  } },
249
261
  },
@@ -408,7 +420,10 @@ function runtimeWriterProfile(task: TaskRecord): { writerModelId?: string; write
408
420
  }
409
421
 
410
422
  function taskDetails(task: TaskRecord): Record<string, unknown> {
411
- return { gentleAgents: { taskId: task.id, agent: task.agent, status: task.status, mode: task.mode, cwd: task.cwd } };
423
+ // Additive fields (label, turns, toolCalls, lastStep, error, model, thinking)
424
+ // feed the status card renderer; the model never sees details, so widening is
425
+ // display-only.
426
+ return { gentleAgents: { taskId: task.id, agent: task.agent, status: task.status, mode: task.mode, cwd: task.cwd, label: task.label, turns: task.turns, toolCalls: task.toolCalls, lastStep: task.lastStep, model: task.model, ...(task.thinking ? { thinking: task.thinking } : {}), ...(task.error ? { error: task.error } : {}) } };
412
427
  }
413
428
 
414
429
  export function describeTask(task: TaskRecord): string {
@@ -422,6 +437,162 @@ function finishedText(task: TaskRecord): string {
422
437
  return `Subagent ${task.agent} ${task.status}${task.error ? `: ${task.error}` : ""}${task.result ? `\n\nLast answer:\n${task.result}` : ""}`;
423
438
  }
424
439
 
440
+ // The status card speaks the Agents widget's visual language: the same glyph
441
+ // per state, and a card tone the reader can scan for — info while alive,
442
+ // success when done, error when the run ended without an answer, warning when
443
+ // the child is blocked on the parent.
444
+ const STATUS_CARD_TONE: Record<string, CardTone> = {
445
+ [TASK_STATUS.QUEUED]: CARD_TONE.INFO,
446
+ [TASK_STATUS.RUNNING]: CARD_TONE.INFO,
447
+ [TASK_STATUS.WAITING]: CARD_TONE.WARNING,
448
+ [TASK_STATUS.COMPLETED]: CARD_TONE.SUCCESS,
449
+ [TASK_STATUS.FAILED]: CARD_TONE.ERROR,
450
+ [TASK_STATUS.CANCELLED]: CARD_TONE.ERROR,
451
+ [TASK_STATUS.TIMED_OUT]: CARD_TONE.ERROR,
452
+ };
453
+ // The per-action identity from the design handoff (agent-tool-cards/04):
454
+ // each agent tool carries its own glyph and reads as a verb, so the transcript
455
+ // feels like working with agents rather than calling functions.
456
+ const ACTION_GLYPH: Record<string, string> = {
457
+ run: "→",
458
+ status: "◎",
459
+ result: "↩",
460
+ cancel: "⨯",
461
+ send_message: "✉",
462
+ reply: "✉",
463
+ continue: "↻",
464
+ list_tasks: "☰",
465
+ list_agents: "☰",
466
+ };
467
+ const ACTION_HEADING: Record<string, string> = {
468
+ run: "Delegating",
469
+ status: "Agent status",
470
+ result: "Agent answer",
471
+ cancel: "Stopping agent",
472
+ send_message: "Messaging agent",
473
+ reply: "Replying to agent",
474
+ continue: "Resuming agent",
475
+ list_tasks: "Agent tasks",
476
+ list_agents: "Agent roster",
477
+ };
478
+
479
+ // The state word as a scanable pill: uppercase, colored by the state's role.
480
+ function statusPill(status: string, theme: CardTheme): string {
481
+ const role = status === TASK_STATUS.COMPLETED ? "success"
482
+ : status === TASK_STATUS.WAITING ? "warning"
483
+ : (status === TASK_STATUS.FAILED || status === TASK_STATUS.CANCELLED || status === TASK_STATUS.TIMED_OUT) ? "error"
484
+ : "accent";
485
+ return theme.fg(role, status.replace("_", " ").toUpperCase());
486
+ }
487
+
488
+ // The agent identity palette from the design handoff (agent-tool-cards/04):
489
+ // agent cards wear the iris chrome — heading, glyph, frame and running pill —
490
+ // whatever the active accent is, so working with agents reads as its own
491
+ // mode. The palette is emitted as truecolor ANSI exactly like pi renders
492
+ // theme hex values; every other role stays theme-native, so body text,
493
+ // hints and the success/error states keep the user's theme.
494
+ const IRIS_FG = "\x1b[38;2;185;167;242m";
495
+ const IRIS_DEEP_FG = "\x1b[38;2;143;122;217m";
496
+ const IRIS_TINT_BG = "\x1b[48;2;26;21;38m";
497
+
498
+ // The float tint follows the card tone: info cards (live agent work) wear the
499
+ // iris tint; success, warning and error cards keep the theme's background.
500
+ function agentTheme(theme: CardTheme, tone: CardTone): CardTheme {
501
+ const tint = tone === CARD_TONE.INFO;
502
+ return {
503
+ fg: (color, text) => color === "accent" ? `${IRIS_FG}${text}\x1b[39m`
504
+ : color === "border" ? `${IRIS_DEEP_FG}${text}\x1b[39m`
505
+ : theme.fg(color, text),
506
+ ...(theme.bg ? { bg: (color, text) => tint && color === "toolSuccessBg" ? `${IRIS_TINT_BG}${text}\x1b[49m` : theme.bg!(color, text) } : {}),
507
+ };
508
+ }
509
+
510
+ // Card headings are one row: fold any line break a caller passes in before
511
+ // the usual control-character escaping.
512
+ function headingText(value: string): string {
513
+ return sanitizeTerminalText(value.replace(/[\r\n]+/g, " "));
514
+ }
515
+
516
+ // Structured task facts carried on the tool result; anything missing or of the
517
+ // wrong shape falls back to the plain preview, so older details and error
518
+ // results keep rendering.
519
+ interface StatusCardFacts {
520
+ taskId?: string;
521
+ agent?: string;
522
+ status?: string;
523
+ mode?: string;
524
+ cwd?: string;
525
+ label?: string;
526
+ turns?: number;
527
+ toolCalls?: number;
528
+ lastStep?: string;
529
+ error?: string;
530
+ model?: string;
531
+ thinking?: string;
532
+ }
533
+
534
+ function statusCardFacts(details: unknown): StatusCardFacts | undefined {
535
+ const raw = (details as { gentleAgents?: unknown } | undefined)?.gentleAgents;
536
+ if (typeof raw !== "object" || raw === null) return undefined;
537
+ const source = raw as Record<string, unknown>;
538
+ if (typeof source.taskId !== "string") return undefined;
539
+ const facts: StatusCardFacts = { taskId: source.taskId };
540
+ for (const key of ["agent", "status", "mode", "cwd", "label", "lastStep", "error", "model", "thinking"] as const) {
541
+ if (typeof source[key] === "string") facts[key] = source[key] as string;
542
+ }
543
+ for (const key of ["turns", "toolCalls"] as const) {
544
+ if (typeof source[key] === "number" && Number.isFinite(source[key])) facts[key] = source[key];
545
+ }
546
+ return facts;
547
+ }
548
+
549
+ // What the child runs on, beside the agent it runs as. The record stores the
550
+ // launch profile's model as `formatModelRef(undefined)` = "default" when no
551
+ // layer picked one, which is an inheritance, not a model name: say so.
552
+ function modelChip(model: string | undefined): string | undefined {
553
+ const named = model ? sanitizeTerminalText(model).trim() : "";
554
+ if (!named) return undefined;
555
+ return named === "default" ? "inherit" : named;
556
+ }
557
+
558
+ // One muted identity line: who, which task, and what the child runs on.
559
+ function subjectLine(chips: Array<string | undefined>): string | undefined {
560
+ const shown = chips.filter((chip): chip is string => typeof chip === "string" && chip !== "");
561
+ return shown.length > 0 ? shown.join(" · ") : undefined;
562
+ }
563
+
564
+ // A heading row carries identity, then the launch profile, then the key hint.
565
+ // The row is one line, so a narrow terminal sheds the profile from the end
566
+ // before it sheds the affordance the reader needs to open the card.
567
+ function fitSubject(
568
+ card: { title: string; tone: CardTone; glyph?: string },
569
+ hint: string | undefined,
570
+ size: number,
571
+ chips: Array<string | undefined>,
572
+ ): string | undefined {
573
+ const shown = chips.filter((chip): chip is string => typeof chip === "string" && chip !== "");
574
+ while (shown.length > 0 && !headingFits({ ...card, subtitle: subjectLine(shown), body: [] }, hint, size)) shown.pop();
575
+ return subjectLine(shown);
576
+ }
577
+
578
+ // One Gentle Shell card body for a task's live or final state, built from the
579
+ // details the execute path already records. Pure: facts in, body rows out.
580
+ // The state leads as a pill (RUNNING/OK/FAIL, colored by role); collapsed
581
+ // keeps pill, task label, and last step; expanded adds workspace and error.
582
+ function statusCardRows(facts: StatusCardFacts, theme: CardTheme, expanded: boolean): string[] {
583
+ const status = facts.status ?? "unknown";
584
+ const pill = statusPill(status, theme);
585
+ const head = [pill, facts.mode];
586
+ if (facts.turns !== undefined && facts.toolCalls !== undefined) head.push(`${facts.turns} turns · ${facts.toolCalls} tool calls`);
587
+ const headLine = head.filter((part) => part !== undefined).join(" · ");
588
+ const label = facts.label ? sanitizeTerminalText(facts.label) : undefined;
589
+ const cwd = facts.cwd ? `cwd ${sanitizeTerminalText(facts.cwd)}` : undefined;
590
+ const last = facts.lastStep ? `last: ${sanitizeTerminalText(facts.lastStep)}` : undefined;
591
+ const error = facts.error ? sanitizeTerminalText(facts.error) : undefined;
592
+ if (!expanded) return [headLine, ...(label ? [label] : []), ...(last ? [last] : [])];
593
+ return [headLine, ...(label ? [label] : []), ...(cwd ? [cwd] : []), ...(last ? [last] : []), ...(error ? [error] : [])];
594
+ }
595
+
425
596
  // pi's keybinding hint needs a live theme; outside one (tests, headless) the
426
597
  // plain words still tell the reader what the key does.
427
598
  function expandHint(expanded: boolean): string {
@@ -527,9 +698,10 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
527
698
  });
528
699
  return;
529
700
  }
530
- const collapseKey = agentsCollapseKey(env);
531
- const viewKey = agentsViewKey(env);
532
- const stopKey = agentsStopKey(env);
701
+ const keymaps = loadKeymaps(env).bindings;
702
+ const collapseKey = agentsCollapseKey(env, keymaps);
703
+ const viewKey = agentsViewKey(env, keymaps);
704
+ const stopKey = agentsStopKey(env, keymaps);
533
705
  const store = new TaskStore();
534
706
  // Attach before any live add/start; restore and unchanged updates are silent.
535
707
  // TaskStore contains bus listener failures so notifications cannot fail tools.
@@ -538,6 +710,53 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
538
710
  const restoredTaskIds = new Set<string>();
539
711
  const tasksDir = historyDir(deps.home, agentHome);
540
712
  let ui: ExtensionContext["ui"] | undefined;
713
+ // The session that owns the Agents widget, so a click on an agent row opens its /gentle:agents view.
714
+ let widgetCtx: ExtensionContext | undefined;
715
+ // The catalog prices a fallback notice ("2.0x the price").
716
+ let modelRegistry: ExtensionContext["modelRegistry"] | undefined;
717
+ const announceFallback = (change: FallbackChange, parentSessionId: string | undefined, taskId?: string) => {
718
+ // Only the session that owns the run hears about it and records it.
719
+ if (parentSessionId !== undefined && activeSessionId() !== parentSessionId) return;
720
+ try { pi.appendEntry(MODEL_FALLBACK_ENTRY, { ...change, ...(taskId ? { taskId } : {}), at: deps.now() }); } catch { /* The switch matters more than its record. */ }
721
+ const prices = (model: { provider: string | undefined; id: string }) => (model.provider ? modelRegistry?.find(model.provider, model.id)?.cost : undefined);
722
+ ui?.notify(fallbackNotice(change, prices), "warning");
723
+ };
724
+ // One episode state per main session: a chain is walked once until a turn succeeds.
725
+ const orchestratorFallbacks = new Map<string, ReturnType<typeof createOrchestratorFallback>>();
726
+ const orchestratorFallbackFor = (ctx: ExtensionContext) => {
727
+ const sessionId = ctx.sessionManager.getSessionId() ?? "";
728
+ let fallback = orchestratorFallbacks.get(sessionId);
729
+ if (fallback) return fallback;
730
+ const find = (model: string) => {
731
+ const ref = parseModelRef(model);
732
+ return ref?.provider ? ctx.modelRegistry?.find(ref.provider, ref.id) : undefined;
733
+ };
734
+ fallback = createOrchestratorFallback({
735
+ chain: () => {
736
+ const configHome = gentlePiConfigHome(deps.env);
737
+ const resolution = resolveSessionProfile({ sessionId: ctx.sessionManager.getSessionId(), cwd: ctx.sessionManager.getCwd(), configHome, resolveWorktree: deps.resolveWorktree, env: deps.env });
738
+ return profileFallbackChain(configHome, resolution.kind === "explicit" ? resolution.name : resolution.profile?.name, "orchestrator");
739
+ },
740
+ current: () => (ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined),
741
+ available: (model) => find(model) !== undefined,
742
+ setModel: async (model) => {
743
+ const found = find(model);
744
+ return found ? pi.setModel(found) : false;
745
+ },
746
+ setThinking: (level) => pi.setThinkingLevel(level),
747
+ // Unknown effort (an older host without the call) keeps each step's own effort only.
748
+ thinking: () => {
749
+ try { return typeof pi.getThinkingLevel === "function" ? pi.getThinkingLevel() as ThinkingLevel : undefined; }
750
+ catch { return undefined; }
751
+ },
752
+ announce: (change) => announceFallback(change, undefined),
753
+ resume: (message) => pi.sendUserMessage(message, { deliverAs: "followUp" }),
754
+ cooldown: sharedCooldown(),
755
+ now: () => deps.now(),
756
+ });
757
+ orchestratorFallbacks.set(sessionId, fallback);
758
+ return fallback;
759
+ };
541
760
  let host: { requestRender(): void } | undefined;
542
761
  let sidebarTui: TUI | undefined;
543
762
  const visualHome = gentlePiConfigHome(env);
@@ -1309,14 +1528,22 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1309
1528
  deliveryRetries = 0;
1310
1529
  endPromptStart();
1311
1530
  });
1312
- pi.on("agent_end", () => {
1531
+ // The last attempt's messages, kept until the run settles: Pi fires agent_end
1532
+ // on every failed attempt and decides on a retry afterwards.
1533
+ let lastRunMessages: readonly unknown[] = [];
1534
+ pi.on("agent_end", (event) => {
1313
1535
  activeAgentRuns = Math.max(0, activeAgentRuns - 1);
1314
1536
  flushAll();
1537
+ lastRunMessages = event?.messages ?? [];
1315
1538
  });
1316
- pi.on("agent_settled", () => {
1539
+ pi.on("agent_settled", (event, ctx) => {
1317
1540
  parentRunActive = false;
1318
1541
  endPromptStart();
1319
1542
  flushAll();
1543
+ const messages = lastRunMessages;
1544
+ lastRunMessages = [];
1545
+ // A child's own failures are handled by the parent's runner, never by the child.
1546
+ if (deps.env.GENTLE_PI_AGENTS_CHILD !== "1" && ctx) void orchestratorFallbackFor(ctx).onSettled(messages, { aborted: event?.aborted === true }).catch((error: unknown) => ui?.notify(`Model fallback failed: ${error instanceof Error ? error.message : String(error)}`, "error"));
1320
1547
  });
1321
1548
  pi.on("turn_end", () => flushAll());
1322
1549
  pi.on("session_compact", scheduleBoundaryFlush);
@@ -1348,6 +1575,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1348
1575
  if (outcome === "replied") messages.consumeQuery(taskId, requestId);
1349
1576
  else messages.expireQuery(taskId, requestId);
1350
1577
  },
1578
+ onFallback: (task, change) => announceFallback({ agent: task.agent, from: change.from, to: change.to, category: change.category, ...(change.launch ? { launch: true } : {}) }, task.parentSessionId, task.id),
1351
1579
  onSuccessfulMutation: (task, tool) => {
1352
1580
  // Same-clone registry attribution remains unchanged. A foreign task
1353
1581
  // uses a separately bound, live-grant path only for successful tool evidence.
@@ -1428,7 +1656,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1428
1656
  const details = (message.details as { gentleAgents?: { taskId?: unknown; agent?: unknown } } | undefined)?.gentleAgents;
1429
1657
  const taskId = typeof details?.taskId === "string" ? details.taskId : "unknown";
1430
1658
  const agent = typeof details?.agent === "string" ? details.agent : "Subagent";
1431
- const heading = `${sanitizeTerminalText(agent)} message · Task ${sanitizeTerminalText(taskId)}`;
1659
+ const heading = `${ACTION_GLYPH.send_message} ${sanitizeTerminalText(agent)} message · Task ${sanitizeTerminalText(taskId)}`;
1432
1660
  const body = sanitizeTerminalText(messageText(message.content));
1433
1661
  return new Text(`${theme.fg("customMessageLabel", heading)}\n${theme.fg("customMessageText", body)}`, options.outputPad, 0);
1434
1662
  });
@@ -1442,12 +1670,21 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1442
1670
  const details = (message.details as { gentleAgents?: { agent?: string; status?: string } } | undefined)?.gentleAgents;
1443
1671
  const content = message.content as string | Array<{ type: string; text?: string }>;
1444
1672
  const text = typeof content === "string" ? content : content.map((part) => (part.type === "text" ? (part.text ?? "") : "")).join("\n");
1445
- const body = options.expanded ? text.split("\n") : agentResultPreview(text).split("\n").filter((line) => line.trim() !== "");
1446
1673
  const tone = details?.status === "completed" ? CARD_TONE.SUCCESS : CARD_TONE.ERROR;
1447
1674
  const hint = expandHint(options.expanded);
1675
+ // The same answer card as the tool result: iris chrome, the state pill
1676
+ // on top, the answer below ("answer" keeps its name through the flow).
1677
+ const t = agentTheme(theme, tone);
1678
+ const facts = details?.status ? statusCardFacts({ gentleAgents: details }) : undefined;
1679
+ const chips = [details?.agent, modelChip(facts?.model), facts?.thinking ? sanitizeTerminalText(facts.thinking) : undefined];
1680
+ const answer = options.expanded ? text.split("\n") : agentResultPreview(text).split("\n").filter((line) => line.trim() !== "");
1681
+ const body = facts ? [statusCardRows(facts, t, false)[0], ...answer] : answer;
1448
1682
  return {
1449
1683
  render(width: number) {
1450
- return renderCard({ title: "Agent result", subtitle: details?.agent, body, tone, glyph: AGENTS_GLYPH }, theme, width, { expanded: options.expanded, previewRows: 3, hint });
1684
+ // Same one-line heading budget as the tool cards: the answer card's
1685
+ // inner columns are the style's, not the terminal's.
1686
+ const subtitle = fitSubject({ title: "Agent answer", tone, glyph: ACTION_GLYPH.result }, hint, panelInnerWidth(theme, width, tone), chips);
1687
+ return renderCard({ title: "Agent answer", subtitle, body, tone, glyph: ACTION_GLYPH.result }, t, width, { expanded: options.expanded, previewRows: 3, hint });
1451
1688
  },
1452
1689
  invalidate() {},
1453
1690
  };
@@ -1469,7 +1706,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1469
1706
  ];
1470
1707
  return {
1471
1708
  render(width: number) {
1472
- return renderCard({ title: "Stale agent result", subtitle: `${agent} · task ${taskId}`, body, tone: CARD_TONE.WARNING, glyph: AGENTS_GLYPH }, theme, width, { expanded: options.expanded, previewRows: 3, hint: expandHint(options.expanded) });
1709
+ return renderCard({ title: "Stale agent answer", subtitle: `${headingText(agent)} · task ${headingText(taskId)}`, body, tone: CARD_TONE.WARNING, glyph: ACTION_GLYPH.result }, agentTheme(theme, CARD_TONE.WARNING), width, { expanded: options.expanded, previewRows: 3, hint: expandHint(options.expanded) });
1473
1710
  },
1474
1711
  invalidate() {},
1475
1712
  };
@@ -1652,7 +1889,9 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1652
1889
  });
1653
1890
 
1654
1891
  const showWidget = (ctx: ExtensionContext) => {
1892
+ widgetCtx = ctx;
1655
1893
  ui = ctx.hasUI ? ctx.ui : undefined;
1894
+ modelRegistry = ctx.modelRegistry;
1656
1895
  sessions = ctx.sessionManager;
1657
1896
  agentsVisible = resolveVisualSettings({ gentlePiConfigHome: visualHome }).settings.visibility.agents;
1658
1897
  stopVisualUpdates?.();
@@ -1681,42 +1920,76 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1681
1920
 
1682
1921
  // One surface of the Agents card. The rail is natively scrollable, so it
1683
1922
  // lists every task; the above-editor widget keeps its row budget. Only the
1684
- // header row is the clickable collapse control, exactly like Todos.
1685
- const agentsCard = (tui: TUI, theme: Parameters<typeof renderAgentsCard>[1], rail: boolean): Component & { dispose(): void; digest(): string } => {
1923
+ // header row is the clickable collapse control, exactly like Todos; a click
1924
+ // on an agent row below it opens /gentle:agents.
1925
+ const agentsCard = (tui: TUI, theme: Parameters<typeof renderAgentsCard>[1], rail: boolean): Component & { dispose(): void; digest(): string; surface?: "panel"; summary?(): ReturnType<typeof agentsSummary>; alert?(width: number): string[]; open?(): void } => {
1686
1926
  let hovered = false;
1927
+ let hoveredRow: number | undefined;
1687
1928
  let headerRow = 0;
1929
+ const agentRows = new Set<number>();
1930
+ // The rows the card drew last, so a click past them (the card's spacer) opens nothing.
1931
+ let drawnRows = 0;
1688
1932
  const card: Component = {
1689
1933
  render(width: number) {
1934
+ drawnRows = 0;
1935
+ agentRows.clear();
1690
1936
  if (!agentsVisible) return [];
1691
1937
  const tasks = visibleTasks();
1692
1938
  const now = deps.now();
1939
+ // The fullscreen rail draws a panel section (header on row 0) that
1940
+ // stays as one idle row without tasks; above the editor it is a card.
1941
+ if (rail) {
1942
+ headerRow = 0;
1943
+ const rows = renderAgentsSection(tasks, theme, width, now, { collapsed, hovered, hoveredRow, onAgentRow: (row) => agentRows.add(row) });
1944
+ drawnRows = tasks.length === 0 ? 0 : rows.length;
1945
+ return rows;
1946
+ }
1693
1947
  headerRow = panelHeaderRow(theme, width, agentsCardTone(tasks, now));
1694
- const lines = renderAgentsCard(tasks, theme, width, now, { collapsed, collapseKey, maxRows: rail ? undefined : widgetRows(tui.terminal?.rows), viewKey, collapseControl: true, hovered });
1695
- return lines.length === 0 || rail ? lines : [...lines, ""];
1948
+ const lines = renderAgentsCard(tasks, theme, width, now, { collapsed, collapseKey, maxRows: widgetRows(tui.terminal?.rows), viewKey, collapseControl: true, hovered, hoveredRow, onAgentRow: (row) => agentRows.add(row) });
1949
+ drawnRows = tasks.length === 0 ? 0 : lines.length;
1950
+ return lines.length === 0 ? lines : [...lines, ""];
1696
1951
  },
1697
1952
  invalidate() {
1698
1953
  hovered = false;
1954
+ hoveredRow = undefined;
1699
1955
  },
1700
1956
  };
1701
1957
  const region = new NativePointerRegion(card, {
1702
1958
  onHover(event) {
1703
1959
  const next = event.y === headerRow;
1704
- if (next === hovered) return { handled: true };
1960
+ const nextRow = agentRows.has(event.y) ? event.y : undefined;
1961
+ if (next || nextRow !== undefined) setSidebarHover(tui, region, () => region.clearHover());
1962
+ else setSidebarHover(tui);
1963
+ if (next === hovered && nextRow === hoveredRow) return { handled: true };
1705
1964
  hovered = next;
1965
+ hoveredRow = nextRow;
1706
1966
  return { handled: true, render: true };
1707
1967
  },
1708
1968
  onLeave() {
1709
- if (!hovered) return;
1969
+ releaseSidebarHover(tui, region);
1970
+ if (!hovered && hoveredRow === undefined) return;
1710
1971
  hovered = false;
1972
+ hoveredRow = undefined;
1711
1973
  host?.requestRender();
1712
1974
  },
1713
1975
  onClick(event) {
1714
- if (event.button !== "left" || event.y !== headerRow) return undefined;
1715
- toggleCollapsed();
1976
+ if (event.button !== "left") return undefined;
1977
+ region.clearHover();
1978
+ if (event.y === headerRow) {
1979
+ toggleCollapsed();
1980
+ return { handled: true, render: true };
1981
+ }
1982
+ if (event.y < headerRow || event.y >= drawnRows || !widgetCtx) return undefined;
1983
+ void openOverlay(widgetCtx);
1716
1984
  return { handled: true, render: true };
1717
1985
  },
1718
1986
  });
1719
1987
  return {
1988
+ // The mobile work row folds this section; a tap on it opens /gentle:agents.
1989
+ ...(rail ? { open: () => { if (widgetCtx) void openOverlay(widgetCtx); } } : {}),
1990
+ // The panel editor draws the alert above its rule while the IDE chrome
1991
+ // hides the above-editor card (rail or mobile work row).
1992
+ ...(rail ? { surface: "panel" as const, summary: () => (agentsVisible ? agentsSummary(visibleTasks(), theme, deps.now()) : undefined), alert: (width: number) => (agentsVisible ? renderAgentsAlert(visibleTasks(), theme, width) : []), spend: () => agentsSpend(visibleTasks()) } : {}),
1720
1993
  // The rail memo repaints a part only when its digest moves: task
1721
1994
  // state, the local controls, and the elapsed clock (to the second)
1722
1995
  // only while a task is still running, so an idle or finished card
@@ -1724,7 +1997,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1724
1997
  digest: () => {
1725
1998
  const tasks = visibleTasks();
1726
1999
  const clock = tasks.some((task) => !isFinished(task.status)) ? Math.floor(deps.now() / 1000) : 0;
1727
- return JSON.stringify([agentsVisible, collapsed, hovered, tui.terminal?.rows, clock, tasks.map((task) => [task.id, task.status, task.tokens, task.cost, task.label, task.lastStep, task.error])]);
2000
+ return JSON.stringify([agentsVisible, collapsed, hovered, hoveredRow, tui.terminal?.rows, clock, tasks.map((task) => [task.id, task.status, task.tokens, task.cost, task.label, task.lastStep, task.error])]);
1728
2001
  },
1729
2002
  render: (width) => region.render(width),
1730
2003
  handleMouse: (event) => region.handleMouse(event),
@@ -1760,6 +2033,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1760
2033
  // bound session used to kill its own non-git writer mid-preparation because
1761
2034
  // admission still read only the pin/global layers). Slice 3b-ii: the same
1762
2035
  // read covers the frozen inherited profile and `follow` mode.
2036
+ requireSessionProfileAuthority(ctx.sessionManager);
1763
2037
  const profileConfigHome = gentlePiConfigHome(deps.env);
1764
2038
  const sessionProfile = resolveSessionProfile({
1765
2039
  sessionId: ctx.sessionManager.getSessionId(),
@@ -1781,6 +2055,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1781
2055
  admittedModel = `${catalogModel.provider}/${catalogModel.id}`;
1782
2056
  if (!current() || !await prepareBoundSessionRepository(originalManager, originalCwd, signal) || !current() || safeBootstrapDirectory(originalCwd) !== root || resolveSessionWorktree(originalCwd, originalCwd)?.root !== root) throw new Error("Writer repository preparation was unavailable or its session/target changed.");
1783
2057
  }
2058
+ requireSessionProfileAuthority(originalManager);
1784
2059
  const parentCwd = ctx.sessionManager.getCwd();
1785
2060
  // An explicit target is validated before any queue or session-dir writes.
1786
2061
  const parentIdentity = deps.resolveWorktree(parentCwd, parentCwd);
@@ -1827,6 +2102,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1827
2102
  // included; only `follow` reads the defaults of the target. The profile is
1828
2103
  // resolved here, at task-request creation, so queued and running children
1829
2104
  // keep the routing frozen into their requests even if the session rebinds.
2105
+ requireSessionProfileAuthority(originalManager);
1830
2106
  // The routing target this launch reads (#1064), reused to name the winning
1831
2107
  // layer (#2180) so both answers come from one resolution.
1832
2108
  const routingTarget = {
@@ -1859,7 +2135,9 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1859
2135
  // inheriting and a matched key never warns. Keys are checked against every
1860
2136
  // discovered agent, so a key naming another agent is never reported here.
1861
2137
  if (ctx.hasUI) {
1862
- const unmatched = unmatchedProfileKeys(config.modelProfiles, discoverAgents(roots(ctx)).agents);
2138
+ // Provider review roles are routed by key and never have an agent file.
2139
+ const known = [...PROVIDER_REVIEW_ROLES.map((name) => ({ name })), ...discoverAgents(roots(ctx)).agents];
2140
+ const unmatched = unmatchedProfileKeys(config.modelProfiles, known);
1863
2141
  const nearMisses = unmatched.filter((entry) => entry.suggestion === agent.name);
1864
2142
  if (nearMisses.length > 0) {
1865
2143
  ctx.ui.notify(nearMisses.map((entry) => `"${entry.key}" did not match any agent, did you mean ${agent.name}?`).join(" "), "warning");
@@ -1895,7 +2173,17 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1895
2173
  const parentWorktreeRoot = ctx.sessionManager.getCwd();
1896
2174
  const parentRepositoryIdentity = resolveCanonicalGitRepositoryIdentitySync(parentWorktreeRoot);
1897
2175
  const childEnv = { ...deps.env };
2176
+ delete childEnv[CHILD_TIER_ENV];
2177
+ const childModel = profile.model ?? ctx.model;
2178
+ if (profile.tier && childModel?.provider && childModel.id) {
2179
+ childEnv[CHILD_TIER_ENV] = JSON.stringify({ tier: profile.tier, model: `${childModel.provider}/${childModel.id}` });
2180
+ }
1898
2181
  if (foreign) for (const key of inheritedUnsafeGitEnvironmentKeys(childEnv)) delete childEnv[key];
2182
+ const extensions = childExtensionRequest(deps.env, deps.childExtensionPaths);
2183
+ if (profile.tier && !parseChildPackageInjection(deps.env)) {
2184
+ const fastPath = fileURLToPath(new URL("./gentle-fast.ts", import.meta.url));
2185
+ if (existsSync(fastPath)) extensions.extensionPaths = [...new Set([...(extensions.extensionPaths ?? []), fastPath])];
2186
+ }
1899
2187
  const request: TaskRequest = {
1900
2188
  agent,
1901
2189
  prompt,
@@ -1919,9 +2207,15 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1919
2207
  model: profile.model,
1920
2208
  ...(modelSource === undefined ? {} : { modelSource }),
1921
2209
  thinking: profile.thinking,
2210
+ ...(() => {
2211
+ // The chain of the profile this launch resolved, else the active profile's.
2212
+ const name = sessionProfile.kind === "explicit" ? sessionProfile.name : sessionProfile.profile?.name;
2213
+ const fallbacks = profileFallbackChain(profileConfigHome, name, agent.name);
2214
+ return fallbacks.length ? { fallbacks } : {};
2215
+ })(),
1922
2216
  sessionDir,
1923
2217
  resumeSessionPath: resume,
1924
- ...childExtensionRequest(deps.env, deps.childExtensionPaths),
2218
+ ...extensions,
1925
2219
  // A writer claims its surfaces in its canonical worktree root for its queued
1926
2220
  // and running lifetime; a continuation is a new task and claims them again.
1927
2221
  ...(isBoundedWriter(agent.name) && surfaces ? { writerSurfaces: surfaces, writerRoot: canonicalWriterRoot(target ?? parentWorktreeRoot, foreign ? resolveSessionWorktree : deps.resolveWorktree) } : {}),
@@ -2025,28 +2319,152 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2025
2319
  };
2026
2320
 
2027
2321
  const tool = (name: string, description: string, parameters: Record<string, unknown>, execute: (params: Record<string, unknown>, ctx: ExtensionContext, signal?: AbortSignal) => Promise<ToolText>) => {
2322
+ const heading = ACTION_HEADING[name] ?? `agent ${name.replace(/_/g, " ")}`;
2323
+ const glyph = ACTION_GLYPH[name] ?? AGENTS_GLYPH;
2324
+ // The agent chip: the call shows who it works with, and what that child
2325
+ // runs on. Status-style calls only carry a task id, so the store resolves
2326
+ // the agent and its launch profile.
2327
+ const subject = (params: { agent?: string; task_id?: string }, launched?: { agentProfile?: boolean; agentModel?: string; agentEffort?: string }): { agent?: string; taskRef?: string; model?: string; effort?: string } => {
2328
+ const task = typeof params.task_id === "string" ? store.get(params.task_id) : undefined;
2329
+ const agent = typeof params.agent === "string" && params.agent.trim() ? headingText(params.agent)
2330
+ : task ? headingText(task.agent) || undefined
2331
+ : undefined;
2332
+ const taskRef = typeof params.task_id === "string" ? `task ${headingText(params.task_id)}` : undefined;
2333
+ // A launch has no task id at call time, so its profile arrives through
2334
+ // the shared row state once the result slot knows it. Once it speaks for
2335
+ // this call it wins whole: a continuation is a new task, so keeping the
2336
+ // predecessor's model — or its effort when the new one has none — would
2337
+ // name the wrong child.
2338
+ const fresh = launched?.agentProfile === true;
2339
+ const model = fresh ? launched?.agentModel : modelChip(task?.model);
2340
+ const effort = fresh ? launched?.agentEffort : task?.thinking ? headingText(task.thinking) : undefined;
2341
+ return { agent, taskRef, model, effort };
2342
+ };
2343
+ const agentToolContext = (context: CardRowContext & { expanded?: boolean; isError?: boolean; state?: { agentFailed?: boolean; agentProfile?: boolean; agentModel?: string; agentEffort?: string } } | undefined) => context ?? {};
2028
2344
  pi.registerTool({
2029
2345
  name: `${TOOL_PREFIX}${name}`,
2030
2346
  renderShell: "self",
2031
2347
  label: `Agent ${name.replace(/_/g, " ")}`,
2032
2348
  description,
2033
2349
  parameters: { type: "object", additionalProperties: false, ...parameters } as never,
2034
- renderCall(args, theme) {
2350
+ // The same tool-card protocol the orchestrator tools use: the call
2351
+ // draws the card heading and closes its own frame while the result
2352
+ // is pending; the result then continues the card (afterHeading) and
2353
+ // closes it — one continuous card in the user's card style, never a
2354
+ // bare title over a second frame.
2355
+ renderCall(args, theme, context) {
2035
2356
  // The result title belongs with the result body so a running poll
2036
2357
  // can hide both without changing the tool call or its model output.
2037
2358
  if (name === "result") return { render: () => [], invalidate() {} };
2038
- const params = args as { agent?: string; task_id?: string };
2039
- return new Text(theme.fg("toolTitle", `${AGENTS_GLYPH} agent ${name.replace(/_/g, " ")}${params.agent ? ` · ${params.agent}` : params.task_id ? ` · ${params.task_id}` : ""}`), 0, 0);
2359
+ return {
2360
+ render(width: number) {
2361
+ if (width <= 0) return [];
2362
+ const row = agentToolContext(context);
2363
+ // Resolved per frame: the store gains the task and its profile after
2364
+ // the call is first drawn, and the heading has to catch up.
2365
+ const { agent, taskRef, model, effort } = subject(args as { agent?: string; task_id?: string }, row.state);
2366
+ const chips = [agent, taskRef, model, effort];
2367
+ // The heading is this slot's, so a failure the result slot learns about
2368
+ // has to travel through the shared row state: a rejected call wears the
2369
+ // error frame instead of reading as a delegation still in flight. The
2370
+ // row context is a snapshot, so its own isError cannot be trusted here.
2371
+ const tone = row.isError || row.state?.agentFailed ? CARD_TONE.ERROR : CARD_TONE.INFO;
2372
+ const iris = agentTheme(theme, tone);
2373
+ const hint = expandHint(!!row.expanded);
2374
+ return floatRows(tone, iris, width, (inner) => ({
2375
+ head: [cardTop({ title: heading, subtitle: fitSubject({ title: heading, tone, glyph }, hint, inner, chips), body: [], tone, glyph }, iris, inner, hint)],
2376
+ ...(cardAwaitingResult(row) ? { body: [cardRunningLine(tone, iris, inner)], bottom: cardBottom(tone, iris, inner) } : {}),
2377
+ }));
2378
+ },
2379
+ invalidate() {},
2380
+ };
2040
2381
  },
2041
- renderResult(result, options, theme) {
2042
- const task = (result.details as { gentleAgents?: { status?: string; taskId?: string } } | undefined)?.gentleAgents;
2382
+ renderResult(result, options, theme, context) {
2383
+ const task = (result.details as { gentleAgents?: { status?: string; taskId?: string; agent?: string } } | undefined)?.gentleAgents;
2043
2384
  if (name === "result" && task?.status === TASK_STATUS.RUNNING) {
2044
2385
  return { render: () => [], invalidate() {} };
2045
2386
  }
2387
+ if (!options.isPartial) markCardResult(agentToolContext(context).state);
2388
+ // A host error (a throw before any details exist) counts like a
2389
+ // details error, so the result keeps the tone the call already shows —
2390
+ // and the call's snapshot needs the flag to wear it too.
2391
+ const row = agentToolContext(context);
2392
+ const failed = row.isError === true || (result.details as { error?: unknown } | undefined)?.error !== undefined;
2393
+ if (row.state !== undefined) {
2394
+ row.state.agentFailed = failed;
2395
+ }
2396
+ // Parsed for every tool: the answer and status cards lead with the
2397
+ // facts, and every card names the launch profile in its heading.
2398
+ const facts = statusCardFacts(result.details);
2399
+ if (row.state !== undefined) {
2400
+ // The call slot draws the heading, so what the child runs on has to
2401
+ // reach it the same way the failure does.
2402
+ row.state.agentModel = modelChip(facts?.model);
2403
+ row.state.agentEffort = facts?.thinking ? headingText(facts.thinking) : undefined;
2404
+ // From here the result speaks for this call's profile: the store's
2405
+ // task may be a different one (a continuation's predecessor).
2406
+ row.state.agentProfile = true;
2407
+ }
2046
2408
  const body = result.content.map((part) => (part.type === "text" ? part.text : "")).join("\n");
2047
- const visibleBody = options.expanded ? body : theme.fg("muted", agentResultPreview(body).split("\n")[0] ?? "");
2048
- const title = `${AGENTS_GLYPH} agent result${task?.taskId ? ` · ${sanitizeTerminalText(task.taskId)}` : ""}`;
2049
- return new Text(name === "result" ? `${theme.fg("toolTitle", title)}\n${visibleBody}` : visibleBody, 0, 0);
2409
+ let tone: CardTone = failed ? CARD_TONE.ERROR : CARD_TONE.INFO;
2410
+ // Status answers a real orchestration decision, so its task facts
2411
+ // lead the card; the answer card gets the state pill when the
2412
+ // result carries them. Anything without structured details (older
2413
+ // sessions, error results) falls back to the text preview.
2414
+ // Only the status and answer cards lead with the facts; every card
2415
+ // still names the launch profile in its heading.
2416
+ const cardFacts = name === "status" || name === "result" ? facts : undefined;
2417
+ if (cardFacts) tone = STATUS_CARD_TONE[cardFacts.status ?? ""] ?? tone;
2418
+ const iris = agentTheme(theme, tone);
2419
+ let rows: string[];
2420
+ if (cardFacts) {
2421
+ if (name === "status") {
2422
+ rows = statusCardRows(cardFacts, iris, options.expanded);
2423
+ } else {
2424
+ // The answer card: the state pill on top, the answer below.
2425
+ const pillRow = statusCardRows(cardFacts, iris, options.expanded)[0] ?? "";
2426
+ const answer = options.expanded ? body.split("\n") : agentResultPreview(body).split("\n").filter((line) => line.trim() !== "");
2427
+ rows = [pillRow, ...answer];
2428
+ }
2429
+ } else if (options.expanded) {
2430
+ rows = failed ? [statusPill(TASK_STATUS.FAILED, iris), ...body.split("\n")] : body.split("\n");
2431
+ } else {
2432
+ // The collapsed preview leads with the meaningful content: the
2433
+ // answer for finished tasks, the state line for anything else.
2434
+ const preview = agentResultPreview(body).split("\n").filter((line) => line.trim() !== "");
2435
+ // Without facts there is no status to name, but a failure still has
2436
+ // to lead: the pill is the card's one scanable state channel.
2437
+ rows = failed ? [statusPill(TASK_STATUS.FAILED, iris), ...preview] : preview;
2438
+ }
2439
+ // The result tool hides its call, so the result draws the heading
2440
+ // itself; every other tool continues the call's card. Either way the
2441
+ // heading names the agent and what it runs on.
2442
+ const ownHeading = name === "result";
2443
+ // A collapsed status card keeps state, label and last step on one
2444
+ // row each, so a narrow terminal clips them instead of wrapping the
2445
+ // last step out of the three-row preview.
2446
+ const fitRows = !options.expanded && name === "status" && facts !== undefined;
2447
+ const ownChips = ownHeading
2448
+ ? [
2449
+ facts?.agent ? headingText(facts.agent) : facts ? `task ${headingText(facts.taskId)}` : undefined,
2450
+ modelChip(facts?.model),
2451
+ facts?.thinking ? headingText(facts.thinking) : undefined,
2452
+ ]
2453
+ : [];
2454
+ return {
2455
+ render(width: number) {
2456
+ if (width <= 0) return [];
2457
+ const hint = expandHint(options.expanded);
2458
+ return floatRows(tone, iris, width, (inner) => ({
2459
+ ...(ownHeading ? {
2460
+ head: [cardTop({ title: heading, subtitle: fitSubject({ title: heading, tone, glyph }, hint, inner, ownChips), body: [], tone, glyph }, iris, inner, hint)],
2461
+ } : { afterHeading: true }),
2462
+ body: cardBodyRows(fitRows ? rows.map((row) => truncateToWidth(row, cardInnerWidth(inner), "…")) : rows, tone, iris, inner, { expanded: options.expanded, previewRows: ownHeading ? 3 : undefined }),
2463
+ bottom: cardBottom(tone, iris, inner),
2464
+ }));
2465
+ },
2466
+ invalidate() {},
2467
+ };
2050
2468
  },
2051
2469
  async execute(_id, params, signal, _onUpdate, ctx) {
2052
2470
  return execute(params as Record<string, unknown>, ctx, signal);
@@ -2057,19 +2475,19 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2057
2475
  pi.registerTool({
2058
2476
  name: "orchestrator_session_id",
2059
2477
  label: "Orchestrator session ID",
2060
- description: "Return this host session's stable routing ID, Initial alias (FIRST TASK), Current alias (CURRENT TASK), and separate human Session name. Explicit subjects update Current even when named; Initial stays the first declared branch topic, unknown for legacy history. Publishing state.work with an explicit topic and no subject also refreshes Current from that topic; keep work.topic current when the task changes. Before delegation or cross-session coordination, declare a short recognizable subject here. Do not require a subject declaration for small direct tasks; do not query all peers. Names never authenticate. Existing Pi names and human renames are preserved. Use a concise non-sensitive label, not a prompt. Progress is published automatically from the todo list; publish state here only for objective, decisions, blockers, or work, never just to report progress. Owner-curated state (2048 UTF-8 bytes total): null withdraws, omission leaves unchanged. Never include credentials, internal instructions, or raw prompts. Historical notes are not consent or an owner reply.",
2478
+ description: "Return this session's stable routing ID, Initial alias (FIRST TASK), Current alias (CURRENT TASK), and separate human Session name. Subject updates Current even when named; Initial is the first declared branch topic, unknown for legacy history. Without subject, explicit state.work.topic updates Current; keep it current as tasks change. Before delegation or cross-session coordination, declare a short recognizable non-sensitive subject, not a prompt. Do not require a subject declaration for small direct tasks. Do not query all peers. Names never authenticate. Existing Pi names and human renames are preserved. Progress is published automatically from the todo list; publish state only for objective, decisions, blockers or work, never just progress. Classified work must publish objective and work.topic/area at session start and every task-topic change; never retain old task state. Catalog flags never-published peers. Owner-curated state: 2048 UTF-8 bytes total; null withdraws, omission leaves unchanged. Never include credentials, internal instructions, or raw prompts. Historical notes are not consent or an owner reply.",
2061
2479
  ...orchestratorToolRenderers("session", expandHint),
2062
2480
  parameters: { type: "object", additionalProperties: false, properties: {
2063
- subject: { type: "string", maxLength: 120, description: "Optional short task subject; updates task aliases independently of human names. Also names an unnamed Pi session." },
2481
+ subject: { type: "string", maxLength: 120, description: "Short task subject; updates aliases independently of human names and names unnamed Pi sessions." },
2064
2482
  state: { anyOf: [{ type: "null" }, { type: "object", additionalProperties: false, properties: {
2065
2483
  objective: { type: "string" }, progress: { type: "string" }, decisions: { type: "string" }, blockers: { type: "string" },
2066
2484
  work: { type: "object", additionalProperties: false,
2067
- description: "Optional historical, non-authoritative classification; topic requires area. Text plus work JSON fits 2048 UTF-8 bytes. Exact duplicate tags/refs are rejected; no ref resolution or routing.",
2485
+ description: "Historical, non-authoritative; topic requires area. Text and work JSON share 2048 UTF-8 bytes. Reject exact duplicate tags/refs; no ref resolution or routing.",
2068
2486
  properties: {
2069
2487
  ...workDescriptorSchema.properties,
2070
2488
  tasks: { type: "object", maxProperties: 8, propertyNames: { type: "string", maxLength: 256 },
2071
2489
  additionalProperties: workDescriptorSchema,
2072
- description: "Exact actual owner-declared task IDs, at most 256 UTF-8 bytes; controls, surrogates and __proto__/prototype/constructor rejected. Root-only; nonempty tasks alone are valid. Replacement omitting tasks clears annotations." },
2490
+ description: "Exact owner-declared task IDs, max 256 UTF-8 bytes; no controls, surrogates or __proto__/prototype/constructor. Root-only; nonempty tasks alone valid; replacement without tasks clears annotations." },
2073
2491
  },
2074
2492
  },
2075
2493
  } }] },
@@ -2157,15 +2575,15 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2157
2575
  name: "orchestrator_list",
2158
2576
  label: "List orchestrators",
2159
2577
  ...orchestratorToolRenderers("list", expandHint),
2160
- description: "List other sessions advertised by the trusted local profile. Optional filter searches only published classified work with bounded, non-exhaustive coverage, no authority and unknown reachability. Omit filter for the existing session list.",
2578
+ description: "List other sessions advertised by the trusted local profile. Omit filter for the existing list; filter searches published classified work only: bounded, non-exhaustive, no authority, unknown reachability. Classified work must publish at session start and each task-topic change; flag peers doing classified work who never published state.",
2161
2579
  parameters: Type.Object({
2162
- recipient_session_id: Type.Optional(Type.String({ description: "Exact routing ID of the peer to inspect." })),
2163
- cursor: Type.Optional(Type.String({ description: "Opaque catalog continuation from that peer; requires recipient_session_id." })),
2580
+ recipient_session_id: Type.Optional(Type.String({ description: "Exact peer routing ID." })),
2581
+ cursor: Type.Optional(Type.String({ description: "Opaque peer catalog continuation; requires recipient_session_id." })),
2164
2582
  filter: Type.Optional(Type.Object({
2165
2583
  area: Type.Optional(Type.String()),
2166
2584
  topic: Type.Optional(Type.String({ description: "Requires area." })),
2167
2585
  tag: Type.Optional(Type.String()),
2168
- text: Type.Optional(Type.String({ description: "Literal label/descriptor search, never state prose or history." })),
2586
+ text: Type.Optional(Type.String({ description: "Literal label/descriptor search, not state prose or history." })),
2169
2587
  ref: Type.Optional(Type.Object({
2170
2588
  kind: Type.Union([Type.Literal("issue"), Type.Literal("pr"), Type.Literal("task")]),
2171
2589
  repository: Type.String({ description: "Exact public host/owner/repo scope." }),
@@ -2176,7 +2594,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2176
2594
  session_id: Type.String({ description: "Exact stable source owner session ID." }),
2177
2595
  task_id: Type.Optional(Type.String({ description: "Actual task ID on the current catalog page, not child session ID." })),
2178
2596
  }, { additionalProperties: false })),
2179
- }, { additionalProperties: false, description: "Explicit {} indexes classified work; criteria combine with AND." })),
2597
+ }, { additionalProperties: false, description: "{} indexes classified work; criteria combine with AND." })),
2180
2598
  }, { additionalProperties: false }),
2181
2599
  async execute(_id, _params, _signal, _onUpdate, ctx) {
2182
2600
  const params = _params as { recipient_session_id?: string; cursor?: string; filter?: unknown };
@@ -2200,7 +2618,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2200
2618
  return text(JSON.stringify(workSearch), { gentleAgents: { workSearch } });
2201
2619
  }
2202
2620
  const peers = discoverOrchestrators(agentHome, activations, Date.now(), params.recipient_session_id
2203
- ? { recipientSessionId: params.recipient_session_id, cursor: params.cursor } : undefined);
2621
+ ? { recipientSessionId: params.recipient_session_id, cursor: params.cursor, stateOnly: true } : { stateOnly: true });
2204
2622
  const repository = (fact?: RepositoryFact) => fact?.root
2205
2623
  ? `repository: ${fact.root} · clone: ${fact.cloneHash} · Git resolved at: ${fact.resolvedAt} (${fact.source})`
2206
2624
  : "repository: unknown";
@@ -2215,9 +2633,16 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2215
2633
  const note = params.recipient_session_id ? `\n owner-curated recorded state (not consent or owner reply; authority none): ${peer.state ? JSON.stringify(peer.state) : "unknown"}` : "";
2216
2634
  // A legacy peer never publishes its scope: say so instead of reporting an unknown.
2217
2635
  const legacy = peer.legacyLabel !== undefined;
2218
- return `- ${peer.sessionId}${context} · ${legacy ? "repository: not published" : repository(peer.scope?.host)} · metadata: ${legacy ? "legacy" : peer.freshness}${tasks}${registered}${gaps}${catalog}${note}${peer.omitted ? `\n (${peer.omitted} more tasks omitted)` : ""}`;
2636
+ // A peer doing classified work without ever publishing state cannot be
2637
+ // routed or coordinated with; the catalog says so explicitly (#2633).
2638
+ const unpublished = !legacy && peer.freshness === "recent" && !peer.state && !peer.statePublished
2639
+ ? " · work state: never published" : "";
2640
+ return `- ${peer.sessionId}${context} · ${legacy ? "repository: not published" : repository(peer.scope?.host)} · metadata: ${legacy ? "legacy" : peer.freshness}${tasks}${registered}${gaps}${catalog}${note}${unpublished}${peer.omitted ? `\n (${peer.omitted} more tasks omitted)` : ""}`;
2219
2641
  });
2220
- return peers.length === 0 ? text("No other sessions are currently advertised. Advertisements have unknown reachability and do not guarantee a live session.") : text(`Advertised sessions (reachability is unknown):\n${rows.join("\n")}`, { gentleAgents: { candidates: peers } });
2642
+ if (peers.length === 0) return text("No other sessions are currently advertised. Advertisements have unknown reachability and do not guarantee a live session.");
2643
+ const unlisted = peers.filter(peer => peer.freshness === "recent" && peer.legacyLabel === undefined && !peer.state && !peer.statePublished);
2644
+ const mandate = unlisted.length > 0 ? `\n${unlisted.length} of ${peers.length} advertised sessions have never published work state. Publication is mandatory for classified work: each owner session publishes state (objective, work.topic) at session start and again on every task-topic change via orchestrator_session_id.` : "";
2645
+ return text(`Advertised sessions (reachability is unknown):\n${rows.join("\n")}${mandate}`, { gentleAgents: { candidates: peers } });
2221
2646
  } catch (error) {
2222
2647
  // SessionPresenceError codes are a fixed enum with no record content,
2223
2648
  // so surfacing the reason is safe and keeps diagnosis possible.
@@ -2326,6 +2751,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2326
2751
  },
2327
2752
  },
2328
2753
  async (params, ctx, signal) => {
2754
+ requireSessionProfileAuthority(ctx.sessionManager);
2329
2755
  const work = Object.hasOwn(params, "work") ? decodeWorkDescriptor(params.work) : undefined;
2330
2756
  const manager = ctx.sessionManager, sessionId = manager.getSessionId();
2331
2757
  if (typeof params.agent !== "string" || !params.agent.trim() || typeof params.task !== "string" || !params.task.trim() || (params.context !== undefined && typeof params.context !== "string") || (params.label !== undefined && typeof params.label !== "string")) throw new Error("Subagent dispatch requires a named agent, non-empty task and string context/label.");
@@ -2411,6 +2837,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2411
2837
  "Resume a finished subagent task in its own session with a follow-up prompt.",
2412
2838
  { required: ["task_id", "prompt"], properties: { task_id: { type: "string" }, prompt: { type: "string" }, label: { type: "string", description: "Three to six words naming the follow-up." }, mode: { type: "string", enum: ["task", "background"] } } },
2413
2839
  async (params, ctx, signal) => {
2840
+ requireSessionProfileAuthority(ctx.sessionManager);
2414
2841
  if (Object.hasOwn(params, "sdd_change") || Object.hasOwn(params, "remediation") || Object.hasOwn(params, "research_selection")) return text("Error: retired SDD delegation is not supported.", { error: "retired SDD delegation" });
2415
2842
  const previous = await resolveTask(String(params.task_id));
2416
2843
  if (!previous) return unknownTask(params.task_id, ctx);