@caupulican/pi-adaptative 0.80.86 → 0.80.89
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 +178 -0
- package/dist/core/agent-session.d.ts +412 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +2053 -41
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/approval-gate.d.ts +4 -0
- package/dist/core/autonomy/approval-gate.d.ts.map +1 -0
- package/dist/core/autonomy/approval-gate.js +27 -0
- package/dist/core/autonomy/approval-gate.js.map +1 -0
- package/dist/core/autonomy/bounded-completion.d.ts +27 -0
- package/dist/core/autonomy/bounded-completion.d.ts.map +1 -0
- package/dist/core/autonomy/bounded-completion.js +44 -0
- package/dist/core/autonomy/bounded-completion.js.map +1 -0
- package/dist/core/autonomy/contracts.d.ts +129 -0
- package/dist/core/autonomy/contracts.d.ts.map +1 -0
- package/dist/core/autonomy/contracts.js +2 -0
- package/dist/core/autonomy/contracts.js.map +1 -0
- package/dist/core/autonomy/gates.d.ts +15 -0
- package/dist/core/autonomy/gates.d.ts.map +1 -0
- package/dist/core/autonomy/gates.js +205 -0
- package/dist/core/autonomy/gates.js.map +1 -0
- package/dist/core/autonomy/lane-tracker.d.ts +48 -0
- package/dist/core/autonomy/lane-tracker.d.ts.map +1 -0
- package/dist/core/autonomy/lane-tracker.js +125 -0
- package/dist/core/autonomy/lane-tracker.js.map +1 -0
- package/dist/core/autonomy/path-scope.d.ts +9 -0
- package/dist/core/autonomy/path-scope.d.ts.map +1 -0
- package/dist/core/autonomy/path-scope.js +122 -0
- package/dist/core/autonomy/path-scope.js.map +1 -0
- package/dist/core/autonomy/risk-assessment.d.ts +3 -0
- package/dist/core/autonomy/risk-assessment.d.ts.map +1 -0
- package/dist/core/autonomy/risk-assessment.js +122 -0
- package/dist/core/autonomy/risk-assessment.js.map +1 -0
- package/dist/core/autonomy/session-lane-record.d.ts +10 -0
- package/dist/core/autonomy/session-lane-record.d.ts.map +1 -0
- package/dist/core/autonomy/session-lane-record.js +36 -0
- package/dist/core/autonomy/session-lane-record.js.map +1 -0
- package/dist/core/autonomy/status.d.ts +40 -0
- package/dist/core/autonomy/status.d.ts.map +1 -0
- package/dist/core/autonomy/status.js +107 -0
- package/dist/core/autonomy/status.js.map +1 -0
- package/dist/core/autonomy/subagent-prompt.d.ts +21 -0
- package/dist/core/autonomy/subagent-prompt.d.ts.map +1 -0
- package/dist/core/autonomy/subagent-prompt.js +28 -0
- package/dist/core/autonomy/subagent-prompt.js.map +1 -0
- package/dist/core/autonomy/telemetry-events.d.ts +18 -0
- package/dist/core/autonomy/telemetry-events.d.ts.map +1 -0
- package/dist/core/autonomy/telemetry-events.js +60 -0
- package/dist/core/autonomy/telemetry-events.js.map +1 -0
- package/dist/core/context/artifact-retrieval.d.ts +49 -0
- package/dist/core/context/artifact-retrieval.d.ts.map +1 -0
- package/dist/core/context/artifact-retrieval.js +49 -0
- package/dist/core/context/artifact-retrieval.js.map +1 -0
- package/dist/core/context/brain-curator.d.ts +88 -0
- package/dist/core/context/brain-curator.d.ts.map +1 -0
- package/dist/core/context/brain-curator.js +192 -0
- package/dist/core/context/brain-curator.js.map +1 -0
- package/dist/core/context/context-artifacts.d.ts +94 -0
- package/dist/core/context/context-artifacts.d.ts.map +1 -0
- package/dist/core/context/context-artifacts.js +307 -0
- package/dist/core/context/context-artifacts.js.map +1 -0
- package/dist/core/context/context-audit.d.ts +66 -0
- package/dist/core/context/context-audit.d.ts.map +1 -0
- package/dist/core/context/context-audit.js +173 -0
- package/dist/core/context/context-audit.js.map +1 -0
- package/dist/core/context/context-composition.d.ts +122 -0
- package/dist/core/context/context-composition.d.ts.map +1 -0
- package/dist/core/context/context-composition.js +163 -0
- package/dist/core/context/context-composition.js.map +1 -0
- package/dist/core/context/context-item.d.ts +117 -0
- package/dist/core/context/context-item.d.ts.map +1 -0
- package/dist/core/context/context-item.js +36 -0
- package/dist/core/context/context-item.js.map +1 -0
- package/dist/core/context/context-prompt-enforcement.d.ts +86 -0
- package/dist/core/context/context-prompt-enforcement.d.ts.map +1 -0
- package/dist/core/context/context-prompt-enforcement.js +168 -0
- package/dist/core/context/context-prompt-enforcement.js.map +1 -0
- package/dist/core/context/context-prompt-policy.d.ts +90 -0
- package/dist/core/context/context-prompt-policy.d.ts.map +1 -0
- package/dist/core/context/context-prompt-policy.js +73 -0
- package/dist/core/context/context-prompt-policy.js.map +1 -0
- package/dist/core/context/context-retention.d.ts +36 -0
- package/dist/core/context/context-retention.d.ts.map +1 -0
- package/dist/core/context/context-retention.js +108 -0
- package/dist/core/context/context-retention.js.map +1 -0
- package/dist/core/context/context-store.d.ts +37 -0
- package/dist/core/context/context-store.d.ts.map +1 -0
- package/dist/core/context/context-store.js +45 -0
- package/dist/core/context/context-store.js.map +1 -0
- package/dist/core/context/memory-diagnostics.d.ts +50 -0
- package/dist/core/context/memory-diagnostics.d.ts.map +1 -0
- package/dist/core/context/memory-diagnostics.js +43 -0
- package/dist/core/context/memory-diagnostics.js.map +1 -0
- package/dist/core/context/memory-index-store.d.ts +28 -0
- package/dist/core/context/memory-index-store.d.ts.map +1 -0
- package/dist/core/context/memory-index-store.js +38 -0
- package/dist/core/context/memory-index-store.js.map +1 -0
- package/dist/core/context/memory-prompt-block.d.ts +34 -0
- package/dist/core/context/memory-prompt-block.d.ts.map +1 -0
- package/dist/core/context/memory-prompt-block.js +58 -0
- package/dist/core/context/memory-prompt-block.js.map +1 -0
- package/dist/core/context/memory-provider-contract.d.ts +114 -0
- package/dist/core/context/memory-provider-contract.d.ts.map +1 -0
- package/dist/core/context/memory-provider-contract.js +121 -0
- package/dist/core/context/memory-provider-contract.js.map +1 -0
- package/dist/core/context/memory-retrieval.d.ts +27 -0
- package/dist/core/context/memory-retrieval.d.ts.map +1 -0
- package/dist/core/context/memory-retrieval.js +91 -0
- package/dist/core/context/memory-retrieval.js.map +1 -0
- package/dist/core/context/okf-memory-provider.d.ts +26 -0
- package/dist/core/context/okf-memory-provider.d.ts.map +1 -0
- package/dist/core/context/okf-memory-provider.js +154 -0
- package/dist/core/context/okf-memory-provider.js.map +1 -0
- package/dist/core/context/okf-memory.d.ts +42 -0
- package/dist/core/context/okf-memory.d.ts.map +1 -0
- package/dist/core/context/okf-memory.js +175 -0
- package/dist/core/context/okf-memory.js.map +1 -0
- package/dist/core/context/policy-engine.d.ts +66 -0
- package/dist/core/context/policy-engine.d.ts.map +1 -0
- package/dist/core/context/policy-engine.js +171 -0
- package/dist/core/context/policy-engine.js.map +1 -0
- package/dist/core/context/policy-types.d.ts +102 -0
- package/dist/core/context/policy-types.d.ts.map +1 -0
- package/dist/core/context/policy-types.js +7 -0
- package/dist/core/context/policy-types.js.map +1 -0
- package/dist/core/context/sqlite-runtime-index.d.ts +19 -0
- package/dist/core/context/sqlite-runtime-index.d.ts.map +1 -0
- package/dist/core/context/sqlite-runtime-index.js +344 -0
- package/dist/core/context/sqlite-runtime-index.js.map +1 -0
- package/dist/core/context/storage-authority.d.ts +20 -0
- package/dist/core/context/storage-authority.d.ts.map +1 -0
- package/dist/core/context/storage-authority.js +51 -0
- package/dist/core/context/storage-authority.js.map +1 -0
- package/dist/core/context/tool-output-packer.d.ts +75 -0
- package/dist/core/context/tool-output-packer.d.ts.map +1 -0
- package/dist/core/context/tool-output-packer.js +77 -0
- package/dist/core/context/tool-output-packer.js.map +1 -0
- package/dist/core/context-gc.d.ts +13 -0
- package/dist/core/context-gc.d.ts.map +1 -1
- package/dist/core/context-gc.js +6 -0
- package/dist/core/context-gc.js.map +1 -1
- package/dist/core/cost/session-usage.d.ts +20 -0
- package/dist/core/cost/session-usage.d.ts.map +1 -0
- package/dist/core/cost/session-usage.js +164 -0
- package/dist/core/cost/session-usage.js.map +1 -0
- package/dist/core/delegation/session-worker-result.d.ts +10 -0
- package/dist/core/delegation/session-worker-result.d.ts.map +1 -0
- package/dist/core/delegation/session-worker-result.js +36 -0
- package/dist/core/delegation/session-worker-result.js.map +1 -0
- package/dist/core/delegation/worker-result.d.ts +9 -0
- package/dist/core/delegation/worker-result.d.ts.map +1 -0
- package/dist/core/delegation/worker-result.js +152 -0
- package/dist/core/delegation/worker-result.js.map +1 -0
- package/dist/core/delegation/worker-runner.d.ts +58 -0
- package/dist/core/delegation/worker-runner.d.ts.map +1 -0
- package/dist/core/delegation/worker-runner.js +188 -0
- package/dist/core/delegation/worker-runner.js.map +1 -0
- package/dist/core/extensions/builtin.d.ts +5 -1
- package/dist/core/extensions/builtin.d.ts.map +1 -1
- package/dist/core/extensions/builtin.js +23 -1
- package/dist/core/extensions/builtin.js.map +1 -1
- package/dist/core/footer-data-provider.d.ts +5 -1
- package/dist/core/footer-data-provider.d.ts.map +1 -1
- package/dist/core/footer-data-provider.js +13 -0
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/goals/goal-continuation-controller.d.ts +22 -0
- package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -0
- package/dist/core/goals/goal-continuation-controller.js +88 -0
- package/dist/core/goals/goal-continuation-controller.js.map +1 -0
- package/dist/core/goals/goal-continuation-defaults.d.ts +10 -0
- package/dist/core/goals/goal-continuation-defaults.d.ts.map +1 -0
- package/dist/core/goals/goal-continuation-defaults.js +10 -0
- package/dist/core/goals/goal-continuation-defaults.js.map +1 -0
- package/dist/core/goals/goal-continuation-prompt.d.ts +18 -0
- package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -0
- package/dist/core/goals/goal-continuation-prompt.js +141 -0
- package/dist/core/goals/goal-continuation-prompt.js.map +1 -0
- package/dist/core/goals/goal-runtime-snapshot.d.ts +19 -0
- package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -0
- package/dist/core/goals/goal-runtime-snapshot.js +23 -0
- package/dist/core/goals/goal-runtime-snapshot.js.map +1 -0
- package/dist/core/goals/goal-state.d.ts +87 -0
- package/dist/core/goals/goal-state.d.ts.map +1 -0
- package/dist/core/goals/goal-state.js +259 -0
- package/dist/core/goals/goal-state.js.map +1 -0
- package/dist/core/goals/goal-tool-core.d.ts +66 -0
- package/dist/core/goals/goal-tool-core.d.ts.map +1 -0
- package/dist/core/goals/goal-tool-core.js +146 -0
- package/dist/core/goals/goal-tool-core.js.map +1 -0
- package/dist/core/goals/session-goal-state.d.ts +10 -0
- package/dist/core/goals/session-goal-state.d.ts.map +1 -0
- package/dist/core/goals/session-goal-state.js +35 -0
- package/dist/core/goals/session-goal-state.js.map +1 -0
- package/dist/core/learning/learning-audit.d.ts +45 -0
- package/dist/core/learning/learning-audit.d.ts.map +1 -0
- package/dist/core/learning/learning-audit.js +139 -0
- package/dist/core/learning/learning-audit.js.map +1 -0
- package/dist/core/learning/learning-gate.d.ts +29 -0
- package/dist/core/learning/learning-gate.d.ts.map +1 -0
- package/dist/core/learning/learning-gate.js +150 -0
- package/dist/core/learning/learning-gate.js.map +1 -0
- package/dist/core/learning/session-learning-decision.d.ts +10 -0
- package/dist/core/learning/session-learning-decision.d.ts.map +1 -0
- package/dist/core/learning/session-learning-decision.js +36 -0
- package/dist/core/learning/session-learning-decision.js.map +1 -0
- package/dist/core/model-capability.d.ts +41 -0
- package/dist/core/model-capability.d.ts.map +1 -0
- package/dist/core/model-capability.js +101 -0
- package/dist/core/model-capability.js.map +1 -0
- package/dist/core/model-router/config-diagnostics.d.ts.map +1 -1
- package/dist/core/model-router/config-diagnostics.js +1 -0
- package/dist/core/model-router/config-diagnostics.js.map +1 -1
- package/dist/core/model-router/intent-classifier.d.ts +2 -0
- package/dist/core/model-router/intent-classifier.d.ts.map +1 -1
- package/dist/core/model-router/intent-classifier.js +154 -9
- package/dist/core/model-router/intent-classifier.js.map +1 -1
- package/dist/core/model-router/route-judge.d.ts +54 -0
- package/dist/core/model-router/route-judge.d.ts.map +1 -0
- package/dist/core/model-router/route-judge.js +128 -0
- package/dist/core/model-router/route-judge.js.map +1 -0
- package/dist/core/model-router/status.d.ts +4 -1
- package/dist/core/model-router/status.d.ts.map +1 -1
- package/dist/core/model-router/status.js +30 -6
- package/dist/core/model-router/status.js.map +1 -1
- package/dist/core/model-router/tool-escalation.d.ts +4 -6
- package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
- package/dist/core/model-router/tool-escalation.js +1 -1
- package/dist/core/model-router/tool-escalation.js.map +1 -1
- package/dist/core/models/fitness-store.d.ts +40 -0
- package/dist/core/models/fitness-store.d.ts.map +1 -0
- package/dist/core/models/fitness-store.js +61 -0
- package/dist/core/models/fitness-store.js.map +1 -0
- package/dist/core/profile-registry.d.ts.map +1 -1
- package/dist/core/profile-registry.js +1 -1
- package/dist/core/profile-registry.js.map +1 -1
- package/dist/core/prompt-templates.d.ts +2 -0
- package/dist/core/prompt-templates.d.ts.map +1 -1
- package/dist/core/prompt-templates.js +12 -4
- package/dist/core/prompt-templates.js.map +1 -1
- package/dist/core/research/automata-provider.d.ts +5 -0
- package/dist/core/research/automata-provider.d.ts.map +1 -0
- package/dist/core/research/automata-provider.js +15 -0
- package/dist/core/research/automata-provider.js.map +1 -0
- package/dist/core/research/evidence-bundle.d.ts +10 -0
- package/dist/core/research/evidence-bundle.d.ts.map +1 -0
- package/dist/core/research/evidence-bundle.js +116 -0
- package/dist/core/research/evidence-bundle.js.map +1 -0
- package/dist/core/research/model-fitness.d.ts +82 -0
- package/dist/core/research/model-fitness.d.ts.map +1 -0
- package/dist/core/research/model-fitness.js +308 -0
- package/dist/core/research/model-fitness.js.map +1 -0
- package/dist/core/research/research-gate.d.ts +11 -0
- package/dist/core/research/research-gate.d.ts.map +1 -0
- package/dist/core/research/research-gate.js +82 -0
- package/dist/core/research/research-gate.js.map +1 -0
- package/dist/core/research/research-runner.d.ts +59 -0
- package/dist/core/research/research-runner.d.ts.map +1 -0
- package/dist/core/research/research-runner.js +155 -0
- package/dist/core/research/research-runner.js.map +1 -0
- package/dist/core/research/session-evidence-bundle.d.ts +11 -0
- package/dist/core/research/session-evidence-bundle.d.ts.map +1 -0
- package/dist/core/research/session-evidence-bundle.js +55 -0
- package/dist/core/research/session-evidence-bundle.js.map +1 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +4 -0
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/settings-manager.d.ts +160 -4
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +304 -9
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/skills.d.ts +4 -0
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +18 -6
- package/dist/core/skills.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +10 -1
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/toolkit/script-registry.d.ts +34 -0
- package/dist/core/toolkit/script-registry.d.ts.map +1 -0
- package/dist/core/toolkit/script-registry.js +71 -0
- package/dist/core/toolkit/script-registry.js.map +1 -0
- package/dist/core/toolkit/script-runner.d.ts +28 -0
- package/dist/core/toolkit/script-runner.d.ts.map +1 -0
- package/dist/core/toolkit/script-runner.js +48 -0
- package/dist/core/toolkit/script-runner.js.map +1 -0
- package/dist/core/tools/artifact-retrieve.d.ts +23 -0
- package/dist/core/tools/artifact-retrieve.d.ts.map +1 -0
- package/dist/core/tools/artifact-retrieve.js +110 -0
- package/dist/core/tools/artifact-retrieve.js.map +1 -0
- package/dist/core/tools/delegate.d.ts +32 -0
- package/dist/core/tools/delegate.d.ts.map +1 -0
- package/dist/core/tools/delegate.js +60 -0
- package/dist/core/tools/delegate.js.map +1 -0
- package/dist/core/tools/fff-search-backend.d.ts +103 -0
- package/dist/core/tools/fff-search-backend.d.ts.map +1 -0
- package/dist/core/tools/fff-search-backend.js +151 -0
- package/dist/core/tools/fff-search-backend.js.map +1 -0
- package/dist/core/tools/find.d.ts +21 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +183 -10
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/goal.d.ts +35 -0
- package/dist/core/tools/goal.d.ts.map +1 -0
- package/dist/core/tools/goal.js +122 -0
- package/dist/core/tools/goal.js.map +1 -0
- package/dist/core/tools/grep.d.ts +21 -1
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +272 -27
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/index.d.ts +4 -1
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +9 -0
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/model-fitness.d.ts +30 -0
- package/dist/core/tools/model-fitness.d.ts.map +1 -0
- package/dist/core/tools/model-fitness.js +38 -0
- package/dist/core/tools/model-fitness.js.map +1 -0
- package/dist/core/tools/run-toolkit-script.d.ts +24 -0
- package/dist/core/tools/run-toolkit-script.d.ts.map +1 -0
- package/dist/core/tools/run-toolkit-script.js +103 -0
- package/dist/core/tools/run-toolkit-script.js.map +1 -0
- package/dist/core/tools/search-router.d.ts +75 -0
- package/dist/core/tools/search-router.d.ts.map +1 -0
- package/dist/core/tools/search-router.js +85 -0
- package/dist/core/tools/search-router.js.map +1 -0
- package/dist/modes/interactive/components/fitness-role-selector.d.ts +13 -0
- package/dist/modes/interactive/components/fitness-role-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/fitness-role-selector.js +65 -0
- package/dist/modes/interactive/components/fitness-role-selector.js.map +1 -0
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +18 -16
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +16 -1
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +555 -11
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +9 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +308 -39
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/utils/tools-manager.d.ts +2 -0
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +154 -2
- package/dist/utils/tools-manager.js.map +1 -1
- 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 +368 -12
- package/package.json +5 -4
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { runBoundedCompletion } from "../autonomy/bounded-completion.js";
|
|
2
|
+
import { createEvidenceBundle } from "../research/evidence-bundle.js";
|
|
3
|
+
import { validateWorkerResult } from "./worker-result.js";
|
|
4
|
+
/**
|
|
5
|
+
* Pure orchestration for one bounded scout-worker delegation: bounded isolated completion ->
|
|
6
|
+
* parse -> `WorkerResult` -> parent validation via {@link validateWorkerResult}.
|
|
7
|
+
*
|
|
8
|
+
* Slice scope: scout (read-only) workers only — the completion receives text prompts, no tools, so
|
|
9
|
+
* `changedFiles` is always empty. Code-writing workers stay out until a real execution envelope
|
|
10
|
+
* enforces path scope at tool level. Worker output is untrusted until the parent verifies it.
|
|
11
|
+
*/
|
|
12
|
+
/** Static across calls so callers can use `cacheRetention: "short"`. */
|
|
13
|
+
export const WORKER_LANE_SYSTEM_PROMPT = [
|
|
14
|
+
"You are a bounded read-only scout worker delegated one task by a coding agent.",
|
|
15
|
+
"You cannot run tools or change files; produce your best analysis of the delegated task.",
|
|
16
|
+
"Respond with STRICT JSON only - no prose, no markdown fences:",
|
|
17
|
+
'{"summary":"<what you concluded>","status":"completed"|"blocked","blockers":["<why you are stuck>"],"findings":[{"summary":"<one concrete finding>","confidence":<0..1>}]}',
|
|
18
|
+
'Use status "blocked" with blockers only when the task cannot be answered from the provided context.',
|
|
19
|
+
"Never invent file paths, APIs, or facts.",
|
|
20
|
+
].join("\n");
|
|
21
|
+
export function buildWorkerUserPrompt(request) {
|
|
22
|
+
return `Delegated task: ${request.instructions}`;
|
|
23
|
+
}
|
|
24
|
+
export function parseWorkerOutput(text) {
|
|
25
|
+
const trimmed = text.trim();
|
|
26
|
+
const candidates = [trimmed];
|
|
27
|
+
const fenced = /```(?:json)?\s*([\s\S]*?)```/.exec(trimmed);
|
|
28
|
+
if (fenced?.[1])
|
|
29
|
+
candidates.push(fenced[1].trim());
|
|
30
|
+
const start = trimmed.indexOf("{");
|
|
31
|
+
const end = trimmed.lastIndexOf("}");
|
|
32
|
+
if (start >= 0 && end > start)
|
|
33
|
+
candidates.push(trimmed.slice(start, end + 1));
|
|
34
|
+
for (const candidate of candidates) {
|
|
35
|
+
let parsed;
|
|
36
|
+
try {
|
|
37
|
+
parsed = JSON.parse(candidate);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
43
|
+
continue;
|
|
44
|
+
const record = parsed;
|
|
45
|
+
const summary = record.summary;
|
|
46
|
+
if (typeof summary !== "string" || summary.trim().length === 0)
|
|
47
|
+
continue;
|
|
48
|
+
const status = record.status === "blocked" ? "blocked" : "completed";
|
|
49
|
+
const blockers = Array.isArray(record.blockers)
|
|
50
|
+
? record.blockers.filter((blocker) => typeof blocker === "string" && blocker.length > 0)
|
|
51
|
+
: [];
|
|
52
|
+
const findings = [];
|
|
53
|
+
if (Array.isArray(record.findings)) {
|
|
54
|
+
for (const item of record.findings) {
|
|
55
|
+
if (!item || typeof item !== "object" || Array.isArray(item))
|
|
56
|
+
continue;
|
|
57
|
+
const findingSummary = item.summary;
|
|
58
|
+
if (typeof findingSummary !== "string" || findingSummary.trim().length === 0)
|
|
59
|
+
continue;
|
|
60
|
+
const confidenceRaw = item.confidence;
|
|
61
|
+
const confidence = typeof confidenceRaw === "number" && Number.isFinite(confidenceRaw)
|
|
62
|
+
? Math.min(Math.max(confidenceRaw, 0), 1)
|
|
63
|
+
: undefined;
|
|
64
|
+
findings.push({ summary: findingSummary.trim(), confidence });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return { summary: summary.trim(), status, blockers, findings };
|
|
68
|
+
}
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
function buildWorkerEvidence(request, findings) {
|
|
72
|
+
if (findings.length === 0)
|
|
73
|
+
return undefined;
|
|
74
|
+
const instructionsRef = {
|
|
75
|
+
id: "src-instructions",
|
|
76
|
+
kind: "user",
|
|
77
|
+
title: "Delegated task instructions",
|
|
78
|
+
trusted: true,
|
|
79
|
+
excerpt: request.instructions.slice(0, 2000),
|
|
80
|
+
};
|
|
81
|
+
const synthesisRef = {
|
|
82
|
+
id: "src-worker",
|
|
83
|
+
kind: "tool",
|
|
84
|
+
title: "Scout-worker synthesis",
|
|
85
|
+
trusted: false,
|
|
86
|
+
};
|
|
87
|
+
const bundleFindings = findings.map((finding, index) => ({
|
|
88
|
+
id: `finding-${index + 1}`,
|
|
89
|
+
summary: finding.summary,
|
|
90
|
+
evidenceIds: [synthesisRef.id],
|
|
91
|
+
...(finding.confidence !== undefined ? { confidence: finding.confidence } : {}),
|
|
92
|
+
}));
|
|
93
|
+
return createEvidenceBundle({
|
|
94
|
+
query: `worker:${request.id}`,
|
|
95
|
+
sources: [instructionsRef, synthesisRef],
|
|
96
|
+
findings: bundleFindings,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
function finishOutcome(args) {
|
|
100
|
+
const acceptance = validateWorkerResult({ request: args.request, result: args.result });
|
|
101
|
+
return {
|
|
102
|
+
result: args.result,
|
|
103
|
+
acceptance,
|
|
104
|
+
accepted: acceptance.outcome === "allow",
|
|
105
|
+
laneStatus: args.laneStatus,
|
|
106
|
+
reasonCode: args.reasonCode,
|
|
107
|
+
costUsd: args.costUsd,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
export async function runWorker(options) {
|
|
111
|
+
const now = options.now ?? (() => new Date().toISOString());
|
|
112
|
+
const baseResult = {
|
|
113
|
+
requestId: options.request.id,
|
|
114
|
+
changedFiles: [],
|
|
115
|
+
usageReportId: options.usageReportId,
|
|
116
|
+
createdAt: now(),
|
|
117
|
+
};
|
|
118
|
+
const bounded = await runBoundedCompletion({
|
|
119
|
+
maxWallClockMs: options.maxWallClockMs,
|
|
120
|
+
signal: options.signal,
|
|
121
|
+
execute: (signal) => options.complete({
|
|
122
|
+
systemPrompt: WORKER_LANE_SYSTEM_PROMPT,
|
|
123
|
+
userPrompt: buildWorkerUserPrompt(options.request),
|
|
124
|
+
signal,
|
|
125
|
+
}),
|
|
126
|
+
});
|
|
127
|
+
const costUsd = bounded.completion?.costUsd ?? 0;
|
|
128
|
+
if (bounded.failure) {
|
|
129
|
+
const cancelled = bounded.failure.status === "canceled" || bounded.failure.status === "timeout";
|
|
130
|
+
return finishOutcome({
|
|
131
|
+
request: options.request,
|
|
132
|
+
result: {
|
|
133
|
+
...baseResult,
|
|
134
|
+
status: cancelled ? "cancelled" : "failed",
|
|
135
|
+
summary: `Worker did not complete: ${bounded.failure.reasonCode}`,
|
|
136
|
+
},
|
|
137
|
+
laneStatus: bounded.failure.status,
|
|
138
|
+
reasonCode: bounded.failure.reasonCode,
|
|
139
|
+
costUsd,
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
const completion = bounded.completion;
|
|
143
|
+
if (!completion || completion.stopReason === "error" || completion.stopReason === "aborted") {
|
|
144
|
+
return finishOutcome({
|
|
145
|
+
request: options.request,
|
|
146
|
+
result: { ...baseResult, status: "failed", summary: "Worker model call failed." },
|
|
147
|
+
laneStatus: "failed",
|
|
148
|
+
reasonCode: "model_error",
|
|
149
|
+
costUsd,
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
const parsed = parseWorkerOutput(completion.text);
|
|
153
|
+
if (!parsed) {
|
|
154
|
+
return finishOutcome({
|
|
155
|
+
request: options.request,
|
|
156
|
+
result: { ...baseResult, status: "failed", summary: "Worker output was not valid structured JSON." },
|
|
157
|
+
laneStatus: "failed",
|
|
158
|
+
reasonCode: "unparseable_output",
|
|
159
|
+
costUsd,
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
const evidence = buildWorkerEvidence(options.request, parsed.findings);
|
|
163
|
+
const result = {
|
|
164
|
+
...baseResult,
|
|
165
|
+
status: parsed.status === "blocked" || parsed.blockers.length > 0 ? "blocked" : "completed",
|
|
166
|
+
summary: parsed.summary,
|
|
167
|
+
...(parsed.blockers.length > 0 ? { blockers: parsed.blockers } : {}),
|
|
168
|
+
...(evidence ? { evidence } : {}),
|
|
169
|
+
};
|
|
170
|
+
if (result.status === "blocked") {
|
|
171
|
+
return finishOutcome({
|
|
172
|
+
request: options.request,
|
|
173
|
+
result,
|
|
174
|
+
laneStatus: "failed",
|
|
175
|
+
reasonCode: "worker_blocked",
|
|
176
|
+
costUsd,
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
const overBudget = options.maxUsd > 0 && costUsd > options.maxUsd;
|
|
180
|
+
return finishOutcome({
|
|
181
|
+
request: options.request,
|
|
182
|
+
result,
|
|
183
|
+
laneStatus: overBudget ? "budget_exhausted" : "succeeded",
|
|
184
|
+
reasonCode: overBudget ? "cost_budget_exceeded" : "worker_completed",
|
|
185
|
+
costUsd,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
//# sourceMappingURL=worker-runner.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker-runner.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AAGzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAE1D;;;;;;;GAOG;AAEH,wEAAwE;A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,OAAO;KACP,CAAC,CAAC;AAAA,CACH","sourcesContent":["import { runBoundedCompletion } from \"../autonomy/bounded-completion.ts\";\nimport type { EvidenceRef, Finding, GateOutcome, WorkerRequest, WorkerResult } from \"../autonomy/contracts.ts\";\nimport type { LaneTerminalStatus } from \"../autonomy/lane-tracker.ts\";\nimport { createEvidenceBundle } from \"../research/evidence-bundle.ts\";\nimport { validateWorkerResult } from \"./worker-result.ts\";\n\n/**\n * Pure orchestration for one bounded scout-worker delegation: bounded isolated completion ->\n * parse -> `WorkerResult` -> parent validation via {@link validateWorkerResult}.\n *\n * Slice scope: scout (read-only) workers only — the completion receives text prompts, no tools, so\n * `changedFiles` is always empty. Code-writing workers stay out until a real execution envelope\n * enforces path scope at tool level. Worker output is untrusted until the parent verifies it.\n */\n\n/** Static across calls so callers can use `cacheRetention: \"short\"`. */\nexport const WORKER_LANE_SYSTEM_PROMPT = [\n\t\"You are a bounded read-only scout worker delegated one task by a coding agent.\",\n\t\"You cannot run tools or change files; produce your best analysis of the delegated task.\",\n\t\"Respond with STRICT JSON only - no prose, no markdown fences:\",\n\t'{\"summary\":\"<what you concluded>\",\"status\":\"completed\"|\"blocked\",\"blockers\":[\"<why you are stuck>\"],\"findings\":[{\"summary\":\"<one concrete finding>\",\"confidence\":<0..1>}]}',\n\t'Use status \"blocked\" with blockers only when the task cannot be answered from the provided context.',\n\t\"Never invent file paths, APIs, or facts.\",\n].join(\"\\n\");\n\nexport interface WorkerCompletion {\n\ttext: string;\n\tcostUsd: number;\n\tstopReason: string;\n}\n\nexport interface WorkerRunnerOptions {\n\trequest: WorkerRequest;\n\t/** Budget for this delegation; a post-hoc breach marks the lane budget_exhausted. */\n\tmaxUsd: number;\n\t/** Wall-clock budget in milliseconds; 0 disables. */\n\tmaxWallClockMs: number;\n\t/**\n\t * Pre-allocated spawned-usage report id. Always stamped on the result so parent validation can\n\t * enforce the cost-visibility invariant (a completed result without a usage report is blocked).\n\t */\n\tusageReportId: string;\n\tcomplete: (args: { systemPrompt: string; userPrompt: string; signal?: AbortSignal }) => Promise<WorkerCompletion>;\n\tsignal?: AbortSignal;\n\tnow?: () => string;\n}\n\nexport interface WorkerRunOutcome {\n\tresult: WorkerResult;\n\t/** Parent-review verdict from {@link validateWorkerResult}; worker output stays untrusted. */\n\tacceptance: GateOutcome;\n\taccepted: boolean;\n\tlaneStatus: LaneTerminalStatus;\n\treasonCode: string;\n\tcostUsd: number;\n}\n\nexport function buildWorkerUserPrompt(request: WorkerRequest): string {\n\treturn `Delegated task: ${request.instructions}`;\n}\n\nexport interface ParsedWorkerOutput {\n\tsummary: string;\n\tstatus: \"completed\" | \"blocked\";\n\tblockers: string[];\n\tfindings: Array<{ summary: string; confidence?: number }>;\n}\n\nexport function parseWorkerOutput(text: string): ParsedWorkerOutput | undefined {\n\tconst trimmed = text.trim();\n\tconst candidates: string[] = [trimmed];\n\tconst fenced = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n\tif (fenced?.[1]) candidates.push(fenced[1].trim());\n\tconst start = trimmed.indexOf(\"{\");\n\tconst end = trimmed.lastIndexOf(\"}\");\n\tif (start >= 0 && end > start) candidates.push(trimmed.slice(start, end + 1));\n\n\tfor (const candidate of candidates) {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(candidate);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) continue;\n\t\tconst record = parsed as Record<string, unknown>;\n\t\tconst summary = record.summary;\n\t\tif (typeof summary !== \"string\" || summary.trim().length === 0) continue;\n\n\t\tconst status = record.status === \"blocked\" ? \"blocked\" : \"completed\";\n\t\tconst blockers = Array.isArray(record.blockers)\n\t\t\t? record.blockers.filter((blocker): blocker is string => typeof blocker === \"string\" && blocker.length > 0)\n\t\t\t: [];\n\t\tconst findings: Array<{ summary: string; confidence?: number }> = [];\n\t\tif (Array.isArray(record.findings)) {\n\t\t\tfor (const item of record.findings) {\n\t\t\t\tif (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n\t\t\t\tconst findingSummary = (item as { summary?: unknown }).summary;\n\t\t\t\tif (typeof findingSummary !== \"string\" || findingSummary.trim().length === 0) continue;\n\t\t\t\tconst confidenceRaw = (item as { confidence?: unknown }).confidence;\n\t\t\t\tconst confidence =\n\t\t\t\t\ttypeof confidenceRaw === \"number\" && Number.isFinite(confidenceRaw)\n\t\t\t\t\t\t? Math.min(Math.max(confidenceRaw, 0), 1)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tfindings.push({ summary: findingSummary.trim(), confidence });\n\t\t\t}\n\t\t}\n\t\treturn { summary: summary.trim(), status, blockers, findings };\n\t}\n\treturn undefined;\n}\n\nfunction buildWorkerEvidence(request: WorkerRequest, findings: ParsedWorkerOutput[\"findings\"]) {\n\tif (findings.length === 0) return undefined;\n\tconst instructionsRef: EvidenceRef = {\n\t\tid: \"src-instructions\",\n\t\tkind: \"user\",\n\t\ttitle: \"Delegated task instructions\",\n\t\ttrusted: true,\n\t\texcerpt: request.instructions.slice(0, 2000),\n\t};\n\tconst synthesisRef: EvidenceRef = {\n\t\tid: \"src-worker\",\n\t\tkind: \"tool\",\n\t\ttitle: \"Scout-worker synthesis\",\n\t\ttrusted: false,\n\t};\n\tconst bundleFindings: Finding[] = findings.map((finding, index) => ({\n\t\tid: `finding-${index + 1}`,\n\t\tsummary: finding.summary,\n\t\tevidenceIds: [synthesisRef.id],\n\t\t...(finding.confidence !== undefined ? { confidence: finding.confidence } : {}),\n\t}));\n\treturn createEvidenceBundle({\n\t\tquery: `worker:${request.id}`,\n\t\tsources: [instructionsRef, synthesisRef],\n\t\tfindings: bundleFindings,\n\t});\n}\n\nfunction finishOutcome(args: {\n\trequest: WorkerRequest;\n\tresult: WorkerResult;\n\tlaneStatus: LaneTerminalStatus;\n\treasonCode: string;\n\tcostUsd: number;\n}): WorkerRunOutcome {\n\tconst acceptance = validateWorkerResult({ request: args.request, result: args.result });\n\treturn {\n\t\tresult: args.result,\n\t\tacceptance,\n\t\taccepted: acceptance.outcome === \"allow\",\n\t\tlaneStatus: args.laneStatus,\n\t\treasonCode: args.reasonCode,\n\t\tcostUsd: args.costUsd,\n\t};\n}\n\nexport async function runWorker(options: WorkerRunnerOptions): Promise<WorkerRunOutcome> {\n\tconst now = options.now ?? (() => new Date().toISOString());\n\tconst baseResult = {\n\t\trequestId: options.request.id,\n\t\tchangedFiles: [] as string[],\n\t\tusageReportId: options.usageReportId,\n\t\tcreatedAt: now(),\n\t};\n\n\tconst bounded = await runBoundedCompletion({\n\t\tmaxWallClockMs: options.maxWallClockMs,\n\t\tsignal: options.signal,\n\t\texecute: (signal) =>\n\t\t\toptions.complete({\n\t\t\t\tsystemPrompt: WORKER_LANE_SYSTEM_PROMPT,\n\t\t\t\tuserPrompt: buildWorkerUserPrompt(options.request),\n\t\t\t\tsignal,\n\t\t\t}),\n\t});\n\tconst costUsd = bounded.completion?.costUsd ?? 0;\n\n\tif (bounded.failure) {\n\t\tconst cancelled = bounded.failure.status === \"canceled\" || bounded.failure.status === \"timeout\";\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tresult: {\n\t\t\t\t...baseResult,\n\t\t\t\tstatus: cancelled ? \"cancelled\" : \"failed\",\n\t\t\t\tsummary: `Worker did not complete: ${bounded.failure.reasonCode}`,\n\t\t\t},\n\t\t\tlaneStatus: bounded.failure.status,\n\t\t\treasonCode: bounded.failure.reasonCode,\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst completion = bounded.completion;\n\tif (!completion || completion.stopReason === \"error\" || completion.stopReason === \"aborted\") {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tresult: { ...baseResult, status: \"failed\", summary: \"Worker model call failed.\" },\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"model_error\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst parsed = parseWorkerOutput(completion.text);\n\tif (!parsed) {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tresult: { ...baseResult, status: \"failed\", summary: \"Worker output was not valid structured JSON.\" },\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"unparseable_output\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst evidence = buildWorkerEvidence(options.request, parsed.findings);\n\tconst result: WorkerResult = {\n\t\t...baseResult,\n\t\tstatus: parsed.status === \"blocked\" || parsed.blockers.length > 0 ? \"blocked\" : \"completed\",\n\t\tsummary: parsed.summary,\n\t\t...(parsed.blockers.length > 0 ? { blockers: parsed.blockers } : {}),\n\t\t...(evidence ? { evidence } : {}),\n\t};\n\n\tif (result.status === \"blocked\") {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tresult,\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"worker_blocked\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst overBudget = options.maxUsd > 0 && costUsd > options.maxUsd;\n\treturn finishOutcome({\n\t\trequest: options.request,\n\t\tresult,\n\t\tlaneStatus: overBudget ? \"budget_exhausted\" : \"succeeded\",\n\t\treasonCode: overBudget ? \"cost_budget_exceeded\" : \"worker_completed\",\n\t\tcostUsd,\n\t});\n}\n"]}
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import type { AgentMessage } from "@caupulican/pi-agent-core";
|
|
2
|
+
import type { MemoryPromptInclusionReport, MemoryRetrievalDiagnostics } from "../context/memory-diagnostics.ts";
|
|
2
3
|
import type { ContextGcReport } from "../context-gc.ts";
|
|
3
4
|
import type { ToolDefinition, ToolInfo } from "./types.ts";
|
|
4
|
-
export declare function createCoreDiagnosticsToolDefinitions(getActiveTools: () => string[], getAllTools: () => ToolInfo[], getContextGcReport?: (messages: AgentMessage[]) => ContextGcReport)
|
|
5
|
+
export declare function createCoreDiagnosticsToolDefinitions(getActiveTools: () => string[], getAllTools: () => ToolInfo[], getContextGcReport?: (messages: AgentMessage[]) => ContextGcReport, getMemoryDiagnostics?: () => {
|
|
6
|
+
retrieval: MemoryRetrievalDiagnostics;
|
|
7
|
+
promptInclusion: MemoryPromptInclusionReport;
|
|
8
|
+
}): ToolDefinition[];
|
|
5
9
|
//# sourceMappingURL=builtin.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builtin.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/builtin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAG9D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAGxD,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAgM3D,wBAAgB,oCAAoC,CACnD,cAAc,EAAE,MAAM,MAAM,EAAE,EAC9B,WAAW,EAAE,MAAM,QAAQ,EAAE,EAC7B,kBAAkB,CAAC,EAAE,CAAC,QAAQ,EAAE,YAAY,EAAE,KAAK,eAAe,GAChE,cAAc,EAAE,CA6HlB","sourcesContent":["import type { AgentMessage } from \"@caupulican/pi-agent-core\";\nimport { Type } from \"typebox\";\nimport { estimateTokens } from \"../compaction/compaction.ts\";\nimport type { ContextGcReport } from \"../context-gc.ts\";\nimport { createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport type { CompactionEntry, SessionEntry } from \"../session-manager.ts\";\nimport type { ToolDefinition, ToolInfo } from \"./types.ts\";\n\ntype ContextAuditParams = {\n\tmaxItems?: number;\n\tminTokens?: number;\n\tquery?: string;\n\tincludePreviews?: boolean;\n};\n\ntype AuditRow = {\n\tkind: string;\n\trole?: string;\n\tentryId?: string;\n\ttimestamp?: string;\n\ttokens: number;\n\tchars: number;\n\tlabel: string;\n\tpreview: string;\n};\n\nconst DEFAULT_MAX_ITEMS = 40;\nconst MAX_MAX_ITEMS = 200;\nconst DEFAULT_PREVIEW_CHARS = 220;\nconst MAX_PREVIEW_CHARS = 600;\n\nfunction estimateTextTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\nfunction cap(text: string, limit = DEFAULT_PREVIEW_CHARS): string {\n\tconst compact = text.replace(/\\s+/g, \" \").trim();\n\treturn compact.length > limit ? `${compact.slice(0, Math.max(0, limit - 1))}…` : compact;\n}\n\nfunction contentText(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return \"\";\n\treturn content\n\t\t.map((part) => {\n\t\t\tif (!part || typeof part !== \"object\") return \"\";\n\t\t\tconst typed = part as { type?: string; text?: string; thinking?: string; name?: string; arguments?: unknown };\n\t\t\tif (typed.type === \"text\") return typed.text || \"\";\n\t\t\tif (typed.type === \"thinking\") return `[thinking ${typed.thinking?.length ?? 0} chars]`;\n\t\t\tif (typed.type === \"toolCall\")\n\t\t\t\treturn `[toolCall ${typed.name || \"unknown\"} ${JSON.stringify(typed.arguments ?? {})}]`;\n\t\t\tif (typed.type === \"image\") return \"[image]\";\n\t\t\treturn \"\";\n\t\t})\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\");\n}\n\nfunction messagePreview(message: AgentMessage): string {\n\tswitch (message.role) {\n\t\tcase \"assistant\":\n\t\tcase \"user\":\n\t\tcase \"toolResult\":\n\t\tcase \"custom\":\n\t\t\treturn contentText((message as { content?: unknown }).content);\n\t\tcase \"bashExecution\":\n\t\t\treturn `Ran ${message.command}\\n${message.output}`;\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\":\n\t\t\treturn message.summary;\n\t\tdefault:\n\t\t\treturn \"\";\n\t}\n}\n\nfunction messageLabel(message: AgentMessage): string {\n\tif (message.role === \"assistant\") {\n\t\tconst toolCalls = message.content.filter((part) => part.type === \"toolCall\").length;\n\t\treturn toolCalls > 0 ? `assistant (${toolCalls} tool call${toolCalls === 1 ? \"\" : \"s\"})` : \"assistant\";\n\t}\n\tif (message.role === \"toolResult\") return `tool result: ${message.toolName}`;\n\tif (message.role === \"custom\") return `custom: ${message.customType}`;\n\tif (message.role === \"bashExecution\") return \"bash execution\";\n\tif (message.role === \"branchSummary\") return \"branch summary\";\n\tif (message.role === \"compactionSummary\") return \"compaction summary\";\n\treturn message.role;\n}\n\nfunction addRow(rows: AuditRow[], entry: SessionEntry, message: AgentMessage, kindOverride?: string) {\n\tconst preview = messagePreview(message);\n\trows.push({\n\t\tkind: kindOverride || entry.type,\n\t\trole: message.role,\n\t\tentryId: entry.id,\n\t\ttimestamp: entry.timestamp,\n\t\ttokens: estimateTokens(message),\n\t\tchars: preview.length,\n\t\tlabel: messageLabel(message),\n\t\tpreview: cap(preview),\n\t});\n}\n\nfunction messageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") return entry.message;\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);\n\t}\n\tif (entry.type === \"branch_summary\" && entry.summary) {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nfunction latestCompaction(entries: SessionEntry[]): CompactionEntry | undefined {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (entry?.type === \"compaction\") return entry;\n\t}\n\treturn undefined;\n}\n\nfunction activeContextMessages(entries: SessionEntry[]): AgentMessage[] {\n\tconst messages: AgentMessage[] = [];\n\tconst compaction = latestCompaction(entries);\n\tif (!compaction) {\n\t\tfor (const entry of entries) {\n\t\t\tconst message = messageFromEntry(entry);\n\t\t\tif (message) messages.push(message);\n\t\t}\n\t\treturn messages;\n\t}\n\n\tmessages.push(createCompactionSummaryMessage(compaction.summary, compaction.tokensBefore, compaction.timestamp));\n\tconst compactionIndex = entries.findIndex((entry) => entry.id === compaction.id);\n\tlet foundFirstKept = false;\n\tfor (let index = 0; index < compactionIndex; index++) {\n\t\tconst entry = entries[index];\n\t\tif (entry.id === compaction.firstKeptEntryId) foundFirstKept = true;\n\t\tif (!foundFirstKept) continue;\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) messages.push(message);\n\t}\n\tfor (let index = compactionIndex + 1; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) messages.push(message);\n\t}\n\treturn messages;\n}\n\nfunction activeContextRows(entries: SessionEntry[]): AuditRow[] {\n\tconst rows: AuditRow[] = [];\n\tconst compaction = latestCompaction(entries);\n\tif (!compaction) {\n\t\tfor (const entry of entries) {\n\t\t\tconst message = messageFromEntry(entry);\n\t\t\tif (message) addRow(rows, entry, message);\n\t\t}\n\t\treturn rows;\n\t}\n\n\tconst compactionMessage = createCompactionSummaryMessage(\n\t\tcompaction.summary,\n\t\tcompaction.tokensBefore,\n\t\tcompaction.timestamp,\n\t);\n\taddRow(rows, compaction, compactionMessage, \"compaction\");\n\n\tconst compactionIndex = entries.findIndex((entry) => entry.id === compaction.id);\n\tlet foundFirstKept = false;\n\tfor (let index = 0; index < compactionIndex; index++) {\n\t\tconst entry = entries[index];\n\t\tif (entry.id === compaction.firstKeptEntryId) foundFirstKept = true;\n\t\tif (!foundFirstKept) continue;\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) addRow(rows, entry, message);\n\t}\n\tfor (let index = compactionIndex + 1; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) addRow(rows, entry, message);\n\t}\n\treturn rows;\n}\n\nfunction groupRows(rows: AuditRow[]): Array<[string, { count: number; tokens: number; chars: number }]> {\n\tconst groups = new Map<string, { count: number; tokens: number; chars: number }>();\n\tfor (const row of rows) {\n\t\tconst key = row.label;\n\t\tconst current = groups.get(key) ?? { count: 0, tokens: 0, chars: 0 };\n\t\tcurrent.count += 1;\n\t\tcurrent.tokens += row.tokens;\n\t\tcurrent.chars += row.chars;\n\t\tgroups.set(key, current);\n\t}\n\treturn [...groups.entries()].sort((a, b) => b[1].tokens - a[1].tokens);\n}\n\nexport function createCoreDiagnosticsToolDefinitions(\n\tgetActiveTools: () => string[],\n\tgetAllTools: () => ToolInfo[],\n\tgetContextGcReport?: (messages: AgentMessage[]) => ContextGcReport,\n): ToolDefinition[] {\n\treturn [\n\t\t{\n\t\t\tname: \"context_audit\",\n\t\t\tlabel: \"Context Audit\",\n\t\t\tdescription:\n\t\t\t\t\"Audit the current provider-visible context composition: model window usage, system prompt estimate, active tool schema estimate, active session message rows, and heaviest context contributors.\",\n\t\t\tpromptSnippet: \"Audit current loaded context composition before optimizing context usage.\",\n\t\t\tpromptGuidelines: [\n\t\t\t\t\"Use context_audit when the user asks what is consuming context, why the footer shows a high percentage, or which messages/tools/system prompt content are loaded.\",\n\t\t\t\t\"Keep output bounded; use query/minTokens/maxItems to narrow rather than dumping full context.\",\n\t\t\t\t\"Treat token counts as estimates except provider usage from ctx.getContextUsage, which is still model/provider dependent.\",\n\t\t\t],\n\t\t\tparameters: Type.Object(\n\t\t\t\t{\n\t\t\t\t\tmaxItems: Type.Optional(\n\t\t\t\t\t\tType.Number({ description: \"Maximum heaviest session-context rows to show. Default 40, max 200.\" }),\n\t\t\t\t\t),\n\t\t\t\t\tminTokens: Type.Optional(\n\t\t\t\t\t\tType.Number({\n\t\t\t\t\t\t\tdescription: \"Only show session-context rows with at least this many estimated tokens.\",\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\tquery: Type.Optional(\n\t\t\t\t\t\tType.String({ description: \"Case-insensitive filter over row label and preview.\" }),\n\t\t\t\t\t),\n\t\t\t\t\tincludePreviews: Type.Optional(\n\t\t\t\t\t\tType.Boolean({ description: \"Include bounded row previews. Defaults true.\" }),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\t{ additionalProperties: false },\n\t\t\t),\n\t\t\tasync execute(_toolCallId, params: ContextAuditParams, _signal, _onUpdate, ctx) {\n\t\t\t\tconst maxItems = Math.max(1, Math.min(MAX_MAX_ITEMS, Math.floor(params.maxItems ?? DEFAULT_MAX_ITEMS)));\n\t\t\t\tconst minTokens = Math.max(0, Math.floor(params.minTokens ?? 0));\n\t\t\t\tconst includePreviews = params.includePreviews !== false;\n\t\t\t\tconst query = params.query?.trim().toLowerCase();\n\n\t\t\t\tconst branch = ctx.sessionManager.getBranch();\n\t\t\t\tconst rows = activeContextRows(branch);\n\t\t\t\tconst activeMessages = activeContextMessages(branch);\n\t\t\t\tconst contextGcReport = getContextGcReport?.(activeMessages);\n\t\t\t\tconst contextUsage = ctx.getContextUsage();\n\t\t\t\tconst systemPrompt = ctx.getSystemPrompt?.() || \"\";\n\t\t\t\tconst activeTools = new Set(getActiveTools());\n\t\t\t\tconst allTools = getAllTools();\n\t\t\t\tconst activeToolInfos = allTools.filter((tool) => activeTools.has(tool.name));\n\t\t\t\tconst systemTokens = estimateTextTokens(systemPrompt);\n\t\t\t\tconst toolSchemaChars = JSON.stringify(\n\t\t\t\t\tactiveToolInfos.map((tool) => ({\n\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\tdescription: tool.description,\n\t\t\t\t\t\tparameters: tool.parameters,\n\t\t\t\t\t\tpromptGuidelines: tool.promptGuidelines,\n\t\t\t\t\t})),\n\t\t\t\t).length;\n\t\t\t\tconst toolSchemaTokens = Math.ceil(toolSchemaChars / 4);\n\t\t\t\tconst rowTokenSum = rows.reduce((sum, row) => sum + row.tokens, 0);\n\t\t\t\tconst effectiveRowTokenSum = Math.max(0, rowTokenSum - (contextGcReport?.savedTokens ?? 0));\n\t\t\t\tconst usageText = contextUsage\n\t\t\t\t\t? contextUsage.tokens === null || contextUsage.percent === null\n\t\t\t\t\t\t? `provider usage: unknown/${contextUsage.contextWindow} tokens (usually right after compaction)`\n\t\t\t\t\t\t: `provider usage: ${contextUsage.tokens}/${contextUsage.contextWindow} tokens (${contextUsage.percent.toFixed(1)}%)`\n\t\t\t\t\t: \"provider usage: unavailable (no active model/context window)\";\n\t\t\t\tconst providerTokens = contextUsage?.tokens ?? null;\n\t\t\t\tconst unattributed =\n\t\t\t\t\tproviderTokens === null\n\t\t\t\t\t\t? null\n\t\t\t\t\t\t: Math.max(0, providerTokens - systemTokens - toolSchemaTokens - rowTokenSum);\n\n\t\t\t\tlet filtered = rows.filter((row) => row.tokens >= minTokens);\n\t\t\t\tif (query) {\n\t\t\t\t\tfiltered = filtered.filter((row) => `${row.label}\\n${row.preview}`.toLowerCase().includes(query));\n\t\t\t\t}\n\t\t\t\tconst heaviest = [...filtered].sort((a, b) => b.tokens - a.tokens).slice(0, maxItems);\n\t\t\t\tconst groupLines = groupRows(rows)\n\t\t\t\t\t.slice(0, 12)\n\t\t\t\t\t.map(([label, group]) => `- ${label}: ${group.tokens} est tok across ${group.count} row(s)`);\n\t\t\t\tconst rowLines = heaviest.map((row, index) => {\n\t\t\t\t\tconst base = `${index + 1}. ${row.tokens} est tok · ${row.label} · ${row.entryId ?? \"no-entry\"}`;\n\t\t\t\t\treturn includePreviews\n\t\t\t\t\t\t? `${base}\\n ${cap(row.preview, MAX_PREVIEW_CHARS) || \"(no text preview)\"}`\n\t\t\t\t\t\t: base;\n\t\t\t\t});\n\n\t\t\t\tconst lines = [\n\t\t\t\t\t\"Context audit\",\n\t\t\t\t\tusageText,\n\t\t\t\t\t`active branch rows: ${rows.length}; session row estimate: ${rowTokenSum} tokens`,\n\t\t\t\t\tcontextGcReport\n\t\t\t\t\t\t? `Context GC estimate: ${contextGcReport.savedTokens} tokens saved by packing ${contextGcReport.packedCount} stale row(s); effective session row estimate: ${effectiveRowTokenSum} tokens`\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\t`system prompt estimate: ${systemTokens} tokens (${systemPrompt.length} chars)`,\n\t\t\t\t\t`active tool schema estimate: ${toolSchemaTokens} tokens across ${activeToolInfos.length} active tool(s)`,\n\t\t\t\t\tunattributed === null\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: `provider-reported remainder not mapped by chars/4 rows: ${unattributed} tokens`,\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"Largest groups:\",\n\t\t\t\t\t...(groupLines.length ? groupLines : [\"- none\"]),\n\t\t\t\t\t\"\",\n\t\t\t\t\t`Heaviest rows${query ? ` matching ${JSON.stringify(params.query)}` : \"\"}:`,\n\t\t\t\t\t...(rowLines.length ? rowLines : [\"- none\"]),\n\t\t\t\t].filter((line): line is string => line !== undefined);\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tcontextUsage,\n\t\t\t\t\t\tsystemPrompt: {\n\t\t\t\t\t\t\tchars: systemPrompt.length,\n\t\t\t\t\t\t\testimatedTokens: systemTokens,\n\t\t\t\t\t\t\tpreview: cap(systemPrompt, MAX_PREVIEW_CHARS),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tactiveTools: activeToolInfos.map((tool) => tool.name),\n\t\t\t\t\t\ttoolSchemaEstimate: { chars: toolSchemaChars, estimatedTokens: toolSchemaTokens },\n\t\t\t\t\t\trowTokenSum,\n\t\t\t\t\t\teffectiveRowTokenSum,\n\t\t\t\t\t\tcontextGc: contextGcReport,\n\t\t\t\t\t\trows,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"builtin.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/builtin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAG9D,OAAO,KAAK,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,kCAAkC,CAAC;AAChH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAGxD,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAiN3D,wBAAgB,oCAAoC,CACnD,cAAc,EAAE,MAAM,MAAM,EAAE,EAC9B,WAAW,EAAE,MAAM,QAAQ,EAAE,EAC7B,kBAAkB,CAAC,EAAE,CAAC,QAAQ,EAAE,YAAY,EAAE,KAAK,eAAe,EAClE,oBAAoB,CAAC,EAAE,MAAM;IAC5B,SAAS,EAAE,0BAA0B,CAAC;IACtC,eAAe,EAAE,2BAA2B,CAAC;CAC7C,GACC,cAAc,EAAE,CAsIlB","sourcesContent":["import type { AgentMessage } from \"@caupulican/pi-agent-core\";\nimport { Type } from \"typebox\";\nimport { estimateTokens } from \"../compaction/compaction.ts\";\nimport type { MemoryPromptInclusionReport, MemoryRetrievalDiagnostics } from \"../context/memory-diagnostics.ts\";\nimport type { ContextGcReport } from \"../context-gc.ts\";\nimport { createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport type { CompactionEntry, SessionEntry } from \"../session-manager.ts\";\nimport type { ToolDefinition, ToolInfo } from \"./types.ts\";\n\ntype ContextAuditParams = {\n\tmaxItems?: number;\n\tminTokens?: number;\n\tquery?: string;\n\tincludePreviews?: boolean;\n};\n\ntype AuditRow = {\n\tkind: string;\n\trole?: string;\n\tentryId?: string;\n\ttimestamp?: string;\n\ttokens: number;\n\tchars: number;\n\tlabel: string;\n\tpreview: string;\n};\n\nconst DEFAULT_MAX_ITEMS = 40;\nconst MAX_MAX_ITEMS = 200;\nconst DEFAULT_PREVIEW_CHARS = 220;\nconst MAX_PREVIEW_CHARS = 600;\n\nfunction estimateTextTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\nfunction cap(text: string, limit = DEFAULT_PREVIEW_CHARS): string {\n\tconst compact = text.replace(/\\s+/g, \" \").trim();\n\treturn compact.length > limit ? `${compact.slice(0, Math.max(0, limit - 1))}…` : compact;\n}\n\nfunction contentText(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return \"\";\n\treturn content\n\t\t.map((part) => {\n\t\t\tif (!part || typeof part !== \"object\") return \"\";\n\t\t\tconst typed = part as { type?: string; text?: string; thinking?: string; name?: string; arguments?: unknown };\n\t\t\tif (typed.type === \"text\") return typed.text || \"\";\n\t\t\tif (typed.type === \"thinking\") return `[thinking ${typed.thinking?.length ?? 0} chars]`;\n\t\t\tif (typed.type === \"toolCall\")\n\t\t\t\treturn `[toolCall ${typed.name || \"unknown\"} ${JSON.stringify(typed.arguments ?? {})}]`;\n\t\t\tif (typed.type === \"image\") return \"[image]\";\n\t\t\treturn \"\";\n\t\t})\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\");\n}\n\nfunction messagePreview(message: AgentMessage): string {\n\tswitch (message.role) {\n\t\tcase \"assistant\":\n\t\tcase \"user\":\n\t\tcase \"toolResult\":\n\t\tcase \"custom\":\n\t\t\treturn contentText((message as { content?: unknown }).content);\n\t\tcase \"bashExecution\":\n\t\t\treturn `Ran ${message.command}\\n${message.output}`;\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\":\n\t\t\treturn message.summary;\n\t\tdefault:\n\t\t\treturn \"\";\n\t}\n}\n\nfunction messageLabel(message: AgentMessage): string {\n\tif (message.role === \"assistant\") {\n\t\tconst toolCalls = message.content.filter((part) => part.type === \"toolCall\").length;\n\t\treturn toolCalls > 0 ? `assistant (${toolCalls} tool call${toolCalls === 1 ? \"\" : \"s\"})` : \"assistant\";\n\t}\n\tif (message.role === \"toolResult\") return `tool result: ${message.toolName}`;\n\tif (message.role === \"custom\") return `custom: ${message.customType}`;\n\tif (message.role === \"bashExecution\") return \"bash execution\";\n\tif (message.role === \"branchSummary\") return \"branch summary\";\n\tif (message.role === \"compactionSummary\") return \"compaction summary\";\n\treturn message.role;\n}\n\nfunction addRow(rows: AuditRow[], entry: SessionEntry, message: AgentMessage, kindOverride?: string) {\n\tconst preview = messagePreview(message);\n\trows.push({\n\t\tkind: kindOverride || entry.type,\n\t\trole: message.role,\n\t\tentryId: entry.id,\n\t\ttimestamp: entry.timestamp,\n\t\ttokens: estimateTokens(message),\n\t\tchars: preview.length,\n\t\tlabel: messageLabel(message),\n\t\tpreview: cap(preview),\n\t});\n}\n\nfunction messageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") return entry.message;\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);\n\t}\n\tif (entry.type === \"branch_summary\" && entry.summary) {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nfunction latestCompaction(entries: SessionEntry[]): CompactionEntry | undefined {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (entry?.type === \"compaction\") return entry;\n\t}\n\treturn undefined;\n}\n\nfunction activeContextMessages(entries: SessionEntry[]): AgentMessage[] {\n\tconst messages: AgentMessage[] = [];\n\tconst compaction = latestCompaction(entries);\n\tif (!compaction) {\n\t\tfor (const entry of entries) {\n\t\t\tconst message = messageFromEntry(entry);\n\t\t\tif (message) messages.push(message);\n\t\t}\n\t\treturn messages;\n\t}\n\n\tmessages.push(createCompactionSummaryMessage(compaction.summary, compaction.tokensBefore, compaction.timestamp));\n\tconst compactionIndex = entries.findIndex((entry) => entry.id === compaction.id);\n\tlet foundFirstKept = false;\n\tfor (let index = 0; index < compactionIndex; index++) {\n\t\tconst entry = entries[index];\n\t\tif (entry.id === compaction.firstKeptEntryId) foundFirstKept = true;\n\t\tif (!foundFirstKept) continue;\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) messages.push(message);\n\t}\n\tfor (let index = compactionIndex + 1; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) messages.push(message);\n\t}\n\treturn messages;\n}\n\nfunction activeContextRows(entries: SessionEntry[]): AuditRow[] {\n\tconst rows: AuditRow[] = [];\n\tconst compaction = latestCompaction(entries);\n\tif (!compaction) {\n\t\tfor (const entry of entries) {\n\t\t\tconst message = messageFromEntry(entry);\n\t\t\tif (message) addRow(rows, entry, message);\n\t\t}\n\t\treturn rows;\n\t}\n\n\tconst compactionMessage = createCompactionSummaryMessage(\n\t\tcompaction.summary,\n\t\tcompaction.tokensBefore,\n\t\tcompaction.timestamp,\n\t);\n\taddRow(rows, compaction, compactionMessage, \"compaction\");\n\n\tconst compactionIndex = entries.findIndex((entry) => entry.id === compaction.id);\n\tlet foundFirstKept = false;\n\tfor (let index = 0; index < compactionIndex; index++) {\n\t\tconst entry = entries[index];\n\t\tif (entry.id === compaction.firstKeptEntryId) foundFirstKept = true;\n\t\tif (!foundFirstKept) continue;\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) addRow(rows, entry, message);\n\t}\n\tfor (let index = compactionIndex + 1; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) addRow(rows, entry, message);\n\t}\n\treturn rows;\n}\n\nfunction groupRows(rows: AuditRow[]): Array<[string, { count: number; tokens: number; chars: number }]> {\n\tconst groups = new Map<string, { count: number; tokens: number; chars: number }>();\n\tfor (const row of rows) {\n\t\tconst key = row.label;\n\t\tconst current = groups.get(key) ?? { count: 0, tokens: 0, chars: 0 };\n\t\tcurrent.count += 1;\n\t\tcurrent.tokens += row.tokens;\n\t\tcurrent.chars += row.chars;\n\t\tgroups.set(key, current);\n\t}\n\treturn [...groups.entries()].sort((a, b) => b[1].tokens - a[1].tokens);\n}\n\n/** Bounded, deterministic summary lines for the memory-retrieval/prompt-inclusion diagnostic (safe metadata only, no content). */\nfunction formatMemoryRetrievalLine(retrieval: MemoryRetrievalDiagnostics): string {\n\treturn `Memory retrieval: ${retrieval.enabled ? `enabled (max ${retrieval.maxResults} results)` : \"disabled\"}`;\n}\n\nfunction formatMemoryProviderLines(retrieval: MemoryRetrievalDiagnostics): string[] {\n\treturn retrieval.providerReports.map((providerReport) => {\n\t\tconst rejection =\n\t\t\tproviderReport.rejectionReasons.length > 0 ? `; rejected: ${providerReport.rejectionReasons.join(\", \")}` : \"\";\n\t\treturn ` provider ${providerReport.providerId}: ${providerReport.status} (${providerReport.resultCount} result(s)${rejection})`;\n\t});\n}\n\nfunction formatMemoryPromptInclusionLine(promptInclusion: MemoryPromptInclusionReport): string {\n\treturn `Prompt inclusion: ${promptInclusion.status} (${promptInclusion.includedCount} included, ${promptInclusion.omittedCount} omitted, ${promptInclusion.blockChars} chars)`;\n}\n\nexport function createCoreDiagnosticsToolDefinitions(\n\tgetActiveTools: () => string[],\n\tgetAllTools: () => ToolInfo[],\n\tgetContextGcReport?: (messages: AgentMessage[]) => ContextGcReport,\n\tgetMemoryDiagnostics?: () => {\n\t\tretrieval: MemoryRetrievalDiagnostics;\n\t\tpromptInclusion: MemoryPromptInclusionReport;\n\t},\n): ToolDefinition[] {\n\treturn [\n\t\t{\n\t\t\tname: \"context_audit\",\n\t\t\tlabel: \"Context Audit\",\n\t\t\tdescription:\n\t\t\t\t\"Audit the current provider-visible context composition: model window usage, system prompt estimate, active tool schema estimate, active session message rows, and heaviest context contributors.\",\n\t\t\tpromptSnippet: \"Audit current loaded context composition before optimizing context usage.\",\n\t\t\tpromptGuidelines: [\n\t\t\t\t\"Use context_audit when the user asks what is consuming context, why the footer shows a high percentage, or which messages/tools/system prompt content are loaded.\",\n\t\t\t\t\"Keep output bounded; use query/minTokens/maxItems to narrow rather than dumping full context.\",\n\t\t\t\t\"Treat token counts as estimates except provider usage from ctx.getContextUsage, which is still model/provider dependent.\",\n\t\t\t],\n\t\t\tparameters: Type.Object(\n\t\t\t\t{\n\t\t\t\t\tmaxItems: Type.Optional(\n\t\t\t\t\t\tType.Number({ description: \"Maximum heaviest session-context rows to show. Default 40, max 200.\" }),\n\t\t\t\t\t),\n\t\t\t\t\tminTokens: Type.Optional(\n\t\t\t\t\t\tType.Number({\n\t\t\t\t\t\t\tdescription: \"Only show session-context rows with at least this many estimated tokens.\",\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\tquery: Type.Optional(\n\t\t\t\t\t\tType.String({ description: \"Case-insensitive filter over row label and preview.\" }),\n\t\t\t\t\t),\n\t\t\t\t\tincludePreviews: Type.Optional(\n\t\t\t\t\t\tType.Boolean({ description: \"Include bounded row previews. Defaults true.\" }),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\t{ additionalProperties: false },\n\t\t\t),\n\t\t\tasync execute(_toolCallId, params: ContextAuditParams, _signal, _onUpdate, ctx) {\n\t\t\t\tconst maxItems = Math.max(1, Math.min(MAX_MAX_ITEMS, Math.floor(params.maxItems ?? DEFAULT_MAX_ITEMS)));\n\t\t\t\tconst minTokens = Math.max(0, Math.floor(params.minTokens ?? 0));\n\t\t\t\tconst includePreviews = params.includePreviews !== false;\n\t\t\t\tconst query = params.query?.trim().toLowerCase();\n\n\t\t\t\tconst branch = ctx.sessionManager.getBranch();\n\t\t\t\tconst rows = activeContextRows(branch);\n\t\t\t\tconst activeMessages = activeContextMessages(branch);\n\t\t\t\tconst contextGcReport = getContextGcReport?.(activeMessages);\n\t\t\t\tconst memoryDiagnostics = getMemoryDiagnostics?.();\n\t\t\t\tconst contextUsage = ctx.getContextUsage();\n\t\t\t\tconst systemPrompt = ctx.getSystemPrompt?.() || \"\";\n\t\t\t\tconst activeTools = new Set(getActiveTools());\n\t\t\t\tconst allTools = getAllTools();\n\t\t\t\tconst activeToolInfos = allTools.filter((tool) => activeTools.has(tool.name));\n\t\t\t\tconst systemTokens = estimateTextTokens(systemPrompt);\n\t\t\t\tconst toolSchemaChars = JSON.stringify(\n\t\t\t\t\tactiveToolInfos.map((tool) => ({\n\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\tdescription: tool.description,\n\t\t\t\t\t\tparameters: tool.parameters,\n\t\t\t\t\t\tpromptGuidelines: tool.promptGuidelines,\n\t\t\t\t\t})),\n\t\t\t\t).length;\n\t\t\t\tconst toolSchemaTokens = Math.ceil(toolSchemaChars / 4);\n\t\t\t\tconst rowTokenSum = rows.reduce((sum, row) => sum + row.tokens, 0);\n\t\t\t\tconst effectiveRowTokenSum = Math.max(0, rowTokenSum - (contextGcReport?.savedTokens ?? 0));\n\t\t\t\tconst usageText = contextUsage\n\t\t\t\t\t? contextUsage.tokens === null || contextUsage.percent === null\n\t\t\t\t\t\t? `provider usage: unknown/${contextUsage.contextWindow} tokens (usually right after compaction)`\n\t\t\t\t\t\t: `provider usage: ${contextUsage.tokens}/${contextUsage.contextWindow} tokens (${contextUsage.percent.toFixed(1)}%)`\n\t\t\t\t\t: \"provider usage: unavailable (no active model/context window)\";\n\t\t\t\tconst providerTokens = contextUsage?.tokens ?? null;\n\t\t\t\tconst unattributed =\n\t\t\t\t\tproviderTokens === null\n\t\t\t\t\t\t? null\n\t\t\t\t\t\t: Math.max(0, providerTokens - systemTokens - toolSchemaTokens - rowTokenSum);\n\n\t\t\t\tlet filtered = rows.filter((row) => row.tokens >= minTokens);\n\t\t\t\tif (query) {\n\t\t\t\t\tfiltered = filtered.filter((row) => `${row.label}\\n${row.preview}`.toLowerCase().includes(query));\n\t\t\t\t}\n\t\t\t\tconst heaviest = [...filtered].sort((a, b) => b.tokens - a.tokens).slice(0, maxItems);\n\t\t\t\tconst groupLines = groupRows(rows)\n\t\t\t\t\t.slice(0, 12)\n\t\t\t\t\t.map(([label, group]) => `- ${label}: ${group.tokens} est tok across ${group.count} row(s)`);\n\t\t\t\tconst rowLines = heaviest.map((row, index) => {\n\t\t\t\t\tconst base = `${index + 1}. ${row.tokens} est tok · ${row.label} · ${row.entryId ?? \"no-entry\"}`;\n\t\t\t\t\treturn includePreviews\n\t\t\t\t\t\t? `${base}\\n ${cap(row.preview, MAX_PREVIEW_CHARS) || \"(no text preview)\"}`\n\t\t\t\t\t\t: base;\n\t\t\t\t});\n\n\t\t\t\tconst lines = [\n\t\t\t\t\t\"Context audit\",\n\t\t\t\t\tusageText,\n\t\t\t\t\t`active branch rows: ${rows.length}; session row estimate: ${rowTokenSum} tokens`,\n\t\t\t\t\tcontextGcReport\n\t\t\t\t\t\t? `Context GC estimate: ${contextGcReport.savedTokens} tokens saved by packing ${contextGcReport.packedCount} stale row(s); effective session row estimate: ${effectiveRowTokenSum} tokens`\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\t`system prompt estimate: ${systemTokens} tokens (${systemPrompt.length} chars)`,\n\t\t\t\t\t`active tool schema estimate: ${toolSchemaTokens} tokens across ${activeToolInfos.length} active tool(s)`,\n\t\t\t\t\tunattributed === null\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: `provider-reported remainder not mapped by chars/4 rows: ${unattributed} tokens`,\n\t\t\t\t\t...(memoryDiagnostics\n\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\tformatMemoryRetrievalLine(memoryDiagnostics.retrieval),\n\t\t\t\t\t\t\t\t...formatMemoryProviderLines(memoryDiagnostics.retrieval),\n\t\t\t\t\t\t\t\tformatMemoryPromptInclusionLine(memoryDiagnostics.promptInclusion),\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t: []),\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"Largest groups:\",\n\t\t\t\t\t...(groupLines.length ? groupLines : [\"- none\"]),\n\t\t\t\t\t\"\",\n\t\t\t\t\t`Heaviest rows${query ? ` matching ${JSON.stringify(params.query)}` : \"\"}:`,\n\t\t\t\t\t...(rowLines.length ? rowLines : [\"- none\"]),\n\t\t\t\t].filter((line): line is string => line !== undefined);\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tcontextUsage,\n\t\t\t\t\t\tsystemPrompt: {\n\t\t\t\t\t\t\tchars: systemPrompt.length,\n\t\t\t\t\t\t\testimatedTokens: systemTokens,\n\t\t\t\t\t\t\tpreview: cap(systemPrompt, MAX_PREVIEW_CHARS),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tactiveTools: activeToolInfos.map((tool) => tool.name),\n\t\t\t\t\t\ttoolSchemaEstimate: { chars: toolSchemaChars, estimatedTokens: toolSchemaTokens },\n\t\t\t\t\t\trowTokenSum,\n\t\t\t\t\t\teffectiveRowTokenSum,\n\t\t\t\t\t\tcontextGc: contextGcReport,\n\t\t\t\t\t\trows,\n\t\t\t\t\t\tmemory: memoryDiagnostics,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t];\n}\n"]}
|
|
@@ -177,7 +177,20 @@ function groupRows(rows) {
|
|
|
177
177
|
}
|
|
178
178
|
return [...groups.entries()].sort((a, b) => b[1].tokens - a[1].tokens);
|
|
179
179
|
}
|
|
180
|
-
|
|
180
|
+
/** Bounded, deterministic summary lines for the memory-retrieval/prompt-inclusion diagnostic (safe metadata only, no content). */
|
|
181
|
+
function formatMemoryRetrievalLine(retrieval) {
|
|
182
|
+
return `Memory retrieval: ${retrieval.enabled ? `enabled (max ${retrieval.maxResults} results)` : "disabled"}`;
|
|
183
|
+
}
|
|
184
|
+
function formatMemoryProviderLines(retrieval) {
|
|
185
|
+
return retrieval.providerReports.map((providerReport) => {
|
|
186
|
+
const rejection = providerReport.rejectionReasons.length > 0 ? `; rejected: ${providerReport.rejectionReasons.join(", ")}` : "";
|
|
187
|
+
return ` provider ${providerReport.providerId}: ${providerReport.status} (${providerReport.resultCount} result(s)${rejection})`;
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
function formatMemoryPromptInclusionLine(promptInclusion) {
|
|
191
|
+
return `Prompt inclusion: ${promptInclusion.status} (${promptInclusion.includedCount} included, ${promptInclusion.omittedCount} omitted, ${promptInclusion.blockChars} chars)`;
|
|
192
|
+
}
|
|
193
|
+
export function createCoreDiagnosticsToolDefinitions(getActiveTools, getAllTools, getContextGcReport, getMemoryDiagnostics) {
|
|
181
194
|
return [
|
|
182
195
|
{
|
|
183
196
|
name: "context_audit",
|
|
@@ -206,6 +219,7 @@ export function createCoreDiagnosticsToolDefinitions(getActiveTools, getAllTools
|
|
|
206
219
|
const rows = activeContextRows(branch);
|
|
207
220
|
const activeMessages = activeContextMessages(branch);
|
|
208
221
|
const contextGcReport = getContextGcReport?.(activeMessages);
|
|
222
|
+
const memoryDiagnostics = getMemoryDiagnostics?.();
|
|
209
223
|
const contextUsage = ctx.getContextUsage();
|
|
210
224
|
const systemPrompt = ctx.getSystemPrompt?.() || "";
|
|
211
225
|
const activeTools = new Set(getActiveTools());
|
|
@@ -256,6 +270,13 @@ export function createCoreDiagnosticsToolDefinitions(getActiveTools, getAllTools
|
|
|
256
270
|
unattributed === null
|
|
257
271
|
? undefined
|
|
258
272
|
: `provider-reported remainder not mapped by chars/4 rows: ${unattributed} tokens`,
|
|
273
|
+
...(memoryDiagnostics
|
|
274
|
+
? [
|
|
275
|
+
formatMemoryRetrievalLine(memoryDiagnostics.retrieval),
|
|
276
|
+
...formatMemoryProviderLines(memoryDiagnostics.retrieval),
|
|
277
|
+
formatMemoryPromptInclusionLine(memoryDiagnostics.promptInclusion),
|
|
278
|
+
]
|
|
279
|
+
: []),
|
|
259
280
|
"",
|
|
260
281
|
"Largest groups:",
|
|
261
282
|
...(groupLines.length ? groupLines : ["- none"]),
|
|
@@ -278,6 +299,7 @@ export function createCoreDiagnosticsToolDefinitions(getActiveTools, getAllTools
|
|
|
278
299
|
effectiveRowTokenSum,
|
|
279
300
|
contextGc: contextGcReport,
|
|
280
301
|
rows,
|
|
302
|
+
memory: memoryDiagnostics,
|
|
281
303
|
},
|
|
282
304
|
};
|
|
283
305
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builtin.js","sourceRoot":"","sources":["../../../src/core/extensions/builtin.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAE7D,OAAO,EAAE,0BAA0B,EAAE,8BAA8B,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAsBjH,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAC7B,MAAM,aAAa,GAAG,GAAG,CAAC;AAC1B,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAClC,MAAM,iBAAiB,GAA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AAC,MAAM;4BAC1B,eAAe,EAAE,YAAY;4BAC7B,OAAO,EAAE,GAAG,CAAC,YAAY,EAAE,iBAAiB,CAAC;yBAC7C;wBACD,WAAW,EAAE,eAAe,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;wBACrD,kBAAkB,EAAE,EAAE,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,gBAAgB,EAAE;wBACjF,WAAW;wBACX,oBAAoB;wBACpB,SAAS,EAAE,eAAe;wBAC1B,IAAI;qBACJ;iBACD,CAAC;YAAA,CACF;SACD;KACD,CAAC;AAAA,CACF","sourcesContent":["import type { AgentMessage } from \"@caupulican/pi-agent-core\";\nimport { Type } from \"typebox\";\nimport { estimateTokens } from \"../compaction/compaction.ts\";\nimport type { ContextGcReport } from \"../context-gc.ts\";\nimport { createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport type { CompactionEntry, SessionEntry } from \"../session-manager.ts\";\nimport type { ToolDefinition, ToolInfo } from \"./types.ts\";\n\ntype ContextAuditParams = {\n\tmaxItems?: number;\n\tminTokens?: number;\n\tquery?: string;\n\tincludePreviews?: boolean;\n};\n\ntype AuditRow = {\n\tkind: string;\n\trole?: string;\n\tentryId?: string;\n\ttimestamp?: string;\n\ttokens: number;\n\tchars: number;\n\tlabel: string;\n\tpreview: string;\n};\n\nconst DEFAULT_MAX_ITEMS = 40;\nconst MAX_MAX_ITEMS = 200;\nconst DEFAULT_PREVIEW_CHARS = 220;\nconst MAX_PREVIEW_CHARS = 600;\n\nfunction estimateTextTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\nfunction cap(text: string, limit = DEFAULT_PREVIEW_CHARS): string {\n\tconst compact = text.replace(/\\s+/g, \" \").trim();\n\treturn compact.length > limit ? `${compact.slice(0, Math.max(0, limit - 1))}…` : compact;\n}\n\nfunction contentText(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return \"\";\n\treturn content\n\t\t.map((part) => {\n\t\t\tif (!part || typeof part !== \"object\") return \"\";\n\t\t\tconst typed = part as { type?: string; text?: string; thinking?: string; name?: string; arguments?: unknown };\n\t\t\tif (typed.type === \"text\") return typed.text || \"\";\n\t\t\tif (typed.type === \"thinking\") return `[thinking ${typed.thinking?.length ?? 0} chars]`;\n\t\t\tif (typed.type === \"toolCall\")\n\t\t\t\treturn `[toolCall ${typed.name || \"unknown\"} ${JSON.stringify(typed.arguments ?? {})}]`;\n\t\t\tif (typed.type === \"image\") return \"[image]\";\n\t\t\treturn \"\";\n\t\t})\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\");\n}\n\nfunction messagePreview(message: AgentMessage): string {\n\tswitch (message.role) {\n\t\tcase \"assistant\":\n\t\tcase \"user\":\n\t\tcase \"toolResult\":\n\t\tcase \"custom\":\n\t\t\treturn contentText((message as { content?: unknown }).content);\n\t\tcase \"bashExecution\":\n\t\t\treturn `Ran ${message.command}\\n${message.output}`;\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\":\n\t\t\treturn message.summary;\n\t\tdefault:\n\t\t\treturn \"\";\n\t}\n}\n\nfunction messageLabel(message: AgentMessage): string {\n\tif (message.role === \"assistant\") {\n\t\tconst toolCalls = message.content.filter((part) => part.type === \"toolCall\").length;\n\t\treturn toolCalls > 0 ? `assistant (${toolCalls} tool call${toolCalls === 1 ? \"\" : \"s\"})` : \"assistant\";\n\t}\n\tif (message.role === \"toolResult\") return `tool result: ${message.toolName}`;\n\tif (message.role === \"custom\") return `custom: ${message.customType}`;\n\tif (message.role === \"bashExecution\") return \"bash execution\";\n\tif (message.role === \"branchSummary\") return \"branch summary\";\n\tif (message.role === \"compactionSummary\") return \"compaction summary\";\n\treturn message.role;\n}\n\nfunction addRow(rows: AuditRow[], entry: SessionEntry, message: AgentMessage, kindOverride?: string) {\n\tconst preview = messagePreview(message);\n\trows.push({\n\t\tkind: kindOverride || entry.type,\n\t\trole: message.role,\n\t\tentryId: entry.id,\n\t\ttimestamp: entry.timestamp,\n\t\ttokens: estimateTokens(message),\n\t\tchars: preview.length,\n\t\tlabel: messageLabel(message),\n\t\tpreview: cap(preview),\n\t});\n}\n\nfunction messageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") return entry.message;\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);\n\t}\n\tif (entry.type === \"branch_summary\" && entry.summary) {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nfunction latestCompaction(entries: SessionEntry[]): CompactionEntry | undefined {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (entry?.type === \"compaction\") return entry;\n\t}\n\treturn undefined;\n}\n\nfunction activeContextMessages(entries: SessionEntry[]): AgentMessage[] {\n\tconst messages: AgentMessage[] = [];\n\tconst compaction = latestCompaction(entries);\n\tif (!compaction) {\n\t\tfor (const entry of entries) {\n\t\t\tconst message = messageFromEntry(entry);\n\t\t\tif (message) messages.push(message);\n\t\t}\n\t\treturn messages;\n\t}\n\n\tmessages.push(createCompactionSummaryMessage(compaction.summary, compaction.tokensBefore, compaction.timestamp));\n\tconst compactionIndex = entries.findIndex((entry) => entry.id === compaction.id);\n\tlet foundFirstKept = false;\n\tfor (let index = 0; index < compactionIndex; index++) {\n\t\tconst entry = entries[index];\n\t\tif (entry.id === compaction.firstKeptEntryId) foundFirstKept = true;\n\t\tif (!foundFirstKept) continue;\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) messages.push(message);\n\t}\n\tfor (let index = compactionIndex + 1; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) messages.push(message);\n\t}\n\treturn messages;\n}\n\nfunction activeContextRows(entries: SessionEntry[]): AuditRow[] {\n\tconst rows: AuditRow[] = [];\n\tconst compaction = latestCompaction(entries);\n\tif (!compaction) {\n\t\tfor (const entry of entries) {\n\t\t\tconst message = messageFromEntry(entry);\n\t\t\tif (message) addRow(rows, entry, message);\n\t\t}\n\t\treturn rows;\n\t}\n\n\tconst compactionMessage = createCompactionSummaryMessage(\n\t\tcompaction.summary,\n\t\tcompaction.tokensBefore,\n\t\tcompaction.timestamp,\n\t);\n\taddRow(rows, compaction, compactionMessage, \"compaction\");\n\n\tconst compactionIndex = entries.findIndex((entry) => entry.id === compaction.id);\n\tlet foundFirstKept = false;\n\tfor (let index = 0; index < compactionIndex; index++) {\n\t\tconst entry = entries[index];\n\t\tif (entry.id === compaction.firstKeptEntryId) foundFirstKept = true;\n\t\tif (!foundFirstKept) continue;\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) addRow(rows, entry, message);\n\t}\n\tfor (let index = compactionIndex + 1; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) addRow(rows, entry, message);\n\t}\n\treturn rows;\n}\n\nfunction groupRows(rows: AuditRow[]): Array<[string, { count: number; tokens: number; chars: number }]> {\n\tconst groups = new Map<string, { count: number; tokens: number; chars: number }>();\n\tfor (const row of rows) {\n\t\tconst key = row.label;\n\t\tconst current = groups.get(key) ?? { count: 0, tokens: 0, chars: 0 };\n\t\tcurrent.count += 1;\n\t\tcurrent.tokens += row.tokens;\n\t\tcurrent.chars += row.chars;\n\t\tgroups.set(key, current);\n\t}\n\treturn [...groups.entries()].sort((a, b) => b[1].tokens - a[1].tokens);\n}\n\nexport function createCoreDiagnosticsToolDefinitions(\n\tgetActiveTools: () => string[],\n\tgetAllTools: () => ToolInfo[],\n\tgetContextGcReport?: (messages: AgentMessage[]) => ContextGcReport,\n): ToolDefinition[] {\n\treturn [\n\t\t{\n\t\t\tname: \"context_audit\",\n\t\t\tlabel: \"Context Audit\",\n\t\t\tdescription:\n\t\t\t\t\"Audit the current provider-visible context composition: model window usage, system prompt estimate, active tool schema estimate, active session message rows, and heaviest context contributors.\",\n\t\t\tpromptSnippet: \"Audit current loaded context composition before optimizing context usage.\",\n\t\t\tpromptGuidelines: [\n\t\t\t\t\"Use context_audit when the user asks what is consuming context, why the footer shows a high percentage, or which messages/tools/system prompt content are loaded.\",\n\t\t\t\t\"Keep output bounded; use query/minTokens/maxItems to narrow rather than dumping full context.\",\n\t\t\t\t\"Treat token counts as estimates except provider usage from ctx.getContextUsage, which is still model/provider dependent.\",\n\t\t\t],\n\t\t\tparameters: Type.Object(\n\t\t\t\t{\n\t\t\t\t\tmaxItems: Type.Optional(\n\t\t\t\t\t\tType.Number({ description: \"Maximum heaviest session-context rows to show. Default 40, max 200.\" }),\n\t\t\t\t\t),\n\t\t\t\t\tminTokens: Type.Optional(\n\t\t\t\t\t\tType.Number({\n\t\t\t\t\t\t\tdescription: \"Only show session-context rows with at least this many estimated tokens.\",\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\tquery: Type.Optional(\n\t\t\t\t\t\tType.String({ description: \"Case-insensitive filter over row label and preview.\" }),\n\t\t\t\t\t),\n\t\t\t\t\tincludePreviews: Type.Optional(\n\t\t\t\t\t\tType.Boolean({ description: \"Include bounded row previews. Defaults true.\" }),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\t{ additionalProperties: false },\n\t\t\t),\n\t\t\tasync execute(_toolCallId, params: ContextAuditParams, _signal, _onUpdate, ctx) {\n\t\t\t\tconst maxItems = Math.max(1, Math.min(MAX_MAX_ITEMS, Math.floor(params.maxItems ?? DEFAULT_MAX_ITEMS)));\n\t\t\t\tconst minTokens = Math.max(0, Math.floor(params.minTokens ?? 0));\n\t\t\t\tconst includePreviews = params.includePreviews !== false;\n\t\t\t\tconst query = params.query?.trim().toLowerCase();\n\n\t\t\t\tconst branch = ctx.sessionManager.getBranch();\n\t\t\t\tconst rows = activeContextRows(branch);\n\t\t\t\tconst activeMessages = activeContextMessages(branch);\n\t\t\t\tconst contextGcReport = getContextGcReport?.(activeMessages);\n\t\t\t\tconst contextUsage = ctx.getContextUsage();\n\t\t\t\tconst systemPrompt = ctx.getSystemPrompt?.() || \"\";\n\t\t\t\tconst activeTools = new Set(getActiveTools());\n\t\t\t\tconst allTools = getAllTools();\n\t\t\t\tconst activeToolInfos = allTools.filter((tool) => activeTools.has(tool.name));\n\t\t\t\tconst systemTokens = estimateTextTokens(systemPrompt);\n\t\t\t\tconst toolSchemaChars = JSON.stringify(\n\t\t\t\t\tactiveToolInfos.map((tool) => ({\n\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\tdescription: tool.description,\n\t\t\t\t\t\tparameters: tool.parameters,\n\t\t\t\t\t\tpromptGuidelines: tool.promptGuidelines,\n\t\t\t\t\t})),\n\t\t\t\t).length;\n\t\t\t\tconst toolSchemaTokens = Math.ceil(toolSchemaChars / 4);\n\t\t\t\tconst rowTokenSum = rows.reduce((sum, row) => sum + row.tokens, 0);\n\t\t\t\tconst effectiveRowTokenSum = Math.max(0, rowTokenSum - (contextGcReport?.savedTokens ?? 0));\n\t\t\t\tconst usageText = contextUsage\n\t\t\t\t\t? contextUsage.tokens === null || contextUsage.percent === null\n\t\t\t\t\t\t? `provider usage: unknown/${contextUsage.contextWindow} tokens (usually right after compaction)`\n\t\t\t\t\t\t: `provider usage: ${contextUsage.tokens}/${contextUsage.contextWindow} tokens (${contextUsage.percent.toFixed(1)}%)`\n\t\t\t\t\t: \"provider usage: unavailable (no active model/context window)\";\n\t\t\t\tconst providerTokens = contextUsage?.tokens ?? null;\n\t\t\t\tconst unattributed =\n\t\t\t\t\tproviderTokens === null\n\t\t\t\t\t\t? null\n\t\t\t\t\t\t: Math.max(0, providerTokens - systemTokens - toolSchemaTokens - rowTokenSum);\n\n\t\t\t\tlet filtered = rows.filter((row) => row.tokens >= minTokens);\n\t\t\t\tif (query) {\n\t\t\t\t\tfiltered = filtered.filter((row) => `${row.label}\\n${row.preview}`.toLowerCase().includes(query));\n\t\t\t\t}\n\t\t\t\tconst heaviest = [...filtered].sort((a, b) => b.tokens - a.tokens).slice(0, maxItems);\n\t\t\t\tconst groupLines = groupRows(rows)\n\t\t\t\t\t.slice(0, 12)\n\t\t\t\t\t.map(([label, group]) => `- ${label}: ${group.tokens} est tok across ${group.count} row(s)`);\n\t\t\t\tconst rowLines = heaviest.map((row, index) => {\n\t\t\t\t\tconst base = `${index + 1}. ${row.tokens} est tok · ${row.label} · ${row.entryId ?? \"no-entry\"}`;\n\t\t\t\t\treturn includePreviews\n\t\t\t\t\t\t? `${base}\\n ${cap(row.preview, MAX_PREVIEW_CHARS) || \"(no text preview)\"}`\n\t\t\t\t\t\t: base;\n\t\t\t\t});\n\n\t\t\t\tconst lines = [\n\t\t\t\t\t\"Context audit\",\n\t\t\t\t\tusageText,\n\t\t\t\t\t`active branch rows: ${rows.length}; session row estimate: ${rowTokenSum} tokens`,\n\t\t\t\t\tcontextGcReport\n\t\t\t\t\t\t? `Context GC estimate: ${contextGcReport.savedTokens} tokens saved by packing ${contextGcReport.packedCount} stale row(s); effective session row estimate: ${effectiveRowTokenSum} tokens`\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\t`system prompt estimate: ${systemTokens} tokens (${systemPrompt.length} chars)`,\n\t\t\t\t\t`active tool schema estimate: ${toolSchemaTokens} tokens across ${activeToolInfos.length} active tool(s)`,\n\t\t\t\t\tunattributed === null\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: `provider-reported remainder not mapped by chars/4 rows: ${unattributed} tokens`,\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"Largest groups:\",\n\t\t\t\t\t...(groupLines.length ? groupLines : [\"- none\"]),\n\t\t\t\t\t\"\",\n\t\t\t\t\t`Heaviest rows${query ? ` matching ${JSON.stringify(params.query)}` : \"\"}:`,\n\t\t\t\t\t...(rowLines.length ? rowLines : [\"- none\"]),\n\t\t\t\t].filter((line): line is string => line !== undefined);\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tcontextUsage,\n\t\t\t\t\t\tsystemPrompt: {\n\t\t\t\t\t\t\tchars: systemPrompt.length,\n\t\t\t\t\t\t\testimatedTokens: systemTokens,\n\t\t\t\t\t\t\tpreview: cap(systemPrompt, MAX_PREVIEW_CHARS),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tactiveTools: activeToolInfos.map((tool) => tool.name),\n\t\t\t\t\t\ttoolSchemaEstimate: { chars: toolSchemaChars, estimatedTokens: toolSchemaTokens },\n\t\t\t\t\t\trowTokenSum,\n\t\t\t\t\t\teffectiveRowTokenSum,\n\t\t\t\t\t\tcontextGc: contextGcReport,\n\t\t\t\t\t\trows,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"builtin.js","sourceRoot":"","sources":["../../../src/core/extensions/builtin.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAG7D,OAAO,EAAE,0BAA0B,EAAE,8BAA8B,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAsBjH,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAC7B,MAAM,aAAa,GAAG,GAAG,CAAC;AAC1B,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAClC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAE9B,SAAS,kBAAkB,CAAC,IAAY,EAAU;IACjD,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AAAA,CAClC;AAED,SAAS,GAAG,CAAC,IAAY,EAAE,KAAK,GAAG,qBAAqB,EAAU;IACjE,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;IACjD,OAAO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import type { AgentMessage } from \"@caupulican/pi-agent-core\";\nimport { Type } from \"typebox\";\nimport { estimateTokens } from \"../compaction/compaction.ts\";\nimport type { MemoryPromptInclusionReport, MemoryRetrievalDiagnostics } from \"../context/memory-diagnostics.ts\";\nimport type { ContextGcReport } from \"../context-gc.ts\";\nimport { createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport type { CompactionEntry, SessionEntry } from \"../session-manager.ts\";\nimport type { ToolDefinition, ToolInfo } from \"./types.ts\";\n\ntype ContextAuditParams = {\n\tmaxItems?: number;\n\tminTokens?: number;\n\tquery?: string;\n\tincludePreviews?: boolean;\n};\n\ntype AuditRow = {\n\tkind: string;\n\trole?: string;\n\tentryId?: string;\n\ttimestamp?: string;\n\ttokens: number;\n\tchars: number;\n\tlabel: string;\n\tpreview: string;\n};\n\nconst DEFAULT_MAX_ITEMS = 40;\nconst MAX_MAX_ITEMS = 200;\nconst DEFAULT_PREVIEW_CHARS = 220;\nconst MAX_PREVIEW_CHARS = 600;\n\nfunction estimateTextTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\nfunction cap(text: string, limit = DEFAULT_PREVIEW_CHARS): string {\n\tconst compact = text.replace(/\\s+/g, \" \").trim();\n\treturn compact.length > limit ? `${compact.slice(0, Math.max(0, limit - 1))}…` : compact;\n}\n\nfunction contentText(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return \"\";\n\treturn content\n\t\t.map((part) => {\n\t\t\tif (!part || typeof part !== \"object\") return \"\";\n\t\t\tconst typed = part as { type?: string; text?: string; thinking?: string; name?: string; arguments?: unknown };\n\t\t\tif (typed.type === \"text\") return typed.text || \"\";\n\t\t\tif (typed.type === \"thinking\") return `[thinking ${typed.thinking?.length ?? 0} chars]`;\n\t\t\tif (typed.type === \"toolCall\")\n\t\t\t\treturn `[toolCall ${typed.name || \"unknown\"} ${JSON.stringify(typed.arguments ?? {})}]`;\n\t\t\tif (typed.type === \"image\") return \"[image]\";\n\t\t\treturn \"\";\n\t\t})\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\");\n}\n\nfunction messagePreview(message: AgentMessage): string {\n\tswitch (message.role) {\n\t\tcase \"assistant\":\n\t\tcase \"user\":\n\t\tcase \"toolResult\":\n\t\tcase \"custom\":\n\t\t\treturn contentText((message as { content?: unknown }).content);\n\t\tcase \"bashExecution\":\n\t\t\treturn `Ran ${message.command}\\n${message.output}`;\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\":\n\t\t\treturn message.summary;\n\t\tdefault:\n\t\t\treturn \"\";\n\t}\n}\n\nfunction messageLabel(message: AgentMessage): string {\n\tif (message.role === \"assistant\") {\n\t\tconst toolCalls = message.content.filter((part) => part.type === \"toolCall\").length;\n\t\treturn toolCalls > 0 ? `assistant (${toolCalls} tool call${toolCalls === 1 ? \"\" : \"s\"})` : \"assistant\";\n\t}\n\tif (message.role === \"toolResult\") return `tool result: ${message.toolName}`;\n\tif (message.role === \"custom\") return `custom: ${message.customType}`;\n\tif (message.role === \"bashExecution\") return \"bash execution\";\n\tif (message.role === \"branchSummary\") return \"branch summary\";\n\tif (message.role === \"compactionSummary\") return \"compaction summary\";\n\treturn message.role;\n}\n\nfunction addRow(rows: AuditRow[], entry: SessionEntry, message: AgentMessage, kindOverride?: string) {\n\tconst preview = messagePreview(message);\n\trows.push({\n\t\tkind: kindOverride || entry.type,\n\t\trole: message.role,\n\t\tentryId: entry.id,\n\t\ttimestamp: entry.timestamp,\n\t\ttokens: estimateTokens(message),\n\t\tchars: preview.length,\n\t\tlabel: messageLabel(message),\n\t\tpreview: cap(preview),\n\t});\n}\n\nfunction messageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") return entry.message;\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);\n\t}\n\tif (entry.type === \"branch_summary\" && entry.summary) {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nfunction latestCompaction(entries: SessionEntry[]): CompactionEntry | undefined {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (entry?.type === \"compaction\") return entry;\n\t}\n\treturn undefined;\n}\n\nfunction activeContextMessages(entries: SessionEntry[]): AgentMessage[] {\n\tconst messages: AgentMessage[] = [];\n\tconst compaction = latestCompaction(entries);\n\tif (!compaction) {\n\t\tfor (const entry of entries) {\n\t\t\tconst message = messageFromEntry(entry);\n\t\t\tif (message) messages.push(message);\n\t\t}\n\t\treturn messages;\n\t}\n\n\tmessages.push(createCompactionSummaryMessage(compaction.summary, compaction.tokensBefore, compaction.timestamp));\n\tconst compactionIndex = entries.findIndex((entry) => entry.id === compaction.id);\n\tlet foundFirstKept = false;\n\tfor (let index = 0; index < compactionIndex; index++) {\n\t\tconst entry = entries[index];\n\t\tif (entry.id === compaction.firstKeptEntryId) foundFirstKept = true;\n\t\tif (!foundFirstKept) continue;\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) messages.push(message);\n\t}\n\tfor (let index = compactionIndex + 1; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) messages.push(message);\n\t}\n\treturn messages;\n}\n\nfunction activeContextRows(entries: SessionEntry[]): AuditRow[] {\n\tconst rows: AuditRow[] = [];\n\tconst compaction = latestCompaction(entries);\n\tif (!compaction) {\n\t\tfor (const entry of entries) {\n\t\t\tconst message = messageFromEntry(entry);\n\t\t\tif (message) addRow(rows, entry, message);\n\t\t}\n\t\treturn rows;\n\t}\n\n\tconst compactionMessage = createCompactionSummaryMessage(\n\t\tcompaction.summary,\n\t\tcompaction.tokensBefore,\n\t\tcompaction.timestamp,\n\t);\n\taddRow(rows, compaction, compactionMessage, \"compaction\");\n\n\tconst compactionIndex = entries.findIndex((entry) => entry.id === compaction.id);\n\tlet foundFirstKept = false;\n\tfor (let index = 0; index < compactionIndex; index++) {\n\t\tconst entry = entries[index];\n\t\tif (entry.id === compaction.firstKeptEntryId) foundFirstKept = true;\n\t\tif (!foundFirstKept) continue;\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) addRow(rows, entry, message);\n\t}\n\tfor (let index = compactionIndex + 1; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message) addRow(rows, entry, message);\n\t}\n\treturn rows;\n}\n\nfunction groupRows(rows: AuditRow[]): Array<[string, { count: number; tokens: number; chars: number }]> {\n\tconst groups = new Map<string, { count: number; tokens: number; chars: number }>();\n\tfor (const row of rows) {\n\t\tconst key = row.label;\n\t\tconst current = groups.get(key) ?? { count: 0, tokens: 0, chars: 0 };\n\t\tcurrent.count += 1;\n\t\tcurrent.tokens += row.tokens;\n\t\tcurrent.chars += row.chars;\n\t\tgroups.set(key, current);\n\t}\n\treturn [...groups.entries()].sort((a, b) => b[1].tokens - a[1].tokens);\n}\n\n/** Bounded, deterministic summary lines for the memory-retrieval/prompt-inclusion diagnostic (safe metadata only, no content). */\nfunction formatMemoryRetrievalLine(retrieval: MemoryRetrievalDiagnostics): string {\n\treturn `Memory retrieval: ${retrieval.enabled ? `enabled (max ${retrieval.maxResults} results)` : \"disabled\"}`;\n}\n\nfunction formatMemoryProviderLines(retrieval: MemoryRetrievalDiagnostics): string[] {\n\treturn retrieval.providerReports.map((providerReport) => {\n\t\tconst rejection =\n\t\t\tproviderReport.rejectionReasons.length > 0 ? `; rejected: ${providerReport.rejectionReasons.join(\", \")}` : \"\";\n\t\treturn ` provider ${providerReport.providerId}: ${providerReport.status} (${providerReport.resultCount} result(s)${rejection})`;\n\t});\n}\n\nfunction formatMemoryPromptInclusionLine(promptInclusion: MemoryPromptInclusionReport): string {\n\treturn `Prompt inclusion: ${promptInclusion.status} (${promptInclusion.includedCount} included, ${promptInclusion.omittedCount} omitted, ${promptInclusion.blockChars} chars)`;\n}\n\nexport function createCoreDiagnosticsToolDefinitions(\n\tgetActiveTools: () => string[],\n\tgetAllTools: () => ToolInfo[],\n\tgetContextGcReport?: (messages: AgentMessage[]) => ContextGcReport,\n\tgetMemoryDiagnostics?: () => {\n\t\tretrieval: MemoryRetrievalDiagnostics;\n\t\tpromptInclusion: MemoryPromptInclusionReport;\n\t},\n): ToolDefinition[] {\n\treturn [\n\t\t{\n\t\t\tname: \"context_audit\",\n\t\t\tlabel: \"Context Audit\",\n\t\t\tdescription:\n\t\t\t\t\"Audit the current provider-visible context composition: model window usage, system prompt estimate, active tool schema estimate, active session message rows, and heaviest context contributors.\",\n\t\t\tpromptSnippet: \"Audit current loaded context composition before optimizing context usage.\",\n\t\t\tpromptGuidelines: [\n\t\t\t\t\"Use context_audit when the user asks what is consuming context, why the footer shows a high percentage, or which messages/tools/system prompt content are loaded.\",\n\t\t\t\t\"Keep output bounded; use query/minTokens/maxItems to narrow rather than dumping full context.\",\n\t\t\t\t\"Treat token counts as estimates except provider usage from ctx.getContextUsage, which is still model/provider dependent.\",\n\t\t\t],\n\t\t\tparameters: Type.Object(\n\t\t\t\t{\n\t\t\t\t\tmaxItems: Type.Optional(\n\t\t\t\t\t\tType.Number({ description: \"Maximum heaviest session-context rows to show. Default 40, max 200.\" }),\n\t\t\t\t\t),\n\t\t\t\t\tminTokens: Type.Optional(\n\t\t\t\t\t\tType.Number({\n\t\t\t\t\t\t\tdescription: \"Only show session-context rows with at least this many estimated tokens.\",\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\tquery: Type.Optional(\n\t\t\t\t\t\tType.String({ description: \"Case-insensitive filter over row label and preview.\" }),\n\t\t\t\t\t),\n\t\t\t\t\tincludePreviews: Type.Optional(\n\t\t\t\t\t\tType.Boolean({ description: \"Include bounded row previews. Defaults true.\" }),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\t{ additionalProperties: false },\n\t\t\t),\n\t\t\tasync execute(_toolCallId, params: ContextAuditParams, _signal, _onUpdate, ctx) {\n\t\t\t\tconst maxItems = Math.max(1, Math.min(MAX_MAX_ITEMS, Math.floor(params.maxItems ?? DEFAULT_MAX_ITEMS)));\n\t\t\t\tconst minTokens = Math.max(0, Math.floor(params.minTokens ?? 0));\n\t\t\t\tconst includePreviews = params.includePreviews !== false;\n\t\t\t\tconst query = params.query?.trim().toLowerCase();\n\n\t\t\t\tconst branch = ctx.sessionManager.getBranch();\n\t\t\t\tconst rows = activeContextRows(branch);\n\t\t\t\tconst activeMessages = activeContextMessages(branch);\n\t\t\t\tconst contextGcReport = getContextGcReport?.(activeMessages);\n\t\t\t\tconst memoryDiagnostics = getMemoryDiagnostics?.();\n\t\t\t\tconst contextUsage = ctx.getContextUsage();\n\t\t\t\tconst systemPrompt = ctx.getSystemPrompt?.() || \"\";\n\t\t\t\tconst activeTools = new Set(getActiveTools());\n\t\t\t\tconst allTools = getAllTools();\n\t\t\t\tconst activeToolInfos = allTools.filter((tool) => activeTools.has(tool.name));\n\t\t\t\tconst systemTokens = estimateTextTokens(systemPrompt);\n\t\t\t\tconst toolSchemaChars = JSON.stringify(\n\t\t\t\t\tactiveToolInfos.map((tool) => ({\n\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\tdescription: tool.description,\n\t\t\t\t\t\tparameters: tool.parameters,\n\t\t\t\t\t\tpromptGuidelines: tool.promptGuidelines,\n\t\t\t\t\t})),\n\t\t\t\t).length;\n\t\t\t\tconst toolSchemaTokens = Math.ceil(toolSchemaChars / 4);\n\t\t\t\tconst rowTokenSum = rows.reduce((sum, row) => sum + row.tokens, 0);\n\t\t\t\tconst effectiveRowTokenSum = Math.max(0, rowTokenSum - (contextGcReport?.savedTokens ?? 0));\n\t\t\t\tconst usageText = contextUsage\n\t\t\t\t\t? contextUsage.tokens === null || contextUsage.percent === null\n\t\t\t\t\t\t? `provider usage: unknown/${contextUsage.contextWindow} tokens (usually right after compaction)`\n\t\t\t\t\t\t: `provider usage: ${contextUsage.tokens}/${contextUsage.contextWindow} tokens (${contextUsage.percent.toFixed(1)}%)`\n\t\t\t\t\t: \"provider usage: unavailable (no active model/context window)\";\n\t\t\t\tconst providerTokens = contextUsage?.tokens ?? null;\n\t\t\t\tconst unattributed =\n\t\t\t\t\tproviderTokens === null\n\t\t\t\t\t\t? null\n\t\t\t\t\t\t: Math.max(0, providerTokens - systemTokens - toolSchemaTokens - rowTokenSum);\n\n\t\t\t\tlet filtered = rows.filter((row) => row.tokens >= minTokens);\n\t\t\t\tif (query) {\n\t\t\t\t\tfiltered = filtered.filter((row) => `${row.label}\\n${row.preview}`.toLowerCase().includes(query));\n\t\t\t\t}\n\t\t\t\tconst heaviest = [...filtered].sort((a, b) => b.tokens - a.tokens).slice(0, maxItems);\n\t\t\t\tconst groupLines = groupRows(rows)\n\t\t\t\t\t.slice(0, 12)\n\t\t\t\t\t.map(([label, group]) => `- ${label}: ${group.tokens} est tok across ${group.count} row(s)`);\n\t\t\t\tconst rowLines = heaviest.map((row, index) => {\n\t\t\t\t\tconst base = `${index + 1}. ${row.tokens} est tok · ${row.label} · ${row.entryId ?? \"no-entry\"}`;\n\t\t\t\t\treturn includePreviews\n\t\t\t\t\t\t? `${base}\\n ${cap(row.preview, MAX_PREVIEW_CHARS) || \"(no text preview)\"}`\n\t\t\t\t\t\t: base;\n\t\t\t\t});\n\n\t\t\t\tconst lines = [\n\t\t\t\t\t\"Context audit\",\n\t\t\t\t\tusageText,\n\t\t\t\t\t`active branch rows: ${rows.length}; session row estimate: ${rowTokenSum} tokens`,\n\t\t\t\t\tcontextGcReport\n\t\t\t\t\t\t? `Context GC estimate: ${contextGcReport.savedTokens} tokens saved by packing ${contextGcReport.packedCount} stale row(s); effective session row estimate: ${effectiveRowTokenSum} tokens`\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\t`system prompt estimate: ${systemTokens} tokens (${systemPrompt.length} chars)`,\n\t\t\t\t\t`active tool schema estimate: ${toolSchemaTokens} tokens across ${activeToolInfos.length} active tool(s)`,\n\t\t\t\t\tunattributed === null\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: `provider-reported remainder not mapped by chars/4 rows: ${unattributed} tokens`,\n\t\t\t\t\t...(memoryDiagnostics\n\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\tformatMemoryRetrievalLine(memoryDiagnostics.retrieval),\n\t\t\t\t\t\t\t\t...formatMemoryProviderLines(memoryDiagnostics.retrieval),\n\t\t\t\t\t\t\t\tformatMemoryPromptInclusionLine(memoryDiagnostics.promptInclusion),\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t: []),\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"Largest groups:\",\n\t\t\t\t\t...(groupLines.length ? groupLines : [\"- none\"]),\n\t\t\t\t\t\"\",\n\t\t\t\t\t`Heaviest rows${query ? ` matching ${JSON.stringify(params.query)}` : \"\"}:`,\n\t\t\t\t\t...(rowLines.length ? rowLines : [\"- none\"]),\n\t\t\t\t].filter((line): line is string => line !== undefined);\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tcontextUsage,\n\t\t\t\t\t\tsystemPrompt: {\n\t\t\t\t\t\t\tchars: systemPrompt.length,\n\t\t\t\t\t\t\testimatedTokens: systemTokens,\n\t\t\t\t\t\t\tpreview: cap(systemPrompt, MAX_PREVIEW_CHARS),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tactiveTools: activeToolInfos.map((tool) => tool.name),\n\t\t\t\t\t\ttoolSchemaEstimate: { chars: toolSchemaChars, estimatedTokens: toolSchemaTokens },\n\t\t\t\t\t\trowTokenSum,\n\t\t\t\t\t\teffectiveRowTokenSum,\n\t\t\t\t\t\tcontextGc: contextGcReport,\n\t\t\t\t\t\trows,\n\t\t\t\t\t\tmemory: memoryDiagnostics,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t];\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type AutonomyStatusSnapshot } from "./autonomy/status.ts";
|
|
1
2
|
/**
|
|
2
3
|
* Provides git branch and extension statuses - data not otherwise accessible to extensions.
|
|
3
4
|
* Token stats, model info available via ctx.sessionManager and ctx.model.
|
|
@@ -7,6 +8,7 @@ export declare class FooterDataProvider {
|
|
|
7
8
|
private static readonly WATCH_DEBOUNCE_MS;
|
|
8
9
|
private extensionStatuses;
|
|
9
10
|
private cachedBranch;
|
|
11
|
+
private autonomyStatus;
|
|
10
12
|
private gitPaths;
|
|
11
13
|
private headWatcher;
|
|
12
14
|
private headWatchFilePath;
|
|
@@ -22,6 +24,8 @@ export declare class FooterDataProvider {
|
|
|
22
24
|
private refreshPending;
|
|
23
25
|
private disposed;
|
|
24
26
|
constructor(cwd: string);
|
|
27
|
+
getAutonomyStatus(): string | undefined;
|
|
28
|
+
setAutonomyStatusSnapshot(snapshot: AutonomyStatusSnapshot | undefined): void;
|
|
25
29
|
/** Current git branch, null if not in repo, "detached" if detached HEAD */
|
|
26
30
|
getGitBranch(): string | null;
|
|
27
31
|
/** Extension status texts set via ctx.ui.setStatus() */
|
|
@@ -50,5 +54,5 @@ export declare class FooterDataProvider {
|
|
|
50
54
|
private setupGitWatcher;
|
|
51
55
|
}
|
|
52
56
|
/** Read-only view for extensions - excludes setExtensionStatus, setAvailableProviderCount and dispose */
|
|
53
|
-
export type ReadonlyFooterDataProvider = Pick<FooterDataProvider, "getGitBranch" | "getExtensionStatuses" | "getAvailableProviderCount" | "onBranchChange">;
|
|
57
|
+
export type ReadonlyFooterDataProvider = Pick<FooterDataProvider, "getGitBranch" | "getExtensionStatuses" | "getAvailableProviderCount" | "onBranchChange" | "getAutonomyStatus">;
|
|
54
58
|
//# sourceMappingURL=footer-data-provider.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"footer-data-provider.d.ts","sourceRoot":"","sources":["../../src/core/footer-data-provider.ts"],"names":[],"mappings":"AA8FA;;;GAGG;AACH,qBAAa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,IAAI,CAQd;IAED,OAAO,CAAC,kBAAkB;IAI1B,OAAO,CAAC,eAAe;YAYT,qBAAqB;IA0BnC,OAAO,CAAC,oBAAoB;YAcd,qBAAqB;IAgBnC,OAAO,CAAC,gBAAgB;IAsBxB,OAAO,CAAC,uBAAuB;IAW/B,OAAO,CAAC,qBAAqB;IAK7B,OAAO,CAAC,eAAe;CA2EvB;AAED,yGAAyG;AACzG,MAAM,MAAM,0BAA0B,GAAG,IAAI,CAC5C,kBAAkB,EAClB,cAAc,GAAG,sBAAsB,GAAG,2BAA2B,GAAG,gBAAgB,CACxF,CAAC","sourcesContent":["import { type ExecFileException, execFile, spawnSync } from \"child_process\";\nimport { existsSync, type FSWatcher, readFileSync, type Stats, statSync, unwatchFile, watchFile } from \"fs\";\nimport { dirname, join, resolve } from \"path\";\nimport { closeWatcher, FS_WATCH_RETRY_DELAY_MS, watchWithErrorHandler } from \"../utils/fs-watch.ts\";\n\ntype GitPaths = {\n\trepoDir: string;\n\tcommonGitDir: string;\n\theadPath: string;\n};\n\n/**\n * Find git metadata paths by walking up from cwd.\n * Handles both regular git repos (.git is a directory) and worktrees (.git is a file).\n */\nfunction findGitPaths(cwd: string): GitPaths | null {\n\tlet dir = cwd;\n\twhile (true) {\n\t\tconst gitPath = join(dir, \".git\");\n\t\tif (existsSync(gitPath)) {\n\t\t\ttry {\n\t\t\t\tconst stat = statSync(gitPath);\n\t\t\t\tif (stat.isFile()) {\n\t\t\t\t\tconst content = readFileSync(gitPath, \"utf8\").trim();\n\t\t\t\t\tif (content.startsWith(\"gitdir: \")) {\n\t\t\t\t\t\tconst gitDir = resolve(dir, content.slice(8).trim());\n\t\t\t\t\t\tconst headPath = join(gitDir, \"HEAD\");\n\t\t\t\t\t\tif (!existsSync(headPath)) return null;\n\t\t\t\t\t\tconst commonDirPath = join(gitDir, \"commondir\");\n\t\t\t\t\t\tconst commonGitDir = existsSync(commonDirPath)\n\t\t\t\t\t\t\t? resolve(gitDir, readFileSync(commonDirPath, \"utf8\").trim())\n\t\t\t\t\t\t\t: gitDir;\n\t\t\t\t\t\treturn { repoDir: dir, commonGitDir, headPath };\n\t\t\t\t\t}\n\t\t\t\t} else if (stat.isDirectory()) {\n\t\t\t\t\tconst headPath = join(gitPath, \"HEAD\");\n\t\t\t\t\tif (!existsSync(headPath)) return null;\n\t\t\t\t\treturn { repoDir: dir, commonGitDir: gitPath, headPath };\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) return null;\n\t\tdir = parent;\n\t}\n}\n\n/** Ask git for the current branch. Returns null on detached HEAD or if git is unavailable. */\nfunction resolveBranchWithGitSync(repoDir: string): string | null {\n\tconst result = spawnSync(\"git\", [\"--no-optional-locks\", \"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"], {\n\t\tcwd: repoDir,\n\t\tencoding: \"utf8\",\n\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t});\n\tconst branch = result.status === 0 ? result.stdout.trim() : \"\";\n\treturn branch || null;\n}\n\n/** Ask git for the current branch asynchronously. Returns null on detached HEAD or if git is unavailable. */\nfunction resolveBranchWithGitAsync(repoDir: string): Promise<string | null> {\n\treturn new Promise((resolvePromise) => {\n\t\texecFile(\n\t\t\t\"git\",\n\t\t\t[\"--no-optional-locks\", \"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"],\n\t\t\t{\n\t\t\t\tcwd: repoDir,\n\t\t\t\tencoding: \"utf8\",\n\t\t\t},\n\t\t\t(error: ExecFileException | null, stdout: string) => {\n\t\t\t\tif (error) {\n\t\t\t\t\tresolvePromise(null);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst branch = stdout.trim();\n\t\t\t\tresolvePromise(branch || null);\n\t\t\t},\n\t\t);\n\t});\n}\n\nfunction isWslEnvironment(): boolean {\n\treturn process.platform === \"linux\" && !!(process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP);\n}\n\nfunction isWindowsMountedRepoPath(repoDir: string): boolean {\n\treturn /^\\/mnt\\/[a-z](?:\\/|$)/i.test(repoDir);\n}\n\nfunction shouldPollGitHead(repoDir: string): boolean {\n\treturn isWslEnvironment() && isWindowsMountedRepoPath(repoDir);\n}\n\n/**\n * Provides git branch and extension statuses - data not otherwise accessible to extensions.\n * Token stats, model info available via ctx.sessionManager and ctx.model.\n */\nexport class FooterDataProvider {\n\tprivate cwd: string;\n\tprivate static readonly WATCH_DEBOUNCE_MS = 500;\n\n\tprivate extensionStatuses = new Map<string, string>();\n\tprivate cachedBranch: string | null | undefined = undefined;\n\tprivate gitPaths: GitPaths | null | undefined = undefined;\n\tprivate headWatcher: FSWatcher | null = null;\n\tprivate headWatchFilePath: string | null = null;\n\tprivate headWatchFileListener: ((current: Stats, previous: Stats) => void) | null = null;\n\tprivate reftableWatcher: FSWatcher | null = null;\n\tprivate reftableTablesListWatcher: FSWatcher | null = null;\n\tprivate reftableTablesListPath: string | null = null;\n\tprivate branchChangeCallbacks = new Set<() => void>();\n\tprivate availableProviderCount = 0;\n\tprivate refreshTimer: ReturnType<typeof setTimeout> | null = null;\n\tprivate gitWatcherRetryTimer: ReturnType<typeof setTimeout> | null = null;\n\tprivate refreshInFlight = false;\n\tprivate refreshPending = false;\n\tprivate disposed = false;\n\n\tconstructor(cwd: string) {\n\t\tthis.cwd = cwd;\n\t\tthis.gitPaths = findGitPaths(cwd);\n\t\tthis.setupGitWatcher();\n\t}\n\n\t/** Current git branch, null if not in repo, \"detached\" if detached HEAD */\n\tgetGitBranch(): string | null {\n\t\tif (this.cachedBranch === undefined) {\n\t\t\tthis.cachedBranch = this.resolveGitBranchSync();\n\t\t}\n\t\treturn this.cachedBranch;\n\t}\n\n\t/** Extension status texts set via ctx.ui.setStatus() */\n\tgetExtensionStatuses(): ReadonlyMap<string, string> {\n\t\treturn this.extensionStatuses;\n\t}\n\n\t/** Subscribe to git branch changes. Returns unsubscribe function. */\n\tonBranchChange(callback: () => void): () => void {\n\t\tthis.branchChangeCallbacks.add(callback);\n\t\treturn () => this.branchChangeCallbacks.delete(callback);\n\t}\n\n\t/** Internal: set extension status */\n\tsetExtensionStatus(key: string, text: string | undefined): void {\n\t\tif (text === undefined) {\n\t\t\tthis.extensionStatuses.delete(key);\n\t\t} else {\n\t\t\tthis.extensionStatuses.set(key, text);\n\t\t}\n\t}\n\n\t/** Internal: clear extension statuses */\n\tclearExtensionStatuses(): void {\n\t\tthis.extensionStatuses.clear();\n\t}\n\n\t/** Number of unique providers with available models (for footer display) */\n\tgetAvailableProviderCount(): number {\n\t\treturn this.availableProviderCount;\n\t}\n\n\t/** Internal: update available provider count */\n\tsetAvailableProviderCount(count: number): void {\n\t\tthis.availableProviderCount = count;\n\t}\n\n\tsetCwd(cwd: string): void {\n\t\tif (this.cwd === cwd) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.cwd = cwd;\n\t\tif (this.refreshTimer) {\n\t\t\tclearTimeout(this.refreshTimer);\n\t\t\tthis.refreshTimer = null;\n\t\t}\n\t\tthis.clearGitWatchers();\n\t\tthis.cachedBranch = undefined;\n\t\tthis.gitPaths = findGitPaths(cwd);\n\t\tthis.setupGitWatcher();\n\t\tthis.notifyBranchChange();\n\t}\n\n\t/** Internal: cleanup */\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tif (this.refreshTimer) {\n\t\t\tclearTimeout(this.refreshTimer);\n\t\t\tthis.refreshTimer = null;\n\t\t}\n\t\tthis.clearGitWatchers();\n\t\tthis.branchChangeCallbacks.clear();\n\t}\n\n\tprivate notifyBranchChange(): void {\n\t\tfor (const cb of this.branchChangeCallbacks) cb();\n\t}\n\n\tprivate scheduleRefresh(): void {\n\t\tif (this.disposed || this.refreshTimer) return;\n\t\tif (this.refreshInFlight) {\n\t\t\tthis.refreshPending = true;\n\t\t\treturn;\n\t\t}\n\t\tthis.refreshTimer = setTimeout(() => {\n\t\t\tthis.refreshTimer = null;\n\t\t\tvoid this.refreshGitBranchAsync();\n\t\t}, FooterDataProvider.WATCH_DEBOUNCE_MS);\n\t}\n\n\tprivate async refreshGitBranchAsync(): Promise<void> {\n\t\tif (this.disposed) return;\n\t\tif (this.refreshInFlight) {\n\t\t\tthis.refreshPending = true;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.refreshInFlight = true;\n\t\ttry {\n\t\t\tconst nextBranch = await this.resolveGitBranchAsync();\n\t\t\tif (this.disposed) return;\n\t\t\tif (this.cachedBranch !== undefined && this.cachedBranch !== nextBranch) {\n\t\t\t\tthis.cachedBranch = nextBranch;\n\t\t\t\tthis.notifyBranchChange();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.cachedBranch = nextBranch;\n\t\t} finally {\n\t\t\tthis.refreshInFlight = false;\n\t\t\tif (this.refreshPending && !this.disposed) {\n\t\t\t\tthis.refreshPending = false;\n\t\t\t\tthis.scheduleRefresh();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate resolveGitBranchSync(): string | null {\n\t\ttry {\n\t\t\tif (!this.gitPaths) return null;\n\t\t\tconst content = readFileSync(this.gitPaths.headPath, \"utf8\").trim();\n\t\t\tif (content.startsWith(\"ref: refs/heads/\")) {\n\t\t\t\tconst branch = content.slice(16);\n\t\t\t\treturn branch === \".invalid\" ? (resolveBranchWithGitSync(this.gitPaths.repoDir) ?? \"detached\") : branch;\n\t\t\t}\n\t\t\treturn \"detached\";\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate async resolveGitBranchAsync(): Promise<string | null> {\n\t\ttry {\n\t\t\tif (!this.gitPaths) return null;\n\t\t\tconst content = readFileSync(this.gitPaths.headPath, \"utf8\").trim();\n\t\t\tif (content.startsWith(\"ref: refs/heads/\")) {\n\t\t\t\tconst branch = content.slice(16);\n\t\t\t\treturn branch === \".invalid\"\n\t\t\t\t\t? ((await resolveBranchWithGitAsync(this.gitPaths.repoDir)) ?? \"detached\")\n\t\t\t\t\t: branch;\n\t\t\t}\n\t\t\treturn \"detached\";\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate clearGitWatchers(): void {\n\t\tcloseWatcher(this.headWatcher);\n\t\tthis.headWatcher = null;\n\t\tif (this.headWatchFilePath && this.headWatchFileListener) {\n\t\t\tunwatchFile(this.headWatchFilePath, this.headWatchFileListener);\n\t\t\tthis.headWatchFilePath = null;\n\t\t\tthis.headWatchFileListener = null;\n\t\t}\n\t\tcloseWatcher(this.reftableWatcher);\n\t\tthis.reftableWatcher = null;\n\t\tcloseWatcher(this.reftableTablesListWatcher);\n\t\tthis.reftableTablesListWatcher = null;\n\t\tif (this.reftableTablesListPath) {\n\t\t\tunwatchFile(this.reftableTablesListPath);\n\t\t\tthis.reftableTablesListPath = null;\n\t\t}\n\t\tif (this.gitWatcherRetryTimer) {\n\t\t\tclearTimeout(this.gitWatcherRetryTimer);\n\t\t\tthis.gitWatcherRetryTimer = null;\n\t\t}\n\t}\n\n\tprivate scheduleGitWatcherRetry(): void {\n\t\tif (this.disposed || this.gitWatcherRetryTimer) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.gitWatcherRetryTimer = setTimeout(() => {\n\t\t\tthis.gitWatcherRetryTimer = null;\n\t\t\tthis.setupGitWatcher();\n\t\t}, FS_WATCH_RETRY_DELAY_MS);\n\t}\n\n\tprivate handleGitWatcherError(): void {\n\t\tthis.clearGitWatchers();\n\t\tthis.scheduleGitWatcherRetry();\n\t}\n\n\tprivate setupGitWatcher(): void {\n\t\tthis.clearGitWatchers();\n\t\tif (!this.gitPaths) return;\n\n\t\tconst pollGitHead = shouldPollGitHead(this.gitPaths.repoDir);\n\n\t\t// Watch the directory containing HEAD, not HEAD itself.\n\t\t// Git uses atomic writes (write temp, rename over HEAD), which changes the inode.\n\t\t// fs.watch on a file stops working after the inode changes.\n\t\tthis.headWatcher = watchWithErrorHandler(\n\t\t\tdirname(this.gitPaths.headPath),\n\t\t\t(_eventType, filename) => {\n\t\t\t\tif (!filename || filename === \"HEAD\") {\n\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => this.handleGitWatcherError(),\n\t\t);\n\t\tif (pollGitHead) {\n\t\t\tthis.headWatchFilePath = this.gitPaths.headPath;\n\t\t\tthis.headWatchFileListener = (current, previous) => {\n\t\t\t\tif (\n\t\t\t\t\tcurrent.mtimeMs !== previous.mtimeMs ||\n\t\t\t\t\tcurrent.ctimeMs !== previous.ctimeMs ||\n\t\t\t\t\tcurrent.size !== previous.size\n\t\t\t\t) {\n\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t}\n\t\t\t};\n\t\t\twatchFile(this.headWatchFilePath, { interval: 1000 }, this.headWatchFileListener);\n\t\t}\n\t\tif (!this.headWatcher && !pollGitHead) {\n\t\t\treturn;\n\t\t}\n\n\t\t// In reftable repos, branch switches update files in the reftable directory\n\t\t// instead of HEAD. Watch it separately so the footer picks up those changes.\n\t\tconst reftableDir = join(this.gitPaths.commonGitDir, \"reftable\");\n\t\tif (existsSync(reftableDir)) {\n\t\t\tthis.reftableWatcher = watchWithErrorHandler(\n\t\t\t\treftableDir,\n\t\t\t\t() => {\n\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t},\n\t\t\t\t() => this.handleGitWatcherError(),\n\t\t\t);\n\t\t\tif (!this.reftableWatcher) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst tablesListPath = join(reftableDir, \"tables.list\");\n\t\t\tif (existsSync(tablesListPath)) {\n\t\t\t\tthis.reftableTablesListPath = tablesListPath;\n\t\t\t\tthis.reftableTablesListWatcher = watchWithErrorHandler(\n\t\t\t\t\ttablesListPath,\n\t\t\t\t\t() => {\n\t\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t\t},\n\t\t\t\t\t() => this.handleGitWatcherError(),\n\t\t\t\t);\n\t\t\t\tif (!this.reftableTablesListWatcher) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\twatchFile(tablesListPath, { interval: 250 }, (current, previous) => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tcurrent.mtimeMs !== previous.mtimeMs ||\n\t\t\t\t\t\tcurrent.ctimeMs !== previous.ctimeMs ||\n\t\t\t\t\t\tcurrent.size !== previous.size\n\t\t\t\t\t) {\n\t\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Read-only view for extensions - excludes setExtensionStatus, setAvailableProviderCount and dispose */\nexport type ReadonlyFooterDataProvider = Pick<\n\tFooterDataProvider,\n\t\"getGitBranch\" | \"getExtensionStatuses\" | \"getAvailableProviderCount\" | \"onBranchChange\"\n>;\n"]}
|
|
1
|
+
{"version":3,"file":"footer-data-provider.d.ts","sourceRoot":"","sources":["../../src/core/footer-data-provider.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,sBAAsB,EAAwB,MAAM,sBAAsB,CAAC;AA2FzF;;;GAGG;AACH,qBAAa,kBAAkB;IAC9B,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAAO;IAEhD,OAAO,CAAC,iBAAiB,CAA6B;IACtD,OAAO,CAAC,YAAY,CAAwC;IAC5D,OAAO,CAAC,cAAc,CAAqB;IAC3C,OAAO,CAAC,QAAQ,CAA0C;IAC1D,OAAO,CAAC,WAAW,CAA0B;IAC7C,OAAO,CAAC,iBAAiB,CAAuB;IAChD,OAAO,CAAC,qBAAqB,CAA4D;IACzF,OAAO,CAAC,eAAe,CAA0B;IACjD,OAAO,CAAC,yBAAyB,CAA0B;IAC3D,OAAO,CAAC,sBAAsB,CAAuB;IACrD,OAAO,CAAC,qBAAqB,CAAyB;IACtD,OAAO,CAAC,sBAAsB,CAAK;IACnC,OAAO,CAAC,YAAY,CAA8C;IAClE,OAAO,CAAC,oBAAoB,CAA8C;IAC1E,OAAO,CAAC,eAAe,CAAS;IAChC,OAAO,CAAC,cAAc,CAAS;IAC/B,OAAO,CAAC,QAAQ,CAAS;IAEzB,YAAY,GAAG,EAAE,MAAM,EAItB;IAED,iBAAiB,IAAI,MAAM,GAAG,SAAS,CAEtC;IAED,yBAAyB,CAAC,QAAQ,EAAE,sBAAsB,GAAG,SAAS,GAAG,IAAI,CAM5E;IAED,2EAA2E;IAC3E,YAAY,IAAI,MAAM,GAAG,IAAI,CAK5B;IAED,wDAAwD;IACxD,oBAAoB,IAAI,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAElD;IAED,qEAAqE;IACrE,cAAc,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAG/C;IAED,qCAAqC;IACrC,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAM9D;IAED,yCAAyC;IACzC,sBAAsB,IAAI,IAAI,CAE7B;IAED,4EAA4E;IAC5E,yBAAyB,IAAI,MAAM,CAElC;IAED,gDAAgD;IAChD,yBAAyB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAE7C;IAED,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAexB;IAED,wBAAwB;IACxB,OAAO,IAAI,IAAI,CAQd;IAED,OAAO,CAAC,kBAAkB;IAI1B,OAAO,CAAC,eAAe;YAYT,qBAAqB;IA0BnC,OAAO,CAAC,oBAAoB;YAcd,qBAAqB;IAgBnC,OAAO,CAAC,gBAAgB;IAsBxB,OAAO,CAAC,uBAAuB;IAW/B,OAAO,CAAC,qBAAqB;IAK7B,OAAO,CAAC,eAAe;CA2EvB;AAED,yGAAyG;AACzG,MAAM,MAAM,0BAA0B,GAAG,IAAI,CAC5C,kBAAkB,EAClB,cAAc,GAAG,sBAAsB,GAAG,2BAA2B,GAAG,gBAAgB,GAAG,mBAAmB,CAC9G,CAAC","sourcesContent":["import { type ExecFileException, execFile, spawnSync } from \"child_process\";\nimport { existsSync, type FSWatcher, readFileSync, type Stats, statSync, unwatchFile, watchFile } from \"fs\";\nimport { dirname, join, resolve } from \"path\";\nimport { closeWatcher, FS_WATCH_RETRY_DELAY_MS, watchWithErrorHandler } from \"../utils/fs-watch.ts\";\nimport { type AutonomyStatusSnapshot, formatAutonomyStatus } from \"./autonomy/status.ts\";\n\ntype GitPaths = {\n\trepoDir: string;\n\tcommonGitDir: string;\n\theadPath: string;\n};\n\n/**\n * Find git metadata paths by walking up from cwd.\n * Handles both regular git repos (.git is a directory) and worktrees (.git is a file).\n */\nfunction findGitPaths(cwd: string): GitPaths | null {\n\tlet dir = cwd;\n\twhile (true) {\n\t\tconst gitPath = join(dir, \".git\");\n\t\tif (existsSync(gitPath)) {\n\t\t\ttry {\n\t\t\t\tconst stat = statSync(gitPath);\n\t\t\t\tif (stat.isFile()) {\n\t\t\t\t\tconst content = readFileSync(gitPath, \"utf8\").trim();\n\t\t\t\t\tif (content.startsWith(\"gitdir: \")) {\n\t\t\t\t\t\tconst gitDir = resolve(dir, content.slice(8).trim());\n\t\t\t\t\t\tconst headPath = join(gitDir, \"HEAD\");\n\t\t\t\t\t\tif (!existsSync(headPath)) return null;\n\t\t\t\t\t\tconst commonDirPath = join(gitDir, \"commondir\");\n\t\t\t\t\t\tconst commonGitDir = existsSync(commonDirPath)\n\t\t\t\t\t\t\t? resolve(gitDir, readFileSync(commonDirPath, \"utf8\").trim())\n\t\t\t\t\t\t\t: gitDir;\n\t\t\t\t\t\treturn { repoDir: dir, commonGitDir, headPath };\n\t\t\t\t\t}\n\t\t\t\t} else if (stat.isDirectory()) {\n\t\t\t\t\tconst headPath = join(gitPath, \"HEAD\");\n\t\t\t\t\tif (!existsSync(headPath)) return null;\n\t\t\t\t\treturn { repoDir: dir, commonGitDir: gitPath, headPath };\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) return null;\n\t\tdir = parent;\n\t}\n}\n\n/** Ask git for the current branch. Returns null on detached HEAD or if git is unavailable. */\nfunction resolveBranchWithGitSync(repoDir: string): string | null {\n\tconst result = spawnSync(\"git\", [\"--no-optional-locks\", \"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"], {\n\t\tcwd: repoDir,\n\t\tencoding: \"utf8\",\n\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t});\n\tconst branch = result.status === 0 ? result.stdout.trim() : \"\";\n\treturn branch || null;\n}\n\n/** Ask git for the current branch asynchronously. Returns null on detached HEAD or if git is unavailable. */\nfunction resolveBranchWithGitAsync(repoDir: string): Promise<string | null> {\n\treturn new Promise((resolvePromise) => {\n\t\texecFile(\n\t\t\t\"git\",\n\t\t\t[\"--no-optional-locks\", \"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"],\n\t\t\t{\n\t\t\t\tcwd: repoDir,\n\t\t\t\tencoding: \"utf8\",\n\t\t\t},\n\t\t\t(error: ExecFileException | null, stdout: string) => {\n\t\t\t\tif (error) {\n\t\t\t\t\tresolvePromise(null);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst branch = stdout.trim();\n\t\t\t\tresolvePromise(branch || null);\n\t\t\t},\n\t\t);\n\t});\n}\n\nfunction isWslEnvironment(): boolean {\n\treturn process.platform === \"linux\" && !!(process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP);\n}\n\nfunction isWindowsMountedRepoPath(repoDir: string): boolean {\n\treturn /^\\/mnt\\/[a-z](?:\\/|$)/i.test(repoDir);\n}\n\nfunction shouldPollGitHead(repoDir: string): boolean {\n\treturn isWslEnvironment() && isWindowsMountedRepoPath(repoDir);\n}\n\n/**\n * Provides git branch and extension statuses - data not otherwise accessible to extensions.\n * Token stats, model info available via ctx.sessionManager and ctx.model.\n */\nexport class FooterDataProvider {\n\tprivate cwd: string;\n\tprivate static readonly WATCH_DEBOUNCE_MS = 500;\n\n\tprivate extensionStatuses = new Map<string, string>();\n\tprivate cachedBranch: string | null | undefined = undefined;\n\tprivate autonomyStatus: string | undefined;\n\tprivate gitPaths: GitPaths | null | undefined = undefined;\n\tprivate headWatcher: FSWatcher | null = null;\n\tprivate headWatchFilePath: string | null = null;\n\tprivate headWatchFileListener: ((current: Stats, previous: Stats) => void) | null = null;\n\tprivate reftableWatcher: FSWatcher | null = null;\n\tprivate reftableTablesListWatcher: FSWatcher | null = null;\n\tprivate reftableTablesListPath: string | null = null;\n\tprivate branchChangeCallbacks = new Set<() => void>();\n\tprivate availableProviderCount = 0;\n\tprivate refreshTimer: ReturnType<typeof setTimeout> | null = null;\n\tprivate gitWatcherRetryTimer: ReturnType<typeof setTimeout> | null = null;\n\tprivate refreshInFlight = false;\n\tprivate refreshPending = false;\n\tprivate disposed = false;\n\n\tconstructor(cwd: string) {\n\t\tthis.cwd = cwd;\n\t\tthis.gitPaths = findGitPaths(cwd);\n\t\tthis.setupGitWatcher();\n\t}\n\n\tgetAutonomyStatus(): string | undefined {\n\t\treturn this.autonomyStatus;\n\t}\n\n\tsetAutonomyStatusSnapshot(snapshot: AutonomyStatusSnapshot | undefined): void {\n\t\tif (snapshot === undefined) {\n\t\t\tthis.autonomyStatus = undefined;\n\t\t} else {\n\t\t\tthis.autonomyStatus = formatAutonomyStatus(snapshot);\n\t\t}\n\t}\n\n\t/** Current git branch, null if not in repo, \"detached\" if detached HEAD */\n\tgetGitBranch(): string | null {\n\t\tif (this.cachedBranch === undefined) {\n\t\t\tthis.cachedBranch = this.resolveGitBranchSync();\n\t\t}\n\t\treturn this.cachedBranch;\n\t}\n\n\t/** Extension status texts set via ctx.ui.setStatus() */\n\tgetExtensionStatuses(): ReadonlyMap<string, string> {\n\t\treturn this.extensionStatuses;\n\t}\n\n\t/** Subscribe to git branch changes. Returns unsubscribe function. */\n\tonBranchChange(callback: () => void): () => void {\n\t\tthis.branchChangeCallbacks.add(callback);\n\t\treturn () => this.branchChangeCallbacks.delete(callback);\n\t}\n\n\t/** Internal: set extension status */\n\tsetExtensionStatus(key: string, text: string | undefined): void {\n\t\tif (text === undefined) {\n\t\t\tthis.extensionStatuses.delete(key);\n\t\t} else {\n\t\t\tthis.extensionStatuses.set(key, text);\n\t\t}\n\t}\n\n\t/** Internal: clear extension statuses */\n\tclearExtensionStatuses(): void {\n\t\tthis.extensionStatuses.clear();\n\t}\n\n\t/** Number of unique providers with available models (for footer display) */\n\tgetAvailableProviderCount(): number {\n\t\treturn this.availableProviderCount;\n\t}\n\n\t/** Internal: update available provider count */\n\tsetAvailableProviderCount(count: number): void {\n\t\tthis.availableProviderCount = count;\n\t}\n\n\tsetCwd(cwd: string): void {\n\t\tif (this.cwd === cwd) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.cwd = cwd;\n\t\tif (this.refreshTimer) {\n\t\t\tclearTimeout(this.refreshTimer);\n\t\t\tthis.refreshTimer = null;\n\t\t}\n\t\tthis.clearGitWatchers();\n\t\tthis.cachedBranch = undefined;\n\t\tthis.gitPaths = findGitPaths(cwd);\n\t\tthis.setupGitWatcher();\n\t\tthis.notifyBranchChange();\n\t}\n\n\t/** Internal: cleanup */\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tif (this.refreshTimer) {\n\t\t\tclearTimeout(this.refreshTimer);\n\t\t\tthis.refreshTimer = null;\n\t\t}\n\t\tthis.clearGitWatchers();\n\t\tthis.branchChangeCallbacks.clear();\n\t}\n\n\tprivate notifyBranchChange(): void {\n\t\tfor (const cb of this.branchChangeCallbacks) cb();\n\t}\n\n\tprivate scheduleRefresh(): void {\n\t\tif (this.disposed || this.refreshTimer) return;\n\t\tif (this.refreshInFlight) {\n\t\t\tthis.refreshPending = true;\n\t\t\treturn;\n\t\t}\n\t\tthis.refreshTimer = setTimeout(() => {\n\t\t\tthis.refreshTimer = null;\n\t\t\tvoid this.refreshGitBranchAsync();\n\t\t}, FooterDataProvider.WATCH_DEBOUNCE_MS);\n\t}\n\n\tprivate async refreshGitBranchAsync(): Promise<void> {\n\t\tif (this.disposed) return;\n\t\tif (this.refreshInFlight) {\n\t\t\tthis.refreshPending = true;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.refreshInFlight = true;\n\t\ttry {\n\t\t\tconst nextBranch = await this.resolveGitBranchAsync();\n\t\t\tif (this.disposed) return;\n\t\t\tif (this.cachedBranch !== undefined && this.cachedBranch !== nextBranch) {\n\t\t\t\tthis.cachedBranch = nextBranch;\n\t\t\t\tthis.notifyBranchChange();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.cachedBranch = nextBranch;\n\t\t} finally {\n\t\t\tthis.refreshInFlight = false;\n\t\t\tif (this.refreshPending && !this.disposed) {\n\t\t\t\tthis.refreshPending = false;\n\t\t\t\tthis.scheduleRefresh();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate resolveGitBranchSync(): string | null {\n\t\ttry {\n\t\t\tif (!this.gitPaths) return null;\n\t\t\tconst content = readFileSync(this.gitPaths.headPath, \"utf8\").trim();\n\t\t\tif (content.startsWith(\"ref: refs/heads/\")) {\n\t\t\t\tconst branch = content.slice(16);\n\t\t\t\treturn branch === \".invalid\" ? (resolveBranchWithGitSync(this.gitPaths.repoDir) ?? \"detached\") : branch;\n\t\t\t}\n\t\t\treturn \"detached\";\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate async resolveGitBranchAsync(): Promise<string | null> {\n\t\ttry {\n\t\t\tif (!this.gitPaths) return null;\n\t\t\tconst content = readFileSync(this.gitPaths.headPath, \"utf8\").trim();\n\t\t\tif (content.startsWith(\"ref: refs/heads/\")) {\n\t\t\t\tconst branch = content.slice(16);\n\t\t\t\treturn branch === \".invalid\"\n\t\t\t\t\t? ((await resolveBranchWithGitAsync(this.gitPaths.repoDir)) ?? \"detached\")\n\t\t\t\t\t: branch;\n\t\t\t}\n\t\t\treturn \"detached\";\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate clearGitWatchers(): void {\n\t\tcloseWatcher(this.headWatcher);\n\t\tthis.headWatcher = null;\n\t\tif (this.headWatchFilePath && this.headWatchFileListener) {\n\t\t\tunwatchFile(this.headWatchFilePath, this.headWatchFileListener);\n\t\t\tthis.headWatchFilePath = null;\n\t\t\tthis.headWatchFileListener = null;\n\t\t}\n\t\tcloseWatcher(this.reftableWatcher);\n\t\tthis.reftableWatcher = null;\n\t\tcloseWatcher(this.reftableTablesListWatcher);\n\t\tthis.reftableTablesListWatcher = null;\n\t\tif (this.reftableTablesListPath) {\n\t\t\tunwatchFile(this.reftableTablesListPath);\n\t\t\tthis.reftableTablesListPath = null;\n\t\t}\n\t\tif (this.gitWatcherRetryTimer) {\n\t\t\tclearTimeout(this.gitWatcherRetryTimer);\n\t\t\tthis.gitWatcherRetryTimer = null;\n\t\t}\n\t}\n\n\tprivate scheduleGitWatcherRetry(): void {\n\t\tif (this.disposed || this.gitWatcherRetryTimer) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.gitWatcherRetryTimer = setTimeout(() => {\n\t\t\tthis.gitWatcherRetryTimer = null;\n\t\t\tthis.setupGitWatcher();\n\t\t}, FS_WATCH_RETRY_DELAY_MS);\n\t}\n\n\tprivate handleGitWatcherError(): void {\n\t\tthis.clearGitWatchers();\n\t\tthis.scheduleGitWatcherRetry();\n\t}\n\n\tprivate setupGitWatcher(): void {\n\t\tthis.clearGitWatchers();\n\t\tif (!this.gitPaths) return;\n\n\t\tconst pollGitHead = shouldPollGitHead(this.gitPaths.repoDir);\n\n\t\t// Watch the directory containing HEAD, not HEAD itself.\n\t\t// Git uses atomic writes (write temp, rename over HEAD), which changes the inode.\n\t\t// fs.watch on a file stops working after the inode changes.\n\t\tthis.headWatcher = watchWithErrorHandler(\n\t\t\tdirname(this.gitPaths.headPath),\n\t\t\t(_eventType, filename) => {\n\t\t\t\tif (!filename || filename === \"HEAD\") {\n\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => this.handleGitWatcherError(),\n\t\t);\n\t\tif (pollGitHead) {\n\t\t\tthis.headWatchFilePath = this.gitPaths.headPath;\n\t\t\tthis.headWatchFileListener = (current, previous) => {\n\t\t\t\tif (\n\t\t\t\t\tcurrent.mtimeMs !== previous.mtimeMs ||\n\t\t\t\t\tcurrent.ctimeMs !== previous.ctimeMs ||\n\t\t\t\t\tcurrent.size !== previous.size\n\t\t\t\t) {\n\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t}\n\t\t\t};\n\t\t\twatchFile(this.headWatchFilePath, { interval: 1000 }, this.headWatchFileListener);\n\t\t}\n\t\tif (!this.headWatcher && !pollGitHead) {\n\t\t\treturn;\n\t\t}\n\n\t\t// In reftable repos, branch switches update files in the reftable directory\n\t\t// instead of HEAD. Watch it separately so the footer picks up those changes.\n\t\tconst reftableDir = join(this.gitPaths.commonGitDir, \"reftable\");\n\t\tif (existsSync(reftableDir)) {\n\t\t\tthis.reftableWatcher = watchWithErrorHandler(\n\t\t\t\treftableDir,\n\t\t\t\t() => {\n\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t},\n\t\t\t\t() => this.handleGitWatcherError(),\n\t\t\t);\n\t\t\tif (!this.reftableWatcher) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst tablesListPath = join(reftableDir, \"tables.list\");\n\t\t\tif (existsSync(tablesListPath)) {\n\t\t\t\tthis.reftableTablesListPath = tablesListPath;\n\t\t\t\tthis.reftableTablesListWatcher = watchWithErrorHandler(\n\t\t\t\t\ttablesListPath,\n\t\t\t\t\t() => {\n\t\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t\t},\n\t\t\t\t\t() => this.handleGitWatcherError(),\n\t\t\t\t);\n\t\t\t\tif (!this.reftableTablesListWatcher) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\twatchFile(tablesListPath, { interval: 250 }, (current, previous) => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tcurrent.mtimeMs !== previous.mtimeMs ||\n\t\t\t\t\t\tcurrent.ctimeMs !== previous.ctimeMs ||\n\t\t\t\t\t\tcurrent.size !== previous.size\n\t\t\t\t\t) {\n\t\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Read-only view for extensions - excludes setExtensionStatus, setAvailableProviderCount and dispose */\nexport type ReadonlyFooterDataProvider = Pick<\n\tFooterDataProvider,\n\t\"getGitBranch\" | \"getExtensionStatuses\" | \"getAvailableProviderCount\" | \"onBranchChange\" | \"getAutonomyStatus\"\n>;\n"]}
|