@caupulican/pi-adaptative 0.90.7 → 0.90.12
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/CHANGELOG.md +56 -0
- package/dist/bundled-resources/skills/tool-call-repair/SKILL.md +5 -4
- package/dist/bundled-resources/skills/tool-call-repair/references/failure-grammar.md +6 -3
- package/dist/bundled-resources/skills/tool-call-repair/references/repair-catalogue.md +1 -0
- package/dist/core/agent-session-contracts.d.ts +2 -0
- package/dist/core/agent-session-contracts.d.ts.map +1 -1
- package/dist/core/agent-session-contracts.js.map +1 -1
- package/dist/core/agent-session.d.ts +8 -7
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +84 -197
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/bounded-completion.d.ts +7 -1
- package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
- package/dist/core/autonomy/bounded-completion.js +8 -2
- package/dist/core/autonomy/bounded-completion.js.map +1 -1
- package/dist/core/autonomy/contracts.d.ts +1 -1
- package/dist/core/autonomy/contracts.d.ts.map +1 -1
- package/dist/core/autonomy/contracts.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +14 -0
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +32 -0
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/billing-failover-controller.js +1 -1
- package/dist/core/billing-failover-controller.js.map +1 -1
- package/dist/core/context/current-work-memory.d.ts +1 -1
- package/dist/core/context/current-work-memory.d.ts.map +1 -1
- package/dist/core/context/current-work-memory.js +2 -1
- package/dist/core/context/current-work-memory.js.map +1 -1
- package/dist/core/context/long-term-memory-trigger.d.ts +1 -1
- package/dist/core/context/long-term-memory-trigger.d.ts.map +1 -1
- package/dist/core/context/long-term-memory-trigger.js +2 -1
- package/dist/core/context/long-term-memory-trigger.js.map +1 -1
- package/dist/core/delegation/managed-lane-controller.js +2 -2
- package/dist/core/delegation/managed-lane-controller.js.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.d.ts +13 -0
- package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.js +71 -8
- package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
- package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
- package/dist/core/delegation/worker-attempt-executor.js +13 -8
- package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
- package/dist/core/delegation/worker-claim.d.ts.map +1 -1
- package/dist/core/delegation/worker-claim.js +14 -1
- package/dist/core/delegation/worker-claim.js.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.d.ts +3 -2
- package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.js +95 -42
- package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
- package/dist/core/delegation/worker-fleet-limits.d.ts.map +1 -1
- package/dist/core/delegation/worker-fleet-limits.js +5 -1
- package/dist/core/delegation/worker-fleet-limits.js.map +1 -1
- package/dist/core/delegation/worker-lane-projection.d.ts.map +1 -1
- package/dist/core/delegation/worker-lane-projection.js +7 -4
- package/dist/core/delegation/worker-lane-projection.js.map +1 -1
- package/dist/core/delegation/worker-lifecycle.d.ts +8 -0
- package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -1
- package/dist/core/delegation/worker-lifecycle.js.map +1 -1
- package/dist/core/delegation/worker-notification-coordinator.d.ts +21 -0
- package/dist/core/delegation/worker-notification-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-notification-coordinator.js +65 -2
- package/dist/core/delegation/worker-notification-coordinator.js.map +1 -1
- package/dist/core/delegation/worker-runner.d.ts +7 -0
- package/dist/core/delegation/worker-runner.d.ts.map +1 -1
- package/dist/core/delegation/worker-runner.js +24 -7
- package/dist/core/delegation/worker-runner.js.map +1 -1
- package/dist/core/delegation/worker-system-prompt.d.ts +54 -0
- package/dist/core/delegation/worker-system-prompt.d.ts.map +1 -0
- package/dist/core/delegation/worker-system-prompt.js +85 -0
- package/dist/core/delegation/worker-system-prompt.js.map +1 -0
- package/dist/core/delegation/worker-tree-budget-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-tree-budget-coordinator.js +4 -0
- package/dist/core/delegation/worker-tree-budget-coordinator.js.map +1 -1
- package/dist/core/delegation/worker-write-reservation-coordinator.d.ts +4 -0
- package/dist/core/delegation/worker-write-reservation-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-write-reservation-coordinator.js +28 -1
- package/dist/core/delegation/worker-write-reservation-coordinator.js.map +1 -1
- package/dist/core/durable-custom-message-turn-controller.d.ts.map +1 -1
- package/dist/core/durable-custom-message-turn-controller.js +14 -3
- package/dist/core/durable-custom-message-turn-controller.js.map +1 -1
- package/dist/core/extension-binding-controller.d.ts +107 -0
- package/dist/core/extension-binding-controller.d.ts.map +1 -0
- package/dist/core/extension-binding-controller.js +224 -0
- package/dist/core/extension-binding-controller.js.map +1 -0
- package/dist/core/extensions/extension-session-scope.d.ts +17 -0
- package/dist/core/extensions/extension-session-scope.d.ts.map +1 -0
- package/dist/core/extensions/extension-session-scope.js +135 -0
- package/dist/core/extensions/extension-session-scope.js.map +1 -0
- package/dist/core/extensions/index.d.ts +1 -0
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js +1 -0
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/types.d.ts +2 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/extensions/wrapper.d.ts +2 -1
- package/dist/core/extensions/wrapper.d.ts.map +1 -1
- package/dist/core/extensions/wrapper.js +10 -4
- package/dist/core/extensions/wrapper.js.map +1 -1
- package/dist/core/foreground-terminal-handoff-controller.d.ts +9 -0
- package/dist/core/foreground-terminal-handoff-controller.d.ts.map +1 -1
- package/dist/core/foreground-terminal-handoff-controller.js +35 -9
- package/dist/core/foreground-terminal-handoff-controller.js.map +1 -1
- package/dist/core/goal-loop-controller.d.ts.map +1 -1
- package/dist/core/goal-loop-controller.js +10 -1
- package/dist/core/goal-loop-controller.js.map +1 -1
- package/dist/core/goals/compact-goal-context.d.ts +1 -1
- package/dist/core/goals/compact-goal-context.d.ts.map +1 -1
- package/dist/core/goals/compact-goal-context.js +2 -1
- package/dist/core/goals/compact-goal-context.js.map +1 -1
- package/dist/core/goals/goal-execution-errors.d.ts +18 -0
- package/dist/core/goals/goal-execution-errors.d.ts.map +1 -0
- package/dist/core/goals/goal-execution-errors.js +21 -0
- package/dist/core/goals/goal-execution-errors.js.map +1 -0
- package/dist/core/goals/goal-lifecycle.d.ts.map +1 -1
- package/dist/core/goals/goal-lifecycle.js +3 -3
- package/dist/core/goals/goal-lifecycle.js.map +1 -1
- package/dist/core/goals/goal-session-controller.d.ts +11 -0
- package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-session-controller.js +74 -14
- package/dist/core/goals/goal-session-controller.js.map +1 -1
- package/dist/core/goals/goal-state.js +1 -1
- package/dist/core/goals/goal-state.js.map +1 -1
- package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
- package/dist/core/goals/goal-tool-core.js +2 -2
- package/dist/core/goals/goal-tool-core.js.map +1 -1
- package/dist/core/goals/natural-language-goal.d.ts +18 -0
- package/dist/core/goals/natural-language-goal.d.ts.map +1 -1
- package/dist/core/goals/natural-language-goal.js +99 -16
- package/dist/core/goals/natural-language-goal.js.map +1 -1
- package/dist/core/model-registry.d.ts +5 -0
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +10 -0
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +3 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/orchestration/capability-gateway.d.ts +1 -1
- package/dist/core/orchestration/capability-gateway.d.ts.map +1 -1
- package/dist/core/orchestration/capability-gateway.js +4 -4
- package/dist/core/orchestration/capability-gateway.js.map +1 -1
- package/dist/core/orchestration/event-store.d.ts +8 -0
- package/dist/core/orchestration/event-store.d.ts.map +1 -1
- package/dist/core/orchestration/event-store.js +9 -7
- package/dist/core/orchestration/event-store.js.map +1 -1
- package/dist/core/orchestration/task-runtime-reducer.js +1 -1
- package/dist/core/orchestration/task-runtime-reducer.js.map +1 -1
- package/dist/core/orchestration/worker-model-pins.d.ts +7 -0
- package/dist/core/orchestration/worker-model-pins.d.ts.map +1 -1
- package/dist/core/orchestration/worker-model-pins.js +17 -1
- package/dist/core/orchestration/worker-model-pins.js.map +1 -1
- package/dist/core/provider-request-runtime-controller.d.ts +9 -0
- package/dist/core/provider-request-runtime-controller.d.ts.map +1 -1
- package/dist/core/provider-request-runtime-controller.js +17 -3
- package/dist/core/provider-request-runtime-controller.js.map +1 -1
- package/dist/core/provider-tool-text.d.ts +15 -1
- package/dist/core/provider-tool-text.d.ts.map +1 -1
- package/dist/core/provider-tool-text.js +42 -10
- package/dist/core/provider-tool-text.js.map +1 -1
- package/dist/core/research/research-lane-controller.d.ts +1 -1
- package/dist/core/research/research-lane-controller.d.ts.map +1 -1
- package/dist/core/research/research-lane-controller.js +2 -1
- package/dist/core/research/research-lane-controller.js.map +1 -1
- package/dist/core/resource-loader.d.ts +3 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +8 -0
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +8 -0
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +6 -0
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/session-supervision-runtime.d.ts.map +1 -1
- package/dist/core/session-supervision-runtime.js +2 -1
- package/dist/core/session-supervision-runtime.js.map +1 -1
- package/dist/core/settings-manager.d.ts +2 -2
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +7 -2
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/tasks/task-state.d.ts +1 -1
- package/dist/core/tasks/task-state.d.ts.map +1 -1
- package/dist/core/tasks/task-state.js +4 -2
- package/dist/core/tasks/task-state.js.map +1 -1
- package/dist/core/tools/delegate.d.ts +13 -0
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +20 -18
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/util/atomic-file.d.ts +7 -0
- package/dist/core/util/atomic-file.d.ts.map +1 -1
- package/dist/core/util/atomic-file.js +8 -6
- package/dist/core/util/atomic-file.js.map +1 -1
- package/dist/core/util/faultable-fs.d.ts +30 -0
- package/dist/core/util/faultable-fs.d.ts.map +1 -0
- package/dist/core/util/faultable-fs.js +30 -0
- package/dist/core/util/faultable-fs.js.map +1 -0
- package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -1
- package/dist/modes/interactive/auth-dialogs-controller.js +1 -0
- package/dist/modes/interactive/auth-dialogs-controller.js.map +1 -1
- package/dist/modes/interactive/components/activity-lane.d.ts.map +1 -1
- package/dist/modes/interactive/components/activity-lane.js +4 -3
- package/dist/modes/interactive/components/activity-lane.js.map +1 -1
- package/dist/modes/interactive/components/footer.js +1 -1
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts +2 -0
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +3 -2
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/report-commands.js +1 -1
- package/dist/modes/interactive/report-commands.js.map +1 -1
- package/dist/modes/interactive/session-flow-commands.d.ts +1 -1
- package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
- package/dist/modes/interactive/session-flow-commands.js +3 -2
- package/dist/modes/interactive/session-flow-commands.js.map +1 -1
- package/docs/extensions.md +1 -0
- package/docs/providers.md +3 -0
- package/docs/settings.md +4 -2
- package/docs/tool-repair.md +1 -0
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +9 -4
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
* them gain locking without forcing an async ripple through their callers; the async variant is for
|
|
18
18
|
* call sites that are already async.
|
|
19
19
|
*/
|
|
20
|
+
import { type FaultableFs } from "./faultable-fs.ts";
|
|
20
21
|
export interface AtomicFileLockOptions {
|
|
21
22
|
/**
|
|
22
23
|
* Bounded retry attempts while waiting for a lock already held elsewhere. Both variants use a
|
|
@@ -53,6 +54,12 @@ export interface AtomicFileLockOptions {
|
|
|
53
54
|
export interface AtomicFileWriteOptions {
|
|
54
55
|
/** POSIX permission bits applied to the temporary file and inherited by the renamed destination. */
|
|
55
56
|
mode?: number;
|
|
57
|
+
/**
|
|
58
|
+
* Injection seam for the mutating fs primitives this write issues (`mkdirSync`, `writeFileSync`,
|
|
59
|
+
* `renameSync`). Defaults to real `node:fs` — omitting this option is a zero-behavior-change no-op.
|
|
60
|
+
* Only the destructive-testing harness passes a fault-injecting implementation.
|
|
61
|
+
*/
|
|
62
|
+
fs?: FaultableFs;
|
|
56
63
|
}
|
|
57
64
|
/**
|
|
58
65
|
* Existing auth/settings/trust paths historically used 10 total attempts separated by 20ms. Keep
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"atomic-file.d.ts","sourceRoot":"","sources":["../../../src/core/util/atomic-file.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;
|
|
1
|
+
{"version":3,"file":"atomic-file.d.ts","sourceRoot":"","sources":["../../../src/core/util/atomic-file.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;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AM,EAAE,OAAO,CAAC,EAAE,sBAAsB,GAAG,IAAI,CAa7G;AAED,wDAAwD;AACxD,wBAAsB,eAAe,CACpC,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,sBAAsB,GAC9B,OAAO,CAAC,IAAI,CAAC,CAcf"}
|
|
@@ -18,9 +18,10 @@
|
|
|
18
18
|
* call sites that are already async.
|
|
19
19
|
*/
|
|
20
20
|
import { randomUUID } from "node:crypto";
|
|
21
|
-
import { promises as fsPromises, mkdirSync,
|
|
21
|
+
import { promises as fsPromises, mkdirSync, unlinkSync } from "node:fs";
|
|
22
22
|
import { dirname, resolve } from "node:path";
|
|
23
23
|
import lockfile from "proper-lockfile";
|
|
24
|
+
import { nodeFs } from "./faultable-fs.js";
|
|
24
25
|
/**
|
|
25
26
|
* Bounded rename retry budget for the win32-only transient-rename handling below (see
|
|
26
27
|
* {@link isTransientRenameErrorOnWin32}). Backoff doubles each attempt starting at
|
|
@@ -52,10 +53,10 @@ function isTransientRenameErrorOnWin32(err) {
|
|
|
52
53
|
return code === "EPERM" || code === "EACCES" || code === "EBUSY";
|
|
53
54
|
}
|
|
54
55
|
/** Sync counterpart of the rename-retry policy; see {@link isTransientRenameErrorOnWin32}. */
|
|
55
|
-
function renameSyncWithRetry(tmpPath, filePath) {
|
|
56
|
+
function renameSyncWithRetry(tmpPath, filePath, fs) {
|
|
56
57
|
for (let attempt = 0; attempt <= RENAME_RETRY_ATTEMPTS; attempt++) {
|
|
57
58
|
try {
|
|
58
|
-
renameSync(tmpPath, filePath);
|
|
59
|
+
fs.renameSync(tmpPath, filePath);
|
|
59
60
|
return;
|
|
60
61
|
}
|
|
61
62
|
catch (err) {
|
|
@@ -302,13 +303,14 @@ async function removeTemporaryPath(tmpPath) {
|
|
|
302
303
|
}
|
|
303
304
|
}
|
|
304
305
|
export function writeFileAtomicSync(filePath, content, options) {
|
|
305
|
-
|
|
306
|
+
const fs = options?.fs ?? nodeFs;
|
|
307
|
+
fs.mkdirSync(dirname(filePath), { recursive: true });
|
|
306
308
|
const tmpPath = temporaryPath(filePath);
|
|
307
309
|
let renamed = false;
|
|
308
310
|
try {
|
|
309
311
|
// `wx` makes a nonce collision harmless: never truncate another writer's temporary file.
|
|
310
|
-
writeFileSync(tmpPath, content, { encoding: "utf-8", flag: "wx", mode: options?.mode });
|
|
311
|
-
renameSyncWithRetry(tmpPath, filePath);
|
|
312
|
+
fs.writeFileSync(tmpPath, content, { encoding: "utf-8", flag: "wx", mode: options?.mode });
|
|
313
|
+
renameSyncWithRetry(tmpPath, filePath, fs);
|
|
312
314
|
renamed = true;
|
|
313
315
|
}
|
|
314
316
|
finally {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"atomic-file.js","sourceRoot":"","sources":["../../../src/core/util/atomic-file.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,QAAQ,IAAI,UAAU,EAAE,SAAS,EAAE,UAAU,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACnG,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC7C,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AAEvC;;;;;;;;;GASG;AACH,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAChC,MAAM,2BAA2B,GAAG,EAAE,CAAC;AACvC,MAAM,2BAA2B,GAAG,GAAG,CAAC;AAExC;;;;;;;;GAQG;AACH,SAAS,6BAA6B,CAAC,GAAY;IAClD,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO;QAAE,OAAO,KAAK,CAAC;IAC/C,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC1D,MAAM,IAAI,GAAI,GAAyB,CAAC,IAAI,CAAC;IAC7C,OAA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,IAAI,OAAO,GAAG,KAAK,CAAC;QACpB,IAAI,CAAC;YACJ,yFAAyF;YACzF,MAAM,UAAU,CAAC,SAAS,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;YACrG,MAAM,eAAe,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YACzC,OAAO,GAAG,IAAI,CAAC;QAChB,CAAC;gBAAS,CAAC;YACV,IAAI,CAAC,OAAO;gBAAE,MAAM,mBAAmB,CAAC,OAAO,CAAC,CAAC;QAClD,CAAC;IACF,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Shared atomic-file helper: a single lock+tmp+rename implementation reused by every\n * on-disk store that does a read-modify-write against a JSON/text file. Modeled on the pattern\n * already proven in `memory/providers/file-store.ts` (proper-lockfile advisory lock + write-tmp-\n * then-rename); before this helper existed the pattern was copy-pasted per store, and most copies\n * were missing either the lock, the atomic write, or both.\n *\n * Two call shapes:\n * - `withFileLock(Sync)` — hold an exclusive advisory lock across an arbitrary read-modify-write\n * callback. The lock spans BOTH the read and the write, closing the classic RMW race where two\n * writers each read the old content before either writes back.\n * - `writeFileAtomic(Sync)` — write-tmp-then-rename. Used INSIDE a `withFileLock` callback (or\n * standalone, for a pure overwrite that has no read step to race).\n *\n * Sync and async variants are both exported. Most existing stores expose a synchronous public API\n * called from hot, non-async paths (e.g. a per-token-stream perf sample), so the sync variant lets\n * them gain locking without forcing an async ripple through their callers; the async variant is for\n * call sites that are already async.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { promises as fsPromises, mkdirSync, renameSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport lockfile from \"proper-lockfile\";\n\n/**\n * Bounded rename retry budget for the win32-only transient-rename handling below (see\n * {@link isTransientRenameErrorOnWin32}). Backoff doubles each attempt starting at\n * {@link RENAME_RETRY_MIN_TIMEOUT_MS} and capped at {@link RENAME_RETRY_MAX_TIMEOUT_MS}, mirroring\n * the doubling-backoff shape used for lock acquisition above. With {@link RENAME_RETRY_ATTEMPTS}\n * extra attempts (10, 20, 40, 80, ... capped at 200) the worst-case total wait is ~1.03s\n * (10+20+40+80+160+200+200+200+200 ~= 1110ms across 9 gaps), which comfortably covers the\n * millisecond-scale window Defender/the Windows Search indexer hold a freshly-written file open\n * without FILE_SHARE_DELETE before releasing it.\n */\nconst RENAME_RETRY_ATTEMPTS = 9;\nconst RENAME_RETRY_MIN_TIMEOUT_MS = 10;\nconst RENAME_RETRY_MAX_TIMEOUT_MS = 200;\n\n/**\n * On win32, antivirus (e.g. Windows Defender's real-time scanner) and the Windows Search indexer\n * routinely open a freshly-written file for a brief scan without `FILE_SHARE_DELETE`, which makes a\n * rename over/of that file fail transiently with EPERM/EACCES/EBUSY for a few milliseconds. This is\n * a well-documented platform semantic, not a bug in our write path — it's exactly why the\n * `graceful-fs` package ships its own win32 rename-retry wrapper. POSIX platforms never exhibit this\n * transient (a POSIX rename either succeeds or fails for a real, non-transient reason), so retry is\n * gated strictly to win32 to keep POSIX behavior byte-identical to a bare rename.\n */\nfunction isTransientRenameErrorOnWin32(err: unknown): boolean {\n\tif (process.platform !== \"win32\") return false;\n\tif (typeof err !== \"object\" || err === null) return false;\n\tconst code = (err as { code?: string }).code;\n\treturn code === \"EPERM\" || code === \"EACCES\" || code === \"EBUSY\";\n}\n\n/** Sync counterpart of the rename-retry policy; see {@link isTransientRenameErrorOnWin32}. */\nfunction renameSyncWithRetry(tmpPath: string, filePath: string): void {\n\tfor (let attempt = 0; attempt <= RENAME_RETRY_ATTEMPTS; attempt++) {\n\t\ttry {\n\t\t\trenameSync(tmpPath, filePath);\n\t\t\treturn;\n\t\t} catch (err) {\n\t\t\tif (!isTransientRenameErrorOnWin32(err) || attempt === RENAME_RETRY_ATTEMPTS) throw err;\n\t\t\tconst backoffMs = Math.min(RENAME_RETRY_MIN_TIMEOUT_MS * 2 ** attempt, RENAME_RETRY_MAX_TIMEOUT_MS);\n\t\t\tblockingSleepMs(backoffMs);\n\t\t}\n\t}\n}\n\n/** Async counterpart of the rename-retry policy; see {@link isTransientRenameErrorOnWin32}. */\nasync function renameWithRetry(tmpPath: string, filePath: string): Promise<void> {\n\tfor (let attempt = 0; attempt <= RENAME_RETRY_ATTEMPTS; attempt++) {\n\t\ttry {\n\t\t\tawait fsPromises.rename(tmpPath, filePath);\n\t\t\treturn;\n\t\t} catch (err) {\n\t\t\tif (!isTransientRenameErrorOnWin32(err) || attempt === RENAME_RETRY_ATTEMPTS) throw err;\n\t\t\tconst backoffMs = Math.min(RENAME_RETRY_MIN_TIMEOUT_MS * 2 ** attempt, RENAME_RETRY_MAX_TIMEOUT_MS);\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, backoffMs));\n\t\t}\n\t}\n}\n\nexport interface AtomicFileLockOptions {\n\t/**\n\t * Bounded retry attempts while waiting for a lock already held elsewhere. Both variants use a\n\t * SHORT, capped backoff (see {@link RETRY_MIN_TIMEOUT_MS}/{@link RETRY_MAX_TIMEOUT_MS}) — these\n\t * stores' critical sections are sub-millisecond reads+writes of small JSON/text files, so\n\t * contention should clear in milliseconds, not the multi-second-to-31-second worst case\n\t * proper-lockfile's OWN default backoff produces for a bare numeric `retries` (its default\n\t * `minTimeout` is 1000ms with factor 2 — see node_modules/retry/lib/retry.js). Passing a bare\n\t * number straight through would turn brief contention into a multi-second stall on a hot path\n\t * (e.g. a per-token-stream perf sample), so both variants instead build an explicit short-backoff\n\t * `retry` options object.\n\t * - Async (`withFileLock`): forwarded as `{retries, minTimeout, maxTimeout}` to proper-lockfile.\n\t * - Sync (`withFileLockSync`): proper-lockfile's sync API REJECTS `retries > 0` outright (it\n\t * requires the whole acquire flow to be synchronous — see proper-lockfile/lib/adapter.js\n\t * `toSyncOptions`, which throws `ESYNC`). So the sync path implements its own bounded retry\n\t * around single `lockfile.lockSync` attempts, blocking briefly between them (Atomics.wait) —\n\t * callers are already fully synchronous fs code, so a short blocking wait on contention matches\n\t * the existing execution model rather than introducing a new one.\n\t */\n\tretries?: number;\n\t/** Initial delay between sync/async acquisition attempts; defaults to 25ms. */\n\tminRetryDelayMs?: number;\n\t/** Maximum delay between sync/async acquisition attempts; defaults to 500ms. */\n\tmaxRetryDelayMs?: number;\n\t/** Retry-delay multiplier; defaults to 2. Set max=min for a fixed delay. */\n\tretryFactor?: number;\n\t/** Resolve symlinks before locking (proper-lockfile `realpath`); false matches file-store.ts. */\n\trealpath?: boolean;\n\t/** Lock staleness window in ms (proper-lockfile `stale`); omitted = proper-lockfile's own default. */\n\tstale?: number;\n\t/** Explicit proper-lockfile directory path; defaults to `${filePath}.lock`. */\n\tlockfilePath?: string;\n}\n\nexport interface AtomicFileWriteOptions {\n\t/** POSIX permission bits applied to the temporary file and inherited by the renamed destination. */\n\tmode?: number;\n}\n\nconst DEFAULT_RETRIES = 10;\nconst DEFAULT_REALPATH = false;\n/**\n * Capped doubling backoff shared by both variants — see {@link AtomicFileLockOptions.retries}.\n * With the current defaults (10 retries, 25ms floor, 500ms cap) the total worst-case contention\n * budget is ~3.3s (25+50+100+200+400+500+500+500+500+500), comfortably over the >= 2s floor this\n * needs to survive a loaded CI runner (e.g. the Windows CI mkdir/rmdir lock-directory churn under\n * two-real-OS-thread contention).\n */\nconst RETRY_MIN_TIMEOUT_MS = 25;\nconst RETRY_MAX_TIMEOUT_MS = 500;\n\n/**\n * Existing auth/settings/trust paths historically used 10 total attempts separated by 20ms. Keep\n * that low-latency user-facing policy explicit while routing the mechanism through this module.\n */\nexport const LOW_LATENCY_FILE_LOCK_OPTIONS: Readonly<AtomicFileLockOptions> = Object.freeze({\n\tretries: 9,\n\tminRetryDelayMs: 20,\n\tmaxRetryDelayMs: 20,\n});\n\nfunction lockDirectory(filePath: string, lockfilePath?: string): string {\n\treturn dirname(lockfilePath ?? filePath);\n}\n\nfunction ensureLockDirSync(filePath: string, lockfilePath?: string): void {\n\tmkdirSync(lockDirectory(filePath, lockfilePath), { recursive: true });\n}\n\nasync function ensureLockDir(filePath: string, lockfilePath?: string): Promise<void> {\n\tawait fsPromises.mkdir(lockDirectory(filePath, lockfilePath), { recursive: true });\n}\n\nfunction isLockedError(err: unknown): boolean {\n\tif (typeof err !== \"object\" || err === null) return false;\n\tconst code = (err as { code?: string }).code;\n\tif (code === \"ELOCKED\") return true;\n\t// On win32, mkdir-ing the lock directory can transiently surface EPERM (rather than the\n\t// expected EEXIST) when a previous incarnation of that directory is concurrently being\n\t// rmdir'd by the racing releaser — the mkdir lands mid-teardown and the OS reports \"operation\n\t// not permitted\" instead of \"already exists\". This is contention, not a real permissions\n\t// failure, so treat it identically to ELOCKED: retry with the existing backoff rather than\n\t// letting it escape as fatal. POSIX platforms don't exhibit this transient and keep surfacing\n\t// real EPERM (e.g. an actually unwritable directory) as fatal.\n\tif (code === \"EPERM\" && process.platform === \"win32\") return true;\n\treturn false;\n}\n\n/** Block the calling thread for `ms` without spinning the CPU (Atomics.wait on a private buffer). */\nfunction blockingSleepMs(ms: number): void {\n\tAtomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);\n}\n\ntype PendingPathOperations = Map<string, Promise<void>>;\n\nconst pendingAsyncFileLockTails: PendingPathOperations = new Map();\nconst pendingAtomicWriteTails: PendingPathOperations = new Map();\n\nfunction pathOperationKey(filePath: string): string {\n\tconst absolutePath = resolve(filePath);\n\treturn process.platform === \"win32\" ? absolutePath.toLowerCase() : absolutePath;\n}\n\n/**\n * Queue only operations that target the same platform path. This prevents same-process callers\n * from entering synchronized OS retry storms without imposing a process-wide or cross-tenant\n * bottleneck. The tail always resolves and self-removes, including after a failed operation.\n */\nasync function withSerializedPathOperation<T>(\n\ttails: PendingPathOperations,\n\tfilePath: string,\n\tfn: () => Promise<T>,\n): Promise<T> {\n\tconst key = pathOperationKey(filePath);\n\tconst preceding = tails.get(key) ?? Promise.resolve();\n\tlet releaseTail: (() => void) | undefined;\n\tconst tail = new Promise<void>((resolveTail) => {\n\t\treleaseTail = resolveTail;\n\t});\n\ttails.set(key, tail);\n\n\tawait preceding;\n\ttry {\n\t\treturn await fn();\n\t} finally {\n\t\treleaseTail?.();\n\t\tif (tails.get(key) === tail) tails.delete(key);\n\t}\n}\n\n/**\n * Acquire a proper-lockfile sync lock with bounded retry on `ELOCKED` (proper-lockfile's sync API\n * itself forbids `retries > 0`; see {@link AtomicFileLockOptions.retries}).\n *\n * Backoff doubles each attempt (mirroring the `retry` module's own `factor: 2` default that the\n * async path gets for free from proper-lockfile), starting at {@link RETRY_MIN_TIMEOUT_MS} and\n * capped at {@link RETRY_MAX_TIMEOUT_MS}.\n *\n * This is budget PARITY between two implementations of the same lock-acquisition contract, not\n * flake-masking: `options.retries` (a count of RETRIES, i.e. attempts after the first) means the\n * same thing on both paths, so both must make `retries + 1` total acquisition attempts with the\n * same per-gap backoff schedule. The async path gets `retries + 1` attempts for free from the\n * `retry` module (it retries `options.retries` times after its initial attempt); the sync path\n * used to loop exactly `attempts` times total (one fewer gap, and one fewer attempt than the\n * async path for the same `retries` value), which under-budgeted it relative to its async sibling\n * and surfaced as spurious ELOCKED failures under real contention (e.g. two OS threads hammering\n * the same file, or mkdir/rmdir lock-directory churn on a loaded Windows CI runner).\n */\nfunction retryCount(options: AtomicFileLockOptions): number {\n\tconst configured = options.retries ?? DEFAULT_RETRIES;\n\treturn Number.isFinite(configured) ? Math.max(0, Math.floor(configured)) : DEFAULT_RETRIES;\n}\n\nfunction retryDelayMs(options: AtomicFileLockOptions, attempt: number): number {\n\tconst configuredMin = options.minRetryDelayMs ?? RETRY_MIN_TIMEOUT_MS;\n\tconst minDelay = Number.isFinite(configuredMin) ? Math.max(0, configuredMin) : RETRY_MIN_TIMEOUT_MS;\n\tconst configuredMax = options.maxRetryDelayMs ?? RETRY_MAX_TIMEOUT_MS;\n\tconst maxDelay = Number.isFinite(configuredMax) ? Math.max(minDelay, configuredMax) : RETRY_MAX_TIMEOUT_MS;\n\tconst configuredFactor = options.retryFactor ?? 2;\n\tconst factor = Number.isFinite(configuredFactor) ? Math.max(1, configuredFactor) : 2;\n\treturn Math.min(minDelay * factor ** (attempt - 1), maxDelay);\n}\n\n/**\n * Acquire a synchronous advisory file lock and return its release function. This is the shared\n * mechanism for coordinators that must hold several locks in a deterministic order before entering\n * one critical section; callers retain ownership of release ordering and release-error semantics.\n */\nexport function acquireFileLockSync(filePath: string, options: AtomicFileLockOptions = {}): () => void {\n\tensureLockDirSync(filePath, options.lockfilePath);\n\tconst attempts = retryCount(options) + 1;\n\tconst lockOptions = {\n\t\tlockfilePath: options.lockfilePath,\n\t\trealpath: options.realpath ?? DEFAULT_REALPATH,\n\t\tstale: options.stale,\n\t};\n\tfor (let attempt = 1; attempt <= attempts; attempt++) {\n\t\ttry {\n\t\t\treturn lockfile.lockSync(filePath, lockOptions);\n\t\t} catch (err) {\n\t\t\tif (!isLockedError(err) || attempt === attempts) throw err;\n\t\t\tblockingSleepMs(retryDelayMs(options, attempt));\n\t\t}\n\t}\n\t// Unreachable (the loop always returns or throws), but keeps the function's return type honest.\n\tthrow new Error(`Failed to acquire lock for ${filePath}`);\n}\n\n/**\n * Hold an exclusive advisory lock on `filePath` for the duration of `fn` (sync). Always releases,\n * including when `fn` throws.\n */\nexport function withFileLockSync<T>(filePath: string, fn: () => T, options?: AtomicFileLockOptions): T {\n\tconst release = acquireFileLockSync(filePath, options);\n\ttry {\n\t\treturn fn();\n\t} finally {\n\t\t// A lock-cleanup failure must never mask fn()'s result (or replace fn()'s own thrown error) —\n\t\t// by this point fn() has already durably committed or failed on its own terms.\n\t\ttry {\n\t\t\trelease();\n\t\t} catch {\n\t\t\t// best-effort cleanup; a stale lock self-expires via proper-lockfile's `stale` window\n\t\t}\n\t}\n}\n\n/** Async counterpart of {@link withFileLockSync}. Always releases, including when `fn` throws/rejects. */\nexport async function withFileLock<T>(\n\tfilePath: string,\n\tfn: () => Promise<T> | T,\n\toptions?: AtomicFileLockOptions,\n): Promise<T> {\n\treturn withSerializedPathOperation(pendingAsyncFileLockTails, options?.lockfilePath ?? filePath, async () => {\n\t\tawait ensureLockDir(filePath, options?.lockfilePath);\n\t\tconst release = await lockfile.lock(filePath, {\n\t\t\tlockfilePath: options?.lockfilePath,\n\t\t\trealpath: options?.realpath ?? DEFAULT_REALPATH,\n\t\t\tretries: {\n\t\t\t\tretries: retryCount(options ?? {}),\n\t\t\t\tfactor: options?.retryFactor ?? 2,\n\t\t\t\tminTimeout: options?.minRetryDelayMs ?? RETRY_MIN_TIMEOUT_MS,\n\t\t\t\tmaxTimeout: options?.maxRetryDelayMs ?? RETRY_MAX_TIMEOUT_MS,\n\t\t\t},\n\t\t\tstale: options?.stale,\n\t\t});\n\t\ttry {\n\t\t\treturn await fn();\n\t\t} finally {\n\t\t\t// See {@link withFileLockSync} — cleanup failures must not mask fn()'s outcome.\n\t\t\tawait release().catch(() => {});\n\t\t}\n\t});\n}\n\n/**\n * Write `content` to `filePath` via write-tmp-then-rename (sync); the rename is atomic on the same\n * filesystem, so a concurrent reader never observes a partially-written file. Does NOT itself lock —\n * call from inside {@link withFileLockSync} when the write follows a read that must not race another\n * writer's read+write; call standalone for an unconditional overwrite with no read step.\n */\nfunction temporaryPath(filePath: string): string {\n\treturn `${filePath}.${process.pid}.${randomUUID()}.tmp`;\n}\n\n/**\n * Async standalone overwrites can legitimately target the same file at once. Unique temporary\n * names prevent writers from corrupting each other's staging files, but Windows still serializes\n * replacement renames internally. Letting every writer retry in lockstep creates a thundering herd\n * that can exhaust the bounded Defender/indexer retry budget even though no external process owns\n * the destination. Keep one FIFO tail per destination inside this process so each destination has\n * one writer at a time; writes to different destinations remain fully parallel. The tail is always\n * resolved and removed, including after a failed write, so one failure cannot poison later writes\n * or retain tenant paths indefinitely. File-lock queues are separate from atomic-write queues so a\n * write inside a held advisory lock never waits on itself.\n */\nasync function withSerializedAtomicWrite<T>(filePath: string, fn: () => Promise<T>): Promise<T> {\n\treturn withSerializedPathOperation(pendingAtomicWriteTails, filePath, fn);\n}\n\n/** Remove one invocation's temporary path without masking the original write/rename failure. */\nfunction removeTemporaryPathSync(tmpPath: string): void {\n\ttry {\n\t\tunlinkSync(tmpPath);\n\t} catch {\n\t\t// The rename may have consumed the path, or another failure may have prevented its creation.\n\t}\n}\n\nasync function removeTemporaryPath(tmpPath: string): Promise<void> {\n\ttry {\n\t\tawait fsPromises.unlink(tmpPath);\n\t} catch {\n\t\t// The rename may have consumed the path, or another failure may have prevented its creation.\n\t}\n}\n\nexport function writeFileAtomicSync(filePath: string, content: string, options?: AtomicFileWriteOptions): void {\n\tmkdirSync(dirname(filePath), { recursive: true });\n\tconst tmpPath = temporaryPath(filePath);\n\tlet renamed = false;\n\ttry {\n\t\t// `wx` makes a nonce collision harmless: never truncate another writer's temporary file.\n\t\twriteFileSync(tmpPath, content, { encoding: \"utf-8\", flag: \"wx\", mode: options?.mode });\n\t\trenameSyncWithRetry(tmpPath, filePath);\n\t\trenamed = true;\n\t} finally {\n\t\tif (!renamed) removeTemporaryPathSync(tmpPath);\n\t}\n}\n\n/** Async counterpart of {@link writeFileAtomicSync}. */\nexport async function writeFileAtomic(\n\tfilePath: string,\n\tcontent: string,\n\toptions?: AtomicFileWriteOptions,\n): Promise<void> {\n\tawait withSerializedAtomicWrite(filePath, async () => {\n\t\tawait fsPromises.mkdir(dirname(filePath), { recursive: true });\n\t\tconst tmpPath = temporaryPath(filePath);\n\t\tlet renamed = false;\n\t\ttry {\n\t\t\t// `wx` makes a nonce collision harmless: never truncate another writer's temporary file.\n\t\t\tawait fsPromises.writeFile(tmpPath, content, { encoding: \"utf-8\", flag: \"wx\", mode: options?.mode });\n\t\t\tawait renameWithRetry(tmpPath, filePath);\n\t\t\trenamed = true;\n\t\t} finally {\n\t\t\tif (!renamed) await removeTemporaryPath(tmpPath);\n\t\t}\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"file":"atomic-file.js","sourceRoot":"","sources":["../../../src/core/util/atomic-file.ts"],"names":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AmB,CAAC,OAAO,CAAC,CAAC;QAClD,CAAC;IACF,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Shared atomic-file helper: a single lock+tmp+rename implementation reused by every\n * on-disk store that does a read-modify-write against a JSON/text file. Modeled on the pattern\n * already proven in `memory/providers/file-store.ts` (proper-lockfile advisory lock + write-tmp-\n * then-rename); before this helper existed the pattern was copy-pasted per store, and most copies\n * were missing either the lock, the atomic write, or both.\n *\n * Two call shapes:\n * - `withFileLock(Sync)` — hold an exclusive advisory lock across an arbitrary read-modify-write\n * callback. The lock spans BOTH the read and the write, closing the classic RMW race where two\n * writers each read the old content before either writes back.\n * - `writeFileAtomic(Sync)` — write-tmp-then-rename. Used INSIDE a `withFileLock` callback (or\n * standalone, for a pure overwrite that has no read step to race).\n *\n * Sync and async variants are both exported. Most existing stores expose a synchronous public API\n * called from hot, non-async paths (e.g. a per-token-stream perf sample), so the sync variant lets\n * them gain locking without forcing an async ripple through their callers; the async variant is for\n * call sites that are already async.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { promises as fsPromises, mkdirSync, unlinkSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport lockfile from \"proper-lockfile\";\nimport { type FaultableFs, nodeFs } from \"./faultable-fs.ts\";\n\n/**\n * Bounded rename retry budget for the win32-only transient-rename handling below (see\n * {@link isTransientRenameErrorOnWin32}). Backoff doubles each attempt starting at\n * {@link RENAME_RETRY_MIN_TIMEOUT_MS} and capped at {@link RENAME_RETRY_MAX_TIMEOUT_MS}, mirroring\n * the doubling-backoff shape used for lock acquisition above. With {@link RENAME_RETRY_ATTEMPTS}\n * extra attempts (10, 20, 40, 80, ... capped at 200) the worst-case total wait is ~1.03s\n * (10+20+40+80+160+200+200+200+200 ~= 1110ms across 9 gaps), which comfortably covers the\n * millisecond-scale window Defender/the Windows Search indexer hold a freshly-written file open\n * without FILE_SHARE_DELETE before releasing it.\n */\nconst RENAME_RETRY_ATTEMPTS = 9;\nconst RENAME_RETRY_MIN_TIMEOUT_MS = 10;\nconst RENAME_RETRY_MAX_TIMEOUT_MS = 200;\n\n/**\n * On win32, antivirus (e.g. Windows Defender's real-time scanner) and the Windows Search indexer\n * routinely open a freshly-written file for a brief scan without `FILE_SHARE_DELETE`, which makes a\n * rename over/of that file fail transiently with EPERM/EACCES/EBUSY for a few milliseconds. This is\n * a well-documented platform semantic, not a bug in our write path — it's exactly why the\n * `graceful-fs` package ships its own win32 rename-retry wrapper. POSIX platforms never exhibit this\n * transient (a POSIX rename either succeeds or fails for a real, non-transient reason), so retry is\n * gated strictly to win32 to keep POSIX behavior byte-identical to a bare rename.\n */\nfunction isTransientRenameErrorOnWin32(err: unknown): boolean {\n\tif (process.platform !== \"win32\") return false;\n\tif (typeof err !== \"object\" || err === null) return false;\n\tconst code = (err as { code?: string }).code;\n\treturn code === \"EPERM\" || code === \"EACCES\" || code === \"EBUSY\";\n}\n\n/** Sync counterpart of the rename-retry policy; see {@link isTransientRenameErrorOnWin32}. */\nfunction renameSyncWithRetry(tmpPath: string, filePath: string, fs: FaultableFs): void {\n\tfor (let attempt = 0; attempt <= RENAME_RETRY_ATTEMPTS; attempt++) {\n\t\ttry {\n\t\t\tfs.renameSync(tmpPath, filePath);\n\t\t\treturn;\n\t\t} catch (err) {\n\t\t\tif (!isTransientRenameErrorOnWin32(err) || attempt === RENAME_RETRY_ATTEMPTS) throw err;\n\t\t\tconst backoffMs = Math.min(RENAME_RETRY_MIN_TIMEOUT_MS * 2 ** attempt, RENAME_RETRY_MAX_TIMEOUT_MS);\n\t\t\tblockingSleepMs(backoffMs);\n\t\t}\n\t}\n}\n\n/** Async counterpart of the rename-retry policy; see {@link isTransientRenameErrorOnWin32}. */\nasync function renameWithRetry(tmpPath: string, filePath: string): Promise<void> {\n\tfor (let attempt = 0; attempt <= RENAME_RETRY_ATTEMPTS; attempt++) {\n\t\ttry {\n\t\t\tawait fsPromises.rename(tmpPath, filePath);\n\t\t\treturn;\n\t\t} catch (err) {\n\t\t\tif (!isTransientRenameErrorOnWin32(err) || attempt === RENAME_RETRY_ATTEMPTS) throw err;\n\t\t\tconst backoffMs = Math.min(RENAME_RETRY_MIN_TIMEOUT_MS * 2 ** attempt, RENAME_RETRY_MAX_TIMEOUT_MS);\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, backoffMs));\n\t\t}\n\t}\n}\n\nexport interface AtomicFileLockOptions {\n\t/**\n\t * Bounded retry attempts while waiting for a lock already held elsewhere. Both variants use a\n\t * SHORT, capped backoff (see {@link RETRY_MIN_TIMEOUT_MS}/{@link RETRY_MAX_TIMEOUT_MS}) — these\n\t * stores' critical sections are sub-millisecond reads+writes of small JSON/text files, so\n\t * contention should clear in milliseconds, not the multi-second-to-31-second worst case\n\t * proper-lockfile's OWN default backoff produces for a bare numeric `retries` (its default\n\t * `minTimeout` is 1000ms with factor 2 — see node_modules/retry/lib/retry.js). Passing a bare\n\t * number straight through would turn brief contention into a multi-second stall on a hot path\n\t * (e.g. a per-token-stream perf sample), so both variants instead build an explicit short-backoff\n\t * `retry` options object.\n\t * - Async (`withFileLock`): forwarded as `{retries, minTimeout, maxTimeout}` to proper-lockfile.\n\t * - Sync (`withFileLockSync`): proper-lockfile's sync API REJECTS `retries > 0` outright (it\n\t * requires the whole acquire flow to be synchronous — see proper-lockfile/lib/adapter.js\n\t * `toSyncOptions`, which throws `ESYNC`). So the sync path implements its own bounded retry\n\t * around single `lockfile.lockSync` attempts, blocking briefly between them (Atomics.wait) —\n\t * callers are already fully synchronous fs code, so a short blocking wait on contention matches\n\t * the existing execution model rather than introducing a new one.\n\t */\n\tretries?: number;\n\t/** Initial delay between sync/async acquisition attempts; defaults to 25ms. */\n\tminRetryDelayMs?: number;\n\t/** Maximum delay between sync/async acquisition attempts; defaults to 500ms. */\n\tmaxRetryDelayMs?: number;\n\t/** Retry-delay multiplier; defaults to 2. Set max=min for a fixed delay. */\n\tretryFactor?: number;\n\t/** Resolve symlinks before locking (proper-lockfile `realpath`); false matches file-store.ts. */\n\trealpath?: boolean;\n\t/** Lock staleness window in ms (proper-lockfile `stale`); omitted = proper-lockfile's own default. */\n\tstale?: number;\n\t/** Explicit proper-lockfile directory path; defaults to `${filePath}.lock`. */\n\tlockfilePath?: string;\n}\n\nexport interface AtomicFileWriteOptions {\n\t/** POSIX permission bits applied to the temporary file and inherited by the renamed destination. */\n\tmode?: number;\n\t/**\n\t * Injection seam for the mutating fs primitives this write issues (`mkdirSync`, `writeFileSync`,\n\t * `renameSync`). Defaults to real `node:fs` — omitting this option is a zero-behavior-change no-op.\n\t * Only the destructive-testing harness passes a fault-injecting implementation.\n\t */\n\tfs?: FaultableFs;\n}\n\nconst DEFAULT_RETRIES = 10;\nconst DEFAULT_REALPATH = false;\n/**\n * Capped doubling backoff shared by both variants — see {@link AtomicFileLockOptions.retries}.\n * With the current defaults (10 retries, 25ms floor, 500ms cap) the total worst-case contention\n * budget is ~3.3s (25+50+100+200+400+500+500+500+500+500), comfortably over the >= 2s floor this\n * needs to survive a loaded CI runner (e.g. the Windows CI mkdir/rmdir lock-directory churn under\n * two-real-OS-thread contention).\n */\nconst RETRY_MIN_TIMEOUT_MS = 25;\nconst RETRY_MAX_TIMEOUT_MS = 500;\n\n/**\n * Existing auth/settings/trust paths historically used 10 total attempts separated by 20ms. Keep\n * that low-latency user-facing policy explicit while routing the mechanism through this module.\n */\nexport const LOW_LATENCY_FILE_LOCK_OPTIONS: Readonly<AtomicFileLockOptions> = Object.freeze({\n\tretries: 9,\n\tminRetryDelayMs: 20,\n\tmaxRetryDelayMs: 20,\n});\n\nfunction lockDirectory(filePath: string, lockfilePath?: string): string {\n\treturn dirname(lockfilePath ?? filePath);\n}\n\nfunction ensureLockDirSync(filePath: string, lockfilePath?: string): void {\n\tmkdirSync(lockDirectory(filePath, lockfilePath), { recursive: true });\n}\n\nasync function ensureLockDir(filePath: string, lockfilePath?: string): Promise<void> {\n\tawait fsPromises.mkdir(lockDirectory(filePath, lockfilePath), { recursive: true });\n}\n\nfunction isLockedError(err: unknown): boolean {\n\tif (typeof err !== \"object\" || err === null) return false;\n\tconst code = (err as { code?: string }).code;\n\tif (code === \"ELOCKED\") return true;\n\t// On win32, mkdir-ing the lock directory can transiently surface EPERM (rather than the\n\t// expected EEXIST) when a previous incarnation of that directory is concurrently being\n\t// rmdir'd by the racing releaser — the mkdir lands mid-teardown and the OS reports \"operation\n\t// not permitted\" instead of \"already exists\". This is contention, not a real permissions\n\t// failure, so treat it identically to ELOCKED: retry with the existing backoff rather than\n\t// letting it escape as fatal. POSIX platforms don't exhibit this transient and keep surfacing\n\t// real EPERM (e.g. an actually unwritable directory) as fatal.\n\tif (code === \"EPERM\" && process.platform === \"win32\") return true;\n\treturn false;\n}\n\n/** Block the calling thread for `ms` without spinning the CPU (Atomics.wait on a private buffer). */\nfunction blockingSleepMs(ms: number): void {\n\tAtomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);\n}\n\ntype PendingPathOperations = Map<string, Promise<void>>;\n\nconst pendingAsyncFileLockTails: PendingPathOperations = new Map();\nconst pendingAtomicWriteTails: PendingPathOperations = new Map();\n\nfunction pathOperationKey(filePath: string): string {\n\tconst absolutePath = resolve(filePath);\n\treturn process.platform === \"win32\" ? absolutePath.toLowerCase() : absolutePath;\n}\n\n/**\n * Queue only operations that target the same platform path. This prevents same-process callers\n * from entering synchronized OS retry storms without imposing a process-wide or cross-tenant\n * bottleneck. The tail always resolves and self-removes, including after a failed operation.\n */\nasync function withSerializedPathOperation<T>(\n\ttails: PendingPathOperations,\n\tfilePath: string,\n\tfn: () => Promise<T>,\n): Promise<T> {\n\tconst key = pathOperationKey(filePath);\n\tconst preceding = tails.get(key) ?? Promise.resolve();\n\tlet releaseTail: (() => void) | undefined;\n\tconst tail = new Promise<void>((resolveTail) => {\n\t\treleaseTail = resolveTail;\n\t});\n\ttails.set(key, tail);\n\n\tawait preceding;\n\ttry {\n\t\treturn await fn();\n\t} finally {\n\t\treleaseTail?.();\n\t\tif (tails.get(key) === tail) tails.delete(key);\n\t}\n}\n\n/**\n * Acquire a proper-lockfile sync lock with bounded retry on `ELOCKED` (proper-lockfile's sync API\n * itself forbids `retries > 0`; see {@link AtomicFileLockOptions.retries}).\n *\n * Backoff doubles each attempt (mirroring the `retry` module's own `factor: 2` default that the\n * async path gets for free from proper-lockfile), starting at {@link RETRY_MIN_TIMEOUT_MS} and\n * capped at {@link RETRY_MAX_TIMEOUT_MS}.\n *\n * This is budget PARITY between two implementations of the same lock-acquisition contract, not\n * flake-masking: `options.retries` (a count of RETRIES, i.e. attempts after the first) means the\n * same thing on both paths, so both must make `retries + 1` total acquisition attempts with the\n * same per-gap backoff schedule. The async path gets `retries + 1` attempts for free from the\n * `retry` module (it retries `options.retries` times after its initial attempt); the sync path\n * used to loop exactly `attempts` times total (one fewer gap, and one fewer attempt than the\n * async path for the same `retries` value), which under-budgeted it relative to its async sibling\n * and surfaced as spurious ELOCKED failures under real contention (e.g. two OS threads hammering\n * the same file, or mkdir/rmdir lock-directory churn on a loaded Windows CI runner).\n */\nfunction retryCount(options: AtomicFileLockOptions): number {\n\tconst configured = options.retries ?? DEFAULT_RETRIES;\n\treturn Number.isFinite(configured) ? Math.max(0, Math.floor(configured)) : DEFAULT_RETRIES;\n}\n\nfunction retryDelayMs(options: AtomicFileLockOptions, attempt: number): number {\n\tconst configuredMin = options.minRetryDelayMs ?? RETRY_MIN_TIMEOUT_MS;\n\tconst minDelay = Number.isFinite(configuredMin) ? Math.max(0, configuredMin) : RETRY_MIN_TIMEOUT_MS;\n\tconst configuredMax = options.maxRetryDelayMs ?? RETRY_MAX_TIMEOUT_MS;\n\tconst maxDelay = Number.isFinite(configuredMax) ? Math.max(minDelay, configuredMax) : RETRY_MAX_TIMEOUT_MS;\n\tconst configuredFactor = options.retryFactor ?? 2;\n\tconst factor = Number.isFinite(configuredFactor) ? Math.max(1, configuredFactor) : 2;\n\treturn Math.min(minDelay * factor ** (attempt - 1), maxDelay);\n}\n\n/**\n * Acquire a synchronous advisory file lock and return its release function. This is the shared\n * mechanism for coordinators that must hold several locks in a deterministic order before entering\n * one critical section; callers retain ownership of release ordering and release-error semantics.\n */\nexport function acquireFileLockSync(filePath: string, options: AtomicFileLockOptions = {}): () => void {\n\tensureLockDirSync(filePath, options.lockfilePath);\n\tconst attempts = retryCount(options) + 1;\n\tconst lockOptions = {\n\t\tlockfilePath: options.lockfilePath,\n\t\trealpath: options.realpath ?? DEFAULT_REALPATH,\n\t\tstale: options.stale,\n\t};\n\tfor (let attempt = 1; attempt <= attempts; attempt++) {\n\t\ttry {\n\t\t\treturn lockfile.lockSync(filePath, lockOptions);\n\t\t} catch (err) {\n\t\t\tif (!isLockedError(err) || attempt === attempts) throw err;\n\t\t\tblockingSleepMs(retryDelayMs(options, attempt));\n\t\t}\n\t}\n\t// Unreachable (the loop always returns or throws), but keeps the function's return type honest.\n\tthrow new Error(`Failed to acquire lock for ${filePath}`);\n}\n\n/**\n * Hold an exclusive advisory lock on `filePath` for the duration of `fn` (sync). Always releases,\n * including when `fn` throws.\n */\nexport function withFileLockSync<T>(filePath: string, fn: () => T, options?: AtomicFileLockOptions): T {\n\tconst release = acquireFileLockSync(filePath, options);\n\ttry {\n\t\treturn fn();\n\t} finally {\n\t\t// A lock-cleanup failure must never mask fn()'s result (or replace fn()'s own thrown error) —\n\t\t// by this point fn() has already durably committed or failed on its own terms.\n\t\ttry {\n\t\t\trelease();\n\t\t} catch {\n\t\t\t// best-effort cleanup; a stale lock self-expires via proper-lockfile's `stale` window\n\t\t}\n\t}\n}\n\n/** Async counterpart of {@link withFileLockSync}. Always releases, including when `fn` throws/rejects. */\nexport async function withFileLock<T>(\n\tfilePath: string,\n\tfn: () => Promise<T> | T,\n\toptions?: AtomicFileLockOptions,\n): Promise<T> {\n\treturn withSerializedPathOperation(pendingAsyncFileLockTails, options?.lockfilePath ?? filePath, async () => {\n\t\tawait ensureLockDir(filePath, options?.lockfilePath);\n\t\tconst release = await lockfile.lock(filePath, {\n\t\t\tlockfilePath: options?.lockfilePath,\n\t\t\trealpath: options?.realpath ?? DEFAULT_REALPATH,\n\t\t\tretries: {\n\t\t\t\tretries: retryCount(options ?? {}),\n\t\t\t\tfactor: options?.retryFactor ?? 2,\n\t\t\t\tminTimeout: options?.minRetryDelayMs ?? RETRY_MIN_TIMEOUT_MS,\n\t\t\t\tmaxTimeout: options?.maxRetryDelayMs ?? RETRY_MAX_TIMEOUT_MS,\n\t\t\t},\n\t\t\tstale: options?.stale,\n\t\t});\n\t\ttry {\n\t\t\treturn await fn();\n\t\t} finally {\n\t\t\t// See {@link withFileLockSync} — cleanup failures must not mask fn()'s outcome.\n\t\t\tawait release().catch(() => {});\n\t\t}\n\t});\n}\n\n/**\n * Write `content` to `filePath` via write-tmp-then-rename (sync); the rename is atomic on the same\n * filesystem, so a concurrent reader never observes a partially-written file. Does NOT itself lock —\n * call from inside {@link withFileLockSync} when the write follows a read that must not race another\n * writer's read+write; call standalone for an unconditional overwrite with no read step.\n */\nfunction temporaryPath(filePath: string): string {\n\treturn `${filePath}.${process.pid}.${randomUUID()}.tmp`;\n}\n\n/**\n * Async standalone overwrites can legitimately target the same file at once. Unique temporary\n * names prevent writers from corrupting each other's staging files, but Windows still serializes\n * replacement renames internally. Letting every writer retry in lockstep creates a thundering herd\n * that can exhaust the bounded Defender/indexer retry budget even though no external process owns\n * the destination. Keep one FIFO tail per destination inside this process so each destination has\n * one writer at a time; writes to different destinations remain fully parallel. The tail is always\n * resolved and removed, including after a failed write, so one failure cannot poison later writes\n * or retain tenant paths indefinitely. File-lock queues are separate from atomic-write queues so a\n * write inside a held advisory lock never waits on itself.\n */\nasync function withSerializedAtomicWrite<T>(filePath: string, fn: () => Promise<T>): Promise<T> {\n\treturn withSerializedPathOperation(pendingAtomicWriteTails, filePath, fn);\n}\n\n/** Remove one invocation's temporary path without masking the original write/rename failure. */\nfunction removeTemporaryPathSync(tmpPath: string): void {\n\ttry {\n\t\tunlinkSync(tmpPath);\n\t} catch {\n\t\t// The rename may have consumed the path, or another failure may have prevented its creation.\n\t}\n}\n\nasync function removeTemporaryPath(tmpPath: string): Promise<void> {\n\ttry {\n\t\tawait fsPromises.unlink(tmpPath);\n\t} catch {\n\t\t// The rename may have consumed the path, or another failure may have prevented its creation.\n\t}\n}\n\nexport function writeFileAtomicSync(filePath: string, content: string, options?: AtomicFileWriteOptions): void {\n\tconst fs = options?.fs ?? nodeFs;\n\tfs.mkdirSync(dirname(filePath), { recursive: true });\n\tconst tmpPath = temporaryPath(filePath);\n\tlet renamed = false;\n\ttry {\n\t\t// `wx` makes a nonce collision harmless: never truncate another writer's temporary file.\n\t\tfs.writeFileSync(tmpPath, content, { encoding: \"utf-8\", flag: \"wx\", mode: options?.mode });\n\t\trenameSyncWithRetry(tmpPath, filePath, fs);\n\t\trenamed = true;\n\t} finally {\n\t\tif (!renamed) removeTemporaryPathSync(tmpPath);\n\t}\n}\n\n/** Async counterpart of {@link writeFileAtomicSync}. */\nexport async function writeFileAtomic(\n\tfilePath: string,\n\tcontent: string,\n\toptions?: AtomicFileWriteOptions,\n): Promise<void> {\n\tawait withSerializedAtomicWrite(filePath, async () => {\n\t\tawait fsPromises.mkdir(dirname(filePath), { recursive: true });\n\t\tconst tmpPath = temporaryPath(filePath);\n\t\tlet renamed = false;\n\t\ttry {\n\t\t\t// `wx` makes a nonce collision harmless: never truncate another writer's temporary file.\n\t\t\tawait fsPromises.writeFile(tmpPath, content, { encoding: \"utf-8\", flag: \"wx\", mode: options?.mode });\n\t\t\tawait renameWithRetry(tmpPath, filePath);\n\t\t\trenamed = true;\n\t\t} finally {\n\t\t\tif (!renamed) await removeTemporaryPath(tmpPath);\n\t\t}\n\t});\n}\n"]}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Injection seam for the narrow set of synchronous mutating filesystem operations that durable
|
|
3
|
+
* stores actually issue on their write path (`mkdirSync`, `writeFileSync`, `renameSync`,
|
|
4
|
+
* `unlinkSync`). Production code always uses {@link nodeFs}, the real `node:fs` bindings, via each
|
|
5
|
+
* store's `fs` constructor option defaulting to it — so wiring this seam changes nothing for any
|
|
6
|
+
* existing caller that does not pass `fs` explicitly.
|
|
7
|
+
*
|
|
8
|
+
* The destructive-testing harness (`test-destructive/harness/faultable-fs.ts`) implements this same
|
|
9
|
+
* interface with a fault-injecting variant (`failAtOp`, `tornWriteAtOp`, `enospcAfterBytes`) to drive
|
|
10
|
+
* crash-consistency sweeps without touching real disks or real timers. Read ops are intentionally
|
|
11
|
+
* excluded: a "crash" in this model is always a `node:fs`-mutating operation not completing; restart
|
|
12
|
+
* recovery always reads the real, unfaulted surviving files.
|
|
13
|
+
*/
|
|
14
|
+
export type FaultableFsWriteFileOptions = {
|
|
15
|
+
encoding?: "utf-8";
|
|
16
|
+
flag?: string;
|
|
17
|
+
mode?: number;
|
|
18
|
+
} | "utf-8";
|
|
19
|
+
/** The mutating fs primitives a durable store's write path issues, kept 1:1 with actual call sites. */
|
|
20
|
+
export interface FaultableFs {
|
|
21
|
+
mkdirSync(path: string, options: {
|
|
22
|
+
recursive: true;
|
|
23
|
+
}): void;
|
|
24
|
+
writeFileSync(path: string, data: string, options?: FaultableFsWriteFileOptions): void;
|
|
25
|
+
renameSync(oldPath: string, newPath: string): void;
|
|
26
|
+
unlinkSync(path: string): void;
|
|
27
|
+
}
|
|
28
|
+
/** The real `node:fs` bindings, wrapped to satisfy {@link FaultableFs}. Zero behavior change vs. calling `node:fs` directly. */
|
|
29
|
+
export declare const nodeFs: FaultableFs;
|
|
30
|
+
//# sourceMappingURL=faultable-fs.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"faultable-fs.d.ts","sourceRoot":"","sources":["../../../src/core/util/faultable-fs.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,MAAM,MAAM,2BAA2B,GAAG;IAAE,QAAQ,CAAC,EAAE,OAAO,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC;AAEzG,uGAAuG;AACvG,MAAM,WAAW,WAAW;IAC3B,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE;QAAE,SAAS,EAAE,IAAI,CAAA;KAAE,GAAG,IAAI,CAAC;IAC5D,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,2BAA2B,GAAG,IAAI,CAAC;IACvF,UAAU,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACnD,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;CAC/B;AAED,gIAAgI;AAChI,eAAO,MAAM,MAAM,EAAE,WAapB,CAAC"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Injection seam for the narrow set of synchronous mutating filesystem operations that durable
|
|
3
|
+
* stores actually issue on their write path (`mkdirSync`, `writeFileSync`, `renameSync`,
|
|
4
|
+
* `unlinkSync`). Production code always uses {@link nodeFs}, the real `node:fs` bindings, via each
|
|
5
|
+
* store's `fs` constructor option defaulting to it — so wiring this seam changes nothing for any
|
|
6
|
+
* existing caller that does not pass `fs` explicitly.
|
|
7
|
+
*
|
|
8
|
+
* The destructive-testing harness (`test-destructive/harness/faultable-fs.ts`) implements this same
|
|
9
|
+
* interface with a fault-injecting variant (`failAtOp`, `tornWriteAtOp`, `enospcAfterBytes`) to drive
|
|
10
|
+
* crash-consistency sweeps without touching real disks or real timers. Read ops are intentionally
|
|
11
|
+
* excluded: a "crash" in this model is always a `node:fs`-mutating operation not completing; restart
|
|
12
|
+
* recovery always reads the real, unfaulted surviving files.
|
|
13
|
+
*/
|
|
14
|
+
import { mkdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
15
|
+
/** The real `node:fs` bindings, wrapped to satisfy {@link FaultableFs}. Zero behavior change vs. calling `node:fs` directly. */
|
|
16
|
+
export const nodeFs = {
|
|
17
|
+
mkdirSync: (path, options) => {
|
|
18
|
+
mkdirSync(path, options);
|
|
19
|
+
},
|
|
20
|
+
writeFileSync: (path, data, options) => {
|
|
21
|
+
writeFileSync(path, data, options);
|
|
22
|
+
},
|
|
23
|
+
renameSync: (oldPath, newPath) => {
|
|
24
|
+
renameSync(oldPath, newPath);
|
|
25
|
+
},
|
|
26
|
+
unlinkSync: (path) => {
|
|
27
|
+
unlinkSync(path);
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
//# sourceMappingURL=faultable-fs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"faultable-fs.js","sourceRoot":"","sources":["../../../src/core/util/faultable-fs.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAY3E,gIAAgI;AAChI,MAAM,CAAC,MAAM,MAAM,GAAgB;IAClC,SAAS,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,EAAE;QAC5B,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAC1B,CAAC;IACD,aAAa,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE;QACtC,aAAa,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;IACpC,CAAC;IACD,UAAU,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE;QAChC,UAAU,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC9B,CAAC;IACD,UAAU,EAAE,CAAC,IAAI,EAAE,EAAE;QACpB,UAAU,CAAC,IAAI,CAAC,CAAC;IAClB,CAAC;CACD,CAAC","sourcesContent":["/**\n * Injection seam for the narrow set of synchronous mutating filesystem operations that durable\n * stores actually issue on their write path (`mkdirSync`, `writeFileSync`, `renameSync`,\n * `unlinkSync`). Production code always uses {@link nodeFs}, the real `node:fs` bindings, via each\n * store's `fs` constructor option defaulting to it — so wiring this seam changes nothing for any\n * existing caller that does not pass `fs` explicitly.\n *\n * The destructive-testing harness (`test-destructive/harness/faultable-fs.ts`) implements this same\n * interface with a fault-injecting variant (`failAtOp`, `tornWriteAtOp`, `enospcAfterBytes`) to drive\n * crash-consistency sweeps without touching real disks or real timers. Read ops are intentionally\n * excluded: a \"crash\" in this model is always a `node:fs`-mutating operation not completing; restart\n * recovery always reads the real, unfaulted surviving files.\n */\n\nimport { mkdirSync, renameSync, unlinkSync, writeFileSync } from \"node:fs\";\n\nexport type FaultableFsWriteFileOptions = { encoding?: \"utf-8\"; flag?: string; mode?: number } | \"utf-8\";\n\n/** The mutating fs primitives a durable store's write path issues, kept 1:1 with actual call sites. */\nexport interface FaultableFs {\n\tmkdirSync(path: string, options: { recursive: true }): void;\n\twriteFileSync(path: string, data: string, options?: FaultableFsWriteFileOptions): void;\n\trenameSync(oldPath: string, newPath: string): void;\n\tunlinkSync(path: string): void;\n}\n\n/** The real `node:fs` bindings, wrapped to satisfy {@link FaultableFs}. Zero behavior change vs. calling `node:fs` directly. */\nexport const nodeFs: FaultableFs = {\n\tmkdirSync: (path, options) => {\n\t\tmkdirSync(path, options);\n\t},\n\twriteFileSync: (path, data, options) => {\n\t\twriteFileSync(path, data, options);\n\t},\n\trenameSync: (oldPath, newPath) => {\n\t\trenameSync(oldPath, newPath);\n\t},\n\tunlinkSync: (path) => {\n\t\tunlinkSync(path);\n\t},\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-dialogs-controller.d.ts","sourceRoot":"","sources":["../../../src/modes/interactive/auth-dialogs-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,EAAgB,KAAK,KAAK,EAAgD,MAAM,mBAAmB,CAAC;AAC3G,OAAO,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,oBAAoB,CAAC;AAEzD,OAAO,KA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B;IAC7D,OAAO,CAAC,gCAAgC,CAAS;IACjD,OAAO,CAAC,yBAAyB,CAA2B;IAE5D,YAAY,IAAI,EAAE,yBAAyB,EAE1C;IAED,OAAO,KAAK,OAAO,GAElB;IACD,OAAO,KAAK,EAAE,GAEb;IAED,kBAAkB,IAAI,IAAI,CAQzB;IAED,OAAO,CAAC,iBAAiB;IAQzB,OAAO,CAAC,gBAAgB;IAcxB,OAAO,CAAC,uBAAuB;IAM/B,OAAO,CAAC,4BAA4B;IAMpC,OAAO,CAAC,kBAAkB;YAMZ,qBAAqB;IAkBnC,OAAO,CAAC,uBAAuB;IA2B/B,OAAO,CAAC,wBAAwB;IAmBhC,OAAO,CAAC,yBAAyB;YAoBnB,kBAAkB;YAUlB,cAAc;IAe5B,OAAO,CAAC,yBAAyB;IAqBjC,OAAO,CAAC,yBAAyB;IAiBjC,OAAO,CAAC,oBAAoB;IAgCtB,iBAAiB,CAAC,IAAI,EAAE,OAAO,GAAG,QAAQ,EAAE,iBAAiB,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CA4C3F;YAEa,8BAA8B;IAqD5C,OAAO,CAAC,sBAAsB;IAwB9B,OAAO,CAAC,2BAA2B;IAInC,OAAO,CAAC,0BAA0B;YASpB,6BAA6B;YAQ7B,oBAAoB;YAapB,+BAA+B;YA8C/B,oBAAoB;YAmDpB,qBAAqB;IA0BnC,OAAO,CAAC,oBAAoB;YA+Bd,eAAe;CAiF7B"}
|
|
@@ -121,6 +121,7 @@ export class AuthDialogsController {
|
|
|
121
121
|
id: provider.id,
|
|
122
122
|
name: provider.name,
|
|
123
123
|
authType: "oauth",
|
|
124
|
+
loginLabel: provider.loginLabel,
|
|
124
125
|
}));
|
|
125
126
|
const modelProviders = new Set(this.session.modelRegistry.getAll().map((model) => model.provider));
|
|
126
127
|
for (const providerId of modelProviders) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-dialogs-controller.js","sourceRoot":"","sources":["../../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BAA8B,CAAC,UAAU,EAAE,YAAY,EAAE,OAAO,EAAE,aAAa,CAAC,EAC3F,sBAAsB,YAAY,IAAI,CACtC,CAAC;IACH,CAAC;CACD","sourcesContent":["/**\n * Auth / login / OAuth dialog controller.\n *\n * Extracted verbatim from interactive-mode.ts (god-file decomposition). Owns the /login and /logout\n * command flows: provider selection, subscription (OAuth) login dialogs, API-key login dialogs, the\n * Amazon Bedrock setup notice, the OAuth in-dialog select prompt, and post-login model adoption. It\n * holds NO state of its own — every credential/provider fact lives in session.modelRegistry.authStorage\n * — so it takes narrow deps (a live session accessor plus a UI callback surface, including the\n * editor-overlay-backed showSelector and the shared EditorOverlayHost for dialog swaps) rather than\n * the whole InteractiveMode instance.\n */\n\nimport * as path from \"node:path\";\nimport { getProviders, type Model, type OAuthProviderId, type OAuthSelectPrompt } from \"@caupulican/pi-ai\";\nimport type { Component, TUI } from \"@caupulican/pi-tui\";\nimport { getAuthPath, getDocsPath } from \"../../config.ts\";\nimport type { AgentSession } from \"../../core/agent-session.ts\";\nimport {\n\tactivateVerifiedBedrockScope,\n\tBEDROCK_PROVIDER_ID,\n\ttype BedrockScopeVerificationRequest,\n\tverifyBedrockScope,\n} from \"../../core/bedrock-scope.ts\";\nimport { type BedrockSsoLoginOptions, loginBedrockSsoProfile } from \"../../core/bedrock-sso-login.ts\";\nimport { cliProviderAliases, defaultModelPerProvider } from \"../../core/model-resolver.ts\";\nimport { BUILT_IN_PROVIDER_DISPLAY_NAMES } from \"../../core/provider-display-names.ts\";\nimport { ExtensionSelectorComponent } from \"./components/extension-selector.ts\";\nimport { LoginDialogComponent } from \"./components/login-dialog.ts\";\nimport { type AuthSelectorProvider, OAuthSelectorComponent } from \"./components/oauth-selector.ts\";\nimport type { EditorOverlayHost } from \"./editor-overlay-host.ts\";\nimport { theme } from \"./theme/theme.ts\";\n\nfunction isUnknownModel(model: Model<any> | undefined): boolean {\n\treturn !!model && model.provider === \"unknown\" && model.id === \"unknown\" && model.api === \"unknown\";\n}\n\nfunction hasDefaultModelProvider(providerId: string): providerId is keyof typeof defaultModelPerProvider {\n\treturn providerId in defaultModelPerProvider;\n}\n\nconst LOGIN_CANCELLATION_MESSAGES = [\"Login cancelled\"] as const;\nconst BEDROCK_CANCELLATION_MESSAGES = [\"Login cancelled\", \"AWS SSO login was cancelled\"] as const;\n\nconst BUILT_IN_MODEL_PROVIDERS = new Set<string>(getProviders());\n\nexport function isApiKeyLoginProvider(\n\tproviderId: string,\n\toauthProviderIds: ReadonlySet<string>,\n\tbuiltInProviderIds: ReadonlySet<string> = BUILT_IN_MODEL_PROVIDERS,\n): boolean {\n\tif (BUILT_IN_PROVIDER_DISPLAY_NAMES[providerId]) {\n\t\treturn true;\n\t}\n\tif (builtInProviderIds.has(providerId)) {\n\t\treturn false;\n\t}\n\treturn !oauthProviderIds.has(providerId);\n}\n\nexport interface AuthDialogsControllerUi {\n\tshowSelector(create: (done: () => void) => { component: Component; focus: Component }): void;\n\tshowStatus(message: string): void;\n\tshowError(message: string): void;\n\trequestRender(): void;\n\treadonly tui: TUI;\n\treadonly overlayHost: EditorOverlayHost;\n\tgetEditor(): Component;\n\tupdateAvailableProviderCount(): Promise<void>;\n\tinvalidateFooter(): void;\n\tupdateEditorBorderColor(): void;\n\tmaybeWarnAboutAnthropicSubscriptionAuth(model?: Model<any>): void;\n\tcheckDaxnutsEasterEgg(model: { provider: string; id: string }): void;\n}\n\nexport interface AuthDialogsControllerDeps {\n\tgetSession(): AgentSession;\n\tui: AuthDialogsControllerUi;\n\tloginBedrockSso?: (profile: string, options?: BedrockSsoLoginOptions) => Promise<void>;\n\tverifyBedrockScope?: typeof verifyBedrockScope;\n}\n\nexport class AuthDialogsController {\n\tprivate readonly deps: AuthDialogsControllerDeps;\n\tprivate activeLoginDialog: LoginDialogComponent | undefined;\n\tprivate activeLoginDialogOnUnmount: (() => void) | undefined;\n\tprivate suppressActiveLoginDialogUnmount = false;\n\tprivate activeOAuthSelectorCancel: (() => void) | undefined;\n\n\tconstructor(deps: AuthDialogsControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tprivate get session(): AgentSession {\n\t\treturn this.deps.getSession();\n\t}\n\tprivate get ui(): AuthDialogsControllerUi {\n\t\treturn this.deps.ui;\n\t}\n\n\tcancelActiveDialog(): void {\n\t\tconst cancelSelector = this.activeOAuthSelectorCancel;\n\t\tthis.activeOAuthSelectorCancel = undefined;\n\t\tcancelSelector?.();\n\t\tconst dialog = this.activeLoginDialog;\n\t\tif (!dialog || !this.clearActiveDialog(dialog)) return;\n\t\tdialog.cancel();\n\t\tthis.ui.overlayHost.swap(this.ui.getEditor());\n\t}\n\n\tprivate clearActiveDialog(dialog: LoginDialogComponent): boolean {\n\t\tif (this.activeLoginDialog !== dialog) return false;\n\t\tthis.activeLoginDialog = undefined;\n\t\tthis.activeLoginDialogOnUnmount = undefined;\n\t\tthis.suppressActiveLoginDialogUnmount = false;\n\t\treturn true;\n\t}\n\n\tprivate mountLoginDialog(dialog: LoginDialogComponent): void {\n\t\tthis.activeLoginDialog = dialog;\n\t\tconst onUnmount = () => {\n\t\t\tif (this.suppressActiveLoginDialogUnmount && this.activeLoginDialog === dialog) {\n\t\t\t\tthis.suppressActiveLoginDialogUnmount = false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!this.clearActiveDialog(dialog)) return;\n\t\t\tdialog.cancel();\n\t\t};\n\t\tthis.activeLoginDialogOnUnmount = onUnmount;\n\t\tthis.ui.overlayHost.swap(dialog, { onUnmount });\n\t}\n\n\tprivate restoreEditorFromDialog(dialog: LoginDialogComponent): boolean {\n\t\tif (!this.clearActiveDialog(dialog)) return false;\n\t\tthis.ui.overlayHost.swap(this.ui.getEditor());\n\t\treturn true;\n\t}\n\n\tprivate detachLoginDialogForSelector(dialog: LoginDialogComponent): void {\n\t\tif (this.activeLoginDialog === dialog && this.activeLoginDialogOnUnmount) {\n\t\t\tthis.suppressActiveLoginDialogUnmount = true;\n\t\t}\n\t}\n\n\tprivate remountLoginDialog(dialog: LoginDialogComponent): boolean {\n\t\tif (this.activeLoginDialog !== dialog || !this.activeLoginDialogOnUnmount) return false;\n\t\tthis.ui.overlayHost.swap(dialog, { onUnmount: this.activeLoginDialogOnUnmount });\n\t\treturn true;\n\t}\n\n\tprivate async runMountedLoginDialog(\n\t\tdialog: LoginDialogComponent,\n\t\tauthenticate: () => Promise<void>,\n\t\tonAuthenticated: () => Promise<void>,\n\t\terrorPrefix: string,\n\t\tcancellationMessages: readonly string[] = LOGIN_CANCELLATION_MESSAGES,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tawait authenticate();\n\t\t\tif (!this.restoreEditorFromDialog(dialog)) return;\n\t\t\tawait onAuthenticated();\n\t\t} catch (error: unknown) {\n\t\t\tif (!this.restoreEditorFromDialog(dialog)) return;\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (!cancellationMessages.includes(message)) this.ui.showError(`${errorPrefix}${message}`);\n\t\t}\n\t}\n\n\tprivate getLoginProviderOptions(authType?: \"oauth\" | \"api_key\"): AuthSelectorProvider[] {\n\t\tconst authStorage = this.session.modelRegistry.authStorage;\n\t\tconst oauthProviders = authStorage.getOAuthProviders();\n\t\tconst oauthProviderIds = new Set(oauthProviders.map((provider) => provider.id));\n\t\tconst options: AuthSelectorProvider[] = oauthProviders.map((provider) => ({\n\t\t\tid: provider.id,\n\t\t\tname: provider.name,\n\t\t\tauthType: \"oauth\",\n\t\t}));\n\n\t\tconst modelProviders = new Set(this.session.modelRegistry.getAll().map((model) => model.provider));\n\t\tfor (const providerId of modelProviders) {\n\t\t\tif (!isApiKeyLoginProvider(providerId, oauthProviderIds)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\toptions.push({\n\t\t\t\tid: providerId,\n\t\t\t\tname: this.session.modelRegistry.getProviderDisplayName(providerId),\n\t\t\t\tauthType: \"api_key\",\n\t\t\t});\n\t\t}\n\n\t\tconst filteredOptions = authType ? options.filter((option) => option.authType === authType) : options;\n\t\treturn filteredOptions.sort((a, b) => a.name.localeCompare(b.name));\n\t}\n\n\tprivate getLogoutProviderOptions(): AuthSelectorProvider[] {\n\t\tconst authStorage = this.session.modelRegistry.authStorage;\n\t\tconst options: AuthSelectorProvider[] = [];\n\n\t\tfor (const providerId of authStorage.list()) {\n\t\t\tconst credential = authStorage.get(providerId);\n\t\t\tif (!credential) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\toptions.push({\n\t\t\t\tid: providerId,\n\t\t\t\tname: this.session.modelRegistry.getProviderDisplayName(providerId),\n\t\t\t\tauthType: credential.type,\n\t\t\t});\n\t\t}\n\n\t\treturn options.sort((a, b) => a.name.localeCompare(b.name));\n\t}\n\n\tprivate resolveAuthProviderOption(\n\t\tproviderReference: string,\n\t\tproviderOptions: AuthSelectorProvider[],\n\t): AuthSelectorProvider | undefined {\n\t\tconst normalized = providerReference.trim().toLowerCase();\n\t\tif (!normalized) return undefined;\n\t\tconst exactMatch = providerOptions.find((provider) => {\n\t\t\tconst id = provider.id.toLowerCase();\n\t\t\tconst name = provider.name.toLowerCase();\n\t\t\treturn id === normalized || name === normalized;\n\t\t});\n\t\tif (exactMatch) return exactMatch;\n\t\tconst aliasTarget = cliProviderAliases[normalized] ?? normalized;\n\t\treturn providerOptions.find((provider) => {\n\t\t\tconst id = provider.id.toLowerCase();\n\t\t\tconst name = provider.name.toLowerCase();\n\t\t\treturn id === aliasTarget || name === aliasTarget;\n\t\t});\n\t}\n\n\tprivate async startProviderLogin(providerOption: AuthSelectorProvider): Promise<void> {\n\t\tif (providerOption.authType === \"oauth\") {\n\t\t\tawait this.showLoginDialog(providerOption.id, providerOption.name);\n\t\t} else if (providerOption.id === BEDROCK_PROVIDER_ID) {\n\t\t\tthis.showBedrockSetupDialog(providerOption.id, providerOption.name);\n\t\t} else {\n\t\t\tawait this.showApiKeyLoginDialog(providerOption.id, providerOption.name);\n\t\t}\n\t}\n\n\tprivate async logoutProvider(providerOption: AuthSelectorProvider): Promise<void> {\n\t\ttry {\n\t\t\tthis.session.modelRegistry.authStorage.logout(providerOption.id);\n\t\t\tthis.session.modelRegistry.refresh();\n\t\t\tawait this.ui.updateAvailableProviderCount();\n\t\t\tconst message =\n\t\t\t\tproviderOption.authType === \"oauth\"\n\t\t\t\t\t? `Logged out of ${providerOption.name}`\n\t\t\t\t\t: `Removed stored API key for ${providerOption.name}. Environment variables and models.json config are unchanged.`;\n\t\t\tthis.ui.showStatus(message);\n\t\t} catch (error: unknown) {\n\t\t\tthis.ui.showError(`Logout failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\t}\n\n\tprivate showLoginAuthTypeSelector(): void {\n\t\tconst subscriptionLabel = \"Use a subscription\";\n\t\tconst apiKeyLabel = \"Use an API key\";\n\t\tthis.ui.showSelector((done) => {\n\t\t\tconst selector = new ExtensionSelectorComponent(\n\t\t\t\t\"Select authentication method:\",\n\t\t\t\t[subscriptionLabel, apiKeyLabel],\n\t\t\t\t(option) => {\n\t\t\t\t\tdone();\n\t\t\t\t\tconst authType = option === subscriptionLabel ? \"oauth\" : \"api_key\";\n\t\t\t\t\tthis.showLoginProviderSelector(authType);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate showLoginProviderSelector(authType: \"oauth\" | \"api_key\"): void {\n\t\tconst providerOptions = this.getLoginProviderOptions(authType);\n\t\tif (providerOptions.length === 0) {\n\t\t\tthis.ui.showStatus(\n\t\t\t\tauthType === \"oauth\" ? \"No subscription providers available.\" : \"No API key providers available.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showProviderSelector(\n\t\t\t\"login\",\n\t\t\tproviderOptions,\n\t\t\t(providerOption) => this.startProviderLogin(providerOption),\n\t\t\t() => this.showLoginAuthTypeSelector(),\n\t\t);\n\t}\n\n\tprivate showProviderSelector(\n\t\tmode: \"login\" | \"logout\",\n\t\tproviderOptions: AuthSelectorProvider[],\n\t\tonSelect: (providerOption: AuthSelectorProvider) => Promise<void>,\n\t\tonCancel: () => void,\n\t): void {\n\t\tthis.ui.showSelector((done) => {\n\t\t\tlet settled = false;\n\t\t\tconst finish = () => {\n\t\t\t\tif (settled) return false;\n\t\t\t\tsettled = true;\n\t\t\t\tdone();\n\t\t\t\treturn true;\n\t\t\t};\n\t\t\tconst selector = new OAuthSelectorComponent(\n\t\t\t\tmode,\n\t\t\t\tthis.session.modelRegistry.authStorage,\n\t\t\t\tproviderOptions,\n\t\t\t\tasync (providerId: string) => {\n\t\t\t\t\tif (!finish()) return;\n\t\t\t\t\tconst providerOption = providerOptions.find((provider) => provider.id === providerId);\n\t\t\t\t\tif (providerOption) await onSelect(providerOption);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tif (finish()) onCancel();\n\t\t\t\t},\n\t\t\t\tmode === \"login\" ? (providerId) => this.session.modelRegistry.getProviderAuthStatus(providerId) : undefined,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tasync showOAuthSelector(mode: \"login\" | \"logout\", providerReference?: string): Promise<void> {\n\t\tif (mode === \"login\") {\n\t\t\tif (providerReference) {\n\t\t\t\tconst providerOptions = this.getLoginProviderOptions();\n\t\t\t\tconst providerOption = this.resolveAuthProviderOption(providerReference, providerOptions);\n\t\t\t\tif (!providerOption) {\n\t\t\t\t\tthis.ui.showError(\n\t\t\t\t\t\t`Unknown login provider \"${providerReference}\". Use /login to select from available providers.`,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait this.startProviderLogin(providerOption);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.showLoginAuthTypeSelector();\n\t\t\treturn;\n\t\t}\n\n\t\tconst providerOptions = this.getLogoutProviderOptions();\n\t\tif (providerOptions.length === 0) {\n\t\t\tthis.ui.showStatus(\n\t\t\t\t\"No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tif (providerReference) {\n\t\t\tconst providerOption = this.resolveAuthProviderOption(providerReference, providerOptions);\n\t\t\tif (!providerOption) {\n\t\t\t\tthis.ui.showError(\n\t\t\t\t\t`No stored credentials found for \"${providerReference}\". Use /logout to select a saved provider.`,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait this.logoutProvider(providerOption);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showProviderSelector(\n\t\t\tmode,\n\t\t\tproviderOptions,\n\t\t\t(providerOption) => this.logoutProvider(providerOption),\n\t\t\t() => this.ui.requestRender(),\n\t\t);\n\t}\n\n\tprivate async completeProviderAuthentication(\n\t\tproviderId: string,\n\t\tproviderName: string,\n\t\tauthType: \"oauth\" | \"api_key\",\n\t\tpreviousModel: Model<any> | undefined,\n\t): Promise<void> {\n\t\tthis.session.modelRegistry.refresh();\n\n\t\tconst actionLabel = authType === \"oauth\" ? `Logged in to ${providerName}` : `Saved API key for ${providerName}`;\n\n\t\tlet selectedModel: Model<any> | undefined;\n\t\tlet selectionError: string | undefined;\n\t\tif (isUnknownModel(previousModel)) {\n\t\t\tconst availableModels = this.session.modelRegistry.getAvailable();\n\t\t\tconst providerModels = availableModels.filter((model) => model.provider === providerId);\n\t\t\tif (!hasDefaultModelProvider(providerId)) {\n\t\t\t\tselectionError = `${actionLabel}, but no default model is configured for provider \"${providerId}\". Use /model to select a model.`;\n\t\t\t} else if (providerModels.length === 0) {\n\t\t\t\tselectionError = `${actionLabel}, but no models are available for that provider. Use /model to select a model.`;\n\t\t\t} else {\n\t\t\t\tconst defaultModelId = defaultModelPerProvider[providerId];\n\t\t\t\tselectedModel = providerModels.find((model) => model.id === defaultModelId);\n\t\t\t\tif (!selectedModel) {\n\t\t\t\t\tselectionError = `${actionLabel}, but its default model \"${defaultModelId}\" is not available. Use /model to select a model.`;\n\t\t\t\t} else {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.session.setModel(selectedModel);\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\tselectedModel = undefined;\n\t\t\t\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\tselectionError = `${actionLabel}, but selecting its default model failed: ${errorMessage}. Use /model to select a model.`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tawait this.ui.updateAvailableProviderCount();\n\t\tthis.ui.invalidateFooter();\n\t\tthis.ui.updateEditorBorderColor();\n\t\tif (selectedModel) {\n\t\t\tthis.ui.showStatus(`${actionLabel}. Selected ${selectedModel.id}. Credentials saved to ${getAuthPath()}`);\n\t\t\tvoid this.ui.maybeWarnAboutAnthropicSubscriptionAuth(selectedModel);\n\t\t\tthis.ui.checkDaxnutsEasterEgg(selectedModel);\n\t\t} else {\n\t\t\tthis.ui.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}`);\n\t\t\tif (selectionError) {\n\t\t\t\tthis.ui.showError(selectionError);\n\t\t\t} else {\n\t\t\t\tvoid this.ui.maybeWarnAboutAnthropicSubscriptionAuth();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate showBedrockSetupDialog(providerId: string, providerName: string): void {\n\t\tconst configuredProfile = this.getConfiguredBedrockProfile();\n\t\tconst ssoLabel = configuredProfile\n\t\t\t? `Sign in with SSO profile \"${configuredProfile}\"`\n\t\t\t: \"Sign in with an AWS SSO profile\";\n\t\tconst otherLabel = \"Use IAM, bearer, or role credentials\";\n\t\tthis.ui.showSelector((done) => {\n\t\t\tconst selector = new ExtensionSelectorComponent(\n\t\t\t\t\"Set up Amazon Bedrock:\",\n\t\t\t\t[ssoLabel, otherLabel],\n\t\t\t\t(option) => {\n\t\t\t\t\tdone();\n\t\t\t\t\tif (option === ssoLabel) void this.showBedrockSsoDialog(providerId, providerName);\n\t\t\t\t\telse void this.showBedrockCredentialInfoDialog(providerId, providerName);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate getConfiguredBedrockProfile(): string | undefined {\n\t\treturn process.env.AWS_PROFILE?.trim() || this.session.settingsManager.getBedrockScopeSettings()?.profile;\n\t}\n\n\tprivate getConfiguredBedrockRegion(): string {\n\t\treturn (\n\t\t\tprocess.env.AWS_REGION?.trim() ||\n\t\t\tthis.session.settingsManager.getBedrockScopeSettings()?.region ||\n\t\t\tprocess.env.AWS_DEFAULT_REGION?.trim() ||\n\t\t\t\"us-east-1\"\n\t\t);\n\t}\n\n\tprivate async verifyAndActivateBedrockScope(\n\t\trequest: BedrockScopeVerificationRequest,\n\t): Promise<Awaited<ReturnType<typeof verifyBedrockScope>>> {\n\t\tconst scope = await (this.deps.verifyBedrockScope ?? verifyBedrockScope)(request, this.session.modelRegistry);\n\t\tactivateVerifiedBedrockScope(this.session.settingsManager, this.session.modelRegistry, scope);\n\t\treturn scope;\n\t}\n\n\tprivate async completeBedrockSetup(\n\t\tscope: Awaited<ReturnType<typeof verifyBedrockScope>>,\n\t\tmessage: string,\n\t): Promise<void> {\n\t\tthis.session.modelRegistry.refresh();\n\t\tawait this.ui.updateAvailableProviderCount();\n\t\tthis.ui.invalidateFooter();\n\t\tthis.ui.updateEditorBorderColor();\n\t\tthis.ui.showStatus(\n\t\t\t`${message} Verified ${scope.modelIds.length} model${scope.modelIds.length === 1 ? \"\" : \"s\"} in ${scope.region}.`,\n\t\t);\n\t}\n\n\tprivate async showBedrockCredentialInfoDialog(providerId: string, providerName: string): Promise<void> {\n\t\tthis.cancelActiveDialog();\n\t\tconst dialog = new LoginDialogComponent(\n\t\t\tthis.ui.tui,\n\t\t\tproviderId,\n\t\t\t() => {\n\t\t\t\tthis.restoreEditorFromDialog(dialog);\n\t\t\t},\n\t\t\tproviderName,\n\t\t\t\"Amazon Bedrock setup\",\n\t\t);\n\t\tdialog.showInfo([\n\t\t\ttheme.fg(\"text\", \"Amazon Bedrock uses AWS credentials instead of a single API key.\"),\n\t\t\ttheme.fg(\n\t\t\t\t\"text\",\n\t\t\t\t\"Configure IAM keys, a bearer token, or role-based credentials, then verify their exact region.\",\n\t\t\t),\n\t\t\ttheme.fg(\"muted\", \"See:\"),\n\t\t\ttheme.fg(\"accent\", ` ${path.join(getDocsPath(), \"providers.md\")}`),\n\t\t]);\n\t\tthis.mountLoginDialog(dialog);\n\t\tlet scope: Awaited<ReturnType<typeof verifyBedrockScope>> | undefined;\n\t\tawait this.runMountedLoginDialog(\n\t\t\tdialog,\n\t\t\tasync () => {\n\t\t\t\tconst region = (\n\t\t\t\t\tawait dialog.showPrompt(\"AWS region (required):\", this.getConfiguredBedrockRegion())\n\t\t\t\t).trim();\n\t\t\t\tif (!region) throw new Error(\"AWS region cannot be empty.\");\n\t\t\t\tdialog.showProgress(\"Verifying AWS identity, Bedrock profiles, and model access...\");\n\t\t\t\tscope = await this.verifyAndActivateBedrockScope({\n\t\t\t\t\tregion,\n\t\t\t\t\tprofile: process.env.AWS_PROFILE?.trim(),\n\t\t\t\t\tsignal: dialog.signal,\n\t\t\t\t\tcredentialMode: \"ambient\",\n\t\t\t\t});\n\t\t\t},\n\t\t\tasync () => {\n\t\t\t\tif (!scope) return;\n\t\t\t\tawait this.completeBedrockSetup(scope, \"Amazon Bedrock credentials are ready.\");\n\t\t\t},\n\t\t\t`Failed to configure ${providerName}: `,\n\t\t\tBEDROCK_CANCELLATION_MESSAGES,\n\t\t);\n\t}\n\n\tprivate async showBedrockSsoDialog(providerId: string, providerName: string): Promise<void> {\n\t\tthis.cancelActiveDialog();\n\t\tconst dialog = new LoginDialogComponent(\n\t\t\tthis.ui.tui,\n\t\t\tproviderId,\n\t\t\t() => {\n\t\t\t\tthis.restoreEditorFromDialog(dialog);\n\t\t\t},\n\t\t\tproviderName,\n\t\t\t\"Amazon Bedrock SSO\",\n\t\t);\n\t\tthis.mountLoginDialog(dialog);\n\t\tlet profile = \"\";\n\t\tlet scope: Awaited<ReturnType<typeof verifyBedrockScope>> | undefined;\n\t\tawait this.runMountedLoginDialog(\n\t\t\tdialog,\n\t\t\tasync () => {\n\t\t\t\tconst configuredProfile = this.getConfiguredBedrockProfile();\n\t\t\t\tprofile = configuredProfile ?? (await dialog.showPrompt(\"AWS SSO profile name:\", \"my-work-profile\")).trim();\n\t\t\t\tif (!profile) throw new Error(\"AWS profile name cannot be empty.\");\n\t\t\t\tconst region = (\n\t\t\t\t\tawait dialog.showPrompt(\"AWS region (required):\", this.getConfiguredBedrockRegion())\n\t\t\t\t).trim();\n\t\t\t\tif (!region) throw new Error(\"AWS region cannot be empty.\");\n\n\t\t\t\tif (configuredProfile) {\n\t\t\t\t\tdialog.showInfo([\n\t\t\t\t\t\ttheme.fg(\"text\", `Using AWS profile: ${profile}`),\n\t\t\t\t\t\ttheme.fg(\"text\", `Bedrock region: ${region}`),\n\t\t\t\t\t\ttheme.fg(\"muted\", \"Complete the IAM Identity Center sign-in in your browser.\"),\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t\tdialog.showProgress(\"Waiting for AWS SSO authentication...\");\n\t\t\t\tawait (this.deps.loginBedrockSso ?? loginBedrockSsoProfile)(profile, { signal: dialog.signal });\n\t\t\t\tdialog.showProgress(\"Verifying AWS identity, Bedrock profiles, and model access...\");\n\t\t\t\tscope = await this.verifyAndActivateBedrockScope({\n\t\t\t\t\tprofile,\n\t\t\t\t\tregion,\n\t\t\t\t\tsignal: dialog.signal,\n\t\t\t\t\tcredentialMode: \"profile\",\n\t\t\t\t});\n\t\t\t},\n\t\t\tasync () => {\n\t\t\t\tif (!scope) return;\n\t\t\t\tawait this.completeBedrockSetup(scope, `Signed in with AWS profile \"${profile}\".`);\n\t\t\t},\n\t\t\t`Failed to sign in to ${providerName}: `,\n\t\t\tBEDROCK_CANCELLATION_MESSAGES,\n\t\t);\n\t}\n\n\tprivate async showApiKeyLoginDialog(providerId: string, providerName: string): Promise<void> {\n\t\tthis.cancelActiveDialog();\n\t\tconst previousModel = this.session.model;\n\n\t\tconst dialog = new LoginDialogComponent(\n\t\t\tthis.ui.tui,\n\t\t\tproviderId,\n\t\t\t(_success, _message) => {\n\t\t\t\t// Completion handled below\n\t\t\t},\n\t\t\tproviderName,\n\t\t);\n\n\t\tthis.mountLoginDialog(dialog);\n\t\tawait this.runMountedLoginDialog(\n\t\t\tdialog,\n\t\t\tasync () => {\n\t\t\t\tconst apiKey = (await dialog.showPrompt(\"Enter API key:\")).trim();\n\t\t\t\tif (!apiKey) throw new Error(\"API key cannot be empty.\");\n\t\t\t\tthis.session.modelRegistry.authStorage.set(providerId, { type: \"api_key\", key: apiKey });\n\t\t\t},\n\t\t\t() => this.completeProviderAuthentication(providerId, providerName, \"api_key\", previousModel),\n\t\t\t`Failed to save API key for ${providerName}: `,\n\t\t);\n\t}\n\n\tprivate showOAuthLoginSelect(dialog: LoginDialogComponent, prompt: OAuthSelectPrompt): Promise<string | undefined> {\n\t\tthis.activeOAuthSelectorCancel?.();\n\t\treturn new Promise((resolve) => {\n\t\t\tlet settled = false;\n\t\t\tlet selector: ExtensionSelectorComponent;\n\t\t\tconst finish = (value: string | undefined, restoreDialog = true) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tif (this.activeOAuthSelectorCancel === cancel) this.activeOAuthSelectorCancel = undefined;\n\t\t\t\tselector.dispose();\n\t\t\t\tif (restoreDialog) {\n\t\t\t\t\tthis.remountLoginDialog(dialog);\n\t\t\t\t} else if (this.clearActiveDialog(dialog)) {\n\t\t\t\t\tdialog.cancel();\n\t\t\t\t}\n\t\t\t\tresolve(value);\n\t\t\t};\n\t\t\tconst cancel = () => finish(undefined);\n\t\t\tthis.activeOAuthSelectorCancel = cancel;\n\t\t\tconst labels = prompt.options.map((option) => option.label);\n\t\t\tselector = new ExtensionSelectorComponent(\n\t\t\t\tprompt.message,\n\t\t\t\tlabels,\n\t\t\t\t(optionLabel) => finish(prompt.options.find((option) => option.label === optionLabel)?.id),\n\t\t\t\tcancel,\n\t\t\t);\n\t\t\tthis.detachLoginDialogForSelector(dialog);\n\t\t\tthis.ui.overlayHost.swap(selector, { onUnmount: () => finish(undefined, false) });\n\t\t});\n\t}\n\n\tprivate async showLoginDialog(providerId: string, providerName: string): Promise<void> {\n\t\tthis.cancelActiveDialog();\n\t\tconst providerInfo = this.session.modelRegistry.authStorage\n\t\t\t.getOAuthProviders()\n\t\t\t.find((provider) => provider.id === providerId);\n\t\tconst previousModel = this.session.model;\n\n\t\t// Providers that use callback servers (can paste redirect URL)\n\t\tconst usesCallbackServer = providerInfo?.usesCallbackServer ?? false;\n\n\t\t// Create login dialog component\n\t\tconst dialog = new LoginDialogComponent(\n\t\t\tthis.ui.tui,\n\t\t\tproviderId,\n\t\t\t(_success, _message) => {\n\t\t\t\t// Completion handled below\n\t\t\t},\n\t\t\tproviderName,\n\t\t);\n\n\t\t// Show dialog in editor container\n\t\tthis.mountLoginDialog(dialog);\n\n\t\t// Promise for manual code input (racing with callback server)\n\t\tlet manualCodeResolve: ((code: string) => void) | undefined;\n\t\tlet manualCodeReject: ((err: Error) => void) | undefined;\n\t\tconst manualCodePromise = new Promise<string>((resolve, reject) => {\n\t\t\tmanualCodeResolve = resolve;\n\t\t\tmanualCodeReject = reject;\n\t\t});\n\n\t\tawait this.runMountedLoginDialog(\n\t\t\tdialog,\n\t\t\t() =>\n\t\t\t\tthis.session.modelRegistry.authStorage.login(providerId as OAuthProviderId, {\n\t\t\t\t\tonAuth: (info: { url: string; instructions?: string }) => {\n\t\t\t\t\t\tdialog.showAuth(info.url, info.instructions);\n\n\t\t\t\t\t\tif (usesCallbackServer) {\n\t\t\t\t\t\t\t// Show input for manual paste, racing with callback\n\t\t\t\t\t\t\tdialog\n\t\t\t\t\t\t\t\t.showManualInput(\"Paste redirect URL below, or complete login in browser:\")\n\t\t\t\t\t\t\t\t.then((value) => {\n\t\t\t\t\t\t\t\t\tif (value && manualCodeResolve) {\n\t\t\t\t\t\t\t\t\t\tmanualCodeResolve(value);\n\t\t\t\t\t\t\t\t\t\tmanualCodeResolve = undefined;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t.catch(() => {\n\t\t\t\t\t\t\t\t\tif (manualCodeReject) {\n\t\t\t\t\t\t\t\t\t\tmanualCodeReject(new Error(\"Login cancelled\"));\n\t\t\t\t\t\t\t\t\t\tmanualCodeReject = undefined;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// For Anthropic: onPrompt is called immediately after\n\t\t\t\t\t},\n\n\t\t\t\t\tonDeviceCode: (info) => {\n\t\t\t\t\t\tdialog.showDeviceCode(info);\n\t\t\t\t\t\tdialog.showWaiting(\"Waiting for authentication...\");\n\t\t\t\t\t},\n\n\t\t\t\t\tonPrompt: async (prompt: { message: string; placeholder?: string }) => {\n\t\t\t\t\t\treturn dialog.showPrompt(prompt.message, prompt.placeholder);\n\t\t\t\t\t},\n\n\t\t\t\t\tonProgress: (message: string) => {\n\t\t\t\t\t\tdialog.showProgress(message);\n\t\t\t\t\t},\n\n\t\t\t\t\tonSelect: (prompt: OAuthSelectPrompt) => this.showOAuthLoginSelect(dialog, prompt),\n\n\t\t\t\t\tonManualCodeInput: () => manualCodePromise,\n\n\t\t\t\t\tsignal: dialog.signal,\n\t\t\t\t}),\n\t\t\t() => this.completeProviderAuthentication(providerId, providerName, \"oauth\", previousModel),\n\t\t\t`Failed to login to ${providerName}: `,\n\t\t);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"auth-dialogs-controller.js","sourceRoot":"","sources":["../../../src/modes/interactive/auth-dialogs-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,YAAY,EAA4D,MAAM,mBA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;CACD","sourcesContent":["/**\n * Auth / login / OAuth dialog controller.\n *\n * Extracted verbatim from interactive-mode.ts (god-file decomposition). Owns the /login and /logout\n * command flows: provider selection, subscription (OAuth) login dialogs, API-key login dialogs, the\n * Amazon Bedrock setup notice, the OAuth in-dialog select prompt, and post-login model adoption. It\n * holds NO state of its own — every credential/provider fact lives in session.modelRegistry.authStorage\n * — so it takes narrow deps (a live session accessor plus a UI callback surface, including the\n * editor-overlay-backed showSelector and the shared EditorOverlayHost for dialog swaps) rather than\n * the whole InteractiveMode instance.\n */\n\nimport * as path from \"node:path\";\nimport { getProviders, type Model, type OAuthProviderId, type OAuthSelectPrompt } from \"@caupulican/pi-ai\";\nimport type { Component, TUI } from \"@caupulican/pi-tui\";\nimport { getAuthPath, getDocsPath } from \"../../config.ts\";\nimport type { AgentSession } from \"../../core/agent-session.ts\";\nimport {\n\tactivateVerifiedBedrockScope,\n\tBEDROCK_PROVIDER_ID,\n\ttype BedrockScopeVerificationRequest,\n\tverifyBedrockScope,\n} from \"../../core/bedrock-scope.ts\";\nimport { type BedrockSsoLoginOptions, loginBedrockSsoProfile } from \"../../core/bedrock-sso-login.ts\";\nimport { cliProviderAliases, defaultModelPerProvider } from \"../../core/model-resolver.ts\";\nimport { BUILT_IN_PROVIDER_DISPLAY_NAMES } from \"../../core/provider-display-names.ts\";\nimport { ExtensionSelectorComponent } from \"./components/extension-selector.ts\";\nimport { LoginDialogComponent } from \"./components/login-dialog.ts\";\nimport { type AuthSelectorProvider, OAuthSelectorComponent } from \"./components/oauth-selector.ts\";\nimport type { EditorOverlayHost } from \"./editor-overlay-host.ts\";\nimport { theme } from \"./theme/theme.ts\";\n\nfunction isUnknownModel(model: Model<any> | undefined): boolean {\n\treturn !!model && model.provider === \"unknown\" && model.id === \"unknown\" && model.api === \"unknown\";\n}\n\nfunction hasDefaultModelProvider(providerId: string): providerId is keyof typeof defaultModelPerProvider {\n\treturn providerId in defaultModelPerProvider;\n}\n\nconst LOGIN_CANCELLATION_MESSAGES = [\"Login cancelled\"] as const;\nconst BEDROCK_CANCELLATION_MESSAGES = [\"Login cancelled\", \"AWS SSO login was cancelled\"] as const;\n\nconst BUILT_IN_MODEL_PROVIDERS = new Set<string>(getProviders());\n\nexport function isApiKeyLoginProvider(\n\tproviderId: string,\n\toauthProviderIds: ReadonlySet<string>,\n\tbuiltInProviderIds: ReadonlySet<string> = BUILT_IN_MODEL_PROVIDERS,\n): boolean {\n\tif (BUILT_IN_PROVIDER_DISPLAY_NAMES[providerId]) {\n\t\treturn true;\n\t}\n\tif (builtInProviderIds.has(providerId)) {\n\t\treturn false;\n\t}\n\treturn !oauthProviderIds.has(providerId);\n}\n\nexport interface AuthDialogsControllerUi {\n\tshowSelector(create: (done: () => void) => { component: Component; focus: Component }): void;\n\tshowStatus(message: string): void;\n\tshowError(message: string): void;\n\trequestRender(): void;\n\treadonly tui: TUI;\n\treadonly overlayHost: EditorOverlayHost;\n\tgetEditor(): Component;\n\tupdateAvailableProviderCount(): Promise<void>;\n\tinvalidateFooter(): void;\n\tupdateEditorBorderColor(): void;\n\tmaybeWarnAboutAnthropicSubscriptionAuth(model?: Model<any>): void;\n\tcheckDaxnutsEasterEgg(model: { provider: string; id: string }): void;\n}\n\nexport interface AuthDialogsControllerDeps {\n\tgetSession(): AgentSession;\n\tui: AuthDialogsControllerUi;\n\tloginBedrockSso?: (profile: string, options?: BedrockSsoLoginOptions) => Promise<void>;\n\tverifyBedrockScope?: typeof verifyBedrockScope;\n}\n\nexport class AuthDialogsController {\n\tprivate readonly deps: AuthDialogsControllerDeps;\n\tprivate activeLoginDialog: LoginDialogComponent | undefined;\n\tprivate activeLoginDialogOnUnmount: (() => void) | undefined;\n\tprivate suppressActiveLoginDialogUnmount = false;\n\tprivate activeOAuthSelectorCancel: (() => void) | undefined;\n\n\tconstructor(deps: AuthDialogsControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tprivate get session(): AgentSession {\n\t\treturn this.deps.getSession();\n\t}\n\tprivate get ui(): AuthDialogsControllerUi {\n\t\treturn this.deps.ui;\n\t}\n\n\tcancelActiveDialog(): void {\n\t\tconst cancelSelector = this.activeOAuthSelectorCancel;\n\t\tthis.activeOAuthSelectorCancel = undefined;\n\t\tcancelSelector?.();\n\t\tconst dialog = this.activeLoginDialog;\n\t\tif (!dialog || !this.clearActiveDialog(dialog)) return;\n\t\tdialog.cancel();\n\t\tthis.ui.overlayHost.swap(this.ui.getEditor());\n\t}\n\n\tprivate clearActiveDialog(dialog: LoginDialogComponent): boolean {\n\t\tif (this.activeLoginDialog !== dialog) return false;\n\t\tthis.activeLoginDialog = undefined;\n\t\tthis.activeLoginDialogOnUnmount = undefined;\n\t\tthis.suppressActiveLoginDialogUnmount = false;\n\t\treturn true;\n\t}\n\n\tprivate mountLoginDialog(dialog: LoginDialogComponent): void {\n\t\tthis.activeLoginDialog = dialog;\n\t\tconst onUnmount = () => {\n\t\t\tif (this.suppressActiveLoginDialogUnmount && this.activeLoginDialog === dialog) {\n\t\t\t\tthis.suppressActiveLoginDialogUnmount = false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!this.clearActiveDialog(dialog)) return;\n\t\t\tdialog.cancel();\n\t\t};\n\t\tthis.activeLoginDialogOnUnmount = onUnmount;\n\t\tthis.ui.overlayHost.swap(dialog, { onUnmount });\n\t}\n\n\tprivate restoreEditorFromDialog(dialog: LoginDialogComponent): boolean {\n\t\tif (!this.clearActiveDialog(dialog)) return false;\n\t\tthis.ui.overlayHost.swap(this.ui.getEditor());\n\t\treturn true;\n\t}\n\n\tprivate detachLoginDialogForSelector(dialog: LoginDialogComponent): void {\n\t\tif (this.activeLoginDialog === dialog && this.activeLoginDialogOnUnmount) {\n\t\t\tthis.suppressActiveLoginDialogUnmount = true;\n\t\t}\n\t}\n\n\tprivate remountLoginDialog(dialog: LoginDialogComponent): boolean {\n\t\tif (this.activeLoginDialog !== dialog || !this.activeLoginDialogOnUnmount) return false;\n\t\tthis.ui.overlayHost.swap(dialog, { onUnmount: this.activeLoginDialogOnUnmount });\n\t\treturn true;\n\t}\n\n\tprivate async runMountedLoginDialog(\n\t\tdialog: LoginDialogComponent,\n\t\tauthenticate: () => Promise<void>,\n\t\tonAuthenticated: () => Promise<void>,\n\t\terrorPrefix: string,\n\t\tcancellationMessages: readonly string[] = LOGIN_CANCELLATION_MESSAGES,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tawait authenticate();\n\t\t\tif (!this.restoreEditorFromDialog(dialog)) return;\n\t\t\tawait onAuthenticated();\n\t\t} catch (error: unknown) {\n\t\t\tif (!this.restoreEditorFromDialog(dialog)) return;\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (!cancellationMessages.includes(message)) this.ui.showError(`${errorPrefix}${message}`);\n\t\t}\n\t}\n\n\tprivate getLoginProviderOptions(authType?: \"oauth\" | \"api_key\"): AuthSelectorProvider[] {\n\t\tconst authStorage = this.session.modelRegistry.authStorage;\n\t\tconst oauthProviders = authStorage.getOAuthProviders();\n\t\tconst oauthProviderIds = new Set(oauthProviders.map((provider) => provider.id));\n\t\tconst options: AuthSelectorProvider[] = oauthProviders.map((provider) => ({\n\t\t\tid: provider.id,\n\t\t\tname: provider.name,\n\t\t\tauthType: \"oauth\",\n\t\t\tloginLabel: provider.loginLabel,\n\t\t}));\n\n\t\tconst modelProviders = new Set(this.session.modelRegistry.getAll().map((model) => model.provider));\n\t\tfor (const providerId of modelProviders) {\n\t\t\tif (!isApiKeyLoginProvider(providerId, oauthProviderIds)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\toptions.push({\n\t\t\t\tid: providerId,\n\t\t\t\tname: this.session.modelRegistry.getProviderDisplayName(providerId),\n\t\t\t\tauthType: \"api_key\",\n\t\t\t});\n\t\t}\n\n\t\tconst filteredOptions = authType ? options.filter((option) => option.authType === authType) : options;\n\t\treturn filteredOptions.sort((a, b) => a.name.localeCompare(b.name));\n\t}\n\n\tprivate getLogoutProviderOptions(): AuthSelectorProvider[] {\n\t\tconst authStorage = this.session.modelRegistry.authStorage;\n\t\tconst options: AuthSelectorProvider[] = [];\n\n\t\tfor (const providerId of authStorage.list()) {\n\t\t\tconst credential = authStorage.get(providerId);\n\t\t\tif (!credential) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\toptions.push({\n\t\t\t\tid: providerId,\n\t\t\t\tname: this.session.modelRegistry.getProviderDisplayName(providerId),\n\t\t\t\tauthType: credential.type,\n\t\t\t});\n\t\t}\n\n\t\treturn options.sort((a, b) => a.name.localeCompare(b.name));\n\t}\n\n\tprivate resolveAuthProviderOption(\n\t\tproviderReference: string,\n\t\tproviderOptions: AuthSelectorProvider[],\n\t): AuthSelectorProvider | undefined {\n\t\tconst normalized = providerReference.trim().toLowerCase();\n\t\tif (!normalized) return undefined;\n\t\tconst exactMatch = providerOptions.find((provider) => {\n\t\t\tconst id = provider.id.toLowerCase();\n\t\t\tconst name = provider.name.toLowerCase();\n\t\t\treturn id === normalized || name === normalized;\n\t\t});\n\t\tif (exactMatch) return exactMatch;\n\t\tconst aliasTarget = cliProviderAliases[normalized] ?? normalized;\n\t\treturn providerOptions.find((provider) => {\n\t\t\tconst id = provider.id.toLowerCase();\n\t\t\tconst name = provider.name.toLowerCase();\n\t\t\treturn id === aliasTarget || name === aliasTarget;\n\t\t});\n\t}\n\n\tprivate async startProviderLogin(providerOption: AuthSelectorProvider): Promise<void> {\n\t\tif (providerOption.authType === \"oauth\") {\n\t\t\tawait this.showLoginDialog(providerOption.id, providerOption.name);\n\t\t} else if (providerOption.id === BEDROCK_PROVIDER_ID) {\n\t\t\tthis.showBedrockSetupDialog(providerOption.id, providerOption.name);\n\t\t} else {\n\t\t\tawait this.showApiKeyLoginDialog(providerOption.id, providerOption.name);\n\t\t}\n\t}\n\n\tprivate async logoutProvider(providerOption: AuthSelectorProvider): Promise<void> {\n\t\ttry {\n\t\t\tthis.session.modelRegistry.authStorage.logout(providerOption.id);\n\t\t\tthis.session.modelRegistry.refresh();\n\t\t\tawait this.ui.updateAvailableProviderCount();\n\t\t\tconst message =\n\t\t\t\tproviderOption.authType === \"oauth\"\n\t\t\t\t\t? `Logged out of ${providerOption.name}`\n\t\t\t\t\t: `Removed stored API key for ${providerOption.name}. Environment variables and models.json config are unchanged.`;\n\t\t\tthis.ui.showStatus(message);\n\t\t} catch (error: unknown) {\n\t\t\tthis.ui.showError(`Logout failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\t}\n\n\tprivate showLoginAuthTypeSelector(): void {\n\t\tconst subscriptionLabel = \"Use a subscription\";\n\t\tconst apiKeyLabel = \"Use an API key\";\n\t\tthis.ui.showSelector((done) => {\n\t\t\tconst selector = new ExtensionSelectorComponent(\n\t\t\t\t\"Select authentication method:\",\n\t\t\t\t[subscriptionLabel, apiKeyLabel],\n\t\t\t\t(option) => {\n\t\t\t\t\tdone();\n\t\t\t\t\tconst authType = option === subscriptionLabel ? \"oauth\" : \"api_key\";\n\t\t\t\t\tthis.showLoginProviderSelector(authType);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate showLoginProviderSelector(authType: \"oauth\" | \"api_key\"): void {\n\t\tconst providerOptions = this.getLoginProviderOptions(authType);\n\t\tif (providerOptions.length === 0) {\n\t\t\tthis.ui.showStatus(\n\t\t\t\tauthType === \"oauth\" ? \"No subscription providers available.\" : \"No API key providers available.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showProviderSelector(\n\t\t\t\"login\",\n\t\t\tproviderOptions,\n\t\t\t(providerOption) => this.startProviderLogin(providerOption),\n\t\t\t() => this.showLoginAuthTypeSelector(),\n\t\t);\n\t}\n\n\tprivate showProviderSelector(\n\t\tmode: \"login\" | \"logout\",\n\t\tproviderOptions: AuthSelectorProvider[],\n\t\tonSelect: (providerOption: AuthSelectorProvider) => Promise<void>,\n\t\tonCancel: () => void,\n\t): void {\n\t\tthis.ui.showSelector((done) => {\n\t\t\tlet settled = false;\n\t\t\tconst finish = () => {\n\t\t\t\tif (settled) return false;\n\t\t\t\tsettled = true;\n\t\t\t\tdone();\n\t\t\t\treturn true;\n\t\t\t};\n\t\t\tconst selector = new OAuthSelectorComponent(\n\t\t\t\tmode,\n\t\t\t\tthis.session.modelRegistry.authStorage,\n\t\t\t\tproviderOptions,\n\t\t\t\tasync (providerId: string) => {\n\t\t\t\t\tif (!finish()) return;\n\t\t\t\t\tconst providerOption = providerOptions.find((provider) => provider.id === providerId);\n\t\t\t\t\tif (providerOption) await onSelect(providerOption);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tif (finish()) onCancel();\n\t\t\t\t},\n\t\t\t\tmode === \"login\" ? (providerId) => this.session.modelRegistry.getProviderAuthStatus(providerId) : undefined,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tasync showOAuthSelector(mode: \"login\" | \"logout\", providerReference?: string): Promise<void> {\n\t\tif (mode === \"login\") {\n\t\t\tif (providerReference) {\n\t\t\t\tconst providerOptions = this.getLoginProviderOptions();\n\t\t\t\tconst providerOption = this.resolveAuthProviderOption(providerReference, providerOptions);\n\t\t\t\tif (!providerOption) {\n\t\t\t\t\tthis.ui.showError(\n\t\t\t\t\t\t`Unknown login provider \"${providerReference}\". Use /login to select from available providers.`,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait this.startProviderLogin(providerOption);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.showLoginAuthTypeSelector();\n\t\t\treturn;\n\t\t}\n\n\t\tconst providerOptions = this.getLogoutProviderOptions();\n\t\tif (providerOptions.length === 0) {\n\t\t\tthis.ui.showStatus(\n\t\t\t\t\"No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tif (providerReference) {\n\t\t\tconst providerOption = this.resolveAuthProviderOption(providerReference, providerOptions);\n\t\t\tif (!providerOption) {\n\t\t\t\tthis.ui.showError(\n\t\t\t\t\t`No stored credentials found for \"${providerReference}\". Use /logout to select a saved provider.`,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait this.logoutProvider(providerOption);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showProviderSelector(\n\t\t\tmode,\n\t\t\tproviderOptions,\n\t\t\t(providerOption) => this.logoutProvider(providerOption),\n\t\t\t() => this.ui.requestRender(),\n\t\t);\n\t}\n\n\tprivate async completeProviderAuthentication(\n\t\tproviderId: string,\n\t\tproviderName: string,\n\t\tauthType: \"oauth\" | \"api_key\",\n\t\tpreviousModel: Model<any> | undefined,\n\t): Promise<void> {\n\t\tthis.session.modelRegistry.refresh();\n\n\t\tconst actionLabel = authType === \"oauth\" ? `Logged in to ${providerName}` : `Saved API key for ${providerName}`;\n\n\t\tlet selectedModel: Model<any> | undefined;\n\t\tlet selectionError: string | undefined;\n\t\tif (isUnknownModel(previousModel)) {\n\t\t\tconst availableModels = this.session.modelRegistry.getAvailable();\n\t\t\tconst providerModels = availableModels.filter((model) => model.provider === providerId);\n\t\t\tif (!hasDefaultModelProvider(providerId)) {\n\t\t\t\tselectionError = `${actionLabel}, but no default model is configured for provider \"${providerId}\". Use /model to select a model.`;\n\t\t\t} else if (providerModels.length === 0) {\n\t\t\t\tselectionError = `${actionLabel}, but no models are available for that provider. Use /model to select a model.`;\n\t\t\t} else {\n\t\t\t\tconst defaultModelId = defaultModelPerProvider[providerId];\n\t\t\t\tselectedModel = providerModels.find((model) => model.id === defaultModelId);\n\t\t\t\tif (!selectedModel) {\n\t\t\t\t\tselectionError = `${actionLabel}, but its default model \"${defaultModelId}\" is not available. Use /model to select a model.`;\n\t\t\t\t} else {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.session.setModel(selectedModel);\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\tselectedModel = undefined;\n\t\t\t\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\tselectionError = `${actionLabel}, but selecting its default model failed: ${errorMessage}. Use /model to select a model.`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tawait this.ui.updateAvailableProviderCount();\n\t\tthis.ui.invalidateFooter();\n\t\tthis.ui.updateEditorBorderColor();\n\t\tif (selectedModel) {\n\t\t\tthis.ui.showStatus(`${actionLabel}. Selected ${selectedModel.id}. Credentials saved to ${getAuthPath()}`);\n\t\t\tvoid this.ui.maybeWarnAboutAnthropicSubscriptionAuth(selectedModel);\n\t\t\tthis.ui.checkDaxnutsEasterEgg(selectedModel);\n\t\t} else {\n\t\t\tthis.ui.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}`);\n\t\t\tif (selectionError) {\n\t\t\t\tthis.ui.showError(selectionError);\n\t\t\t} else {\n\t\t\t\tvoid this.ui.maybeWarnAboutAnthropicSubscriptionAuth();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate showBedrockSetupDialog(providerId: string, providerName: string): void {\n\t\tconst configuredProfile = this.getConfiguredBedrockProfile();\n\t\tconst ssoLabel = configuredProfile\n\t\t\t? `Sign in with SSO profile \"${configuredProfile}\"`\n\t\t\t: \"Sign in with an AWS SSO profile\";\n\t\tconst otherLabel = \"Use IAM, bearer, or role credentials\";\n\t\tthis.ui.showSelector((done) => {\n\t\t\tconst selector = new ExtensionSelectorComponent(\n\t\t\t\t\"Set up Amazon Bedrock:\",\n\t\t\t\t[ssoLabel, otherLabel],\n\t\t\t\t(option) => {\n\t\t\t\t\tdone();\n\t\t\t\t\tif (option === ssoLabel) void this.showBedrockSsoDialog(providerId, providerName);\n\t\t\t\t\telse void this.showBedrockCredentialInfoDialog(providerId, providerName);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate getConfiguredBedrockProfile(): string | undefined {\n\t\treturn process.env.AWS_PROFILE?.trim() || this.session.settingsManager.getBedrockScopeSettings()?.profile;\n\t}\n\n\tprivate getConfiguredBedrockRegion(): string {\n\t\treturn (\n\t\t\tprocess.env.AWS_REGION?.trim() ||\n\t\t\tthis.session.settingsManager.getBedrockScopeSettings()?.region ||\n\t\t\tprocess.env.AWS_DEFAULT_REGION?.trim() ||\n\t\t\t\"us-east-1\"\n\t\t);\n\t}\n\n\tprivate async verifyAndActivateBedrockScope(\n\t\trequest: BedrockScopeVerificationRequest,\n\t): Promise<Awaited<ReturnType<typeof verifyBedrockScope>>> {\n\t\tconst scope = await (this.deps.verifyBedrockScope ?? verifyBedrockScope)(request, this.session.modelRegistry);\n\t\tactivateVerifiedBedrockScope(this.session.settingsManager, this.session.modelRegistry, scope);\n\t\treturn scope;\n\t}\n\n\tprivate async completeBedrockSetup(\n\t\tscope: Awaited<ReturnType<typeof verifyBedrockScope>>,\n\t\tmessage: string,\n\t): Promise<void> {\n\t\tthis.session.modelRegistry.refresh();\n\t\tawait this.ui.updateAvailableProviderCount();\n\t\tthis.ui.invalidateFooter();\n\t\tthis.ui.updateEditorBorderColor();\n\t\tthis.ui.showStatus(\n\t\t\t`${message} Verified ${scope.modelIds.length} model${scope.modelIds.length === 1 ? \"\" : \"s\"} in ${scope.region}.`,\n\t\t);\n\t}\n\n\tprivate async showBedrockCredentialInfoDialog(providerId: string, providerName: string): Promise<void> {\n\t\tthis.cancelActiveDialog();\n\t\tconst dialog = new LoginDialogComponent(\n\t\t\tthis.ui.tui,\n\t\t\tproviderId,\n\t\t\t() => {\n\t\t\t\tthis.restoreEditorFromDialog(dialog);\n\t\t\t},\n\t\t\tproviderName,\n\t\t\t\"Amazon Bedrock setup\",\n\t\t);\n\t\tdialog.showInfo([\n\t\t\ttheme.fg(\"text\", \"Amazon Bedrock uses AWS credentials instead of a single API key.\"),\n\t\t\ttheme.fg(\n\t\t\t\t\"text\",\n\t\t\t\t\"Configure IAM keys, a bearer token, or role-based credentials, then verify their exact region.\",\n\t\t\t),\n\t\t\ttheme.fg(\"muted\", \"See:\"),\n\t\t\ttheme.fg(\"accent\", ` ${path.join(getDocsPath(), \"providers.md\")}`),\n\t\t]);\n\t\tthis.mountLoginDialog(dialog);\n\t\tlet scope: Awaited<ReturnType<typeof verifyBedrockScope>> | undefined;\n\t\tawait this.runMountedLoginDialog(\n\t\t\tdialog,\n\t\t\tasync () => {\n\t\t\t\tconst region = (\n\t\t\t\t\tawait dialog.showPrompt(\"AWS region (required):\", this.getConfiguredBedrockRegion())\n\t\t\t\t).trim();\n\t\t\t\tif (!region) throw new Error(\"AWS region cannot be empty.\");\n\t\t\t\tdialog.showProgress(\"Verifying AWS identity, Bedrock profiles, and model access...\");\n\t\t\t\tscope = await this.verifyAndActivateBedrockScope({\n\t\t\t\t\tregion,\n\t\t\t\t\tprofile: process.env.AWS_PROFILE?.trim(),\n\t\t\t\t\tsignal: dialog.signal,\n\t\t\t\t\tcredentialMode: \"ambient\",\n\t\t\t\t});\n\t\t\t},\n\t\t\tasync () => {\n\t\t\t\tif (!scope) return;\n\t\t\t\tawait this.completeBedrockSetup(scope, \"Amazon Bedrock credentials are ready.\");\n\t\t\t},\n\t\t\t`Failed to configure ${providerName}: `,\n\t\t\tBEDROCK_CANCELLATION_MESSAGES,\n\t\t);\n\t}\n\n\tprivate async showBedrockSsoDialog(providerId: string, providerName: string): Promise<void> {\n\t\tthis.cancelActiveDialog();\n\t\tconst dialog = new LoginDialogComponent(\n\t\t\tthis.ui.tui,\n\t\t\tproviderId,\n\t\t\t() => {\n\t\t\t\tthis.restoreEditorFromDialog(dialog);\n\t\t\t},\n\t\t\tproviderName,\n\t\t\t\"Amazon Bedrock SSO\",\n\t\t);\n\t\tthis.mountLoginDialog(dialog);\n\t\tlet profile = \"\";\n\t\tlet scope: Awaited<ReturnType<typeof verifyBedrockScope>> | undefined;\n\t\tawait this.runMountedLoginDialog(\n\t\t\tdialog,\n\t\t\tasync () => {\n\t\t\t\tconst configuredProfile = this.getConfiguredBedrockProfile();\n\t\t\t\tprofile = configuredProfile ?? (await dialog.showPrompt(\"AWS SSO profile name:\", \"my-work-profile\")).trim();\n\t\t\t\tif (!profile) throw new Error(\"AWS profile name cannot be empty.\");\n\t\t\t\tconst region = (\n\t\t\t\t\tawait dialog.showPrompt(\"AWS region (required):\", this.getConfiguredBedrockRegion())\n\t\t\t\t).trim();\n\t\t\t\tif (!region) throw new Error(\"AWS region cannot be empty.\");\n\n\t\t\t\tif (configuredProfile) {\n\t\t\t\t\tdialog.showInfo([\n\t\t\t\t\t\ttheme.fg(\"text\", `Using AWS profile: ${profile}`),\n\t\t\t\t\t\ttheme.fg(\"text\", `Bedrock region: ${region}`),\n\t\t\t\t\t\ttheme.fg(\"muted\", \"Complete the IAM Identity Center sign-in in your browser.\"),\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t\tdialog.showProgress(\"Waiting for AWS SSO authentication...\");\n\t\t\t\tawait (this.deps.loginBedrockSso ?? loginBedrockSsoProfile)(profile, { signal: dialog.signal });\n\t\t\t\tdialog.showProgress(\"Verifying AWS identity, Bedrock profiles, and model access...\");\n\t\t\t\tscope = await this.verifyAndActivateBedrockScope({\n\t\t\t\t\tprofile,\n\t\t\t\t\tregion,\n\t\t\t\t\tsignal: dialog.signal,\n\t\t\t\t\tcredentialMode: \"profile\",\n\t\t\t\t});\n\t\t\t},\n\t\t\tasync () => {\n\t\t\t\tif (!scope) return;\n\t\t\t\tawait this.completeBedrockSetup(scope, `Signed in with AWS profile \"${profile}\".`);\n\t\t\t},\n\t\t\t`Failed to sign in to ${providerName}: `,\n\t\t\tBEDROCK_CANCELLATION_MESSAGES,\n\t\t);\n\t}\n\n\tprivate async showApiKeyLoginDialog(providerId: string, providerName: string): Promise<void> {\n\t\tthis.cancelActiveDialog();\n\t\tconst previousModel = this.session.model;\n\n\t\tconst dialog = new LoginDialogComponent(\n\t\t\tthis.ui.tui,\n\t\t\tproviderId,\n\t\t\t(_success, _message) => {\n\t\t\t\t// Completion handled below\n\t\t\t},\n\t\t\tproviderName,\n\t\t);\n\n\t\tthis.mountLoginDialog(dialog);\n\t\tawait this.runMountedLoginDialog(\n\t\t\tdialog,\n\t\t\tasync () => {\n\t\t\t\tconst apiKey = (await dialog.showPrompt(\"Enter API key:\")).trim();\n\t\t\t\tif (!apiKey) throw new Error(\"API key cannot be empty.\");\n\t\t\t\tthis.session.modelRegistry.authStorage.set(providerId, { type: \"api_key\", key: apiKey });\n\t\t\t},\n\t\t\t() => this.completeProviderAuthentication(providerId, providerName, \"api_key\", previousModel),\n\t\t\t`Failed to save API key for ${providerName}: `,\n\t\t);\n\t}\n\n\tprivate showOAuthLoginSelect(dialog: LoginDialogComponent, prompt: OAuthSelectPrompt): Promise<string | undefined> {\n\t\tthis.activeOAuthSelectorCancel?.();\n\t\treturn new Promise((resolve) => {\n\t\t\tlet settled = false;\n\t\t\tlet selector: ExtensionSelectorComponent;\n\t\t\tconst finish = (value: string | undefined, restoreDialog = true) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tif (this.activeOAuthSelectorCancel === cancel) this.activeOAuthSelectorCancel = undefined;\n\t\t\t\tselector.dispose();\n\t\t\t\tif (restoreDialog) {\n\t\t\t\t\tthis.remountLoginDialog(dialog);\n\t\t\t\t} else if (this.clearActiveDialog(dialog)) {\n\t\t\t\t\tdialog.cancel();\n\t\t\t\t}\n\t\t\t\tresolve(value);\n\t\t\t};\n\t\t\tconst cancel = () => finish(undefined);\n\t\t\tthis.activeOAuthSelectorCancel = cancel;\n\t\t\tconst labels = prompt.options.map((option) => option.label);\n\t\t\tselector = new ExtensionSelectorComponent(\n\t\t\t\tprompt.message,\n\t\t\t\tlabels,\n\t\t\t\t(optionLabel) => finish(prompt.options.find((option) => option.label === optionLabel)?.id),\n\t\t\t\tcancel,\n\t\t\t);\n\t\t\tthis.detachLoginDialogForSelector(dialog);\n\t\t\tthis.ui.overlayHost.swap(selector, { onUnmount: () => finish(undefined, false) });\n\t\t});\n\t}\n\n\tprivate async showLoginDialog(providerId: string, providerName: string): Promise<void> {\n\t\tthis.cancelActiveDialog();\n\t\tconst providerInfo = this.session.modelRegistry.authStorage\n\t\t\t.getOAuthProviders()\n\t\t\t.find((provider) => provider.id === providerId);\n\t\tconst previousModel = this.session.model;\n\n\t\t// Providers that use callback servers (can paste redirect URL)\n\t\tconst usesCallbackServer = providerInfo?.usesCallbackServer ?? false;\n\n\t\t// Create login dialog component\n\t\tconst dialog = new LoginDialogComponent(\n\t\t\tthis.ui.tui,\n\t\t\tproviderId,\n\t\t\t(_success, _message) => {\n\t\t\t\t// Completion handled below\n\t\t\t},\n\t\t\tproviderName,\n\t\t);\n\n\t\t// Show dialog in editor container\n\t\tthis.mountLoginDialog(dialog);\n\n\t\t// Promise for manual code input (racing with callback server)\n\t\tlet manualCodeResolve: ((code: string) => void) | undefined;\n\t\tlet manualCodeReject: ((err: Error) => void) | undefined;\n\t\tconst manualCodePromise = new Promise<string>((resolve, reject) => {\n\t\t\tmanualCodeResolve = resolve;\n\t\t\tmanualCodeReject = reject;\n\t\t});\n\n\t\tawait this.runMountedLoginDialog(\n\t\t\tdialog,\n\t\t\t() =>\n\t\t\t\tthis.session.modelRegistry.authStorage.login(providerId as OAuthProviderId, {\n\t\t\t\t\tonAuth: (info: { url: string; instructions?: string }) => {\n\t\t\t\t\t\tdialog.showAuth(info.url, info.instructions);\n\n\t\t\t\t\t\tif (usesCallbackServer) {\n\t\t\t\t\t\t\t// Show input for manual paste, racing with callback\n\t\t\t\t\t\t\tdialog\n\t\t\t\t\t\t\t\t.showManualInput(\"Paste redirect URL below, or complete login in browser:\")\n\t\t\t\t\t\t\t\t.then((value) => {\n\t\t\t\t\t\t\t\t\tif (value && manualCodeResolve) {\n\t\t\t\t\t\t\t\t\t\tmanualCodeResolve(value);\n\t\t\t\t\t\t\t\t\t\tmanualCodeResolve = undefined;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t.catch(() => {\n\t\t\t\t\t\t\t\t\tif (manualCodeReject) {\n\t\t\t\t\t\t\t\t\t\tmanualCodeReject(new Error(\"Login cancelled\"));\n\t\t\t\t\t\t\t\t\t\tmanualCodeReject = undefined;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// For Anthropic: onPrompt is called immediately after\n\t\t\t\t\t},\n\n\t\t\t\t\tonDeviceCode: (info) => {\n\t\t\t\t\t\tdialog.showDeviceCode(info);\n\t\t\t\t\t\tdialog.showWaiting(\"Waiting for authentication...\");\n\t\t\t\t\t},\n\n\t\t\t\t\tonPrompt: async (prompt: { message: string; placeholder?: string }) => {\n\t\t\t\t\t\treturn dialog.showPrompt(prompt.message, prompt.placeholder);\n\t\t\t\t\t},\n\n\t\t\t\t\tonProgress: (message: string) => {\n\t\t\t\t\t\tdialog.showProgress(message);\n\t\t\t\t\t},\n\n\t\t\t\t\tonSelect: (prompt: OAuthSelectPrompt) => this.showOAuthLoginSelect(dialog, prompt),\n\n\t\t\t\t\tonManualCodeInput: () => manualCodePromise,\n\n\t\t\t\t\tsignal: dialog.signal,\n\t\t\t\t}),\n\t\t\t() => this.completeProviderAuthentication(providerId, providerName, \"oauth\", previousModel),\n\t\t\t`Failed to login to ${providerName}: `,\n\t\t);\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"activity-lane.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/activity-lane.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAEpD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wCAAwC,CAAC;AACzE,OAAO,EAAE,KAAK,SAAS,
|
|
1
|
+
{"version":3,"file":"activity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E,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAKtC;IAED,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAEvB;IAED,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAQnC;IAED,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,GAAG,SAAS,GAAG,SAAS,EAAE,QAAQ,CAAC,EAAE,IAAI,CAAC,gBAAgB,EAAE,QAAQ,CAAC,GAAG,IAAI,CAK/G;IAED,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,GAAE,SAAS,GAAG,SAAS,GAAG,SAAqB,GAAG,IAAI,CAGnF;IAED,OAAO,CAAC,cAAc;IAMtB,QAAQ,IAAI,gBAAgB,EAAE,CAG7B;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAE9B;IAED,UAAU,IAAI,IAAI,CAAG;IAErB,OAAO,IAAI,IAAI,CAKd;CACD"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { truncateToWidth, visibleWidth } from "@caupulican/pi-tui";
|
|
2
|
-
import { isGoalUnfinishedStatus } from "../../../core/goals/goal-state.js";
|
|
2
|
+
import { isGoalExecutionActive, isGoalUnfinishedStatus } from "../../../core/goals/goal-state.js";
|
|
3
3
|
const DEFAULT_TERMINAL_HOLD_MS = 2_000;
|
|
4
4
|
const MAX_ACTIVITY_LABEL_LENGTH = 240;
|
|
5
5
|
const MAX_SEEN_TERMINALS = 512;
|
|
@@ -66,14 +66,15 @@ function projectGoalState(state) {
|
|
|
66
66
|
const satisfied = state.requirements.filter((requirement) => requirement.status === "satisfied").length;
|
|
67
67
|
const progress = state.requirements.length > 0 ? ` ${satisfied}/${state.requirements.length}` : "";
|
|
68
68
|
if (isGoalUnfinishedStatus(state.status)) {
|
|
69
|
-
const
|
|
69
|
+
const goalActive = isGoalExecutionActive(state.status);
|
|
70
|
+
const stopped = goalActive ? "" : ` ${state.status.replace("_", " ")}`;
|
|
70
71
|
return {
|
|
71
72
|
active: [
|
|
72
73
|
{
|
|
73
74
|
id: `goal:${state.goalId}`,
|
|
74
75
|
kind: "goal",
|
|
75
76
|
label: boundedLabel(`Goal${stopped}${progress} · ${state.userGoal}`),
|
|
76
|
-
status:
|
|
77
|
+
status: goalActive ? "active" : "waiting",
|
|
77
78
|
},
|
|
78
79
|
],
|
|
79
80
|
terminal: [],
|