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
@@ -573,6 +573,9 @@ export function readGitBranch(cwd: string, run: typeof execFile = execFile, time
573
573
  // Pi dispatches its subcommands purely on the first argument, so only that
574
574
  // token decides. Flag values such as the package directory the Gentle Shell
575
575
  // launcher injects with `-e <dir>` must not be mistaken for a subcommand.
576
+ const GUIDE_COMMAND = "gentle:guide";
577
+ export const GUIDE_REMINDER = "Tip: run /gentle:guide for a guided tour of Gentle Shell";
578
+
576
579
  export function isPiCliSubcommandInvocation(argv: readonly string[]): boolean {
577
580
  const first = argv[2];
578
581
  return first !== undefined && (PI_SUBCOMMANDS as readonly string[]).includes(first);
@@ -676,6 +679,8 @@ export default function (pi: ExtensionAPI) {
676
679
  let backgroundAgentsCount = 0;
677
680
 
678
681
  const allCommands = pi.getCommands();
682
+ // A one-line reminder under the banner on every start, while the tour exists.
683
+ const guideReminder = allCommands.some((c) => c.name === GUIDE_COMMAND) ? GUIDE_REMINDER : undefined;
679
684
  const skills = allCommands.filter((c) => c.source === "skill");
680
685
  const allTools = pi.getAllTools();
681
686
  const customTools = allTools.filter(
@@ -774,6 +779,9 @@ export default function (pi: ExtensionAPI) {
774
779
  if (finished || Date.now() - animStart > 5000) {
775
780
  clearInterval(state.timer!);
776
781
  state.timer = null;
782
+ if (!finished) {
783
+ tick = Number.MAX_SAFE_INTEGER;
784
+ }
777
785
  }
778
786
  try { tui.requestRender(); } catch { cleanup(); }
779
787
  }, performance ? 250 : 25);
@@ -826,13 +834,23 @@ export default function (pi: ExtensionAPI) {
826
834
  b.center(width);
827
835
 
828
836
  if (state.mode === "minimal") {
829
- if (bannerConfig.showTextLogo) for (let logoI = 0; logoI < logoBase.lines.length; logoI++) {
830
- const logoLine = logoBase.lines[logoI];
831
- b.addRow();
832
- b.lines[b.lines.length - 1].push(
833
- ...buildPenLogoLine(logoLine, logoI, logoBase.lines.length, tick),
834
- );
835
- b.center(width);
837
+ if (bannerConfig.showTextLogo) {
838
+ if (width >= logoBase.width + 2) {
839
+ for (let logoI = 0; logoI < logoBase.lines.length; logoI++) {
840
+ const logoLine = logoBase.lines[logoI];
841
+ b.addRow();
842
+ b.lines[b.lines.length - 1].push(
843
+ ...buildPenLogoLine(logoLine, logoI, logoBase.lines.length, tick),
844
+ );
845
+ b.center(width);
846
+ }
847
+ } else {
848
+ b.addRow();
849
+ b.add("accent", "✿ ");
850
+ b.add("value", "Gentle Shell");
851
+ b.add("accent", " ✿");
852
+ b.center(width);
853
+ }
836
854
  }
837
855
  } else if (horizontal) {
838
856
  const rowCount = Math.max(roseBase.lines.length, logoBase.lines.length);
@@ -873,6 +891,16 @@ export default function (pi: ExtensionAPI) {
873
891
  b.addRow();
874
892
  b.center(width);
875
893
  }
894
+ } else if (bannerConfig.showTextLogo) {
895
+ b.addRow();
896
+ b.add("accent", "✿ ");
897
+ b.add("value", "Gentle Shell");
898
+ b.add("accent", " ✿");
899
+ b.center(width);
900
+ if (showRose) {
901
+ b.addRow();
902
+ b.center(width);
903
+ }
876
904
  }
877
905
  if (showRose) {
878
906
  for (const roseLine of roseBase.lines) {
@@ -1101,6 +1129,10 @@ export default function (pi: ExtensionAPI) {
1101
1129
  out.push(truncateToWidth(line, Math.max(1, width), ""));
1102
1130
  }
1103
1131
 
1132
+ if (guideReminder) {
1133
+ const pad = " ".repeat(Math.max(0, Math.floor((width - guideReminder.length) / 2)));
1134
+ out.push(truncateToWidth(theme.fg("muted", pad + guideReminder), Math.max(1, width), ""));
1135
+ }
1104
1136
  headerCache = { key: headerKey, out };
1105
1137
  return out;
1106
1138
  },
@@ -21,6 +21,9 @@ const LEGACY_MANAGED_ASSET_MANIFESTS = Object.freeze([
21
21
  { path: join(ASSETS_DIR, "migrations", "managed-assets-v0.14.json"), version: "0.14.0" },
22
22
  { path: join(ASSETS_DIR, "migrations", "managed-assets-v2.5.0.json"), version: "2.5.0" },
23
23
  ]);
24
+ // Hashes of every agent body (text after the frontmatter) the package has
25
+ // shipped. Regenerate with `node scripts/update-agent-body-history.mjs`.
26
+ const AGENT_BODY_HISTORY = join(ASSETS_DIR, "migrations", "agent-body-history.json");
24
27
 
25
28
  const ASSET_OWNER_BY_KEY = Object.freeze({
26
29
  "agents/gentle-ai-explore.md": "delegation",
@@ -236,6 +239,43 @@ function readLegacyManagedAssetHashes(): Record<string, readonly string[]> {
236
239
  return hashes;
237
240
  }
238
241
 
242
+ /** @internal Exported for the history generator and its freshness test. */
243
+ export function agentBody(content: string): string {
244
+ if (!content.startsWith("---\n")) return content;
245
+ const endIndex = content.indexOf("\n---", 4);
246
+ return endIndex === -1 ? content : content.slice(endIndex);
247
+ }
248
+
249
+ /** @internal */
250
+ export function readAgentBodyHistory(): Record<string, readonly string[]> {
251
+ try {
252
+ const parsed: unknown = JSON.parse(readFileSync(AGENT_BODY_HISTORY, "utf8"));
253
+ if (!isRecord(parsed) || parsed.schemaVersion !== 1 || !isRecord(parsed.bodies)) return {};
254
+ return Object.fromEntries(
255
+ Object.entries(parsed.bodies).filter(
256
+ (entry): entry is [string, string[]] =>
257
+ Array.isArray(entry[1]) && entry[1].every((hash) => typeof hash === "string"),
258
+ ),
259
+ );
260
+ } catch {
261
+ return {};
262
+ }
263
+ }
264
+
265
+ // A package agent whose body still matches a shipped version was only touched
266
+ // in its frontmatter (model routing, or a tool that reformatted it), so it
267
+ // stays package-owned instead of freezing on an outdated contract.
268
+ function hasShippedAgentBody(
269
+ ownershipKey: string,
270
+ installedContent: string,
271
+ bodyHistory: () => Readonly<Record<string, readonly string[]>>,
272
+ ): boolean {
273
+ return (
274
+ ownershipKey.startsWith("agents/") &&
275
+ (bodyHistory()[ownershipKey] ?? []).includes(managedAssetHash(agentBody(installedContent)))
276
+ );
277
+ }
278
+
239
279
  function updateAgentFrontmatterRouting(
240
280
  content: string,
241
281
  routingLines: readonly string[],
@@ -403,6 +443,8 @@ function copyDirectoryFiles(
403
443
  selected?: ReadonlySet<string>,
404
444
  ): { copied: number; skipped: number } {
405
445
  if (!existsSync(sourceDir)) return { copied: 0, skipped: 0 };
446
+ let cachedBodyHistory: Record<string, readonly string[]> | undefined;
447
+ const bodyHistory = () => (cachedBodyHistory ??= readAgentBodyHistory());
406
448
  if (selected && ![...selected].some(key => key.startsWith(`${ownershipPrefix}/`))) {
407
449
  return { copied: 0, skipped: 0 };
408
450
  }
@@ -430,6 +472,7 @@ function copyDirectoryFiles(
430
472
  if (!entry.isFile() || (selected && !selected.has(ownershipKey))) continue;
431
473
  const source = readFileSync(sourcePath, "utf8");
432
474
  let nextSource = source;
475
+ let keepsLocalRouting = false;
433
476
  if (existsSync(targetPath)) {
434
477
  if (!force) {
435
478
  skipped += 1;
@@ -445,27 +488,40 @@ function copyDirectoryFiles(
445
488
  const installedHash = installedContent === undefined
446
489
  ? undefined
447
490
  : managedAssetHash(installedContent);
448
- if (managedHash === undefined) {
449
- const legacyHashes = legacyAssetHashes?.()[ownershipKey];
450
- const comparableLegacyHash = installedContent === undefined
451
- ? undefined
452
- : managedAssetHash(
453
- legacyComparableAssetContent(ownershipKey, installedContent),
454
- );
455
- if (
456
- legacyHashes === undefined ||
457
- comparableLegacyHash === undefined ||
458
- !legacyHashes.includes(comparableLegacyHash)
459
- ) {
460
- delete manifest.assets[ownershipKey];
461
- skipped += 1;
462
- continue;
463
- }
491
+ const comparableHash = installedContent === undefined
492
+ ? undefined
493
+ : managedAssetHash(
494
+ legacyComparableAssetContent(ownershipKey, installedContent),
495
+ );
496
+ const legacyHashes = managedHash === undefined
497
+ ? legacyAssetHashes?.()[ownershipKey]
498
+ : undefined;
499
+ if (
500
+ managedHash === undefined &&
501
+ comparableHash !== undefined &&
502
+ legacyHashes?.includes(comparableHash) === true
503
+ ) {
464
504
  nextSource = migrateLegacyAssetContent(
465
505
  ownershipKey,
466
506
  installedContent,
467
507
  source,
468
508
  );
509
+ } else if (
510
+ installedContent !== undefined &&
511
+ installedHash !== managedHash &&
512
+ // Only outdated instructions are refreshed; a frontmatter edit on the
513
+ // current agent (routing, tool allowlist) keeps the local-edit rules below.
514
+ agentBody(installedContent) !== agentBody(source) &&
515
+ hasShippedAgentBody(ownershipKey, installedContent, bodyHistory)
516
+ ) {
517
+ nextSource = migrateLegacyAssetContent(ownershipKey, installedContent, source);
518
+ // Saved model config owns managed routing and a refresh resets it, so a
519
+ // copy carrying its own routing stays unmanaged to keep that routing.
520
+ keepsLocalRouting = nextSource !== source;
521
+ } else if (managedHash === undefined) {
522
+ delete manifest.assets[ownershipKey];
523
+ skipped += 1;
524
+ continue;
469
525
  } else if (installedHash !== managedHash) {
470
526
  delete manifest.assets[ownershipKey];
471
527
  skipped += 1;
@@ -476,7 +532,8 @@ function copyDirectoryFiles(
476
532
  }
477
533
  }
478
534
  writeFileSync(targetPath, nextSource);
479
- manifest.assets[ownershipKey] = managedAssetHash(nextSource);
535
+ if (keepsLocalRouting) delete manifest.assets[ownershipKey];
536
+ else manifest.assets[ownershipKey] = managedAssetHash(nextSource);
480
537
  copied += 1;
481
538
  }
482
539
  return { copied, skipped };
@@ -423,7 +423,7 @@ export function formatOrchestratorSelection(entry: AgentRoutingEntry | undefined
423
423
  ? INHERIT_MODEL_LABEL
424
424
  : `${INHERIT_MODEL_LABEL} · ${entry.thinking}`;
425
425
  }
426
- return entry.thinking === undefined ? entry.model : `${entry.model} · ${entry.thinking}`;
426
+ return [entry.model, entry.thinking, entry.tier === "fast" ? "Fast" : entry.tier === "standard" ? "Standard" : undefined].filter(Boolean).join(" · ");
427
427
  }
428
428
 
429
429
  export interface ProfileListItem {
@@ -1,6 +1,6 @@
1
1
  import { existsSync, readdirSync, readFileSync } from "node:fs";
2
2
  import { basename, join } from "node:path";
3
- import { THINKING_LEVELS as ROUTING_THINKING_LEVELS, type AgentModelConfig, type ThinkingLevel as RoutingThinkingLevel } from "./model-routing-authority.ts";
3
+ import { THINKING_LEVELS as ROUTING_THINKING_LEVELS, isServiceTier, type AgentModelConfig, type ServiceTier, type ThinkingLevel as RoutingThinkingLevel } from "./model-routing-authority.ts";
4
4
 
5
5
  // Gentle Agents configuration. Agent definitions are markdown files with YAML
6
6
  // frontmatter (the format gentle-ai installs) and runtime settings come from
@@ -62,6 +62,7 @@ export interface AgentDefinitionError {
62
62
  export interface ModelProfile {
63
63
  model: ModelRef | undefined;
64
64
  thinking: ThinkingLevel | undefined;
65
+ tier?: ServiceTier;
65
66
  }
66
67
 
67
68
  export interface AgentsConfig {
@@ -83,6 +84,7 @@ export interface ProfileSources {
83
84
  export interface ResolvedProfile {
84
85
  model: ModelRef | undefined;
85
86
  thinking: ThinkingLevel | undefined;
87
+ tier?: ServiceTier;
86
88
  source: ProfileSources;
87
89
  }
88
90
 
@@ -246,7 +248,7 @@ function parseProfiles(value: unknown): Record<string, ModelProfile> {
246
248
  if (!raw || typeof raw !== "object") continue;
247
249
  const entry = raw as Record<string, unknown>;
248
250
  const thinking = parseThinking(entry.effort ?? entry.thinking);
249
- profiles[name] = { model: parseModelRef(entry.model), thinking: thinking !== undefined && THINKING_LEVELS.includes(thinking) ? (thinking as ThinkingLevel) : undefined };
251
+ profiles[name] = { model: parseModelRef(entry.model), thinking: thinking !== undefined && THINKING_LEVELS.includes(thinking) ? (thinking as ThinkingLevel) : undefined, ...(isServiceTier(entry.tier) ? { tier: entry.tier } : {}) };
250
252
  }
251
253
  return profiles;
252
254
  }
@@ -327,6 +329,13 @@ export interface UnmatchedProfileKey {
327
329
  // profile to a user-owned same-short-name agent is the exact silence the
328
330
  // prefix exists to prevent; reporting the unmatched key keeps resolution
329
331
  // exact-match and makes the misconfiguration visible instead.
332
+ /**
333
+ * Provider review roles (gentle-pi#2271): routed by key for the in-process
334
+ * reviewer, never installed as agent files, so a model_profiles entry for them
335
+ * is always matched.
336
+ */
337
+ export const PROVIDER_REVIEW_ROLES = ["review-refuter", "review-validator"] as const;
338
+
330
339
  export function unmatchedProfileKeys(
331
340
  modelProfiles: Record<string, ModelProfile>,
332
341
  agents: ReadonlyArray<{ name: string }>,
@@ -363,7 +372,7 @@ export function resolveAgentProfile(agent: AgentDefinition, config: AgentsConfig
363
372
  [agent.thinking, PROFILE_SOURCE.DEFINITION],
364
373
  [config.defaultThinking, PROFILE_SOURCE.DEFAULT],
365
374
  ]);
366
- return { model, thinking, source: { model: modelSource, thinking: thinkingSource } };
375
+ return { model, thinking, ...(profile?.tier === undefined ? {} : { tier: profile.tier }), source: { model: modelSource, thinking: thinkingSource } };
367
376
  }
368
377
 
369
378
  export function formatModelRef(model: ModelRef | undefined): string {
@@ -2,26 +2,18 @@
2
2
  // extensions/gentle-agents.ts (which owns the view) and other extensions
3
3
  // that only need the key mapping (extensions/gentle-shell.ts, for the
4
4
  // command palette's shortcut hints) can depend on it without importing one
5
- // another.
5
+ // another. Defaults and the saved keymaps live in lib/keymaps.ts.
6
6
 
7
- const COLLAPSE_KEY_DEFAULT = "ctrl+shift+a";
8
- const VIEW_KEY_DEFAULT = "alt+a";
9
- const STOP_KEY_DEFAULT = "alt+s";
7
+ import { effectiveKey, type KeymapBindings } from "./keymaps.ts";
10
8
 
11
- export function agentsViewKey(env: NodeJS.ProcessEnv = process.env): string | undefined {
12
- const value = env.GENTLE_PI_AGENTS_VIEW_KEY?.trim();
13
- if (value === undefined) return VIEW_KEY_DEFAULT;
14
- return value === "" || value.toLowerCase() === "off" ? undefined : value;
9
+ export function agentsViewKey(env: NodeJS.ProcessEnv = process.env, bindings: KeymapBindings = {}): string | undefined {
10
+ return effectiveKey("agents.view", env, bindings);
15
11
  }
16
12
 
17
- export function agentsCollapseKey(env: NodeJS.ProcessEnv = process.env): string | undefined {
18
- const value = env.GENTLE_PI_AGENTS_KEY?.trim();
19
- if (value === undefined) return COLLAPSE_KEY_DEFAULT;
20
- return value === "" || value.toLowerCase() === "off" ? undefined : value;
13
+ export function agentsCollapseKey(env: NodeJS.ProcessEnv = process.env, bindings: KeymapBindings = {}): string | undefined {
14
+ return effectiveKey("agents.collapse", env, bindings);
21
15
  }
22
16
 
23
- export function agentsStopKey(env: NodeJS.ProcessEnv = process.env): string | undefined {
24
- const value = env.GENTLE_PI_AGENTS_STOP_KEY?.trim();
25
- if (value === undefined) return STOP_KEY_DEFAULT;
26
- return value === "" || value.toLowerCase() === "off" ? undefined : value;
17
+ export function agentsStopKey(env: NodeJS.ProcessEnv = process.env, bindings: KeymapBindings = {}): string | undefined {
18
+ return effectiveKey("agents.stop", env, bindings);
27
19
  }
@@ -59,11 +59,28 @@ export interface ToolStartEvent { type: typeof TASK_EVENT.TOOL_START; callId: st
59
59
  export interface ToolUpdateEvent { type: typeof TASK_EVENT.TOOL_UPDATE; callId: string; output: string }
60
60
  export interface ToolEndEvent { type: typeof TASK_EVENT.TOOL_END; callId: string; output: string; isError: boolean }
61
61
  export interface TurnEndEvent { type: typeof TASK_EVENT.TURN_END }
62
+ /** Closed terminal-error vocabulary (#2322). A category, never provider text. */
63
+ export const TERMINAL_ERROR_CATEGORY = {
64
+ AUTH: "auth",
65
+ RATE_LIMIT: "rate_limit",
66
+ QUOTA: "quota",
67
+ CONTEXT_LENGTH: "context_length",
68
+ TIMEOUT: "timeout",
69
+ NETWORK: "network",
70
+ PROVIDER_UNAVAILABLE: "provider_unavailable",
71
+ INVALID_REQUEST: "invalid_request",
72
+ UNAVAILABLE: "unavailable",
73
+ } as const;
74
+
75
+ export type TerminalErrorCategory = (typeof TERMINAL_ERROR_CATEGORY)[keyof typeof TERMINAL_ERROR_CATEGORY];
76
+
62
77
  export interface AgentEndEvent {
63
78
  type: typeof TASK_EVENT.AGENT_END;
64
79
  text: string;
65
80
  outcome: "success" | "error" | "aborted" | "empty";
66
81
  diagnostic?: string;
82
+ /** Present only when outcome is "error". */
83
+ errorCategory?: TerminalErrorCategory;
67
84
  }
68
85
  export interface AgentSettledEvent { type: typeof TASK_EVENT.AGENT_SETTLED }
69
86
  export interface ErrorEvent { type: typeof TASK_EVENT.ERROR; message: string }
@@ -130,6 +147,8 @@ export interface TaskRecord {
130
147
  /** Launch-layer token recorded next to `model` (#2180): which profile layer won.
131
148
  * Host-computed at the launch seam; absent for requests and records that never named one. */
132
149
  modelSource?: string;
150
+ /** Set when the run moved to a fallback model: the model it moved away from first. */
151
+ fallbackFrom?: string;
133
152
  thinking: string | undefined;
134
153
  sessionPath: string | null;
135
154
  error: string | null;
@@ -194,15 +213,72 @@ function keepTail(text: string, max: number): string {
194
213
  return text.length <= max ? text : `${ELLIPSIS}${text.slice(text.length - max + 1)}`;
195
214
  }
196
215
 
216
+ const ERROR_SCAN_MAX = 4096;
217
+ const ERROR_IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/;
218
+ // First match wins: specific causes before the generic statuses they share
219
+ // (quota and context errors often arrive as 429 or 400).
220
+ const ERROR_KEYWORDS: ReadonlyArray<readonly [TerminalErrorCategory, RegExp]> = [
221
+ [TERMINAL_ERROR_CATEGORY.CONTEXT_LENGTH, /context.?length|context.?window|maximum context|prompt is too long|too many tokens/i],
222
+ [TERMINAL_ERROR_CATEGORY.QUOTA, /quota|billing|out of budget|usage.?limit|credit balance/i],
223
+ [TERMINAL_ERROR_CATEGORY.AUTH, /unauthori[sz]ed|forbidden|authenticat|api.?key|permission.?denied/i],
224
+ [TERMINAL_ERROR_CATEGORY.RATE_LIMIT, /rate.?limit|too many requests/i],
225
+ [TERMINAL_ERROR_CATEGORY.TIMEOUT, /time.?out|timed out|deadline exceeded/i],
226
+ [TERMINAL_ERROR_CATEGORY.NETWORK, /network|connection|websocket|ECONN(?:RESET|REFUSED|ABORTED)|ENOTFOUND|EAI_AGAIN|fetch failed|socket hang up|other side closed/i],
227
+ [TERMINAL_ERROR_CATEGORY.PROVIDER_UNAVAILABLE, /overloaded|unavailable|server.?error|internal.?error|server_busy|capacity|high demand/i],
228
+ [TERMINAL_ERROR_CATEGORY.INVALID_REQUEST, /invalid.?request|bad request/i],
229
+ ];
230
+ // Only a status in a status position: leading ("429: ...", "429 {...}"),
231
+ // parenthesized ("Provider (403): ...") or labeled ("status 503", "HTTP 502").
232
+ const HTTP_STATUS = /(?:^\s*|\(|\b(?:status(?:\s+code)?|http)\s*:?\s*)([45]\d\d)(?=[\s):,{]|$)/i;
233
+
234
+ function statusCategory(status: number): TerminalErrorCategory {
235
+ if (status === 401 || status === 403) return TERMINAL_ERROR_CATEGORY.AUTH;
236
+ if (status === 429) return TERMINAL_ERROR_CATEGORY.RATE_LIMIT;
237
+ if (status === 408 || status === 504) return TERMINAL_ERROR_CATEGORY.TIMEOUT;
238
+ if (status >= 500) return TERMINAL_ERROR_CATEGORY.PROVIDER_UNAVAILABLE;
239
+ return TERMINAL_ERROR_CATEGORY.INVALID_REQUEST;
240
+ }
241
+
242
+ function diagnosticCodes(diagnostics: unknown): string[] {
243
+ if (!Array.isArray(diagnostics)) return [];
244
+ return diagnostics.slice(0, 8).map((entry) => {
245
+ const code = (entry as { error?: { code?: unknown } } | null)?.error?.code;
246
+ return typeof code === "number" ? String(code) : typeof code === "string" && ERROR_IDENTIFIER.test(code) ? code : "";
247
+ });
248
+ }
249
+
250
+ /** Scans bounded structured signals; the scanned text itself is never retained. */
251
+ function terminalErrorCategory(message: { errorMessage?: unknown; rawStopReason?: unknown; diagnostics?: unknown }): TerminalErrorCategory {
252
+ const signals = [
253
+ typeof message.errorMessage === "string" ? message.errorMessage.slice(0, ERROR_SCAN_MAX) : "",
254
+ typeof message.rawStopReason === "string" && ERROR_IDENTIFIER.test(message.rawStopReason) ? message.rawStopReason : "",
255
+ ...diagnosticCodes(message.diagnostics),
256
+ ].filter((signal) => signal.length > 0);
257
+ for (const [category, pattern] of ERROR_KEYWORDS) if (signals.some((signal) => pattern.test(signal))) return category;
258
+ for (const signal of signals) {
259
+ const status = HTTP_STATUS.exec(signal)?.[1];
260
+ if (status) return statusCategory(Number(status));
261
+ }
262
+ return TERMINAL_ERROR_CATEGORY.UNAVAILABLE;
263
+ }
264
+
265
+ /** The closed error category of a failed assistant message; undefined unless it stopped with an error. */
266
+ export function assistantErrorCategory(message: { stopReason?: unknown; errorMessage?: unknown; rawStopReason?: unknown; diagnostics?: unknown } | undefined): TerminalErrorCategory | undefined {
267
+ return message && clean(message.stopReason).toLowerCase() === "error" ? terminalErrorCategory(message) : undefined;
268
+ }
269
+
197
270
  function terminalAssistant(messages: unknown): Omit<AgentEndEvent, "type"> {
198
271
  if (!Array.isArray(messages)) return { text: "", outcome: "empty", diagnostic: "assistant returned no final report" };
199
272
  for (let index = messages.length - 1; index >= 0; index -= 1) {
200
- const message = messages[index] as { role?: string; content?: unknown; stopReason?: unknown };
273
+ const message = messages[index] as { role?: string; content?: unknown; stopReason?: unknown; errorMessage?: unknown; rawStopReason?: unknown; diagnostics?: unknown };
201
274
  if (message?.role !== "assistant") continue;
202
275
  const stopReason = clean(message.stopReason).toLowerCase();
203
- // Do not preserve unbounded provider error payloads. The terminal reason is
204
- // enough for an operator to distinguish failure from an empty report.
205
- if (stopReason === "error") return { text: "", outcome: "error", diagnostic: "assistant reported an error" };
276
+ // Do not preserve unbounded provider error payloads. Only a category from
277
+ // the closed vocabulary leaves this function, never the scanned text.
278
+ if (stopReason === "error") {
279
+ const errorCategory = terminalErrorCategory(message);
280
+ return { text: "", outcome: "error", diagnostic: `assistant reported an error (${errorCategory})`, errorCategory };
281
+ }
206
282
  if (stopReason === "aborted") return { text: "", outcome: "aborted", diagnostic: "assistant aborted" };
207
283
  const text = contentText(message.content);
208
284
  return text.length > 0
@@ -1,3 +1,6 @@
1
+ import { pickModel, sharedCooldown, shouldFallBack, type ModelCooldown } from "./model-fallback-policy.ts";
2
+ import type { FallbackChain } from "./model-fallback-store.ts";
3
+ import { fallbackContinuePrompt } from "./model-fallback-notice.ts";
1
4
  import { isSessionChangeEvidence, type SessionChangeEvidence } from "./session-changes.ts";
2
5
  import { chmodSync, existsSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
3
6
  import { DefaultPackageManager, SettingsManager } from "@earendil-works/pi-coding-agent";
@@ -9,10 +12,10 @@ import { withoutInteractiveHost } from "./rpc-host.ts";
9
12
  import { gentlePiConfigHome } from "./agent-home.ts";
10
13
  import { resolveBackgroundSubagentsPolicy } from "./background-subagents-policy.ts";
11
14
  import { childPackageExtensionArgs } from "./child-package-injection.ts";
12
- import { AGENT_MODE, formatModelRef, type AgentDefinition, type AgentMode, type ModelRef } from "./agents-config.ts";
15
+ import { AGENT_MODE, formatModelRef, parseModelRef, type AgentDefinition, type AgentMode, type ModelRef } from "./agents-config.ts";
13
16
  import { CHILD_QUERY_MAX_INFLIGHT, CHILD_QUERY_TIMEOUT_MS, parseChildFrame, validChildMessage, validChildQueryId } from "./agents-messaging.ts";
14
17
  import { ParentStandingReviewPermissionBroker } from "./review-session-standing-permission-ipc.ts";
15
- import { isFinished, normalizeRpcEvent, ToolArgumentProgress, TASK_EVENT, TASK_STATUS, taskLabel, type AskRequest, type ChildResponseObservation, type TaskRecord, type TaskStore } from "./agents-protocol.ts";
18
+ import { isFinished, normalizeRpcEvent, ToolArgumentProgress, TASK_EVENT, TASK_STATUS, taskLabel, type AskRequest, type ChildResponseObservation, type TaskRecord, type TaskStore, type TerminalErrorCategory } from "./agents-protocol.ts";
16
19
  import { WriterSurfaceRegistry, writerSurfaceConflictMessage } from "./writer-surfaces.ts";
17
20
  import { holdSubagentScratch, releaseSubagentScratch, SUBAGENT_SCRATCH_PREFIX } from "./session-scratch.ts";
18
21
 
@@ -64,6 +67,8 @@ export interface RunnerDeps {
64
67
  pi: PiCommand;
65
68
  resolvePi?(): PiCommand;
66
69
  process?: ProcessControl;
70
+ /** Models that recently ran out; the process-wide registry when absent. */
71
+ cooldown?: ModelCooldown;
67
72
  }
68
73
 
69
74
  export interface RunnerLimits {
@@ -120,6 +125,8 @@ export interface RunnerHooks {
120
125
  onQuerySettled?(taskId: string, requestId: string, outcome: "replied" | "expired"): void;
121
126
  // Parent-only observation of a paired successful filesystem tool, not prose.
122
127
  onSuccessfulMutation?(task: TaskRecord, tool: { toolName: "write" | "edit"; toolCallId: string; path: string; evidence?: SessionChangeEvidence }): void | Promise<void>;
128
+ /** The child moved to the next model of its fallback chain and keeps going. */
129
+ onFallback?(task: TaskRecord, change: { from: string; to: string; category: TerminalErrorCategory; launch?: boolean }): void;
123
130
  }
124
131
 
125
132
  export interface TaskRequest {
@@ -132,6 +139,8 @@ export interface TaskRequest {
132
139
  parentSessionId: string;
133
140
  model: ModelRef | undefined;
134
141
  thinking: string | undefined;
142
+ /** Ordered fallbacks for when `model` runs out or keeps failing; only models the user chose. */
143
+ fallbacks?: FallbackChain;
135
144
  sessionDir: string;
136
145
  resumeSessionPath: string | undefined;
137
146
  env: NodeJS.ProcessEnv;
@@ -199,6 +208,10 @@ interface PendingReply {
199
208
  interface LiveTask {
200
209
  child: ChildLike;
201
210
  sawRunEvent: boolean;
211
+ /** The category of the last failed final response, for the fallback decision. */
212
+ errorCategory?: TerminalErrorCategory;
213
+ /** Models this run already used or tried, so a chain never loops. */
214
+ triedModels?: Set<string>;
202
215
  observations?: ChildObservationBuffer;
203
216
  observationGuard?: () => boolean;
204
217
  observationPreparation?: () => boolean;
@@ -604,9 +617,10 @@ export class AgentRunner {
604
617
  if (this.processControl.platform === "win32") { env.TMP = scratchDir; env.TEMP = scratchDir; }
605
618
  } catch { scratchDir = undefined; }
606
619
  let child: ChildLike;
620
+ const launch = this.launchRequest(id, request);
607
621
  try {
608
622
  const pi = this.deps.resolvePi?.() ?? this.deps.pi;
609
- child = this.deps.spawn(pi.command, [...pi.args, ...childArguments(request, instructionsTransportPath)], {
623
+ child = this.deps.spawn(pi.command, [...pi.args, ...childArguments(launch.request, instructionsTransportPath)], {
610
624
  cwd: request.cwd,
611
625
  env,
612
626
  detached,
@@ -622,6 +636,7 @@ export class AgentRunner {
622
636
  this.finish(id, TASK_STATUS.FAILED, `could not start pi: ${error instanceof Error ? error.message : String(error)}`);
623
637
  return;
624
638
  }
639
+ launch.announce?.();
625
640
  const processGroup = detached && typeof child.pid === "number" && child.pid > 0 ? child.pid : undefined;
626
641
  const live: LiveTask = { child, sawRunEvent: false, mutationStarts: new Map(), inFlightTools: new Map(), argumentProgress: new ToolArgumentProgress(), pending: new Map(), queries: new Map(), replies: new Map(), cancelStall: () => {}, cancelGrace: () => {}, processGroup, terminal: undefined, childExit: undefined, childExitSignal: undefined, instructionsTransportDir, scratchDir, cleanupDeadlineAt: undefined, quarantined: false, nextId: 0, ipcClosed: false, acknowledgedIpcIds: new Set(), acknowledgedIpcOrder: [], stderrTail: "" };
627
642
  if (request.prepareResponseObservations) {
@@ -725,6 +740,90 @@ export class AgentRunner {
725
740
  }, budget);
726
741
  }
727
742
 
743
+ /** The request a child starts with: a primary model that is cooling down gives way to its first usable fallback. */
744
+ private launchRequest(id: string, request: TaskRequest): { request: TaskRequest; announce?: () => void } {
745
+ const chain = request.fallbacks ?? [];
746
+ if (!chain.length || !request.model) return { request };
747
+ const cooldown = this.deps.cooldown ?? sharedCooldown();
748
+ const now = this.deps.now();
749
+ const primary = formatModelRef(request.model);
750
+ const pick = pickModel(primary, chain, { cooldown, now });
751
+ const model = pick?.fallback && pick.model ? parseModelRef(pick.model) : undefined;
752
+ if (!model?.provider || !pick?.model) return { request };
753
+ const updated = this.store.update(id, { model: pick.model, fallbackFrom: primary, ...(pick.thinking ? { thinking: pick.thinking } : {}) });
754
+ const category = cooldown.reason(primary, now);
755
+ const to = pick.model;
756
+ // Announced by the caller once the child actually started.
757
+ const announce = () => {
758
+ try { if (updated && category) this.hooks.onFallback?.(this.store.get(id) ?? updated, { from: primary, to, category, launch: true }); }
759
+ catch { /* A notice failure must not stop the launch. */ }
760
+ };
761
+ return { request: { ...request, model, thinking: pick.thinking ?? request.thinking }, announce };
762
+ }
763
+
764
+ /**
765
+ * After a failed final response, moves the live child to the next usable
766
+ * model of its chain and asks it to continue the same conversation. False
767
+ * when the error would repeat on any model or nothing is left: the caller
768
+ * then fails the task as before.
769
+ */
770
+ private fallBack(id: string, request: TaskRequest, live: LiveTask): boolean {
771
+ const chain = request.fallbacks ?? [];
772
+ const category = live.errorCategory;
773
+ if (!chain.length || live.terminal || !shouldFallBack(category)) return false;
774
+ const cooldown = this.deps.cooldown ?? sharedCooldown();
775
+ const now = this.deps.now();
776
+ const task = this.store.get(id);
777
+ const current = task?.model && task.model !== "default" ? task.model : request.model ? formatModelRef(request.model) : undefined;
778
+ const tried = (live.triedModels ??= new Set());
779
+ if (current) {
780
+ tried.add(current);
781
+ cooldown.mark(current, category!, now);
782
+ }
783
+ // The next selectable step: one with a provider, untried and not cooling down.
784
+ const next = () => {
785
+ for (;;) {
786
+ const pick = pickModel(current, chain, { cooldown, now: this.deps.now(), tried });
787
+ if (!pick?.fallback || !pick.model) return undefined;
788
+ tried.add(pick.model);
789
+ if (parseModelRef(pick.model)?.provider) return pick;
790
+ }
791
+ };
792
+ let pick = next();
793
+ if (!pick) return false;
794
+ live.errorCategory = undefined;
795
+ this.store.update(id, { error: null, result: null, lastStep: `↪ ${pick.model}` });
796
+ const alive = () => this.live.get(id) === live && !live.terminal;
797
+ const fail = (reason: string) => { if (alive()) this.settleOrderly(id, TASK_STATUS.FAILED, reason); };
798
+ void (async () => {
799
+ // Pi may refuse a step (no key, unknown model): the next one gets its turn.
800
+ for (;;) {
801
+ const target = parseModelRef(pick.model!)!;
802
+ const switched = await this.send(id, { type: "set_model", provider: target.provider, modelId: target.id });
803
+ if (!alive()) return;
804
+ if (switched.success !== false) break;
805
+ const refused = `could not switch to ${pick.model}: ${String(switched.error ?? "rejected")}`;
806
+ const following = next();
807
+ if (!following) return fail(refused);
808
+ pick = following;
809
+ this.store.update(id, { lastStep: `↪ ${pick.model}` });
810
+ }
811
+ const to = pick.model!;
812
+ // Pi accepted the model: the record follows at once, even if the run stops next.
813
+ const level = pick.thinking ?? request.thinking;
814
+ this.store.update(id, { model: to, fallbackFrom: this.store.get(id)?.fallbackFrom ?? current ?? "default", ...(level ? { thinking: level } : {}) });
815
+ // A step without its own effort runs at the agent's configured effort, not the previous step's.
816
+ if (level) await this.send(id, { type: "set_thinking_level", level });
817
+ if (!alive()) return;
818
+ const updated = this.store.get(id);
819
+ try { if (updated) this.hooks.onFallback?.(updated, { from: current ?? "default", to, category: category! }); }
820
+ catch { /* A notice failure must not stop the switch. */ }
821
+ const resumed = await this.send(id, { type: "prompt", message: fallbackContinuePrompt(current, to, category!) });
822
+ if (resumed.success === false) fail(`could not continue on ${to}: ${String(resumed.error ?? "prompt rejected")}`);
823
+ })().catch((error) => fail(`could not continue: ${error instanceof Error ? error.message : String(error)}`));
824
+ return true;
825
+ }
826
+
728
827
  private send(id: string, command: Record<string, unknown>): Promise<Record<string, unknown>> {
729
828
  const live = this.live.get(id);
730
829
  if (!live) return Promise.resolve({ success: false, error: "task is not running" });
@@ -894,6 +993,7 @@ export class AgentRunner {
894
993
  continue; // Separate from store persistence, UI totals and notifications.
895
994
  }
896
995
  live.sawRunEvent = true;
996
+ if (event.type === TASK_EVENT.AGENT_END) live.errorCategory = event.outcome === "error" ? event.errorCategory : undefined;
897
997
  this.store.apply(id, event, this.deps.now());
898
998
  if (event.type === TASK_EVENT.TOOL_START && event.callId) {
899
999
  live.inFlightTools.set(event.callId, event.name);
@@ -920,7 +1020,8 @@ export class AgentRunner {
920
1020
  if (event.type === TASK_EVENT.AGENT_SETTLED) {
921
1021
  if (live.observations) live.observations.agentSettled = true;
922
1022
  const terminal = this.store.get(id);
923
- if (terminal?.error) this.settleOrderly(id, TASK_STATUS.FAILED, terminal.error);
1023
+ if (terminal?.error && this.fallBack(id, request, live)) { /* The child keeps going on its next model. */ }
1024
+ else if (terminal?.error) this.settleOrderly(id, TASK_STATUS.FAILED, terminal.error);
924
1025
  else if (terminal?.result) this.settleOrderly(id, TASK_STATUS.COMPLETED, null);
925
1026
  else this.settleOrderly(id, TASK_STATUS.FAILED, "assistant settled without a final report");
926
1027
  }
@@ -778,8 +778,13 @@ export class AgentsView {
778
778
  }
779
779
 
780
780
  private scrollBy(delta: number): void {
781
+ const task = this.selectedTask();
782
+ const layout = this.layout();
783
+ const lines = task ? this.threadLines(this.remoteThreads.get(task.id) ?? this.deps.store.thread(task.id), layout.threadWidth) : [];
784
+ const maxScroll = Math.max(0, lines.length - Math.max(0, layout.bodyRows - 1));
781
785
  this.follow = false;
782
- this.scroll = Math.max(0, this.scroll + delta);
786
+ // Clamp the current visible position before moving, including after resize.
787
+ this.scroll = Math.max(0, Math.min(maxScroll, Math.min(this.scroll, maxScroll) + delta));
783
788
  this.deps.requestRender();
784
789
  }
785
790