pi-ui-extend 1.0.42 → 1.0.45
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -12
- package/dist/app/app.d.ts +10 -0
- package/dist/app/app.js +132 -8
- package/dist/app/cli/install.js +2 -2
- package/dist/app/commands/command-controller.d.ts +4 -0
- package/dist/app/commands/command-controller.js +11 -0
- package/dist/app/commands/command-git-actions.d.ts +25 -0
- package/dist/app/commands/command-git-actions.js +381 -0
- package/dist/app/commands/command-host.d.ts +3 -0
- package/dist/app/commands/command-host.js +5 -2
- package/dist/app/commands/command-model-actions.d.ts +1 -0
- package/dist/app/commands/command-model-actions.js +51 -34
- package/dist/app/commands/command-navigation-actions.d.ts +1 -0
- package/dist/app/commands/command-navigation-actions.js +16 -3
- package/dist/app/commands/command-registry.d.ts +2 -0
- package/dist/app/commands/command-registry.js +14 -0
- package/dist/app/commands/reload-context-inventory.js +12 -1
- package/dist/app/input/autocomplete-controller.js +61 -34
- package/dist/app/input/input-action-controller.d.ts +2 -0
- package/dist/app/input/input-action-controller.js +8 -1
- package/dist/app/input/input-controller.d.ts +2 -1
- package/dist/app/input/input-controller.js +7 -2
- package/dist/app/input/prompt-enhancer-controller.js +53 -35
- package/dist/app/input/voice-controller.d.ts +41 -45
- package/dist/app/input/voice-controller.js +351 -419
- package/dist/app/model/model-usage-controller.js +17 -7
- package/dist/app/model/model-usage-status.d.ts +4 -1
- package/dist/app/model/model-usage-status.js +270 -46
- package/dist/app/popup/menu-items-controller.d.ts +13 -3
- package/dist/app/popup/menu-items-controller.js +37 -21
- package/dist/app/popup/popup-action-controller.d.ts +12 -2
- package/dist/app/popup/popup-action-controller.js +77 -24
- package/dist/app/popup/popup-menu-controller.d.ts +36 -14
- package/dist/app/popup/popup-menu-controller.js +239 -69
- package/dist/app/rendering/dcp-stats.d.ts +9 -4
- package/dist/app/rendering/dcp-stats.js +40 -425
- package/dist/app/rendering/popup-menu-renderer.d.ts +3 -5
- package/dist/app/rendering/popup-menu-renderer.js +42 -37
- package/dist/app/rendering/render-controller.js +23 -2
- package/dist/app/rendering/status-line-renderer.d.ts +5 -0
- package/dist/app/rendering/status-line-renderer.js +41 -5
- package/dist/app/rendering/tab-line-renderer.js +26 -20
- package/dist/app/runtime.d.ts +12 -1
- package/dist/app/runtime.js +120 -12
- package/dist/app/screen/mouse-controller.d.ts +2 -0
- package/dist/app/screen/mouse-controller.js +17 -7
- package/dist/app/screen/status-controller.d.ts +4 -0
- package/dist/app/screen/status-controller.js +5 -0
- package/dist/app/session/lazy-session-manager.js +34 -0
- package/dist/app/session/session-event-controller.d.ts +1 -0
- package/dist/app/session/session-event-controller.js +10 -1
- package/dist/app/session/session-history.d.ts +1 -0
- package/dist/app/session/session-history.js +12 -1
- package/dist/app/session/session-lifecycle-controller.d.ts +6 -1
- package/dist/app/session/session-lifecycle-controller.js +10 -1
- package/dist/app/session/tabs-controller.d.ts +25 -1
- package/dist/app/session/tabs-controller.js +442 -153
- package/dist/app/subagents/subagents-widget-controller.d.ts +1 -0
- package/dist/app/subagents/subagents-widget-controller.js +6 -0
- package/dist/app/types.d.ts +11 -1
- package/dist/app/workspace/workspace-actions-controller.js +10 -2
- package/dist/app/workspace/workspace-undo.d.ts +1 -0
- package/dist/app/workspace/workspace-undo.js +1 -0
- package/dist/bundled-extensions/question/index.js +9 -1
- package/dist/bundled-extensions/question/remote.d.ts +4 -0
- package/dist/bundled-extensions/question/remote.js +33 -0
- package/dist/bundled-extensions/telegram-connector/bot.d.ts +43 -0
- package/dist/bundled-extensions/telegram-connector/bot.js +166 -0
- package/dist/bundled-extensions/telegram-connector/config.d.ts +8 -0
- package/dist/bundled-extensions/telegram-connector/config.js +87 -0
- package/dist/bundled-extensions/telegram-connector/coordinator.d.ts +66 -0
- package/dist/bundled-extensions/telegram-connector/coordinator.js +413 -0
- package/dist/bundled-extensions/telegram-connector/index.d.ts +3 -0
- package/dist/bundled-extensions/telegram-connector/index.js +195 -0
- package/dist/bundled-extensions/terminal-bell/index.d.ts +0 -8
- package/dist/bundled-extensions/terminal-bell/index.js +0 -76
- package/dist/bundled-extensions/workspace-undo/index.d.ts +26 -0
- package/dist/bundled-extensions/workspace-undo/index.js +191 -0
- package/dist/config.d.ts +21 -2
- package/dist/config.js +159 -32
- package/dist/default-pix-config.js +20 -10
- package/dist/schemas/pi-tools-suite-schema.d.ts +8 -4
- package/dist/schemas/pi-tools-suite-schema.js +11 -5
- package/dist/schemas/pix-schema.d.ts +12 -2
- package/dist/schemas/pix-schema.js +37 -9
- package/dist/schemas/tasks-schema.js +1 -1
- package/docs/concurrency.md +3 -1
- package/docs/desktop-mvp.md +10 -5
- package/docs/desktop-task-manager.md +81 -28
- package/docs/release.md +30 -6
- package/external/pi-tools-suite/README.md +165 -39
- package/external/pi-tools-suite/docs/session-recovery.md +7 -0
- package/external/pi-tools-suite/docs/subagent-model-pools.md +12 -5
- package/external/pi-tools-suite/docs/ui-qa-subagent.md +440 -0
- package/external/pi-tools-suite/package.json +6 -1
- package/external/pi-tools-suite/src/antigravity-auth/auth-store.ts +2 -1
- package/external/pi-tools-suite/src/antigravity-auth/constants.ts +9 -3
- package/external/pi-tools-suite/src/antigravity-auth/headers.ts +41 -3
- package/external/pi-tools-suite/src/antigravity-auth/models.ts +94 -21
- package/external/pi-tools-suite/src/antigravity-auth/oauth.ts +5 -17
- package/external/pi-tools-suite/src/antigravity-auth/payload.ts +72 -7
- package/external/pi-tools-suite/src/antigravity-auth/stream.ts +13 -1
- package/external/pi-tools-suite/src/async-subagents/agents/implement.md +1 -1
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/backends/browser.mjs +346 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/backends/desktop.mjs +1038 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/backends/tui.mjs +759 -0
- package/external/pi-tools-suite/src/async-subagents/agents/{browser-qa → ui-qa/browser}/scripts/browser-qa-runner.mjs +32 -23
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/drivers/chrome-devtools/chrome-devtools-provider.mjs +895 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/drivers/linux/linux-atspi.py +494 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/drivers/macos/macos-accessibility.swift +1085 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/drivers/native-terminal/bridge-client.mjs +50 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/drivers/native-terminal/native-terminal-host.mjs +501 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/drivers/windows/windows-uia.ps1 +454 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/guides/browser-auth.md +114 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/guides/browser-chrome-devtools.md +91 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/guides/browser-playwright.md +145 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/guides/browser.md +82 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/guides/desktop-linux.md +26 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/guides/desktop-macos.md +29 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/guides/desktop-windows.md +23 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/guides/desktop.md +54 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/guides/tui-native-terminal.md +59 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/guides/tui-pty.md +37 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/guides/tui.md +60 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa/scripts/ui-qa-runner.mjs +535 -0
- package/external/pi-tools-suite/src/async-subagents/agents/ui-qa.md +75 -0
- package/external/pi-tools-suite/src/async-subagents/commands.ts +1 -1
- package/external/pi-tools-suite/src/async-subagents/core/agent-strategy.ts +1 -1
- package/external/pi-tools-suite/src/async-subagents/core/agents-dir.ts +0 -2
- package/external/pi-tools-suite/src/async-subagents/core/browser-qa.ts +16 -2
- package/external/pi-tools-suite/src/async-subagents/core/config.ts +40 -17
- package/external/pi-tools-suite/src/async-subagents/core/model-selection.ts +2 -1
- package/external/pi-tools-suite/src/async-subagents/core/registry.ts +158 -33
- package/external/pi-tools-suite/src/async-subagents/core/routing.ts +7 -4
- package/external/pi-tools-suite/src/async-subagents/core/spawn.ts +34 -24
- package/external/pi-tools-suite/src/async-subagents/core/ultrawork-auto.ts +51 -45
- package/external/pi-tools-suite/src/async-subagents/lib.ts +9 -1
- package/external/pi-tools-suite/src/async-subagents/tools/spawn.ts +0 -1
- package/external/pi-tools-suite/src/async-subagents/tools/subagents.ts +2 -2
- package/external/pi-tools-suite/src/coding-discipline/index.ts +90 -59
- package/external/pi-tools-suite/src/config.ts +14 -0
- package/external/pi-tools-suite/src/context-gateway/accounting-log.ts +282 -0
- package/external/pi-tools-suite/src/context-gateway/config.ts +66 -1
- package/external/pi-tools-suite/src/context-gateway/efficiency.ts +414 -0
- package/external/pi-tools-suite/src/context-gateway/enforcement.ts +123 -3
- package/external/pi-tools-suite/src/context-gateway/index.ts +137 -4
- package/external/pi-tools-suite/src/context-gateway/storeless-capabilities.ts +5 -5
- package/external/pi-tools-suite/src/context-gateway/telemetry.ts +2 -2
- package/external/pi-tools-suite/src/context-gateway/types.ts +8 -1
- package/external/pi-tools-suite/src/dcp/auto-compress-budget.ts +39 -4
- package/external/pi-tools-suite/src/dcp/auto-compress.ts +41 -14
- package/external/pi-tools-suite/src/dcp/commands.ts +14 -156
- package/external/pi-tools-suite/src/dcp/compress-tool.ts +8 -2
- package/external/pi-tools-suite/src/dcp/compression-progress.ts +22 -0
- package/external/pi-tools-suite/src/dcp/config.ts +58 -4
- package/external/pi-tools-suite/src/dcp/conversation-index.ts +36 -9
- package/external/pi-tools-suite/src/dcp/diagnostics.ts +41 -0
- package/external/pi-tools-suite/src/dcp/fresh-tool-results.ts +38 -0
- package/external/pi-tools-suite/src/dcp/index.ts +338 -66
- package/external/pi-tools-suite/src/dcp/journal.ts +126 -4
- package/external/pi-tools-suite/src/dcp/progress-controller.ts +2 -1
- package/external/pi-tools-suite/src/dcp/pruner-candidates.ts +92 -2
- package/external/pi-tools-suite/src/dcp/pruner-nudge.ts +36 -33
- package/external/pi-tools-suite/src/dcp/pruner.ts +1 -0
- package/external/pi-tools-suite/src/dcp/routine-pressure.ts +86 -0
- package/external/pi-tools-suite/src/dcp/state.ts +9 -0
- package/external/pi-tools-suite/src/dcp/statistics.d.ts +8 -0
- package/external/pi-tools-suite/src/dcp/statistics.js +156 -0
- package/external/pi-tools-suite/src/default-pi-tools-suite-config.ts +68 -16
- package/external/pi-tools-suite/src/lib/project.ts +36 -1
- package/external/pi-tools-suite/src/model-tools/index.ts +10 -7
- package/external/pi-tools-suite/src/repo-discovery/index.ts +304 -4
- package/external/pi-tools-suite/src/resource-registry/index.ts +282 -21
- package/external/pi-tools-suite/src/session-recovery/index.ts +17 -0
- package/external/pi-tools-suite/src/todo/index.ts +21 -0
- package/external/pi-tools-suite/src/todo/todo.ts +19 -1
- package/external/pi-tools-suite/src/tool-descriptions.ts +44 -15
- package/package.json +7 -8
- package/schemas/pi-tools-suite.json +44 -12
- package/schemas/pix.json +109 -15
- package/schemas/tasks.json +1 -2
- package/skills/simplify/SKILL.md +33 -5
- package/external/pi-tools-suite/docs/browser-qa-subagent.md +0 -196
- package/external/pi-tools-suite/src/async-subagents/agents/browser-qa.md +0 -598
- package/skills/playwright-cli/SKILL.md +0 -420
- package/skills/playwright-cli/references/element-attributes.md +0 -23
- package/skills/playwright-cli/references/playwright-tests.md +0 -50
- package/skills/playwright-cli/references/request-mocking.md +0 -87
- package/skills/playwright-cli/references/running-code.md +0 -241
- package/skills/playwright-cli/references/session-management.md +0 -273
- package/skills/playwright-cli/references/spec-driven-testing.md +0 -311
- package/skills/playwright-cli/references/storage-state.md +0 -290
- package/skills/playwright-cli/references/test-generation.md +0 -142
- package/skills/playwright-cli/references/tracing.md +0 -154
- package/skills/playwright-cli/references/video-recording.md +0 -147
- package/skills/spec-wiki/SKILL.md +0 -55
- package/skills/spec-wiki/evals/evals.json +0 -132
- package/skills/spec-wiki/evals/files/bootstrap/architecture/rfc-007.md +0 -14
- package/skills/spec-wiki/evals/files/bootstrap/docs/how-to-pay.md +0 -4
- package/skills/spec-wiki/evals/files/bootstrap/docs/overview.md +0 -9
- package/skills/spec-wiki/evals/files/bootstrap/requirements/payment-behavior.md +0 -17
- package/skills/spec-wiki/evals/files/bootstrap/src/payments.ts +0 -12
- package/skills/spec-wiki/evals/files/bootstrap/tests/payments.test.ts +0 -11
- package/skills/spec-wiki/evals/files/focused/src/session.ts +0 -5
- package/skills/spec-wiki/evals/files/focused/tests/session.test.ts +0 -17
- package/skills/spec-wiki/evals/files/maintenance/low-signal/incoming/capture.txt +0 -2
- package/skills/spec-wiki/evals/files/maintenance/low-signal/src/capture.ts +0 -3
- package/skills/spec-wiki/evals/files/maintenance/move/docs/old-job-contract.md +0 -18
- package/skills/spec-wiki/evals/files/maintenance/move/src/job.ts +0 -5
- package/skills/spec-wiki/evals/files/maintenance/new-relation/docs/session-refresh.md +0 -24
- package/skills/spec-wiki/evals/files/maintenance/new-relation/incoming/refresh-worker.ts +0 -7
- package/skills/spec-wiki/evals/files/maintenance/new-relation/src/session.ts +0 -7
- package/skills/spec-wiki/evals/files/maintenance/no-impact/docs/auth-contract.md +0 -17
- package/skills/spec-wiki/evals/files/maintenance/no-impact/incoming/telemetry-format.ts +0 -3
- package/skills/spec-wiki/evals/files/maintenance/no-impact/src/auth.ts +0 -3
- package/skills/spec-wiki/evals/files/query/docs/how-to-run-jobs.md +0 -4
- package/skills/spec-wiki/evals/files/query/docs/spec-overview.md +0 -9
- package/skills/spec-wiki/evals/files/query/features/jobs/cancellation-contract.md +0 -15
- package/skills/spec-wiki/evals/files/query/features/jobs/retry-spec.md +0 -6
- package/skills/spec-wiki/evals/maintenance_regression.py +0 -311
- package/skills/spec-wiki/evals/retrieval-eval.md +0 -37
- package/skills/spec-wiki/evals/retrieval-evals.json +0 -37
- package/skills/spec-wiki/evals/trigger-evals.json +0 -94
- package/skills/spec-wiki/references/bootstrap.md +0 -100
- package/skills/spec-wiki/references/focused-spec.md +0 -117
- package/skills/spec-wiki/references/index-schema.md +0 -330
- package/skills/spec-wiki/references/maintenance.md +0 -134
- package/skills/spec-wiki/references/query.md +0 -74
- package/skills/spec-wiki/scripts/spec_wiki.py +0 -2076
- /package/external/pi-tools-suite/src/async-subagents/agents/{browser-qa → ui-qa/browser}/examples/qa-auth.example.jsonc +0 -0
- /package/external/pi-tools-suite/src/async-subagents/agents/{browser-qa → ui-qa/browser}/examples/qa-flow.example.jsonc +0 -0
- /package/external/pi-tools-suite/src/async-subagents/agents/{browser-qa → ui-qa/browser}/vendor/fflate.LICENSE +0 -0
- /package/external/pi-tools-suite/src/async-subagents/agents/{browser-qa → ui-qa/browser}/vendor/fflate.mjs +0 -0
|
@@ -59,40 +59,58 @@ export async function decideUltraworkAuto(
|
|
|
59
59
|
if (!routing.enabled) return "none";
|
|
60
60
|
if (signal?.aborted) throw new Error("Aborted");
|
|
61
61
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
62
|
+
const refs = [routing.model, ...routing.fallbackModels];
|
|
63
|
+
const parentModel = currentModelRef(ctx.model);
|
|
64
|
+
if (parentModel) refs.push(parentModel);
|
|
65
|
+
const seen = new Set<string>();
|
|
66
|
+
|
|
67
|
+
for (const ref of refs) {
|
|
68
|
+
const modelRef = ref?.trim();
|
|
69
|
+
if (!modelRef || seen.has(modelRef)) continue;
|
|
70
|
+
seen.add(modelRef);
|
|
71
|
+
|
|
72
|
+
let resolved: Awaited<ReturnType<typeof resolveModelRef>>;
|
|
73
|
+
try {
|
|
74
|
+
resolved = await resolveModelRef(ctx, modelRef);
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (signal?.aborted || isAbortError(error)) throw error;
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (!resolved) continue;
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
const response = await completeWithModelRegistry(
|
|
83
|
+
ctx.modelRegistry,
|
|
84
|
+
resolved.model,
|
|
85
|
+
{
|
|
86
|
+
systemPrompt: CLASSIFIER_SYSTEM_PROMPT,
|
|
87
|
+
messages: [
|
|
88
|
+
{
|
|
89
|
+
role: "user" as const,
|
|
90
|
+
content: [{ type: "text" as const, text: buildClassifierPrompt(userText) }],
|
|
91
|
+
timestamp: Date.now(),
|
|
92
|
+
},
|
|
93
|
+
],
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
apiKey: resolved.apiKey,
|
|
97
|
+
headers: resolved.headers,
|
|
98
|
+
env: resolved.env,
|
|
99
|
+
cacheRetention: "none",
|
|
100
|
+
maxRetries: routing.maxRetries,
|
|
101
|
+
maxTokens: Math.min(routing.maxTokens, 32),
|
|
102
|
+
signal,
|
|
103
|
+
timeoutMs: routing.timeoutMs,
|
|
104
|
+
},
|
|
105
|
+
);
|
|
106
|
+
if (signal?.aborted || response.stopReason === "aborted") throw new Error("Aborted");
|
|
107
|
+
if (response.stopReason === "error") continue;
|
|
108
|
+
return parseUltraworkAutoDecision(responseText(response));
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (signal?.aborted || isAbortError(error)) throw error;
|
|
111
|
+
}
|
|
95
112
|
}
|
|
113
|
+
return "none";
|
|
96
114
|
}
|
|
97
115
|
|
|
98
116
|
export function parseUltraworkAutoDecision(raw: string): UltraworkAutoDecision {
|
|
@@ -128,18 +146,6 @@ function buildClassifierPrompt(userText: string): string {
|
|
|
128
146
|
].join("\n");
|
|
129
147
|
}
|
|
130
148
|
|
|
131
|
-
async function resolveClassifierModel(ctx: UltraworkAutoContext, modelRef: string): Promise<{
|
|
132
|
-
model: Model<Api>;
|
|
133
|
-
apiKey?: string;
|
|
134
|
-
headers?: ProviderHeaders;
|
|
135
|
-
env?: Record<string, string>;
|
|
136
|
-
} | undefined> {
|
|
137
|
-
const configured = await resolveModelRef(ctx, modelRef);
|
|
138
|
-
if (configured) return configured;
|
|
139
|
-
const parentModel = currentModelRef(ctx.model);
|
|
140
|
-
return parentModel && parentModel !== modelRef ? resolveModelRef(ctx, parentModel) : undefined;
|
|
141
|
-
}
|
|
142
|
-
|
|
143
149
|
async function resolveModelRef(ctx: UltraworkAutoContext, modelRef: string): Promise<{
|
|
144
150
|
model: Model<Api>;
|
|
145
151
|
apiKey?: string;
|
|
@@ -34,7 +34,15 @@ export {
|
|
|
34
34
|
shouldForceCurrentSubagentModel,
|
|
35
35
|
} from "./core/config.js";
|
|
36
36
|
export { routeSubagentTasks, SubagentRoutingError } from "./core/routing.js";
|
|
37
|
-
export {
|
|
37
|
+
export {
|
|
38
|
+
BROWSER_QA_RUNNER_ENV,
|
|
39
|
+
UI_QA_RUNNER_ENV,
|
|
40
|
+
LEGACY_BROWSER_QA_TYPE,
|
|
41
|
+
UI_QA_TYPE,
|
|
42
|
+
getBrowserQaRunnerPath,
|
|
43
|
+
getUiQaRunnerPath,
|
|
44
|
+
isUiQaType,
|
|
45
|
+
} from "./core/browser-qa.js";
|
|
38
46
|
export type { RoutedSubagentTasks, SubagentRoutingContext } from "./core/routing.js";
|
|
39
47
|
export { agentDefinitionFiles, agentNameFromFilename, parseAgentMarkdown, projectAgentDefinitionFiles, projectAgentsDir, readAgentDefinitionsFromDir, readProjectAgentDefinitions } from "./core/agents-dir.js";
|
|
40
48
|
export type { AgentDefinition, ProjectAgentDefinition } from "./core/agents-dir.js";
|
|
@@ -99,7 +99,6 @@ async function launchQueuedAgent(options: LaunchQueuedAgentOptions): Promise<voi
|
|
|
99
99
|
parentSession,
|
|
100
100
|
maxResultBytes: resolved.maxResultBytes,
|
|
101
101
|
timeoutMs: resolved.timeoutMs,
|
|
102
|
-
isolatedSkills: resolved.isolatedSkills,
|
|
103
102
|
};
|
|
104
103
|
if (resolved.retry.maxRetries > 0 || resolved.fallbackModels.length > 0) {
|
|
105
104
|
const retryResult = spawnAgentWithRetry(
|
|
@@ -3,7 +3,7 @@ import { Type } from "@earendil-works/pi-ai";
|
|
|
3
3
|
import { Text } from "@earendil-works/pi-tui";
|
|
4
4
|
import { asyncSubagentToolDescriptions } from "../../tool-descriptions.js";
|
|
5
5
|
import { SUBAGENT_TYPE_SELECTION_GUIDANCE } from "../core/agent-catalog.js";
|
|
6
|
-
import {
|
|
6
|
+
import { hasAvailableIndexedProjectRoot } from "../../lib/project.js";
|
|
7
7
|
import type { AgentCompletionHandler, RpcEventRecord } from "../lib.js";
|
|
8
8
|
import { DEFAULT_SPAWN_WATCH_SECONDS, INLINE_RENDERING } from "../constants.js";
|
|
9
9
|
import { renderSubagentSpawnPrompts } from "../render.js";
|
|
@@ -75,7 +75,7 @@ export function registerSubagentsTool(
|
|
|
75
75
|
onLiveAgentsChange?: () => void,
|
|
76
76
|
onAgentRpcEvent?: (runDir: string, agentId: string, event: RpcEventRecord) => void,
|
|
77
77
|
): void {
|
|
78
|
-
const toolDescriptions = asyncSubagentToolDescriptions(
|
|
78
|
+
const toolDescriptions = asyncSubagentToolDescriptions(hasAvailableIndexedProjectRoot());
|
|
79
79
|
const collector = new ToolCollector();
|
|
80
80
|
registerSpawnTool(collector as any, liveAgents, handleAgentCompletion, onLiveAgentsChange, onAgentRpcEvent);
|
|
81
81
|
registerStatusTool(collector as any);
|
|
@@ -22,6 +22,11 @@ type LookupDetails = {
|
|
|
22
22
|
contextChars: number;
|
|
23
23
|
stopReason?: string;
|
|
24
24
|
error?: string;
|
|
25
|
+
attempts?: Array<{
|
|
26
|
+
ref: string;
|
|
27
|
+
outcome: "ok" | "unavailable" | "error" | "empty";
|
|
28
|
+
error?: string;
|
|
29
|
+
}>;
|
|
25
30
|
};
|
|
26
31
|
|
|
27
32
|
type ResolvedLookupModel = {
|
|
@@ -473,8 +478,9 @@ function createLookupTool() {
|
|
|
473
478
|
executionMode: "sequential" as const,
|
|
474
479
|
async execute(_toolCallId: string, params: LookupParams, signal: AbortSignal | undefined, _onUpdate: unknown, ctx: unknown) {
|
|
475
480
|
const cwd = contextCwd(ctx) ?? process.cwd();
|
|
476
|
-
const
|
|
477
|
-
|
|
481
|
+
const lookupModelRefs = lookupModelRefsFromConfig(cwd);
|
|
482
|
+
const primaryLookupModelRef = lookupModelRefs[0];
|
|
483
|
+
if (!primaryLookupModelRef) {
|
|
478
484
|
return lookupToolTextResult("lookupModel is not configured in pi-tools-suite config; lookup is disabled.", {
|
|
479
485
|
model: "",
|
|
480
486
|
imageCount: 0,
|
|
@@ -484,69 +490,86 @@ function createLookupTool() {
|
|
|
484
490
|
});
|
|
485
491
|
}
|
|
486
492
|
|
|
487
|
-
const resolved = await resolveLookupModel(ctx, lookupModelRef);
|
|
488
|
-
if (!resolved) {
|
|
489
|
-
return lookupToolTextResult(`Lookup model is unavailable or unauthenticated: ${lookupModelRef}`, {
|
|
490
|
-
model: lookupModelRef,
|
|
491
|
-
imageCount: 0,
|
|
492
|
-
imagePathCount: params.imagePaths?.length ?? 0,
|
|
493
|
-
contextChars: 0,
|
|
494
|
-
error: "lookup model unavailable",
|
|
495
|
-
});
|
|
496
|
-
}
|
|
497
|
-
|
|
498
493
|
const recentContext = buildRecentSessionContext(ctx, DEFAULT_LOOKUP_MAX_CONTEXT_CHARS);
|
|
499
494
|
const sessionImages = extractRecentSessionImages(ctx, DEFAULT_LOOKUP_MAX_IMAGES);
|
|
500
495
|
const pathImages = readImagePathContents(cwd, params.imagePaths ?? [], Math.max(0, DEFAULT_LOOKUP_MAX_IMAGES - sessionImages.length));
|
|
501
496
|
const images = [...sessionImages, ...pathImages.images].slice(0, DEFAULT_LOOKUP_MAX_IMAGES);
|
|
502
497
|
const promptText = buildLookupPrompt(params, recentContext, images.length, pathImages.warnings);
|
|
498
|
+
const attempts: NonNullable<LookupDetails["attempts"]> = [];
|
|
499
|
+
|
|
500
|
+
for (const lookupModelRef of lookupModelRefs) {
|
|
501
|
+
if (signal?.aborted) throw signal.reason ?? new Error("Lookup aborted");
|
|
502
|
+
let resolved: ResolvedLookupModel | undefined;
|
|
503
|
+
try {
|
|
504
|
+
resolved = await resolveLookupModel(ctx, lookupModelRef);
|
|
505
|
+
} catch (error) {
|
|
506
|
+
if (signal?.aborted || isAbortError(error)) throw error;
|
|
507
|
+
attempts.push({ ref: lookupModelRef, outcome: "error", error: error instanceof Error ? error.message : String(error) });
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
if (!resolved) {
|
|
511
|
+
attempts.push({ ref: lookupModelRef, outcome: "unavailable" });
|
|
512
|
+
continue;
|
|
513
|
+
}
|
|
503
514
|
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
})
|
|
515
|
+
try {
|
|
516
|
+
const response = await completeWithModelRegistry(
|
|
517
|
+
resolved.modelRegistry,
|
|
518
|
+
resolved.model,
|
|
519
|
+
{
|
|
520
|
+
systemPrompt: LOOKUP_SYSTEM_PROMPT,
|
|
521
|
+
messages: [
|
|
522
|
+
{
|
|
523
|
+
role: "user" as const,
|
|
524
|
+
content: [{ type: "text" as const, text: promptText }, ...images],
|
|
525
|
+
timestamp: Date.now(),
|
|
526
|
+
},
|
|
527
|
+
],
|
|
528
|
+
},
|
|
529
|
+
{
|
|
530
|
+
apiKey: resolved.apiKey,
|
|
531
|
+
headers: resolved.headers,
|
|
532
|
+
env: resolved.env,
|
|
533
|
+
cacheRetention: "none",
|
|
534
|
+
maxRetries: 1,
|
|
535
|
+
maxTokens: DEFAULT_LOOKUP_MAX_TOKENS,
|
|
536
|
+
signal,
|
|
537
|
+
timeoutMs: DEFAULT_LOOKUP_TIMEOUT_MS,
|
|
538
|
+
},
|
|
539
|
+
);
|
|
540
|
+
if (signal?.aborted || response.stopReason === "aborted") throw signal?.reason ?? new Error("Lookup aborted");
|
|
541
|
+
if (response.stopReason === "error") {
|
|
542
|
+
attempts.push({ ref: lookupModelRef, outcome: "error", ...(response.errorMessage ? { error: response.errorMessage } : {}) });
|
|
543
|
+
continue;
|
|
544
|
+
}
|
|
545
|
+
const text = responseText(response).trim();
|
|
546
|
+
if (!text) {
|
|
547
|
+
attempts.push({ ref: lookupModelRef, outcome: "empty" });
|
|
548
|
+
continue;
|
|
549
|
+
}
|
|
550
|
+
attempts.push({ ref: lookupModelRef, outcome: "ok" });
|
|
551
|
+
return lookupToolTextResult(text, {
|
|
552
|
+
model: lookupModelRef,
|
|
553
|
+
imageCount: images.length,
|
|
554
|
+
imagePathCount: pathImages.images.length,
|
|
555
|
+
contextChars: recentContext.length,
|
|
556
|
+
stopReason: response.stopReason,
|
|
557
|
+
attempts,
|
|
558
|
+
});
|
|
559
|
+
} catch (error) {
|
|
560
|
+
if (signal?.aborted || isAbortError(error)) throw error;
|
|
561
|
+
attempts.push({ ref: lookupModelRef, outcome: "error", error: error instanceof Error ? error.message : String(error) });
|
|
562
|
+
}
|
|
549
563
|
}
|
|
564
|
+
|
|
565
|
+
return lookupToolTextResult("Lookup failed across configured models.", {
|
|
566
|
+
model: primaryLookupModelRef,
|
|
567
|
+
imageCount: images.length,
|
|
568
|
+
imagePathCount: pathImages.images.length,
|
|
569
|
+
contextChars: recentContext.length,
|
|
570
|
+
error: "all lookup models failed",
|
|
571
|
+
attempts,
|
|
572
|
+
});
|
|
550
573
|
},
|
|
551
574
|
};
|
|
552
575
|
}
|
|
@@ -585,7 +608,15 @@ function isInstructionMessage(message: unknown): boolean {
|
|
|
585
608
|
}
|
|
586
609
|
|
|
587
610
|
function lookupModelFromConfig(cwd?: string): string | undefined {
|
|
588
|
-
return
|
|
611
|
+
return lookupModelRefsFromConfig(cwd)[0];
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
function lookupModelRefsFromConfig(cwd?: string): string[] {
|
|
615
|
+
const config = loadPiToolsSuiteConfig(["coding-discipline"], { cwd: cwd ?? process.cwd() });
|
|
616
|
+
if (!config.lookupModel) return [];
|
|
617
|
+
return [...new Set([config.lookupModel, ...config.lookupFallbackModels]
|
|
618
|
+
.map((modelRef) => modelRef.trim())
|
|
619
|
+
.filter(Boolean))];
|
|
589
620
|
}
|
|
590
621
|
|
|
591
622
|
function buildLookupPrompt(params: LookupParams, recentContext: string, imageCount: number, warnings: string[]): string {
|
|
@@ -12,6 +12,8 @@ export interface PiToolsSuiteConfig {
|
|
|
12
12
|
todoThinkingOverrides: Record<string, TodoThinkingLevel>;
|
|
13
13
|
/** Vision-capable model used by the coding-discipline lookup tool; unset disables lookup. */
|
|
14
14
|
lookupModel?: string;
|
|
15
|
+
/** Ordered lookup fallbacks tried after lookupModel. Always present, even when empty. */
|
|
16
|
+
lookupFallbackModels: string[];
|
|
15
17
|
resourceRegistry: ResourceRegistryConfig;
|
|
16
18
|
}
|
|
17
19
|
|
|
@@ -30,6 +32,7 @@ type MutableConfig = {
|
|
|
30
32
|
todoThinking: boolean;
|
|
31
33
|
todoThinkingOverrides: Map<string, TodoThinkingLevel>;
|
|
32
34
|
lookupModel: string | undefined;
|
|
35
|
+
lookupFallbackModels: string[];
|
|
33
36
|
resourceRegistry: ResourceRegistryConfig;
|
|
34
37
|
};
|
|
35
38
|
|
|
@@ -80,6 +83,14 @@ function normalizeLookupModel(raw: unknown): string | undefined {
|
|
|
80
83
|
return trimmed ? trimmed : undefined;
|
|
81
84
|
}
|
|
82
85
|
|
|
86
|
+
function normalizeModelList(raw: unknown): string[] {
|
|
87
|
+
if (!Array.isArray(raw)) return [];
|
|
88
|
+
return [...new Set(raw
|
|
89
|
+
.filter((value): value is string => typeof value === "string")
|
|
90
|
+
.map((value) => value.trim())
|
|
91
|
+
.filter(Boolean))];
|
|
92
|
+
}
|
|
93
|
+
|
|
83
94
|
function normalizeNonEmptyString(raw: unknown): string | undefined {
|
|
84
95
|
if (typeof raw !== "string") return undefined;
|
|
85
96
|
const trimmed = raw.trim();
|
|
@@ -175,6 +186,7 @@ function mergeConfigLayer(config: MutableConfig, raw: Record<string, unknown>, k
|
|
|
175
186
|
if (typeof raw.todoThinking === "boolean") config.todoThinking = raw.todoThinking;
|
|
176
187
|
mergeTodoThinkingOverrides(config, raw.todoThinkingOverrides);
|
|
177
188
|
if (Object.prototype.hasOwnProperty.call(raw, "lookupModel")) config.lookupModel = normalizeLookupModel(raw.lookupModel);
|
|
189
|
+
if (Object.prototype.hasOwnProperty.call(raw, "lookupFallbackModels")) config.lookupFallbackModels = normalizeModelList(raw.lookupFallbackModels);
|
|
178
190
|
mergeResourceRegistry(config, raw.resourceRegistry);
|
|
179
191
|
|
|
180
192
|
for (const key of DISABLED_LIST_KEYS) addDisabled(config, raw[key], knownModules);
|
|
@@ -241,6 +253,7 @@ export function loadPiToolsSuiteConfig(moduleNames: readonly string[], options:
|
|
|
241
253
|
todoThinking: false,
|
|
242
254
|
todoThinkingOverrides: new Map(DEFAULT_TODO_THINKING_OVERRIDES),
|
|
243
255
|
lookupModel: undefined,
|
|
256
|
+
lookupFallbackModels: [],
|
|
244
257
|
resourceRegistry: { branch: DEFAULT_RESOURCE_REGISTRY_BRANCH },
|
|
245
258
|
};
|
|
246
259
|
const userConfigPath = getPiToolsSuiteUserConfigPath(options.homeDir);
|
|
@@ -262,6 +275,7 @@ export function loadPiToolsSuiteConfig(moduleNames: readonly string[], options:
|
|
|
262
275
|
todoThinking: config.todoThinking,
|
|
263
276
|
todoThinkingOverrides: Object.fromEntries(config.todoThinkingOverrides),
|
|
264
277
|
...(config.lookupModel ? { lookupModel: config.lookupModel } : {}),
|
|
278
|
+
lookupFallbackModels: [...config.lookupFallbackModels],
|
|
265
279
|
resourceRegistry: { ...config.resourceRegistry },
|
|
266
280
|
};
|
|
267
281
|
}
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import * as fs from "node:fs/promises";
|
|
2
|
+
import * as os from "node:os";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
|
|
5
|
+
import type { ContextGatewayResolvedConfig } from "./types.js";
|
|
6
|
+
|
|
7
|
+
const TRUE_ENV_RE = /^(1|true|yes|on)$/i;
|
|
8
|
+
const FALSE_ENV_RE = /^(0|false|no|off)$/i;
|
|
9
|
+
const DEFAULT_MAX_BYTES = 5 * 1024 * 1024;
|
|
10
|
+
const DEFAULT_MAX_BACKUPS = 3;
|
|
11
|
+
const MIN_MAX_BACKUPS = 1;
|
|
12
|
+
const MAX_MAX_BYTES = 64 * 1024 * 1024;
|
|
13
|
+
const MAX_MAX_BACKUPS = 100;
|
|
14
|
+
const ROTATION_CHECK_INTERVAL = 32;
|
|
15
|
+
const MAX_TRACKED_LOG_PATHS = 64;
|
|
16
|
+
const MAX_REPORTED_FAILURES = 32;
|
|
17
|
+
const ROTATION_LOCK_STALE_MS = 30_000;
|
|
18
|
+
|
|
19
|
+
interface RotationLockOwner {
|
|
20
|
+
pid: number;
|
|
21
|
+
token: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function truthyEnv(value: string | undefined): boolean | undefined {
|
|
25
|
+
if (value === undefined) return undefined;
|
|
26
|
+
const trimmed = value.trim();
|
|
27
|
+
if (TRUE_ENV_RE.test(trimmed)) return true;
|
|
28
|
+
if (FALSE_ENV_RE.test(trimmed)) return false;
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function positiveIntEnv(value: string | undefined): number | undefined {
|
|
33
|
+
if (value === undefined) return undefined;
|
|
34
|
+
const normalized = value.trim();
|
|
35
|
+
if (!/^\d+$/.test(normalized)) return undefined;
|
|
36
|
+
const parsed = Number(normalized);
|
|
37
|
+
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function contextGatewayAccountingLogEnabled(config: ContextGatewayResolvedConfig): boolean {
|
|
41
|
+
return truthyEnv(process.env.PI_CONTEXT_GATEWAY_ACCOUNTING_LOG_ENABLED)
|
|
42
|
+
?? config.accountingLog?.enabled
|
|
43
|
+
?? true;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function contextGatewayAccountingLogPath(): string {
|
|
47
|
+
const explicit = process.env.PI_CONTEXT_GATEWAY_ACCOUNTING_LOG?.trim();
|
|
48
|
+
if (explicit) return explicit;
|
|
49
|
+
const agentDir = process.env.PI_AGENT_DIR || path.join(os.homedir(), ".pi", "agent");
|
|
50
|
+
return path.join(agentDir, "context-gateway-accounting.jsonl");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function contextGatewayAccountingLogMaxBytes(config: ContextGatewayResolvedConfig): number {
|
|
54
|
+
const envValue = positiveIntEnv(process.env.PI_CONTEXT_GATEWAY_ACCOUNTING_MAX_BYTES);
|
|
55
|
+
return (envValue !== undefined && envValue <= MAX_MAX_BYTES ? envValue : undefined)
|
|
56
|
+
?? config.accountingLog?.maxBytes
|
|
57
|
+
?? DEFAULT_MAX_BYTES;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function contextGatewayAccountingLogMaxBackups(config: ContextGatewayResolvedConfig): number {
|
|
61
|
+
const envValue = positiveIntEnv(process.env.PI_CONTEXT_GATEWAY_ACCOUNTING_MAX_BACKUPS);
|
|
62
|
+
const value = (envValue !== undefined && envValue <= MAX_MAX_BACKUPS ? envValue : undefined)
|
|
63
|
+
?? config.accountingLog?.maxBackups
|
|
64
|
+
?? DEFAULT_MAX_BACKUPS;
|
|
65
|
+
return Math.max(MIN_MAX_BACKUPS, Math.floor(value));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
let writeChain: Promise<void> = Promise.resolve();
|
|
69
|
+
const ensuredDirs = new Set<string>();
|
|
70
|
+
const appendsSinceRotationCheck = new Map<string, number>();
|
|
71
|
+
const reportedFailures = new Set<string>();
|
|
72
|
+
|
|
73
|
+
function errorCode(error: unknown): string {
|
|
74
|
+
if (!error || typeof error !== "object" || !("code" in error)) return "unknown";
|
|
75
|
+
const code = (error as { code?: unknown }).code;
|
|
76
|
+
return typeof code === "string" ? code : "unknown";
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function reportFailure(operation: string, error: unknown): void {
|
|
80
|
+
const key = `${operation}:${errorCode(error)}`;
|
|
81
|
+
if (reportedFailures.has(key)) return;
|
|
82
|
+
if (reportedFailures.size >= MAX_REPORTED_FAILURES) reportedFailures.clear();
|
|
83
|
+
reportedFailures.add(key);
|
|
84
|
+
process.emitWarning(
|
|
85
|
+
`Context Gateway accounting ${operation} failed (${errorCode(error)}); accounting remains best-effort.`,
|
|
86
|
+
{ code: "PI_CONTEXT_GATEWAY_ACCOUNTING_FAILURE" },
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function setAppendCount(logPath: string, count: number): void {
|
|
91
|
+
if (!appendsSinceRotationCheck.has(logPath) && appendsSinceRotationCheck.size >= MAX_TRACKED_LOG_PATHS) {
|
|
92
|
+
const oldest = appendsSinceRotationCheck.keys().next().value;
|
|
93
|
+
if (oldest !== undefined) appendsSinceRotationCheck.delete(oldest);
|
|
94
|
+
}
|
|
95
|
+
appendsSinceRotationCheck.set(logPath, count);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function ensureLogDir(logPath: string): Promise<void> {
|
|
99
|
+
const dir = path.dirname(logPath);
|
|
100
|
+
if (ensuredDirs.delete(dir)) {
|
|
101
|
+
ensuredDirs.add(dir);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
await fs.mkdir(dir, { recursive: true });
|
|
105
|
+
if (ensuredDirs.size >= MAX_TRACKED_LOG_PATHS) {
|
|
106
|
+
const oldest = ensuredDirs.values().next().value;
|
|
107
|
+
if (oldest !== undefined) ensuredDirs.delete(oldest);
|
|
108
|
+
}
|
|
109
|
+
ensuredDirs.add(dir);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function rotationLockOwner(): RotationLockOwner {
|
|
113
|
+
return {
|
|
114
|
+
pid: process.pid,
|
|
115
|
+
token: `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function isRotationLockOwner(value: unknown): value is RotationLockOwner {
|
|
120
|
+
if (!value || typeof value !== "object") return false;
|
|
121
|
+
const candidate = value as Partial<RotationLockOwner>;
|
|
122
|
+
return Number.isInteger(candidate.pid) && (candidate.pid ?? 0) > 0 && typeof candidate.token === "string";
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function readRotationLockOwner(lockPath: string): Promise<RotationLockOwner | undefined> {
|
|
126
|
+
try {
|
|
127
|
+
const parsed: unknown = JSON.parse(await fs.readFile(lockPath, "utf8"));
|
|
128
|
+
return isRotationLockOwner(parsed) ? parsed : undefined;
|
|
129
|
+
} catch {
|
|
130
|
+
return undefined;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function isProcessAlive(pid: number): boolean {
|
|
135
|
+
try {
|
|
136
|
+
process.kill(pid, 0);
|
|
137
|
+
return true;
|
|
138
|
+
} catch (error) {
|
|
139
|
+
return errorCode(error) !== "ESRCH";
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function createRotationLock(lockPath: string, owner: RotationLockOwner): Promise<boolean> {
|
|
144
|
+
let handle: Awaited<ReturnType<typeof fs.open>>;
|
|
145
|
+
try {
|
|
146
|
+
handle = await fs.open(lockPath, "wx", 0o600);
|
|
147
|
+
} catch (error) {
|
|
148
|
+
if (errorCode(error) === "EEXIST") return false;
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
151
|
+
try {
|
|
152
|
+
await handle.writeFile(JSON.stringify(owner), "utf8");
|
|
153
|
+
} catch (error) {
|
|
154
|
+
await handle.close();
|
|
155
|
+
await fs.unlink(lockPath).catch(() => {});
|
|
156
|
+
throw error;
|
|
157
|
+
}
|
|
158
|
+
await handle.close();
|
|
159
|
+
return true;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async function acquireRotationLock(lockPath: string, owner: RotationLockOwner): Promise<boolean> {
|
|
163
|
+
if (await createRotationLock(lockPath, owner)) return true;
|
|
164
|
+
|
|
165
|
+
let lockStat: Awaited<ReturnType<typeof fs.stat>>;
|
|
166
|
+
try {
|
|
167
|
+
lockStat = await fs.stat(lockPath);
|
|
168
|
+
} catch (error) {
|
|
169
|
+
if (errorCode(error) === "ENOENT") return createRotationLock(lockPath, owner);
|
|
170
|
+
throw error;
|
|
171
|
+
}
|
|
172
|
+
const existingOwner = await readRotationLockOwner(lockPath);
|
|
173
|
+
if (existingOwner && isProcessAlive(existingOwner.pid)) return false;
|
|
174
|
+
if (!existingOwner && Date.now() - lockStat.mtimeMs <= ROTATION_LOCK_STALE_MS) return false;
|
|
175
|
+
|
|
176
|
+
const quarantinePath = `${lockPath}.stale-${owner.token}`;
|
|
177
|
+
try {
|
|
178
|
+
await fs.rename(lockPath, quarantinePath);
|
|
179
|
+
} catch (error) {
|
|
180
|
+
if (errorCode(error) === "ENOENT") return createRotationLock(lockPath, owner);
|
|
181
|
+
throw error;
|
|
182
|
+
}
|
|
183
|
+
const movedStat = await fs.stat(quarantinePath);
|
|
184
|
+
if (movedStat.dev !== lockStat.dev || movedStat.ino !== lockStat.ino) {
|
|
185
|
+
await fs.rename(quarantinePath, lockPath).catch(() => {});
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
await fs.rm(quarantinePath, { recursive: true, force: true });
|
|
189
|
+
return createRotationLock(lockPath, owner);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async function releaseRotationLock(lockPath: string, owner: RotationLockOwner): Promise<void> {
|
|
193
|
+
const currentOwner = await readRotationLockOwner(lockPath);
|
|
194
|
+
if (currentOwner?.token !== owner.token) {
|
|
195
|
+
reportFailure("rotation lock ownership", { code: "EBUSY" });
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
await fs.unlink(lockPath);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function rotateIfNeeded(logPath: string, maxBytes: number, maxBackups: number): Promise<void> {
|
|
202
|
+
const lockPath = `${logPath}.rotation.lock`;
|
|
203
|
+
const lockOwner = rotationLockOwner();
|
|
204
|
+
let locked = false;
|
|
205
|
+
try {
|
|
206
|
+
locked = await acquireRotationLock(lockPath, lockOwner);
|
|
207
|
+
if (!locked) {
|
|
208
|
+
reportFailure("rotation lock", { code: "EBUSY" });
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
let stat: Awaited<ReturnType<typeof fs.stat>>;
|
|
213
|
+
try {
|
|
214
|
+
stat = await fs.stat(logPath);
|
|
215
|
+
} catch (error) {
|
|
216
|
+
if (errorCode(error) === "ENOENT") return;
|
|
217
|
+
throw error;
|
|
218
|
+
}
|
|
219
|
+
if (stat.size < maxBytes) return;
|
|
220
|
+
|
|
221
|
+
const dir = path.dirname(logPath);
|
|
222
|
+
const base = path.basename(logPath);
|
|
223
|
+
await fs.rm(path.join(dir, `${base}.${maxBackups}`), { force: true });
|
|
224
|
+
for (let index = maxBackups - 1; index >= 1; index--) {
|
|
225
|
+
try {
|
|
226
|
+
await fs.rename(path.join(dir, `${base}.${index}`), path.join(dir, `${base}.${index + 1}`));
|
|
227
|
+
} catch (error) {
|
|
228
|
+
if (errorCode(error) !== "ENOENT") throw error;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
await fs.rename(logPath, path.join(dir, `${base}.1`));
|
|
232
|
+
} catch (error) {
|
|
233
|
+
reportFailure("rotation", error);
|
|
234
|
+
} finally {
|
|
235
|
+
if (locked) {
|
|
236
|
+
await releaseRotationLock(lockPath, lockOwner).catch((error) => reportFailure("rotation unlock", error));
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async function appendRecord(
|
|
242
|
+
logPath: string,
|
|
243
|
+
record: Record<string, unknown>,
|
|
244
|
+
maxBytes: number,
|
|
245
|
+
maxBackups: number,
|
|
246
|
+
): Promise<void> {
|
|
247
|
+
await ensureLogDir(logPath);
|
|
248
|
+
const appendCount = appendsSinceRotationCheck.get(logPath) ?? ROTATION_CHECK_INTERVAL;
|
|
249
|
+
if (appendCount >= ROTATION_CHECK_INTERVAL) {
|
|
250
|
+
await rotateIfNeeded(logPath, maxBytes, maxBackups);
|
|
251
|
+
setAppendCount(logPath, 0);
|
|
252
|
+
}
|
|
253
|
+
await fs.appendFile(logPath, `${JSON.stringify(record)}\n`, "utf8");
|
|
254
|
+
setAppendCount(logPath, (appendsSinceRotationCheck.get(logPath) ?? 0) + 1);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export function writeContextGatewayAccountingLog(
|
|
258
|
+
config: ContextGatewayResolvedConfig,
|
|
259
|
+
event: string,
|
|
260
|
+
details: Record<string, unknown> = {},
|
|
261
|
+
): void {
|
|
262
|
+
if (!contextGatewayAccountingLogEnabled(config)) return;
|
|
263
|
+
const record = {
|
|
264
|
+
version: 1,
|
|
265
|
+
ts: new Date().toISOString(),
|
|
266
|
+
event,
|
|
267
|
+
...details,
|
|
268
|
+
};
|
|
269
|
+
const logPath = contextGatewayAccountingLogPath();
|
|
270
|
+
const maxBytes = contextGatewayAccountingLogMaxBytes(config);
|
|
271
|
+
const maxBackups = contextGatewayAccountingLogMaxBackups(config);
|
|
272
|
+
writeChain = writeChain
|
|
273
|
+
.then(() => appendRecord(logPath, record, maxBytes, maxBackups))
|
|
274
|
+
.catch((error) => {
|
|
275
|
+
// Accounting must never affect the session, provider call, or tool outcome.
|
|
276
|
+
reportFailure("write", error);
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export function contextGatewayAccountingLogDrain(): Promise<void> {
|
|
281
|
+
return writeChain;
|
|
282
|
+
}
|