gentle-pi 4.5.1 → 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.
- package/README.md +9 -6
- package/assets/agents/gentle-ai-verify.md +4 -0
- package/assets/agents/gentle-ai-worker.md +1 -0
- package/assets/migrations/agent-body-history.json +147 -0
- package/assets/orchestrator-delegation-reference.md +3 -3
- package/assets/orchestrator-delegation.md +2 -2
- package/assets/orchestrator-verification.md +10 -6
- package/assets/orchestrator.md +8 -8
- package/bin/gentle-shell.mjs +61 -26
- package/docs/ci-performance.md +11 -0
- package/docs/delegated-verification.md +6 -0
- package/docs/fast-mode.md +15 -0
- package/docs/gentle-agents-activity.md +8 -0
- package/docs/gentle-shell.md +69 -19
- package/docs/install-wizard.md +1 -1
- package/docs/mcp-status.md +52 -0
- package/docs/prompt-budget.md +28 -0
- package/docs/readme-reference.md +79 -20
- package/docs/session-profile-format.md +20 -5
- package/docs/sound-notifications.md +1 -1
- package/docs/star-prompt.md +32 -0
- package/docs/work-continuity.md +46 -0
- package/extensions/ask-user-question.ts +1 -0
- package/extensions/codegraph-tools.ts +38 -4
- package/extensions/gentle-agents.ts +477 -50
- package/extensions/gentle-ai.ts +1041 -188
- package/extensions/gentle-fast.ts +61 -0
- package/extensions/gentle-guide.ts +174 -0
- package/extensions/gentle-herdr-activity.ts +21 -1
- package/extensions/gentle-herdr-agent.ts +144 -0
- package/extensions/gentle-program-identity.ts +61 -0
- package/extensions/gentle-shell.ts +642 -97
- package/extensions/gentle-star-prompt.ts +334 -0
- package/extensions/gentle-stats.ts +5 -5
- package/extensions/gentle-todo.ts +42 -22
- package/extensions/history/store.ts +18 -12
- package/extensions/skill-registry.ts +35 -3
- package/extensions/startup-banner.ts +39 -7
- package/lib/agent-assets.ts +74 -17
- package/lib/agent-profiles.ts +1 -1
- package/lib/agents-config.ts +12 -3
- package/lib/agents-keys.ts +8 -16
- package/lib/agents-protocol.ts +80 -4
- package/lib/agents-runner.ts +105 -4
- package/lib/agents-view.ts +6 -1
- package/lib/agents-widget.ts +132 -9
- package/lib/bridge-cost.ts +28 -0
- package/lib/codemode-renderer.ts +16 -0
- package/lib/command-palette-catalog.ts +1 -0
- package/lib/command-palette.ts +21 -8
- package/lib/exploration-budget.ts +62 -0
- package/lib/gentle-guide.ts +201 -0
- package/lib/gentle-shell-launcher.ts +4 -0
- package/lib/herdr-activity.ts +9 -3
- package/lib/herdr-task-summary-policy.ts +85 -0
- package/lib/inprocess-reviewer.ts +33 -13
- package/lib/jobs-sidebar-state.ts +5 -6
- package/lib/jobs-widget.ts +16 -52
- package/lib/keymaps-customize.ts +81 -0
- package/lib/keymaps.ts +291 -0
- package/lib/model-fallback-notice.ts +61 -0
- package/lib/model-fallback-policy.ts +141 -0
- package/lib/model-fallback-store.ts +143 -0
- package/lib/model-routing-authority.ts +10 -2
- package/lib/nan-provider.ts +3 -2
- package/lib/native-review-cli.ts +7 -2
- package/lib/notification-customize.ts +48 -51
- package/lib/openai-fast-tier.ts +22 -0
- package/lib/orchestrator-discovery.ts +5 -1
- package/lib/orchestrator-fallback.ts +75 -0
- package/lib/pasted-image-paths.ts +113 -0
- package/lib/questionnaire/questionnaire-view.ts +121 -7
- package/lib/review-candidate-view-owner.ts +4 -0
- package/lib/review-candidate-view.ts +10 -7
- package/lib/review-host-relay.ts +5 -1
- package/lib/review-integration-v2.ts +22 -7
- package/lib/review-repository.ts +5 -0
- package/lib/session-profile-append-controller.ts +21 -6
- package/lib/session-profile-authority.ts +119 -0
- package/lib/session-profile-binding.ts +54 -5
- package/lib/session-profile-freeze.ts +105 -9
- package/lib/session-profile-integration.ts +313 -0
- package/lib/session-profile-persistence.ts +63 -9
- package/lib/shell-bar.ts +171 -56
- package/lib/shell-card.ts +26 -6
- package/lib/shell-page.ts +120 -0
- package/lib/shell-panel.ts +149 -0
- package/lib/shell-prompt.ts +53 -1
- package/lib/shell-sidebar-layout.ts +98 -25
- package/lib/shell-sidebar.ts +54 -1
- package/lib/shell-stats.ts +123 -0
- package/lib/shell-todo.ts +71 -0
- package/lib/shell-usage.ts +12 -2
- package/lib/star-prompt.ts +197 -0
- package/lib/verifier-admission.ts +18 -8
- package/lib/verifier-settle-reminder.ts +64 -0
- package/lib/vim-editor-adapter.ts +6 -1
- package/lib/visual-customization-policy.ts +41 -6
- package/lib/visual-customize-view.ts +164 -26
- package/lib/visual-layout-preview.ts +43 -0
- package/lib/yolo-session-policy.ts +28 -1
- package/package.json +1 -1
- package/runtime/gentle-shell-launcher.mjs +4 -0
- package/runtime/native-review-cli.mjs +7 -2
- package/runtime/review-integration-v2.mjs +22 -7
- package/runtime/windows-session-transport.ps1 +60 -3
- package/scripts/bootstrap.sh +4 -1
- package/scripts/installer-preflight.mjs +1 -1
- package/scripts/pi-update.mjs +113 -3
- package/scripts/run-test-suite.mjs +17 -1
- package/scripts/shell-snapshot.mjs +340 -0
- package/scripts/test-packed-runner.mjs +1 -1
- package/scripts/update-agent-body-history.mjs +41 -0
- package/scripts/verify-installer-tap.mjs +45 -0
- package/scripts/verify-package-files.mjs +2 -0
- package/skills/gentle-ai/SKILL.md +2 -2
- package/skills/tui-design/NOTICE.md +5 -0
- package/skills/tui-design/SKILL.md +56 -0
- package/skills/tui-design/references/commands.md +75 -0
- package/skills/tui-design/references/critique.md +48 -0
- package/skills/tui-design/references/design-doc.md +44 -0
- package/skills/tui-design/references/terminal-craft.md +64 -0
- package/skills/tui-design/references/visual-loop.md +32 -0
- package/tests/agents-protocol.test.ts +53 -1
- package/tests/agents-runner.test.ts +168 -3
- package/tests/agents-view.test.ts +27 -0
- package/tests/agents-widget.test.ts +312 -10
- package/tests/bounded-scan-contract.test.ts +39 -0
- package/tests/bridge-cost.test.ts +32 -0
- package/tests/bundled-install.test.ts +6 -4
- package/tests/ci-concurrency.test.ts +11 -0
- package/tests/ci-merge-base-identity.test.ts +114 -0
- package/tests/codegraph-tools.test.ts +69 -0
- package/tests/codemode-rendering.test.ts +22 -2
- package/tests/command-palette.test.ts +16 -2
- package/tests/commit-slice-signal.test.ts +11 -9
- package/tests/delegate-for-reason-contract.test.ts +5 -4
- package/tests/exploration-budget.test.ts +128 -0
- package/tests/fixtures/agent-assets/gentle-ai-worker.strict-tdd-era.md +122 -0
- package/tests/fixtures/measure-orchestrator-prompt.mjs +2 -1
- package/tests/fixtures/primary-session-prompt/gentleman.golden.md +18 -10
- package/tests/fixtures/session-profile-v1/replay.ts +125 -0
- package/tests/fixtures/session-profile-v1/session-profile-authority.ts +113 -0
- package/tests/fixtures/session-profile-v1/session-profile-binding.ts +83 -0
- package/tests/fixtures/session-profile-v1/session-profile-disk-reader.ts +182 -0
- package/tests/fixtures/session-profile-v1/session-profile-freeze.ts +290 -0
- package/tests/fixtures/session-profile-v1/session-profile-persistence.ts +195 -0
- package/tests/fixtures/session-profile-v1/v1-inputs.ts +16 -0
- package/tests/fixtures/windows-pipe-availability.ps1 +26 -0
- package/tests/fixtures/windows-session-bootstrap.ps1 +6 -2
- package/tests/gentle-agents.test.ts +416 -21
- package/tests/gentle-ai-exploration-budget.test.ts +135 -0
- package/tests/gentle-ai.test.ts +1007 -33
- package/tests/gentle-fast.test.ts +73 -0
- package/tests/gentle-guide.test.ts +208 -0
- package/tests/gentle-herdr-activity.test.ts +76 -2
- package/tests/gentle-herdr-agent.test.ts +111 -0
- package/tests/gentle-program-identity.test.ts +197 -0
- package/tests/gentle-shell-bin.test.ts +49 -26
- package/tests/gentle-shell-launcher.test.ts +18 -2
- package/tests/gentle-shell.test.ts +1068 -37
- package/tests/gentle-stats.test.ts +15 -2
- package/tests/gentle-todo.test.ts +50 -4
- package/tests/herdr-task-summary-policy.test.ts +128 -0
- package/tests/history-store-private-mode.test.ts +40 -0
- package/tests/image-paste-chips.test.ts +42 -0
- package/tests/inprocess-reviewer.test.ts +122 -0
- package/tests/installer-posix-bootstrap.test.ts +67 -5
- package/tests/installer-server.test.ts +2 -2
- package/tests/installer-windows-diagnostics.test.ts +4 -5
- package/tests/isolated-config-home.ts +28 -0
- package/tests/jobs-widget.test.ts +25 -37
- package/tests/keymaps-customize.test.ts +114 -0
- package/tests/keymaps.test.ts +103 -0
- package/tests/maintainer/mcp-status.maintest.ts +88 -0
- package/tests/maintainer/pi-update-source.maintest.ts +116 -0
- package/tests/model-fallback-notice.test.ts +45 -0
- package/tests/model-fallback-policy.test.ts +83 -0
- package/tests/model-fallback-store.test.ts +111 -0
- package/tests/nan-provider.test.ts +4 -4
- package/tests/no-self-pause-contract.test.ts +19 -0
- package/tests/notification-customize.test.ts +58 -34
- package/tests/odd-routing-canonical-ratchet.test.ts +3 -3
- package/tests/odd-routing-contract.test.ts +1 -1
- package/tests/orchestrator-fallback.test.ts +82 -0
- package/tests/orchestrator-prompt-budget.test.ts +131 -0
- package/tests/package-manifest.test.ts +160 -7
- package/tests/pasted-image-paths.test.ts +118 -0
- package/tests/persona-reply-language.test.ts +20 -1
- package/tests/pi-update-launcher.test.ts +32 -8
- package/tests/pi-update-source.test.ts +162 -0
- package/tests/profile-fast-tier.test.ts +311 -0
- package/tests/profile-tier-footer.test.ts +79 -0
- package/tests/questionnaire-view.test.ts +150 -0
- package/tests/review-candidate-owner-sweep.test.ts +93 -0
- package/tests/review-candidate-view.test.ts +51 -0
- package/tests/review-controller-native-routing.test.ts +120 -6
- package/tests/review-gate.test.ts +24 -0
- package/tests/review-inspect-preflight.test.ts +197 -0
- package/tests/review-integration-v2-forward.test.ts +59 -0
- package/tests/review-repository.test.ts +52 -1
- package/tests/review-sidebar-state.test.ts +5 -5
- package/tests/run-test-suite.test.ts +61 -5
- package/tests/sensitive-path-tools.test.ts +74 -0
- package/tests/session-profile-append-controller.test.ts +63 -0
- package/tests/session-profile-authority.test.ts +259 -0
- package/tests/session-profile-binding.test.ts +15 -0
- package/tests/session-profile-extension.test.ts +615 -0
- package/tests/session-profile-freeze.test.ts +110 -2
- package/tests/session-profile-integration.test.ts +857 -0
- package/tests/session-profile-persistence.test.ts +57 -0
- package/tests/session-profile-v1-compat.test.ts +221 -0
- package/tests/shell-bar.test.ts +113 -55
- package/tests/shell-card.test.ts +13 -1
- package/tests/shell-page.test.ts +108 -0
- package/tests/shell-panel.test.ts +332 -0
- package/tests/shell-prompt.test.ts +54 -0
- package/tests/shell-render-cache.test.ts +5 -0
- package/tests/shell-sidebar-fullscreen.test.ts +12 -0
- package/tests/shell-sidebar-layout.test.ts +159 -27
- package/tests/shell-stats.test.ts +90 -0
- package/tests/shell-usage.test.ts +14 -0
- package/tests/skill-registry.test.ts +68 -1
- package/tests/star-prompt.test.ts +470 -0
- package/tests/startup-banner.test.ts +57 -1
- package/tests/task-size-routing-contract.test.ts +45 -1
- package/tests/verifier-settle-reminder.test.ts +281 -0
- package/tests/verify-first-launch-contract.test.ts +56 -5
- package/tests/verify-installer-tap.test.ts +57 -0
- package/tests/vim-editor-adapter.test.ts +2 -2
- package/tests/visual-customization-policy.test.ts +61 -7
- package/tests/visual-customize-view.test.ts +253 -8
- package/tests/visual-layout-preview.test.ts +28 -0
- package/tests/windows-session-bootstrap.test.ts +105 -2
- package/tests/work-continuity-contract.test.ts +86 -0
- package/tests/writer-surfaces.test.ts +12 -10
- package/tests/yolo-customize.test.ts +30 -11
- package/tests/yolo-mode-runtime.test.ts +4 -2
- 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)
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
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
|
},
|
package/lib/agent-assets.ts
CHANGED
|
@@ -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
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
)
|
|
460
|
-
|
|
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]
|
|
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 };
|
package/lib/agent-profiles.ts
CHANGED
|
@@ -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 ===
|
|
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 {
|
package/lib/agents-config.ts
CHANGED
|
@@ -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 {
|
package/lib/agents-keys.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
}
|
package/lib/agents-protocol.ts
CHANGED
|
@@ -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.
|
|
204
|
-
//
|
|
205
|
-
if (stopReason === "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
|
package/lib/agents-runner.ts
CHANGED
|
@@ -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
|
|
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
|
}
|
package/lib/agents-view.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
|