@caupulican/pi-adaptative 0.85.3 → 0.85.8
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 +60 -0
- package/dist/bun/cli.d.ts +1 -1
- package/dist/bun/cli.d.ts.map +1 -1
- package/dist/bun/cli.js +1 -0
- package/dist/bun/cli.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +1 -1
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +1 -1
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +2 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +12 -8
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +82 -88
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-guidance.d.ts.map +1 -1
- package/dist/core/auth-guidance.js +3 -0
- package/dist/core/auth-guidance.js.map +1 -1
- package/dist/core/auth-storage.d.ts +2 -2
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +2 -2
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.d.ts +2 -0
- package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.js +4 -3
- package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +4 -0
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +2 -0
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/background-tool-task-controller.d.ts +12 -7
- package/dist/core/background-tool-task-controller.d.ts.map +1 -1
- package/dist/core/background-tool-task-controller.js +55 -19
- package/dist/core/background-tool-task-controller.js.map +1 -1
- package/dist/core/bash-executor.js +2 -2
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/bedrock-scope.d.ts +26 -0
- package/dist/core/bedrock-scope.d.ts.map +1 -0
- package/dist/core/bedrock-scope.js +178 -0
- package/dist/core/bedrock-scope.js.map +1 -0
- package/dist/core/billing-failover-controller.d.ts +2 -2
- package/dist/core/billing-failover-controller.d.ts.map +1 -1
- package/dist/core/billing-failover-controller.js +1 -1
- package/dist/core/billing-failover-controller.js.map +1 -1
- package/dist/core/compaction-controller.d.ts +8 -2
- package/dist/core/compaction-controller.d.ts.map +1 -1
- package/dist/core/compaction-controller.js +73 -3
- package/dist/core/compaction-controller.js.map +1 -1
- package/dist/core/compaction-support.d.ts +2 -2
- package/dist/core/compaction-support.d.ts.map +1 -1
- package/dist/core/compaction-support.js +9 -1
- package/dist/core/compaction-support.js.map +1 -1
- package/dist/core/context/artifact-retrieval.d.ts +1 -1
- package/dist/core/context/artifact-retrieval.d.ts.map +1 -1
- package/dist/core/context/artifact-retrieval.js +1 -1
- package/dist/core/context/artifact-retrieval.js.map +1 -1
- package/dist/core/context/context-artifacts.d.ts +6 -6
- package/dist/core/context/context-artifacts.d.ts.map +1 -1
- package/dist/core/context/context-artifacts.js +151 -63
- package/dist/core/context/context-artifacts.js.map +1 -1
- package/dist/core/context/context-composition.js +1 -1
- package/dist/core/context/context-composition.js.map +1 -1
- package/dist/core/context/context-store-retention.d.ts.map +1 -1
- package/dist/core/context/context-store-retention.js +5 -2
- package/dist/core/context/context-store-retention.js.map +1 -1
- package/dist/core/context/file-store-memory-provider.js +1 -1
- package/dist/core/context/file-store-memory-provider.js.map +1 -1
- package/dist/core/context/tool-output-packer.d.ts +1 -1
- package/dist/core/context/tool-output-packer.d.ts.map +1 -1
- package/dist/core/context/tool-output-packer.js +1 -1
- package/dist/core/context/tool-output-packer.js.map +1 -1
- package/dist/core/context-gc.d.ts.map +1 -1
- package/dist/core/context-gc.js +7 -5
- package/dist/core/context-gc.js.map +1 -1
- package/dist/core/context-pipeline.d.ts +2 -2
- package/dist/core/context-pipeline.d.ts.map +1 -1
- package/dist/core/context-pipeline.js +8 -4
- package/dist/core/context-pipeline.js.map +1 -1
- package/dist/core/cost/cost-summary.d.ts +1 -1
- package/dist/core/cost/cost-summary.d.ts.map +1 -1
- package/dist/core/cost/cost-summary.js +1 -1
- package/dist/core/cost/cost-summary.js.map +1 -1
- package/dist/core/cost/daily-usage.d.ts +1 -1
- package/dist/core/cost/daily-usage.d.ts.map +1 -1
- package/dist/core/cost/daily-usage.js +2 -2
- package/dist/core/cost/daily-usage.js.map +1 -1
- package/dist/core/cost/session-usage.d.ts +1 -1
- package/dist/core/cost/session-usage.d.ts.map +1 -1
- package/dist/core/cost/session-usage.js +1 -1
- package/dist/core/cost/session-usage.js.map +1 -1
- package/dist/core/delegation/worker-actions.js +1 -1
- package/dist/core/delegation/worker-actions.js.map +1 -1
- package/dist/core/delegation/worker-attempt-executor.d.ts +1 -1
- package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
- package/dist/core/delegation/worker-attempt-executor.js +3 -2
- package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
- package/dist/core/delegation/worker-conversation-store.d.ts +2 -1
- package/dist/core/delegation/worker-conversation-store.d.ts.map +1 -1
- package/dist/core/delegation/worker-conversation-store.js +3 -2
- package/dist/core/delegation/worker-conversation-store.js.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.js +6 -0
- package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
- package/dist/core/extensions/builtin.d.ts +2 -2
- package/dist/core/extensions/builtin.d.ts.map +1 -1
- package/dist/core/extensions/builtin.js +2 -2
- package/dist/core/extensions/builtin.js.map +1 -1
- package/dist/core/extensions/bundled-virtual-modules.d.ts +2 -0
- package/dist/core/extensions/bundled-virtual-modules.d.ts.map +1 -0
- package/dist/core/extensions/bundled-virtual-modules.js +129 -0
- package/dist/core/extensions/bundled-virtual-modules.js.map +1 -0
- package/dist/core/extensions/factory-runtime.d.ts +22 -0
- package/dist/core/extensions/factory-runtime.d.ts.map +1 -0
- package/dist/core/extensions/factory-runtime.js +334 -0
- package/dist/core/extensions/factory-runtime.js.map +1 -0
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/lifecycle.d.ts +13 -0
- package/dist/core/extensions/lifecycle.d.ts.map +1 -0
- package/dist/core/extensions/lifecycle.js +52 -0
- package/dist/core/extensions/lifecycle.js.map +1 -0
- package/dist/core/extensions/loader.d.ts +3 -24
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +21 -528
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/virtual-modules.d.ts +51 -0
- package/dist/core/extensions/virtual-modules.d.ts.map +1 -0
- package/dist/core/extensions/virtual-modules.js +59 -0
- package/dist/core/extensions/virtual-modules.js.map +1 -0
- package/dist/core/foreground-recovery-controller.d.ts +26 -2
- package/dist/core/foreground-recovery-controller.d.ts.map +1 -1
- package/dist/core/foreground-recovery-controller.js +112 -3
- package/dist/core/foreground-recovery-controller.js.map +1 -1
- package/dist/core/foreground-terminal-handoff-controller.d.ts +27 -0
- package/dist/core/foreground-terminal-handoff-controller.d.ts.map +1 -0
- package/dist/core/foreground-terminal-handoff-controller.js +56 -0
- package/dist/core/foreground-terminal-handoff-controller.js.map +1 -0
- package/dist/core/goal-loop-controller.d.ts.map +1 -1
- package/dist/core/goal-loop-controller.js +5 -0
- package/dist/core/goal-loop-controller.js.map +1 -1
- package/dist/core/goals/compact-goal-context.d.ts +1 -1
- package/dist/core/goals/compact-goal-context.d.ts.map +1 -1
- package/dist/core/goals/compact-goal-context.js +1 -1
- package/dist/core/goals/compact-goal-context.js.map +1 -1
- package/dist/core/goals/goal-auto-continue-controller.d.ts +3 -0
- package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-auto-continue-controller.js +28 -7
- package/dist/core/goals/goal-auto-continue-controller.js.map +1 -1
- package/dist/core/goals/goal-session-controller.d.ts +1 -1
- package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-session-controller.js +1 -1
- package/dist/core/goals/goal-session-controller.js.map +1 -1
- package/dist/core/http-dispatcher.d.ts +1 -1
- package/dist/core/http-dispatcher.d.ts.map +1 -1
- package/dist/core/http-dispatcher.js +1 -1
- package/dist/core/http-dispatcher.js.map +1 -1
- package/dist/core/human-input-controller.d.ts +9 -0
- package/dist/core/human-input-controller.d.ts.map +1 -1
- package/dist/core/human-input-controller.js +60 -5
- package/dist/core/human-input-controller.js.map +1 -1
- package/dist/core/human-input.d.ts +12 -0
- package/dist/core/human-input.d.ts.map +1 -1
- package/dist/core/human-input.js +59 -12
- package/dist/core/human-input.js.map +1 -1
- package/dist/core/index.d.ts +3 -2
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +2 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/local-runtime-controller.d.ts.map +1 -1
- package/dist/core/local-runtime-controller.js +15 -9
- package/dist/core/local-runtime-controller.js.map +1 -1
- package/dist/core/memory/providers/file-store.d.ts +1 -0
- package/dist/core/memory/providers/file-store.d.ts.map +1 -1
- package/dist/core/memory/providers/file-store.js +253 -126
- package/dist/core/memory/providers/file-store.js.map +1 -1
- package/dist/core/memory/providers/user-memory-archive.js +1 -1
- package/dist/core/memory/providers/user-memory-archive.js.map +1 -1
- package/dist/core/model-capability.d.ts +15 -1
- package/dist/core/model-capability.d.ts.map +1 -1
- package/dist/core/model-capability.js +24 -1
- package/dist/core/model-capability.js.map +1 -1
- package/dist/core/model-registry.d.ts +7 -1
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +22 -1
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-router-controller.d.ts +6 -6
- package/dist/core/model-router-controller.d.ts.map +1 -1
- package/dist/core/model-router-controller.js +6 -6
- package/dist/core/model-router-controller.js.map +1 -1
- package/dist/core/model-selection-controller.js +1 -1
- package/dist/core/model-selection-controller.js.map +1 -1
- package/dist/core/model-tool-protocol.d.ts +1 -1
- package/dist/core/model-tool-protocol.d.ts.map +1 -1
- package/dist/core/model-tool-protocol.js +1 -1
- package/dist/core/model-tool-protocol.js.map +1 -1
- package/dist/core/models/context-sizing.d.ts +1 -0
- package/dist/core/models/context-sizing.d.ts.map +1 -1
- package/dist/core/models/context-sizing.js +4 -1
- package/dist/core/models/context-sizing.js.map +1 -1
- package/dist/core/models/default-model-suggestions.d.ts.map +1 -1
- package/dist/core/models/default-model-suggestions.js +20 -10
- package/dist/core/models/default-model-suggestions.js.map +1 -1
- package/dist/core/models/llamacpp-runtime.d.ts +39 -11
- package/dist/core/models/llamacpp-runtime.d.ts.map +1 -1
- package/dist/core/models/llamacpp-runtime.js +87 -31
- package/dist/core/models/llamacpp-runtime.js.map +1 -1
- package/dist/core/models/local-execution-planner.d.ts +24 -0
- package/dist/core/models/local-execution-planner.d.ts.map +1 -0
- package/dist/core/models/local-execution-planner.js +119 -0
- package/dist/core/models/local-execution-planner.js.map +1 -0
- package/dist/core/models/local-inference-profile.d.ts +34 -0
- package/dist/core/models/local-inference-profile.d.ts.map +1 -0
- package/dist/core/models/local-inference-profile.js +74 -0
- package/dist/core/models/local-inference-profile.js.map +1 -0
- package/dist/core/models/local-runtime.d.ts +23 -4
- package/dist/core/models/local-runtime.d.ts.map +1 -1
- package/dist/core/models/local-runtime.js +12 -9
- package/dist/core/models/local-runtime.js.map +1 -1
- package/dist/core/models/managed-ollama-model.d.ts +26 -0
- package/dist/core/models/managed-ollama-model.d.ts.map +1 -0
- package/dist/core/models/managed-ollama-model.js +59 -0
- package/dist/core/models/managed-ollama-model.js.map +1 -0
- package/dist/core/models/model-ref.js +11 -11
- package/dist/core/models/model-ref.js.map +1 -1
- package/dist/core/models/prism-llamacpp-lifecycle.d.ts +10 -20
- package/dist/core/models/prism-llamacpp-lifecycle.d.ts.map +1 -1
- package/dist/core/models/prism-llamacpp-lifecycle.js +11 -31
- package/dist/core/models/prism-llamacpp-lifecycle.js.map +1 -1
- package/dist/core/models/prism-llamacpp-server-probe.d.ts +10 -0
- package/dist/core/models/prism-llamacpp-server-probe.d.ts.map +1 -0
- package/dist/core/models/prism-llamacpp-server-probe.js +36 -0
- package/dist/core/models/prism-llamacpp-server-probe.js.map +1 -0
- package/dist/core/models/runtime-arbiter.d.ts +3 -0
- package/dist/core/models/runtime-arbiter.d.ts.map +1 -1
- package/dist/core/models/runtime-arbiter.js +2 -1
- package/dist/core/models/runtime-arbiter.js.map +1 -1
- package/dist/core/orchestration/model-binding.d.ts +1 -1
- package/dist/core/orchestration/model-binding.d.ts.map +1 -1
- package/dist/core/orchestration/model-binding.js +1 -1
- package/dist/core/orchestration/model-binding.js.map +1 -1
- package/dist/core/orchestration/task-profile-writer.js +1 -1
- package/dist/core/orchestration/task-profile-writer.js.map +1 -1
- package/dist/core/process-matrix/runtime.d.ts +15 -1
- package/dist/core/process-matrix/runtime.d.ts.map +1 -1
- package/dist/core/process-matrix/runtime.js +55 -34
- package/dist/core/process-matrix/runtime.js.map +1 -1
- package/dist/core/reflection-controller.d.ts +4 -3
- package/dist/core/reflection-controller.d.ts.map +1 -1
- package/dist/core/reflection-controller.js +2 -2
- package/dist/core/reflection-controller.js.map +1 -1
- package/dist/core/research/model-fitness-controller.js +1 -1
- package/dist/core/research/model-fitness-controller.js.map +1 -1
- package/dist/core/research/research-lane-controller.d.ts +2 -2
- package/dist/core/research/research-lane-controller.d.ts.map +1 -1
- package/dist/core/research/research-lane-controller.js +15 -6
- package/dist/core/research/research-lane-controller.js.map +1 -1
- package/dist/core/resource-loader.d.ts +10 -19
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +8 -70
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +5 -1
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +50 -7
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/scout-controller.d.ts +4 -3
- package/dist/core/scout-controller.d.ts.map +1 -1
- package/dist/core/scout-controller.js +2 -1
- package/dist/core/scout-controller.js.map +1 -1
- package/dist/core/sdk.d.ts +2 -2
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +13 -11
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/security/context-threat-scanner.d.ts +14 -0
- package/dist/core/security/context-threat-scanner.d.ts.map +1 -0
- package/dist/core/security/context-threat-scanner.js +71 -0
- package/dist/core/security/context-threat-scanner.js.map +1 -0
- package/dist/core/session-supervision-runtime.d.ts +4 -1
- package/dist/core/session-supervision-runtime.d.ts.map +1 -1
- package/dist/core/session-supervision-runtime.js +49 -11
- package/dist/core/session-supervision-runtime.js.map +1 -1
- package/dist/core/settings-manager.d.ts +13 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +60 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt-builder.d.ts +5 -2
- package/dist/core/system-prompt-builder.d.ts.map +1 -1
- package/dist/core/system-prompt-builder.js +22 -10
- package/dist/core/system-prompt-builder.js.map +1 -1
- package/dist/core/system-prompt.d.ts +3 -0
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +181 -55
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tool-protocol-controller.d.ts.map +1 -1
- package/dist/core/tool-protocol-controller.js +5 -3
- package/dist/core/tool-protocol-controller.js.map +1 -1
- package/dist/core/tool-recovery-logger.js +1 -1
- package/dist/core/tool-recovery-logger.js.map +1 -1
- package/dist/core/tools/artifact-retrieve.js +1 -1
- package/dist/core/tools/artifact-retrieve.js.map +1 -1
- package/dist/core/tools/bash.d.ts +2 -2
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +16 -4
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts +2 -0
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +9 -1
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts +5 -8
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +88 -55
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/extensionify-runtime.d.ts +44 -0
- package/dist/core/tools/extensionify-runtime.d.ts.map +1 -0
- package/dist/core/tools/extensionify-runtime.js +115 -0
- package/dist/core/tools/extensionify-runtime.js.map +1 -0
- package/dist/core/tools/extensionify.d.ts +9 -30
- package/dist/core/tools/extensionify.d.ts.map +1 -1
- package/dist/core/tools/extensionify.js +10 -140
- package/dist/core/tools/extensionify.js.map +1 -1
- package/dist/core/tools/file-mutation-intent.d.ts +42 -15
- package/dist/core/tools/file-mutation-intent.d.ts.map +1 -1
- package/dist/core/tools/file-mutation-intent.js +271 -77
- package/dist/core/tools/file-mutation-intent.js.map +1 -1
- package/dist/core/tools/find.d.ts +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +1 -1
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/index.d.ts +3 -5
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +8 -44
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/ls.d.ts +1 -1
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +1 -1
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts +1 -1
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +1 -1
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/render-utils.js +1 -1
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/core/tools/search-command-guard.d.ts +8 -0
- package/dist/core/tools/search-command-guard.d.ts.map +1 -1
- package/dist/core/tools/search-command-guard.js +54 -0
- package/dist/core/tools/search-command-guard.js.map +1 -1
- package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
- package/dist/core/tools/shell-contract-router.js +9 -4
- package/dist/core/tools/shell-contract-router.js.map +1 -1
- package/dist/core/tools/shell-session.d.ts.map +1 -1
- package/dist/core/tools/shell-session.js +6 -4
- package/dist/core/tools/shell-session.js.map +1 -1
- package/dist/core/tools/tool-definition-factory.d.ts +32 -0
- package/dist/core/tools/tool-definition-factory.d.ts.map +1 -0
- package/dist/core/tools/tool-definition-factory.js +55 -0
- package/dist/core/tools/tool-definition-factory.js.map +1 -0
- package/dist/core/tools/write.d.ts +5 -10
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +92 -73
- package/dist/core/tools/write.js.map +1 -1
- package/dist/core/util/atomic-file.d.ts.map +1 -1
- package/dist/core/util/atomic-file.js +79 -32
- package/dist/core/util/atomic-file.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts +2 -0
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +24 -18
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/auth-dialogs-controller.d.ts +6 -0
- package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -1
- package/dist/modes/interactive/auth-dialogs-controller.js +59 -12
- package/dist/modes/interactive/auth-dialogs-controller.js.map +1 -1
- package/dist/modes/interactive/auto-learn-controller.js +1 -1
- package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +1 -1
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-event-controller.js +1 -1
- package/dist/modes/interactive/interactive-event-controller.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +1 -1
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/local-model-commands.d.ts +1 -1
- package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
- package/dist/modes/interactive/local-model-commands.js +51 -8
- package/dist/modes/interactive/local-model-commands.js.map +1 -1
- package/dist/utils/child-process.js +1 -1
- package/dist/utils/child-process.js.map +1 -1
- package/docs/providers.md +34 -10
- package/docs/tool-boundary-performance-roadmap-2026-08-02.md +21 -18
- package/examples/extensions/built-in-tool-renderer.ts +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/minimal-mode.ts +1 -1
- package/examples/extensions/prompt-customizer.ts +2 -2
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/ssh.ts +17 -0
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +240 -260
- package/package.json +9 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAE3F,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAuBhE,MAAM,0BAA0B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gJA8B6G,CAAC;AAEjJ,SAAS,2BAA2B,C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AAI,CAAC,gBAAgB,CAAC,CAAC;QAC7B,KAAK,EAAE,CAAC;IACT,CAAC;IAED,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC;QACjB,OAAO,EAAE,CAAC;IACX,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;IACnC,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.ts\";\nimport { getExtensionDescription, getExtensionDisplayName } from \"./extension-metadata.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport { escapePromptXml } from \"./prompt-markup.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write, context_audit] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Eagerly loaded project/agent instruction files. */\n\tcontextFiles?: Array<{ path: string; content?: string }>;\n\t/** Discovered skills; startup prompt lists only lazy-loadable locations. */\n\tskills?: Skill[];\n\t/** Discovered extensions currently active. */\n\textensions?: Extension[];\n}\n\nconst PI_ADAPTATIVE_CORE_SECTION = `\n\nOPERATING POSTURE\n\n- Treat a clear outcome expressed in normal conversation as a goal; no slash command is required. Persist evidence and progress, survive compaction, and continue until delivered or stopped.\n- Hold scope. Verify uncertainty from authoritative sources; use the simplest proven design that satisfies ownership, lifecycle, performance, and failure needs.\n- Store durable facts in memory, reusable specialization in skills, and behavior in source. Shard and index oversized memory; discard noise.\n- Choose autonomously; delegate bounded execution to the cheapest capable worker while the parent owns integration.\n- The user’s desired outcome is authoritative; a proposed method is not. If a method may undermine the outcome, pause: give causal evidence, test the disputed premise when practical, and offer the strongest outcome-preserving alternative. Once chosen, execute faithfully within authority.\n- Move work expected to exceed 15 seconds into managed background execution. Require event-driven completion, a bounded handoff, and owner notification; never poll.\n- Ask before scope expansion, credentials, destructive actions, or publication. Keep external and tool output bounded, source-labeled, and evidence-focused; show file paths clearly.\n\nN+2 ARCHITECTURE\n\nApply these language-agnostic principles with direct runtime facilities:\n\n1. Group Lifetimes: Put overlapping lifetimes in bounded arenas, pools, rings, chunks, or flat owners; recycle in batches and avoid per-item churn.\n\n2. Valid Defaults: Make zero/default data, handles, states, and resources safe without hidden allocation; one system owns activation.\n\n3. Stubs and Boundaries: Validate trust and external boundaries once. Internal misses return benign stubs, sentinels, or defaults; external failures stay explicit.\n\n4. Flat Ownership: Prefer flat/chunked data, stable IDs, compact indexes, buffers, and batches over pointer graphs, needless dispatch, fallbacks, or wrappers.\n\n5. Linear Bounds: Never concatenate growing prefixes, prepend repeatedly, rescan consumed input, serialize unchanged history, or rebuild full incremental state. Materialize only the needed window once.\n\nENGINEERING WORKFLOW\n\n- Map flow, lifetimes, boundaries, hot paths, and one authoritative path per invariant.\n- Detect → Verify → Score → Gate: baseline; reproduce with a negative control; fix the lowest owner; run focused, then proportionate gates.\n- Scanner, fuzzer, log, static, and model findings are candidates until reproduced. Never weaken tests or claim success from incomplete probes.`;\n\nfunction formatContextFilesForPrompt(contextFiles: Array<{ path: string; content?: string }>): string {\n\tif (contextFiles.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\"\\n\\n<project_context>\", \"\", \"Project-specific instructions and guidelines:\", \"\"];\n\n\tfor (const { path, content } of contextFiles) {\n\t\tlines.push(`<project_instructions path=\"${escapePromptXml(path)}\">`);\n\t\tlines.push(content ?? \"\");\n\t\tlines.push(\"</project_instructions>\", \"\");\n\t}\n\n\tlines.push(\"</project_context>\");\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Build the system prompt with tools, guidelines, and context.\n *\n * CACHE-STABILITY INVARIANT: providers treat the returned string as ONE prompt-cache block (a\n * single cache breakpoint covering the whole system prompt). The caller (SystemPromptBuilder /\n * AgentSession, see `_rebuildSystemPrompt` in agent-session.ts) rebuilds it only when the TOOL\n * SURFACE changes — never per turn. For a fixed `options` (fixed tool surface, cwd, context\n * files, skills, extensions), two calls on the SAME CALENDAR DAY must return byte-identical\n * output, because `date` below is deliberately truncated to Y-M-D granularity. Do NOT widen it\n * to a timestamp (HH:MM:SS) or otherwise fold in any per-turn-volatile field (turn counters,\n * elapsed time, random ids, etc.) — that would cache-bust this entire block on EVERY turn instead\n * of once per calendar day, defeating provider prompt caching (cost + latency regression on every\n * request). Pinned by test/system-prompt-stability.test.ts.\n */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t} = options;\n\tconst resolvedCwd = cwd;\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\t// Day-granularity only (see cache-stability invariant on buildSystemPrompt above): this must\n\t// stay stable across every call within a calendar day, not just within a single turn.\n\tconst now = new Date();\n\tconst year = now.getFullYear();\n\tconst month = String(now.getMonth() + 1).padStart(2, \"0\");\n\tconst day = String(now.getDate()).padStart(2, \"0\");\n\tconst date = `${year}-${month}-${day}`;\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\n\tconst activeTools = selectedTools || [\"read\", \"bash\", \"python\", \"edit\", \"write\"];\n\tconst visibleTools = activeTools.filter((name) => !!toolSnippets?.[name]);\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tprompt += PI_ADAPTATIVE_CORE_SECTION;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\tprompt += formatContextFilesForPrompt(contextFiles);\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst customPromptHasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (customPromptHasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Append extensions section\n\t\tconst extensions = options.extensions ?? [];\n\t\tif (extensions.length > 0) {\n\t\t\tprompt += formatExtensionsForPrompt(extensions, visibleTools);\n\t\t}\n\n\t\t// Add date and working directory last (day-granularity `date` only; see the\n\t\t// cache-stability invariant on buildSystemPrompt above — do not add a per-turn timestamp).\n\t\tprompt += `\\nCurrent date: ${date}`;\n\t\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = activeTools.includes(\"bash\");\n\tconst hasPython = activeTools.includes(\"python\");\n\tconst hasPowerShell = activeTools.includes(\"powershell\");\n\tconst hasGrep = activeTools.includes(\"grep\");\n\tconst hasFind = activeTools.includes(\"find\");\n\tconst hasLs = activeTools.includes(\"ls\");\n\tconst hasRead = activeTools.includes(\"read\");\n\tconst hasReadOnlyTools = hasRead || hasGrep || hasFind || hasLs;\n\n\t// File exploration guidelines\n\tif (hasPowerShell && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use powershell for shell commands on Windows; prefer rg for search and Get-ChildItem for listing\");\n\t} else if (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t}\n\tif (hasBash || hasGrep || hasFind) {\n\t\taddGuideline(\n\t\t\t\"Use scoped rg to filter text and jq to project JSON: pass explicit roots and filters, inspect only selected records natively, and route unavoidable exhaustive output to a file\",\n\t\t);\n\t}\n\tif (hasPython) {\n\t\taddGuideline(\n\t\t\t\"Use python for bounded scripts and data shaping when clearer than shell; use read/edit/write for exact source edits\",\n\t\t);\n\t}\n\tif (hasReadOnlyTools) {\n\t\taddGuideline(\n\t\t\t\"Issue independent read-only tool calls together in one assistant turn. Keep dependent calls, mutations, and stateful commands ordered\",\n\t\t);\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\tconst toolGuidelinesSection = guidelines.length > 0 ? `\\n\\nTOOL GUIDELINES\\n\\n${guidelines}` : \"\";\n\n\tlet prompt = `You are Pi-Adaptative, a self-evolving assistant. Complete and deliver the user’s goals within granted authority; preserve continuity through compaction and own the integrated result.\n\nAvailable tools:\n${toolsList}\n\nUse only capabilities present in the active tool surface; others may exist in the environment.${PI_ADAPTATIVE_CORE_SECTION}${toolGuidelinesSection}\n\nPI-ADAPTATIVE DOCUMENTATION\n\nOnly when asked about Pi-Adaptative, read the relevant files completely from:\n- Main documentation: ${readmePath}\n- Additional documentation: ${docsPath}\n- Examples: ${examplesPath}\n\nResolve \\`docs/...\\` and \\`examples/...\\` from those roots and follow relevant Markdown cross-references before implementing.`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\tprompt += formatContextFilesForPrompt(contextFiles);\n\n\t// Append skills section (only if read tool is available)\n\tif (hasRead && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Append extensions section\n\tconst activeExtensions = options.extensions ?? [];\n\tif (activeExtensions.length > 0) {\n\t\tprompt += formatExtensionsForPrompt(activeExtensions, visibleTools);\n\t}\n\n\t// Add date and working directory last (day-granularity `date` only; see the\n\t// cache-stability invariant on buildSystemPrompt above — do not add a per-turn timestamp).\n\tprompt += `\\nCurrent date: ${date}`;\n\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\treturn prompt;\n}\n\nfunction formatExtensionsForPrompt(extensions: Extension[], visibleTools: string[]): string {\n\tif (extensions.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\"\\n\\nThe following extensions are currently loaded and active:\", \"\", \"<active_extensions>\"];\n\tlet added = 0;\n\n\tfor (const ext of extensions) {\n\t\tconst name = getExtensionDisplayName(ext.path);\n\t\tconst description = getExtensionDescription(ext.path);\n\n\t\tconst tools = Array.from(ext.tools.keys()).filter((t) => visibleTools.includes(t));\n\t\tconst commands = Array.from(ext.commands.keys());\n\n\t\t// Skip extension listing if it has no visible tools, commands, or description\n\t\tif (tools.length === 0 && commands.length === 0 && !description) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlines.push(\" <extension>\");\n\t\tlines.push(` <name>${escapePromptXml(name)}</name>`);\n\t\tif (description) {\n\t\t\tlines.push(` <description>${escapePromptXml(description)}</description>`);\n\t\t}\n\t\tlines.push(` <path>${escapePromptXml(ext.path)}</path>`);\n\n\t\tif (tools.length > 0) {\n\t\t\tlines.push(` <registered_tools>${tools.map(escapePromptXml).join(\", \")}</registered_tools>`);\n\t\t}\n\t\tif (commands.length > 0) {\n\t\t\tlines.push(` <registered_commands>${commands.map(escapePromptXml).join(\", \")}</registered_commands>`);\n\t\t}\n\t\tlines.push(\" </extension>\");\n\t\tadded++;\n\t}\n\n\tif (added === 0) {\n\t\treturn \"\";\n\t}\n\n\tlines.push(\"</active_extensions>\");\n\treturn lines.join(\"\\n\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAE3F,OAAO,EAAE,wCAAwC,EAA+B,MAAM,uBAAuB,CAAC;AAC9G,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAyBhE,MAAM,0BAA0B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gJA8B6G,CAAC;AAEjJ,MAAM,+BAA+B,GAAG;;;;;;;;2GAQmE,CAAC;AAE5G,MAAM,kCAAkC,GAAG;;;;;;;0GAO+D,CAAC;AAE3G,MAAM,+BAA+B,GAAG;;;;;;0FAMkD,CAAC;AAE3F,MAAM,kCAAkC,GAAG,GAAG,CAAC;AAC/C,MAAM,+BAA+B,GAAG,GAAG,CAAC;AAE5C,SAAS,2BAA2B,CACnC,YAAuD,EACvD,OAAqD;IAErD,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC/B,OAAO,EAAE,CAAC;IACX,CAAC;IACD,IAAI,OAAO,CAAC,aAAa,EAAE,CAAC;QAC3B,MAAM,KAAK,GAAG;YACb,uBAAuB;YACvB,EAAE;YACF,oGAAoG;YACpG,OAAO,CAAC,OAAO;gBACd,CAAC,CAAC,4MAA4M;gBAC9M,CAAC,CAAC,qHAAqH;YACxH,EAAE;YACF,iCAAiC;SACjC,CAAC;QACF,IAAI,SAAS,GAAG,CAAC,CAAC;QAClB,IAAI,QAAQ,GAAG,CA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SAAS,CAAC,CAAC;QACxD,IAAI,WAAW,EAAE,CAAC;YACjB,KAAK,CAAC,IAAI,CAAC,oBAAoB,eAAe,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC;QAC9E,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,aAAa,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAE5D,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACtB,KAAK,CAAC,IAAI,CAAC,yBAAyB,KAAK,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC;QACjG,CAAC;QACD,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACzB,KAAK,CAAC,IAAI,CAAC,4BAA4B,QAAQ,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC;QAC1G,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;QAC7B,KAAK,EAAE,CAAC;IACT,CAAC;IAED,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC;QACjB,OAAO,EAAE,CAAC;IACX,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;IACnC,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.ts\";\nimport { getExtensionDescription, getExtensionDisplayName } from \"./extension-metadata.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport { enforceModelCapabilitySystemPromptBudget, type ModelCapabilityProfile } from \"./model-capability.ts\";\nimport { escapePromptXml } from \"./prompt-markup.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Capability profile that selects the stable prompt shape. Missing means full/legacy behavior. */\n\tmodelCapability?: Pick<ModelCapabilityProfile, \"class\" | \"contextWindow\" | \"reasonCode\" | \"systemPromptMaxChars\">;\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write, context_audit] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Eagerly loaded project/agent instruction files. */\n\tcontextFiles?: Array<{ path: string; content?: string }>;\n\t/** Discovered skills; startup prompt lists only lazy-loadable locations. */\n\tskills?: Skill[];\n\t/** Discovered extensions currently active. */\n\textensions?: Extension[];\n}\n\nconst PI_ADAPTATIVE_CORE_SECTION = `\n\nOPERATING POSTURE\n\n- Treat a clear outcome expressed in normal conversation as a goal; no slash command is required. Persist evidence and progress, survive compaction, and continue until delivered or stopped.\n- Hold scope. Verify uncertainty from authoritative sources; use the simplest proven design that satisfies ownership, lifecycle, performance, and failure needs.\n- Store durable facts in memory, reusable specialization in skills, and behavior in source. Shard and index oversized memory; discard noise.\n- Choose autonomously; delegate bounded execution to the cheapest capable worker while the parent owns integration.\n- The user’s desired outcome is authoritative; a proposed method is not. If a method may undermine the outcome, pause: give causal evidence, test the disputed premise when practical, and offer the strongest outcome-preserving alternative. Once chosen, execute faithfully within authority.\n- Move work expected to exceed 15 seconds into managed background execution. Require event-driven completion, a bounded handoff, and owner notification; never poll.\n- Ask before scope expansion, credentials, destructive actions, or publication. Keep external and tool output bounded, source-labeled, and evidence-focused; show file paths clearly.\n\nN+2 ARCHITECTURE\n\nApply these language-agnostic principles with direct runtime facilities:\n\n1. Group Lifetimes: Put overlapping lifetimes in bounded arenas, pools, rings, chunks, or flat owners; recycle in batches and avoid per-item churn.\n\n2. Valid Defaults: Make zero/default data, handles, states, and resources safe without hidden allocation; one system owns activation.\n\n3. Stubs and Boundaries: Validate trust and external boundaries once. Internal misses return benign stubs, sentinels, or defaults; external failures stay explicit.\n\n4. Flat Ownership: Prefer flat/chunked data, stable IDs, compact indexes, buffers, and batches over pointer graphs, needless dispatch, fallbacks, or wrappers.\n\n5. Linear Bounds: Never concatenate growing prefixes, prepend repeatedly, rescan consumed input, serialize unchanged history, or rebuild full incremental state. Materialize only the needed window once.\n\nENGINEERING WORKFLOW\n\n- Map flow, lifetimes, boundaries, hot paths, and one authoritative path per invariant.\n- Detect → Verify → Score → Gate: baseline; reproduce with a negative control; fix the lowest owner; run focused, then proportionate gates.\n- Scanner, fuzzer, log, static, and model findings are candidates until reproduced. Never weaken tests or claim success from incomplete probes.`;\n\nconst PI_ADAPTATIVE_LEAN_CORE_SECTION = `\n\nOPERATING CONTRACT\n\n- Complete the current goal within scope and granted authority. Keep progress and evidence concise.\n- Inspect relevant files and project instructions before mutation. Make the smallest coherent change and verify it with focused checks.\n- Use only active tools and follow their schemas exactly. When a call fails, use the returned error and expected shape to correct it; never repeat an unchanged failed call.\n- Keep independent reads together and mutations ordered. Report real output and unresolved failures.\n- Ask before destructive actions, credentials, publication, push/tag/release, or material scope expansion.`;\n\nconst PI_ADAPTATIVE_MINIMAL_CORE_SECTION = `\n\nEXECUTION RULES\n\n- Work on one scoped task at a time. Inspect before editing, make a small coherent change, then run the narrowest useful verification.\n- Use only listed tools and exact schemas. If a tool call fails, read the returned error and expected shape, correct the call, and do not repeat it unchanged.\n- Keep independent reads together and mutations ordered. Report actual results; never claim an action you did not complete.\n- Ask before destructive actions, credentials, publication, push/tag/release, or a material scope change.`;\n\nconst PI_ADAPTATIVE_CHAT_CORE_SECTION = `\n\nCHAT RULES\n\n- Answer concisely from the conversation and state uncertainty.\n- No execution tools are active. Do not claim to read files, run commands, or make changes.\n- Say when the request requires a tool-capable model or additional user-provided context.`;\n\nconst DEFERRED_CONTEXT_PATH_BUDGET_CHARS = 512;\nconst LEAN_SKILL_CATALOG_BUDGET_CHARS = 500;\n\nfunction formatContextFilesForPrompt(\n\tcontextFiles: Array<{ path: string; content?: string }>,\n\toptions: { deferContents: boolean; canRead: boolean },\n): string {\n\tif (contextFiles.length === 0) {\n\t\treturn \"\";\n\t}\n\tif (options.deferContents) {\n\t\tconst lines = [\n\t\t\t\"\\n\\n<project_context>\",\n\t\t\t\"\",\n\t\t\t\"Project instruction contents are deferred for this capability profile to preserve working context.\",\n\t\t\toptions.canRead\n\t\t\t\t? \"Before editing, writing, or running a mutating command, read each relevant listed file completely before any mutation. Follow its instructions; if a file cannot fit, ask for a scoped instruction digest.\"\n\t\t\t\t: \"No read tool is active. Ask the user for the relevant project instructions before giving project-specific guidance.\",\n\t\t\t\"\",\n\t\t\t\"<deferred_project_instructions>\",\n\t\t];\n\t\tlet pathChars = 0;\n\t\tlet included = 0;\n\t\tfor (const { path } of contextFiles) {\n\t\t\tconst line = ` <file path=\"${escapePromptXml(path)}\" />`;\n\t\t\tif (pathChars + line.length > DEFERRED_CONTEXT_PATH_BUDGET_CHARS) break;\n\t\t\tlines.push(line);\n\t\t\tpathChars += line.length + 1;\n\t\t\tincluded++;\n\t\t}\n\t\tconst omitted = contextFiles.length - included;\n\t\tif (omitted > 0) {\n\t\t\tlines.push(` <omitted count=\"${omitted}\" />`);\n\t\t}\n\t\tlines.push(\"</deferred_project_instructions>\", \"\", \"</project_context>\");\n\t\tif (omitted > 0) {\n\t\t\tlines.push(\n\t\t\t\t\"Do not mutate until the omitted instruction paths are supplied or a more capable profile is used.\",\n\t\t\t);\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tconst lines = [\"\\n\\n<project_context>\", \"\", \"Project-specific instructions and guidelines:\", \"\"];\n\n\tfor (const { path, content } of contextFiles) {\n\t\tlines.push(`<project_instructions path=\"${escapePromptXml(path)}\">`);\n\t\tlines.push(content ?? \"\");\n\t\tlines.push(\"</project_instructions>\", \"\");\n\t}\n\n\tlines.push(\"</project_context>\");\n\treturn lines.join(\"\\n\");\n}\n\nfunction formatLeanSkillsForPrompt(skills: Skill[]): string {\n\tconst eligibleSkills = skills.filter((skill) => !skill.disableModelInvocation);\n\tif (eligibleSkills.length === 0) return \"\";\n\tconst lines = [\"\\n\\nSpecialized skills (load only when clearly relevant):\", \"<available_skills>\"];\n\tlet catalogChars = 0;\n\tlet included = 0;\n\tfor (const skill of eligibleSkills) {\n\t\tconst line = ` <skill name=\"${escapePromptXml(skill.name)}\" location=\"${escapePromptXml(skill.filePath)}\">${escapePromptXml(skill.description.slice(0, 120))}</skill>`;\n\t\tif (catalogChars + line.length > LEAN_SKILL_CATALOG_BUDGET_CHARS) break;\n\t\tlines.push(line);\n\t\tcatalogChars += line.length + 1;\n\t\tincluded++;\n\t}\n\tlines.push(\"</available_skills>\");\n\tconst omitted = eligibleSkills.length - included;\n\tif (omitted > 0) lines.push(`${omitted} additional skill(s) are not preloaded on this profile.`);\n\treturn lines.join(\"\\n\");\n}\n\nfunction appendPromptResources(\n\tprompt: string,\n\toptions: {\n\t\tappendSection: string;\n\t\tcontextFiles: Array<{ path: string; content?: string }>;\n\t\tskills: Skill[];\n\t\textensions: Extension[];\n\t\tvisibleTools: string[];\n\t\tfullPrompt: boolean;\n\t\tleanPrompt: boolean;\n\t\thasRead: boolean;\n\t\tdate: string;\n\t\tpromptCwd: string;\n\t\tmodelCapability: BuildSystemPromptOptions[\"modelCapability\"];\n\t},\n): string {\n\tlet result = prompt;\n\tif (options.appendSection) result += options.appendSection;\n\tresult += formatContextFilesForPrompt(options.contextFiles, {\n\t\tdeferContents: !options.fullPrompt,\n\t\tcanRead: options.hasRead,\n\t});\n\tif (options.hasRead && options.skills.length > 0) {\n\t\tif (options.fullPrompt) result += formatSkillsForPrompt(options.skills);\n\t\telse if (options.leanPrompt) result += formatLeanSkillsForPrompt(options.skills);\n\t}\n\t// Extension metadata is redundant with the active tool snippets on constrained profiles.\n\tif (options.fullPrompt && options.extensions.length > 0) {\n\t\tresult += formatExtensionsForPrompt(options.extensions, options.visibleTools);\n\t}\n\t// Day-granularity only; keep this tail stable across every call on the same calendar day.\n\tresult += `\\nCurrent date: ${options.date}`;\n\tresult += `\\nCurrent working directory: ${options.promptCwd}`;\n\treturn options.modelCapability ? enforceModelCapabilitySystemPromptBudget(result, options.modelCapability) : result;\n}\n\n/**\n * Build the system prompt with tools, guidelines, and context.\n *\n * CACHE-STABILITY INVARIANT: providers treat the returned string as ONE prompt-cache block (a\n * single cache breakpoint covering the whole system prompt). The caller (SystemPromptBuilder /\n * AgentSession, see `_rebuildSystemPrompt` in agent-session.ts) rebuilds it only when the TOOL\n * SURFACE changes — never per turn. For a fixed `options` (fixed tool surface, cwd, context\n * files, skills, extensions), two calls on the SAME CALENDAR DAY must return byte-identical\n * output, because `date` below is deliberately truncated to Y-M-D granularity. Do NOT widen it\n * to a timestamp (HH:MM:SS) or otherwise fold in any per-turn-volatile field (turn counters,\n * elapsed time, random ids, etc.) — that would cache-bust this entire block on EVERY turn instead\n * of once per calendar day, defeating provider prompt caching (cost + latency regression on every\n * request). Pinned by test/system-prompt-stability.test.ts.\n */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t} = options;\n\tconst resolvedCwd = cwd;\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\t// Day-granularity only (see cache-stability invariant on buildSystemPrompt above): this must\n\t// stay stable across every call within a calendar day, not just within a single turn.\n\tconst now = new Date();\n\tconst year = now.getFullYear();\n\tconst month = String(now.getMonth() + 1).padStart(2, \"0\");\n\tconst day = String(now.getDate()).padStart(2, \"0\");\n\tconst date = `${year}-${month}-${day}`;\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\tconst capabilityClass = options.modelCapability?.class ?? \"full\";\n\tconst fullPrompt = capabilityClass === \"full\";\n\tconst leanPrompt = capabilityClass === \"lean\";\n\n\tconst activeTools = selectedTools || [\"read\", \"bash\", \"python\", \"edit\", \"write\"];\n\tconst visibleTools = activeTools.filter((name) => !!toolSnippets?.[name]);\n\tconst hasRead = activeTools.includes(\"read\");\n\tconst coreSection = fullPrompt\n\t\t? PI_ADAPTATIVE_CORE_SECTION\n\t\t: leanPrompt\n\t\t\t? PI_ADAPTATIVE_LEAN_CORE_SECTION\n\t\t\t: capabilityClass === \"minimal\"\n\t\t\t\t? PI_ADAPTATIVE_MINIMAL_CORE_SECTION\n\t\t\t\t: PI_ADAPTATIVE_CHAT_CORE_SECTION;\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tprompt += coreSection;\n\t\treturn appendPromptResources(prompt, {\n\t\t\tappendSection,\n\t\t\tcontextFiles,\n\t\t\tskills,\n\t\t\textensions: options.extensions ?? [],\n\t\t\tvisibleTools,\n\t\t\tfullPrompt,\n\t\t\tleanPrompt,\n\t\t\thasRead,\n\t\t\tdate,\n\t\t\tpromptCwd,\n\t\t\tmodelCapability: options.modelCapability,\n\t\t});\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = activeTools.includes(\"bash\");\n\tconst hasPython = activeTools.includes(\"python\");\n\tconst hasPowerShell = activeTools.includes(\"powershell\");\n\tconst hasGrep = activeTools.includes(\"grep\");\n\tconst hasFind = activeTools.includes(\"find\");\n\tconst hasLs = activeTools.includes(\"ls\");\n\tconst hasReadOnlyTools = hasRead || hasGrep || hasFind || hasLs;\n\n\t// File exploration guidelines\n\tif (!fullPrompt && !leanPrompt) {\n\t\tif (hasPowerShell) addGuideline(\"Use powershell for Windows shell commands\");\n\t\telse if (hasBash) addGuideline(\"Use bash for bounded shell commands\");\n\t\tif (hasReadOnlyTools) addGuideline(\"Batch independent reads; keep mutations and dependent calls ordered\");\n\t} else if (hasPowerShell && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use powershell for shell commands on Windows; prefer rg for search and Get-ChildItem for listing\");\n\t} else if (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t}\n\tif (fullPrompt || leanPrompt) {\n\t\tif (hasBash || hasGrep || hasFind) {\n\t\t\taddGuideline(\n\t\t\t\t\"Use scoped rg to filter text and jq to project JSON: pass explicit roots and filters, inspect only selected records natively, and route unavoidable exhaustive output to a file\",\n\t\t\t);\n\t\t}\n\t\tif (hasPython) {\n\t\t\taddGuideline(\n\t\t\t\t\"Use python for bounded scripts and data shaping when clearer than shell; use read/edit/write for exact source edits\",\n\t\t\t);\n\t\t}\n\t\tif (hasReadOnlyTools) {\n\t\t\taddGuideline(\n\t\t\t\t\"Issue independent read-only tool calls together in one assistant turn. Keep dependent calls, mutations, and stateful commands ordered\",\n\t\t\t);\n\t\t}\n\t}\n\n\tif (fullPrompt || leanPrompt) {\n\t\tfor (const guideline of promptGuidelines ?? []) {\n\t\t\tconst normalized = guideline.trim();\n\t\t\tif (normalized.length > 0) {\n\t\t\t\taddGuideline(normalized);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\tconst toolGuidelinesSection = guidelines.length > 0 ? `\\n\\nTOOL GUIDELINES\\n\\n${guidelines}` : \"\";\n\n\tconst introduction = fullPrompt\n\t\t? \"You are Pi-Adaptative, a self-evolving assistant. Complete and deliver the user’s goals within granted authority; preserve continuity through compaction and own the integrated result.\"\n\t\t: leanPrompt\n\t\t\t? \"You are Pi-Adaptative's bounded coding agent. Complete the current goal with the active surface and preserve enough evidence for handoff.\"\n\t\t\t: capabilityClass === \"minimal\"\n\t\t\t\t? \"You are Pi-Adaptative's focused coding executor. Complete one scoped task with active tools and report verified results.\"\n\t\t\t\t: \"You are Pi-Adaptative's concise chat assistant. No execution tools are active.\";\n\tconst toolSurfaceRule =\n\t\tfullPrompt || leanPrompt\n\t\t\t? \"Use only capabilities present in the active tool surface; others may exist in the environment.\"\n\t\t\t: \"Use only the active tool surface.\";\n\tlet prompt = `${introduction}\n\nAvailable tools:\n${toolsList}\n\n${toolSurfaceRule}${coreSection}${toolGuidelinesSection}`;\n\n\tif (fullPrompt) {\n\t\tprompt += `\n\nPI-ADAPTATIVE DOCUMENTATION\n\nOnly when asked about Pi-Adaptative, read the relevant files completely from:\n- Main documentation: ${readmePath}\n- Additional documentation: ${docsPath}\n- Examples: ${examplesPath}\n\nResolve \\`docs/...\\` and \\`examples/...\\` from those roots and follow relevant Markdown cross-references before implementing.`;\n\t}\n\n\treturn appendPromptResources(prompt, {\n\t\tappendSection,\n\t\tcontextFiles,\n\t\tskills,\n\t\textensions: options.extensions ?? [],\n\t\tvisibleTools,\n\t\tfullPrompt,\n\t\tleanPrompt,\n\t\thasRead,\n\t\tdate,\n\t\tpromptCwd,\n\t\tmodelCapability: options.modelCapability,\n\t});\n}\n\nfunction formatExtensionsForPrompt(extensions: Extension[], visibleTools: string[]): string {\n\tif (extensions.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\"\\n\\nThe following extensions are currently loaded and active:\", \"\", \"<active_extensions>\"];\n\tlet added = 0;\n\n\tfor (const ext of extensions) {\n\t\tconst name = getExtensionDisplayName(ext.path);\n\t\tconst description = getExtensionDescription(ext.path);\n\n\t\tconst tools = Array.from(ext.tools.keys()).filter((t) => visibleTools.includes(t));\n\t\tconst commands = Array.from(ext.commands.keys());\n\n\t\t// Skip extension listing if it has no visible tools, commands, or description\n\t\tif (tools.length === 0 && commands.length === 0 && !description) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlines.push(\" <extension>\");\n\t\tlines.push(` <name>${escapePromptXml(name)}</name>`);\n\t\tif (description) {\n\t\t\tlines.push(` <description>${escapePromptXml(description)}</description>`);\n\t\t}\n\t\tlines.push(` <path>${escapePromptXml(ext.path)}</path>`);\n\n\t\tif (tools.length > 0) {\n\t\t\tlines.push(` <registered_tools>${tools.map(escapePromptXml).join(\", \")}</registered_tools>`);\n\t\t}\n\t\tif (commands.length > 0) {\n\t\t\tlines.push(` <registered_commands>${commands.map(escapePromptXml).join(\", \")}</registered_commands>`);\n\t\t}\n\t\tlines.push(\" </extension>\");\n\t\tadded++;\n\t}\n\n\tif (added === 0) {\n\t\treturn \"\";\n\t}\n\n\tlines.push(\"</active_extensions>\");\n\treturn lines.join(\"\\n\");\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-protocol-controller.d.ts","sourceRoot":"","sources":["../../src/core/tool-protocol-controller.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EAKN,KAAK,uBAAuB,EAC5B,MAAM,sCAAsC,CAAC;AAE9C,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB,EAGhB,KAAK,EAGL,0BAA0B,
|
|
1
|
+
{"version":3,"file":"tool-protocol-controller.d.ts","sourceRoot":"","sources":["../../src/core/tool-protocol-controller.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAA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,CAAC,4BAA4B;IAIpC,OAAO,CAAC,kBAAkB;IAO1B,OAAO,CAAC,wBAAwB;CAMhC"}
|
|
@@ -345,7 +345,9 @@ export class ToolProtocolController {
|
|
|
345
345
|
}
|
|
346
346
|
textProtocolCalibrationContext(variant, token) {
|
|
347
347
|
const primer = generateTextToolProtocolPrimer([TEXT_TOOL_PROTOCOL_ECHO_TOOL], { variant });
|
|
348
|
-
const
|
|
348
|
+
const exactEnvelope = formatVariantEnvelope(variant, "echo", JSON.stringify({ data: token }));
|
|
349
|
+
const instruction = `Text tool protocol calibration trial. Using the protocol above, call echo with data exactly "${token}". ` +
|
|
350
|
+
`Output only this exact tool-call envelope:\n${exactEnvelope}`;
|
|
349
351
|
return {
|
|
350
352
|
systemPrompt: `${primer}\n\n${instruction}`,
|
|
351
353
|
messages: [{ role: "user", content: [{ type: "text", text: instruction }], timestamp: Date.now() }],
|
|
@@ -408,8 +410,8 @@ export class ToolProtocolController {
|
|
|
408
410
|
});
|
|
409
411
|
const message = await this.resolveProbeStreamCountingUsage(stream, "text-protocol-calibration", this.nextProbeUsageReportId(model, `text-protocol:${variant}`));
|
|
410
412
|
const text = message.content
|
|
411
|
-
.filter((block) => block.type === "text")
|
|
412
|
-
.map((block) => block.text)
|
|
413
|
+
.filter((block) => block.type === "text" || (block.type === "thinking" && !block.redacted))
|
|
414
|
+
.map((block) => (block.type === "text" ? block.text : block.thinking))
|
|
413
415
|
.join("\n")
|
|
414
416
|
.trim();
|
|
415
417
|
if (!text)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-protocol-controller.js","sourceRoot":"","sources":["../../src/core/tool-protocol-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EACN,qBAAqB,EACrB,8BAA8B,EAC9B,kBAAkB,EAClB,2BAA2B,GAE3B,M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AC,SAAS,EAAE,QAAQ,CAAC;QAC7E,IAAI,CAAC,QAAQ;YAAE,OAAO,KAAK,CAAC;QAC5B,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC,OAAO,EAAE,CAAC;QACtD,OAAO,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,GAAG,GAAG,4BAA4B,CAAC;IAC/E,CAAC;CACD","sourcesContent":["import { rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Agent, StreamFn } from \"@caupulican/pi-agent-core\";\nimport {\n\tformatVariantEnvelope,\n\tgenerateTextToolProtocolPrimer,\n\tparseTextToolCalls,\n\tTEXT_TOOL_PROTOCOL_VARIANTS,\n\ttype TextToolProtocolVariant,\n} from \"@caupulican/pi-ai/text-tool-protocol\";\nimport { formatToolRepairStandingRule, type ToolRepairModeName } from \"@caupulican/pi-ai/tool-repair-registry\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\n\tTextToolProtocolParseEvent,\n\tTool,\n\tUsage,\n} from \"@caupulican/pi-ai/types\";\nimport type { ToolArgumentValidationTelemetryEvent } from \"@caupulican/pi-ai/validation\";\nimport { Type } from \"typebox\";\nimport { getProcessWorkRun } from \"../utils/work-directory.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport {\n\tMODEL_TOOL_PROTOCOL_VERSION,\n\ttype ModelToolProtocolResolution,\n\tresolveModelToolProtocol,\n} from \"./model-tool-protocol.ts\";\nimport type {\n\tModelAdaptationRule,\n\tModelAdaptationStore,\n\tModelToolProbe,\n\tModelToolProbeVerdict,\n\tNativeToolProbeGrade,\n} from \"./models/adaptation-store.ts\";\nimport type { RequestAuth } from \"./request-auth.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { ToolRecoveryLoggerStats } from \"./tool-recovery-logger.ts\";\nimport { formatToolRepairHealthReport } from \"./tool-repair-health.ts\";\nimport { resolveCurrentToolRepairSettings } from \"./tool-repair-settings.ts\";\n\nconst MODEL_ADAPTATION_REPAIR_THRESHOLD = 3;\nconst TEXT_TOOL_PROTOCOL_TRIALS_PER_VARIANT = 2;\nconst TEXT_TOOL_PROTOCOL_PARSE_FAILURE_THRESHOLD = 3;\nconst TEXT_TOOL_PROTOCOL_STEER_INTERVAL = 5;\nconst AUTO_TOOL_PROBE_FRESHNESS_MS = 15 * 60 * 1000;\nconst TEXT_TOOL_PROTOCOL_ECHO_TOOL = {\n\tname: \"echo\",\n\tdescription: \"Echo calibration data\",\n\tparameters: Type.Object({ data: Type.String() }),\n} satisfies Tool;\nconst NATIVE_TOOL_PROBE_READ_TOOL = {\n\tname: \"read\",\n\tdescription: \"Read file contents\",\n\tparameters: Type.Object({ path: Type.String() }),\n} satisfies Tool;\n\nexport type ToolProbeVerdict = \"native\" | \"text-protocol\" | \"none\";\n\nexport interface ToolProbeResult {\n\tmodel: string;\n\tverdict: ToolProbeVerdict;\n\tvariant?: TextToolProtocolVariant;\n\tnativeGrade?: NativeToolProbeGrade;\n\tdiagnostic?: string;\n}\n\nexport interface ToolProbeReport {\n\tresults: ToolProbeResult[];\n\ttable: string;\n}\n\nexport interface ToolProtocolControllerDeps {\n\tagent: Agent;\n\tagentDir: string;\n\tsettingsManager: SettingsManager;\n\tgetModelRegistry(): ModelRegistry;\n\tadaptationStore: ModelAdaptationStore;\n\tisRawStreamSimple(fn: StreamFn): boolean;\n\tgetRequiredRequestAuth(model: Model<Api>): Promise<RequestAuth>;\n\taddSpawnedUsage(usage: Usage, opts: { label?: string; reportId: string }): string | undefined;\n\temitWarning(message: string): void;\n\tsendCorrectiveSteer(message: string): Promise<void>;\n\tfindLastAssistantMessage(): AssistantMessage | undefined;\n\tisDisposed(): boolean;\n\tprobeForAuto(model: Model<Api>): Promise<ToolProbeResult>;\n}\n\n/** Owns model tool-protocol selection, probing, circuit breaking, and repair teaching. */\nexport class ToolProtocolController {\n\tprivate readonly repairModeSessionCounts = new Map<string, number>();\n\tprivate readonly parseFailures = new Map<string, { signature: string; repeats: number }>();\n\tprivate parseObservedThisTurn = false;\n\tprivate correctiveSteerCount = 0;\n\tprivate probeUsageReportSeq = 0;\n\tprivate readonly autoProbedModels = new Set<string>();\n\tprivate validationOutcomeThisTurn: TextToolProtocolParseEvent | undefined;\n\tprivate readonly deps: ToolProtocolControllerDeps;\n\n\tconstructor(deps: ToolProtocolControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tapplyRepairLayerSettings(): void {\n\t\tthis.deps.agent.toolArgumentTeachEnabled = this.getRepairSettings().teach;\n\t}\n\n\tresetTurnState(): void {\n\t\tthis.parseObservedThisTurn = false;\n\t\tthis.validationOutcomeThisTurn = undefined;\n\t}\n\n\tgetAdaptationRulesForPrompt(): ModelAdaptationRule[] {\n\t\tif (!this.getRepairSettings().teach) return [];\n\t\tconst modelKey = this.modelKey(this.deps.agent.state.model);\n\t\treturn modelKey ? this.deps.adaptationStore.get(modelKey).rules : [];\n\t}\n\n\tresolveModelToolProtocol(model: Model<Api>): ModelToolProtocolResolution {\n\t\treturn resolveModelToolProtocol({\n\t\t\tmodel,\n\t\t\tsettingsOverride: this.getRepairSettings().textProtocol,\n\t\t\tadaptation: this.deps.adaptationStore.get(this.modelRef(model)),\n\t\t});\n\t}\n\n\tasync ensureActiveModelProtocol(): Promise<void> {\n\t\tconst model = this.deps.agent.state.model;\n\t\tconst resolution = this.resolveModelToolProtocol(model);\n\t\tthis.deps.agent.textToolCallProtocol = resolution.protocol;\n\t\tif (\n\t\t\tresolution.reasonCode !== \"probe_calibration_missing\" &&\n\t\t\tresolution.reasonCode !== \"probe_calibration_failed\" &&\n\t\t\tresolution.reasonCode !== \"probe_calibration_invalid\"\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tconst modelKey = this.modelRef(model);\n\t\tthis.deps.emitWarning(\n\t\t\tresolution.reasonCode === \"probe_calibration_failed\"\n\t\t\t\t? `Text tool protocol calibration for ${modelKey} previously failed (variants tried: ${(resolution.variantsTried ?? []).join(\", \")}); falling back to native tool calls this turn. Run /toolprobe ${modelKey} to recalibrate.`\n\t\t\t\t: `Text tool protocol for ${modelKey} has no valid calibration on record; falling back to native tool calls this turn. Run /toolprobe ${modelKey} to calibrate.`,\n\t\t);\n\t}\n\n\tgetToolProbeVerdict(model: Model<Api>): ModelToolProbeVerdict | undefined {\n\t\treturn this.deps.adaptationStore.get(this.modelRef(model)).toolProbe?.status;\n\t}\n\n\tasync probeToolCalling(target?: string): Promise<ToolProbeReport> {\n\t\tconst models = await this.resolveToolProbeModels(target);\n\t\tif (models.length === 0) throw new Error(\"No available models to probe.\");\n\t\tconst results: ToolProbeResult[] = [];\n\t\tfor (const model of models) results.push(await this.probeToolCallingForModel(model));\n\t\treturn { results, table: this.formatToolProbeReport(results) };\n\t}\n\n\tasync probeToolCallingForModel(model: Model<Api>): Promise<ToolProbeResult> {\n\t\tconst modelKey = this.modelRef(model);\n\t\tconst probedAt = new Date().toISOString();\n\t\tlet nativeGrade: NativeToolProbeGrade = \"absent\";\n\t\tlet diagnostic: string | undefined;\n\t\ttry {\n\t\t\tnativeGrade = await this.gradeNativeToolCallingForModel(model, \"pi-native-probe\");\n\t\t\tif (nativeGrade === \"task\") {\n\t\t\t\tthis.storeToolProbe(modelKey, {\n\t\t\t\t\tversion: MODEL_TOOL_PROTOCOL_VERSION,\n\t\t\t\t\tstatus: \"native\",\n\t\t\t\t\tprobedAt,\n\t\t\t\t\tnativeGrade,\n\t\t\t\t});\n\t\t\t\treturn { model: modelKey, verdict: \"native\", nativeGrade };\n\t\t\t}\n\t\t\tdiagnostic =\n\t\t\t\tnativeGrade === \"echo-only\"\n\t\t\t\t\t? \"Native echo probe passed but task-scale read probe failed.\"\n\t\t\t\t\t: \"Native task-scale read and echo probes did not produce provider-native tool calls.\";\n\t\t} catch (error) {\n\t\t\tdiagnostic = error instanceof Error ? error.message : String(error);\n\t\t}\n\n\t\ttry {\n\t\t\tconst calibrated = await this.calibrateTextToolProtocolForModel(model, modelKey, { persistFailure: false });\n\t\t\tif (calibrated.status === \"calibrated\") {\n\t\t\t\tthis.storeToolProbe(modelKey, {\n\t\t\t\t\tversion: MODEL_TOOL_PROTOCOL_VERSION,\n\t\t\t\t\tstatus: \"text-protocol\",\n\t\t\t\t\tprobedAt: calibrated.calibratedAt,\n\t\t\t\t\tvariant: calibrated.variant,\n\t\t\t\t\tnativeGrade,\n\t\t\t\t\tdiagnostic,\n\t\t\t\t});\n\t\t\t\treturn { model: modelKey, verdict: \"text-protocol\", variant: calibrated.variant, nativeGrade, diagnostic };\n\t\t\t}\n\t\t\tdiagnostic = `${diagnostic ? `${diagnostic} ` : \"\"}Text protocol variants failed: ${calibrated.variantsTried.join(\", \")}`;\n\t\t} catch (error) {\n\t\t\tdiagnostic = error instanceof Error ? error.message : String(error);\n\t\t}\n\n\t\tthis.storeToolProbe(modelKey, {\n\t\t\tversion: MODEL_TOOL_PROTOCOL_VERSION,\n\t\t\tstatus: \"none\",\n\t\t\tprobedAt,\n\t\t\tnativeGrade,\n\t\t\tdiagnostic,\n\t\t});\n\t\treturn { model: modelKey, verdict: \"none\", nativeGrade, diagnostic };\n\t}\n\n\thandleTextProtocolParse(event: TextToolProtocolParseEvent): void {\n\t\tthis.parseObservedThisTurn = true;\n\t\tconst modelKey = `${event.provider}/${event.model}`;\n\t\tif (event.status === \"parsed\") return;\n\t\tthis.maybeInjectCorrectiveSteer(event.variant);\n\t\tconst signature = `${event.variant}:${event.reason ?? \"failed\"}`;\n\t\tconst previous = this.parseFailures.get(modelKey);\n\t\tconst repeats = previous?.signature === signature ? previous.repeats + 1 : 1;\n\t\tthis.parseFailures.set(modelKey, { signature, repeats });\n\t\tif (repeats < TEXT_TOOL_PROTOCOL_PARSE_FAILURE_THRESHOLD) return;\n\n\t\tconst profile = this.deps.adaptationStore.get(modelKey);\n\t\tif (profile.protocol?.version === MODEL_TOOL_PROTOCOL_VERSION && profile.protocol.status !== \"failed\") {\n\t\t\tthis.deps.adaptationStore.removeProtocol(modelKey);\n\t\t\tthis.deps.agent.textToolCallProtocol = undefined;\n\t\t}\n\t\tthis.parseFailures.delete(modelKey);\n\t\tconst probedAt = new Date().toISOString();\n\t\tthis.deps.adaptationStore.setToolProbe(\n\t\t\tmodelKey,\n\t\t\t{\n\t\t\t\tversion: MODEL_TOOL_PROTOCOL_VERSION,\n\t\t\t\tstatus: \"none\",\n\t\t\t\tprobedAt,\n\t\t\t\tnativeGrade: profile.toolProbe?.nativeGrade,\n\t\t\t\tdiagnostic: `Text protocol parsing failed ${TEXT_TOOL_PROTOCOL_PARSE_FAILURE_THRESHOLD}x in a row with signature \"${signature}\".`,\n\t\t\t},\n\t\t\tprobedAt,\n\t\t);\n\t\tthis.deps.emitWarning(\n\t\t\t`Text tool protocol for ${modelKey} stopped parsing after ${TEXT_TOOL_PROTOCOL_PARSE_FAILURE_THRESHOLD} attempts; demoted to native fallback. Run /toolprobe ${modelKey} to recalibrate.`,\n\t\t);\n\t}\n\n\thandleValidationOutcome(event: ToolArgumentValidationTelemetryEvent): void {\n\t\tif (event.source !== \"text-protocol\") return;\n\t\tconst protocol = this.deps.agent.textToolCallProtocol;\n\t\tconst variant = protocol === true ? \"tool-tag\" : protocol ? protocol.variant : undefined;\n\t\tif (!variant) return;\n\t\tconst status = event.outcome === \"bounced\" ? \"failed\" : \"parsed\";\n\t\tif (this.validationOutcomeThisTurn?.status === \"parsed\" && status === \"failed\") return;\n\t\tthis.validationOutcomeThisTurn = {\n\t\t\tprovider: event.provider ?? this.deps.agent.state.model.provider,\n\t\t\tmodel: event.model ?? this.deps.agent.state.model.id,\n\t\t\tvariant,\n\t\t\tstatus,\n\t\t\tcallCount: 1,\n\t\t\ttextLength: 0,\n\t\t\t...(status === \"failed\" && {\n\t\t\t\treason: event.errorKeywords?.includes(\"unknown_tool\") ? \"unknown-tool\" : \"validation-failed\",\n\t\t\t}),\n\t\t};\n\t}\n\n\trecordParseOutcomeFromLastAssistant(): void {\n\t\tconst validationOutcome = this.validationOutcomeThisTurn;\n\t\tthis.validationOutcomeThisTurn = undefined;\n\t\tif (validationOutcome?.status === \"parsed\") {\n\t\t\tthis.parseObservedThisTurn = true;\n\t\t\tthis.parseFailures.delete(`${validationOutcome.provider}/${validationOutcome.model}`);\n\t\t\treturn;\n\t\t}\n\t\tif (validationOutcome) {\n\t\t\tthis.handleTextProtocolParse(validationOutcome);\n\t\t\treturn;\n\t\t}\n\t\tif (this.parseObservedThisTurn) return;\n\t\tconst protocol = this.deps.agent.textToolCallProtocol;\n\t\tif (protocol === false || protocol === true || !protocol?.variant) return;\n\t\tconst response = this.deps.findLastAssistantMessage();\n\t\tif (!response) return;\n\t\tconst responseText = response.content\n\t\t\t.filter((content): content is TextContent => content.type === \"text\")\n\t\t\t.map((content) => content.text)\n\t\t\t.join(\"\\n\");\n\t\tif (!responseText) return;\n\n\t\tconst parsed = parseTextToolCalls(responseText, this.deps.agent.state.tools);\n\t\tconst attempted = parsed.attempted || this.looksLikeTextProtocolAttempt(responseText);\n\t\tif (!attempted) return;\n\t\tthis.handleTextProtocolParse({\n\t\t\tprovider: this.deps.agent.state.model.provider,\n\t\t\tmodel: this.deps.agent.state.model.id,\n\t\t\tvariant: protocol.variant,\n\t\t\tstatus: parsed.calls.length > 0 ? \"parsed\" : \"failed\",\n\t\t\treason: parsed.failure,\n\t\t\tcallCount: parsed.calls.length,\n\t\t\ttextLength: responseText.length,\n\t\t});\n\t}\n\n\ttagAdaptationRuleTeaching(event: ToolArgumentValidationTelemetryEvent): ToolArgumentValidationTelemetryEvent {\n\t\tif (!this.getRepairSettings().teach || event.taught !== \"none\") return event;\n\t\tconst modelKey =\n\t\t\tevent.provider && event.model\n\t\t\t\t? `${event.provider}/${event.model}`\n\t\t\t\t: this.modelKey(this.deps.agent.state.model);\n\t\tif (!modelKey) return event;\n\t\ttry {\n\t\t\tconst rules = this.deps.adaptationStore.get(modelKey).rules;\n\t\t\tconst modes = new Set([...event.failureModes, ...event.repairsApplied]);\n\t\t\tif (rules.some((rule) => modes.has(rule.mode as ToolRepairModeName))) return { ...event, taught: \"rule\" };\n\t\t} catch {\n\t\t\t// Best-effort telemetry tagging.\n\t\t}\n\t\treturn event;\n\t}\n\n\thandleAdaptationTelemetry(event: ToolArgumentValidationTelemetryEvent): void {\n\t\tif (!this.getRepairSettings().teach || event.outcome !== \"repaired\" || event.repairsApplied.length === 0) return;\n\t\tconst modelKey =\n\t\t\tevent.provider && event.model\n\t\t\t\t? `${event.provider}/${event.model}`\n\t\t\t\t: this.modelKey(this.deps.agent.state.model);\n\t\tif (!modelKey) return;\n\t\ttry {\n\t\t\tfor (const mode of [...new Set(event.repairsApplied)]) {\n\t\t\t\tconst profile = this.deps.adaptationStore.get(modelKey);\n\t\t\t\tconst stats = profile.teachStats[mode] ?? { taught: 0, recurrenceBefore: 0, recurrenceAfter: 0 };\n\t\t\t\tif (profile.rules.some((rule) => rule.mode === mode)) {\n\t\t\t\t\tthis.deps.adaptationStore.markRuleFired(modelKey, mode);\n\t\t\t\t\tthis.deps.adaptationStore.setTeachStats(modelKey, mode, {\n\t\t\t\t\t\t...stats,\n\t\t\t\t\t\trecurrenceAfter: stats.recurrenceAfter + 1,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst recurrenceBefore = stats.recurrenceBefore + 1;\n\t\t\t\tthis.deps.adaptationStore.setTeachStats(modelKey, mode, { ...stats, recurrenceBefore });\n\t\t\t\tconst sessionCount = this.repairSessionCount(modelKey, mode);\n\t\t\t\tif (\n\t\t\t\t\tsessionCount >= MODEL_ADAPTATION_REPAIR_THRESHOLD ||\n\t\t\t\t\trecurrenceBefore >= MODEL_ADAPTATION_REPAIR_THRESHOLD\n\t\t\t\t) {\n\t\t\t\t\tthis.deps.adaptationStore.addRule(modelKey, { mode, text: formatToolRepairStandingRule(mode) });\n\t\t\t\t\tthis.deps.adaptationStore.setTeachStats(modelKey, mode, {\n\t\t\t\t\t\t...stats,\n\t\t\t\t\t\ttaught: stats.taught + 1,\n\t\t\t\t\t\trecurrenceBefore,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Best-effort adaptation persistence.\n\t\t}\n\t}\n\n\tmaybeAutoProbe(model: Model<Api>): void {\n\t\tconst modelKey = this.modelRef(model);\n\t\tif (this.autoProbedModels.has(modelKey) || this.hasFreshToolProbeVerdict(modelKey)) return;\n\t\tthis.autoProbedModels.add(modelKey);\n\t\tvoid this.deps\n\t\t\t.probeForAuto(model)\n\t\t\t.then((result) => {\n\t\t\t\tif (this.deps.isDisposed()) return;\n\t\t\t\tconst detail =\n\t\t\t\t\tresult.verdict === \"text-protocol\"\n\t\t\t\t\t\t? ` (variant ${result.variant}); it will use the text tool protocol starting next turn`\n\t\t\t\t\t\t: result.verdict === \"none\"\n\t\t\t\t\t\t\t? \" — no working tool-call path was found; run /toolprobe for details\"\n\t\t\t\t\t\t\t: \"; native tool calls stay in use\";\n\t\t\t\tthis.deps.emitWarning(\n\t\t\t\t\t`Auto-probed ${modelKey} after repeated native tool-call validation failures: verdict \"${result.verdict}\"${detail}.`,\n\t\t\t\t);\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tif (this.deps.isDisposed()) return;\n\t\t\t\tthis.deps.emitWarning(\n\t\t\t\t\t`Auto-probe for ${modelKey} (triggered by repeated tool-call validation failures) did not complete: ${error instanceof Error ? error.message : String(error)}.`,\n\t\t\t\t);\n\t\t\t});\n\t}\n\n\tformatRepairHealth(stats?: ToolRecoveryLoggerStats): string {\n\t\treturn formatToolRepairHealthReport(this.deps.adaptationStore, new Date(), stats);\n\t}\n\n\tremoveRepairRule(model: string, mode: string): boolean {\n\t\treturn this.deps.adaptationStore.removeRule(model, mode);\n\t}\n\n\tresetProtocolCalibration(model: string): boolean {\n\t\tconst removed = this.deps.adaptationStore.removeProtocol(model);\n\t\tthis.parseFailures.delete(model);\n\t\treturn removed;\n\t}\n\n\tgetRepairSettings() {\n\t\treturn resolveCurrentToolRepairSettings(this.deps.settingsManager.settings);\n\t}\n\n\tprivate modelKey(model: Model<Api> | undefined): string | undefined {\n\t\treturn model ? this.modelRef(model) : undefined;\n\t}\n\n\tprivate modelRef(model: Model<Api>): string {\n\t\treturn `${model.provider}/${model.id}`;\n\t}\n\n\tprivate async streamForProbe(model: Model<Api>, context: Context, options: SimpleStreamOptions) {\n\t\tlet requestOptions = options;\n\t\tif (this.deps.isRawStreamSimple(this.deps.agent.streamFn)) {\n\t\t\tconst auth = await this.deps.getRequiredRequestAuth(model);\n\t\t\trequestOptions = {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\theaders: auth.headers || options.headers ? { ...auth.headers, ...options.headers } : undefined,\n\t\t\t};\n\t\t}\n\t\treturn this.deps.agent.streamFn(model, context, requestOptions);\n\t}\n\n\tprivate nextProbeUsageReportId(model: Model<Api>, kind: string): string {\n\t\treturn `tool-probe:${this.modelRef(model)}:${kind}:${this.probeUsageReportSeq++}`;\n\t}\n\n\tprivate async resolveProbeStreamCountingUsage(\n\t\tstream: AssistantMessageEventStream,\n\t\tlabel: string,\n\t\treportId: string,\n\t): Promise<AssistantMessage> {\n\t\tconst message = await stream.result();\n\t\tconst usage = message.usage;\n\t\tif (usage && (usage.cost.total > 0 || usage.totalTokens > 0)) {\n\t\t\tthis.deps.addSpawnedUsage(usage, { label, reportId });\n\t\t}\n\t\treturn message;\n\t}\n\n\tprivate textProtocolCalibrationContext(variant: TextToolProtocolVariant, token: string): Context {\n\t\tconst primer = generateTextToolProtocolPrimer([TEXT_TOOL_PROTOCOL_ECHO_TOOL], { variant });\n\t\tconst instruction = `Text tool protocol calibration trial. Using the protocol above, call echo with data exactly \"${token}\". Output only the tool-call envelope.`;\n\t\treturn {\n\t\t\tsystemPrompt: `${primer}\\n\\n${instruction}`,\n\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: instruction }], timestamp: Date.now() }],\n\t\t};\n\t}\n\n\tprivate messageHasToolCallWithStringArgument(\n\t\tmessage: AssistantMessage,\n\t\ttoolName: string,\n\t\targName: string,\n\t\targValue: string,\n\t): boolean {\n\t\treturn message.content.some((block) => {\n\t\t\tif (block.type !== \"toolCall\" || block.name !== toolName) return false;\n\t\t\tconst args = block.arguments as unknown;\n\t\t\treturn (\n\t\t\t\ttypeof args === \"object\" &&\n\t\t\t\targs !== null &&\n\t\t\t\t!Array.isArray(args) &&\n\t\t\t\t(args as Record<string, unknown>)[argName] === argValue\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate nativeToolProbeSystemPrompt(instruction: string): string {\n\t\tconst base = (this.deps.agent.state.systemPrompt ?? \"\").trim();\n\t\treturn base ? `${base}\\n\\n${instruction}` : instruction;\n\t}\n\n\tprivate async runNativeToolProbeTrial(\n\t\tmodel: Model<Api>,\n\t\tinstruction: string,\n\t\ttool: Tool,\n\t\tmaxTokens: number,\n\t\treportKind: string,\n\t\targName: string,\n\t\targValue: string,\n\t): Promise<boolean> {\n\t\tconst stream = await this.streamForProbe(\n\t\t\tmodel,\n\t\t\t{\n\t\t\t\tsystemPrompt: this.nativeToolProbeSystemPrompt(instruction),\n\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: instruction }], timestamp: Date.now() }],\n\t\t\t\ttools: [tool],\n\t\t\t},\n\t\t\t{ textToolCallProtocol: false, maxRetries: 0, temperature: 0, maxTokens },\n\t\t);\n\t\tconst message = await this.resolveProbeStreamCountingUsage(\n\t\t\tstream,\n\t\t\t\"tool-probe\",\n\t\t\tthis.nextProbeUsageReportId(model, reportKind),\n\t\t);\n\t\treturn this.messageHasToolCallWithStringArgument(message, tool.name, argName, argValue);\n\t}\n\n\tprivate async runNativeReadTaskProbeTrial(model: Model<Api>, path: string): Promise<boolean> {\n\t\tconst instruction =\n\t\t\t`Native tool-call capability probe: task-scale read. Use provider-native tool calling, not prose. ` +\n\t\t\t`Call read exactly once with path exactly \"${path}\".`;\n\t\treturn this.runNativeToolProbeTrial(\n\t\t\tmodel,\n\t\t\tinstruction,\n\t\t\tNATIVE_TOOL_PROBE_READ_TOOL,\n\t\t\t768,\n\t\t\t\"read-task\",\n\t\t\t\"path\",\n\t\t\tpath,\n\t\t);\n\t}\n\n\tprivate async runNativeEchoToolProbeTrial(model: Model<Api>, token: string): Promise<boolean> {\n\t\tconst instruction =\n\t\t\t`Native tool-call capability probe: echo-only. Use provider-native tool calling, not prose. ` +\n\t\t\t`Call echo with data exactly \"${token}\".`;\n\t\treturn this.runNativeToolProbeTrial(model, instruction, TEXT_TOOL_PROTOCOL_ECHO_TOOL, 256, \"echo\", \"data\", token);\n\t}\n\n\tprivate async gradeNativeToolCallingForModel(model: Model<Api>, token: string): Promise<NativeToolProbeGrade> {\n\t\tconst path = join(\n\t\t\tgetProcessWorkRun(this.deps.agentDir, \"probes\", \"native-tools\").path,\n\t\t\t`pi-native-probe-${process.pid}-${Date.now()}.txt`,\n\t\t);\n\t\twriteFileSync(path, token, \"utf-8\");\n\t\ttry {\n\t\t\tif (await this.runNativeReadTaskProbeTrial(model, path)) return \"task\";\n\t\t\tif (await this.runNativeEchoToolProbeTrial(model, token)) return \"echo-only\";\n\t\t\treturn \"absent\";\n\t\t} finally {\n\t\t\trmSync(path, { force: true });\n\t\t}\n\t}\n\n\tprivate async runTextProtocolTrial(\n\t\tmodel: Model<Api>,\n\t\tvariant: TextToolProtocolVariant,\n\t\ttoken: string,\n\t): Promise<boolean> {\n\t\tconst stream = await this.streamForProbe(model, this.textProtocolCalibrationContext(variant, token), {\n\t\t\ttextToolCallProtocol: false,\n\t\t\tmaxRetries: 0,\n\t\t\ttemperature: 0,\n\t\t\tmaxTokens: 256,\n\t\t});\n\t\tconst message = await this.resolveProbeStreamCountingUsage(\n\t\t\tstream,\n\t\t\t\"text-protocol-calibration\",\n\t\t\tthis.nextProbeUsageReportId(model, `text-protocol:${variant}`),\n\t\t);\n\t\tconst text = message.content\n\t\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t\t.map((block) => block.text)\n\t\t\t.join(\"\\n\")\n\t\t\t.trim();\n\t\tif (!text) return false;\n\t\tconst parsed = parseTextToolCalls(text, [TEXT_TOOL_PROTOCOL_ECHO_TOOL]);\n\t\treturn parsed.calls.some((call) => call.name === \"echo\" && call.arguments.data === token);\n\t}\n\n\tprivate async calibrateTextToolProtocolForModel(\n\t\tmodel: Model<Api>,\n\t\tmodelKey: string | undefined,\n\t\toptions: { persistFailure: boolean },\n\t): Promise<\n\t\t| { status: \"calibrated\"; variant: TextToolProtocolVariant; calibratedAt: string }\n\t\t| { status: \"failed\"; attemptedAt: string; variantsTried: string[] }\n\t> {\n\t\tconst variantsTried: string[] = [];\n\t\tfor (const variant of TEXT_TOOL_PROTOCOL_VARIANTS) {\n\t\t\tvariantsTried.push(variant);\n\t\t\tlet passed = true;\n\t\t\tfor (let trial = 0; trial < TEXT_TOOL_PROTOCOL_TRIALS_PER_VARIANT; trial++) {\n\t\t\t\tif (!(await this.runTextProtocolTrial(model, variant, `pi-calibration-${trial + 1}`))) {\n\t\t\t\t\tpassed = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (passed) {\n\t\t\t\tconst calibratedAt = new Date().toISOString();\n\t\t\t\tif (modelKey) {\n\t\t\t\t\tthis.deps.adaptationStore.setProtocol(\n\t\t\t\t\t\tmodelKey,\n\t\t\t\t\t\t{ version: MODEL_TOOL_PROTOCOL_VERSION, status: \"calibrated\", variant, calibratedAt },\n\t\t\t\t\t\tcalibratedAt,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn { status: \"calibrated\", variant, calibratedAt };\n\t\t\t}\n\t\t}\n\n\t\tconst attemptedAt = new Date().toISOString();\n\t\tif (modelKey && options.persistFailure) {\n\t\t\tthis.deps.adaptationStore.setProtocol(\n\t\t\t\tmodelKey,\n\t\t\t\t{ version: MODEL_TOOL_PROTOCOL_VERSION, status: \"failed\", attemptedAt, variantsTried },\n\t\t\t\tattemptedAt,\n\t\t\t);\n\t\t}\n\t\treturn { status: \"failed\", attemptedAt, variantsTried };\n\t}\n\n\tprivate formatToolProbeReport(results: readonly ToolProbeResult[]): string {\n\t\tconst lines = [\n\t\t\t\"Tool probe results:\",\n\t\t\t\"Model | Verdict | Variant | Native grade | Diagnostic\",\n\t\t\t\"--- | --- | --- | --- | ---\",\n\t\t];\n\t\tfor (const result of results) {\n\t\t\tlines.push(\n\t\t\t\t[\n\t\t\t\t\tresult.model,\n\t\t\t\t\tresult.verdict,\n\t\t\t\t\tresult.variant ?? \"-\",\n\t\t\t\t\tresult.nativeGrade ?? \"-\",\n\t\t\t\t\tresult.diagnostic ? result.diagnostic.replace(/\\s+/g, \" \").slice(0, 160) : \"-\",\n\t\t\t\t].join(\" | \"),\n\t\t\t);\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tprivate storeToolProbe(modelKey: string, probe: ModelToolProbe): void {\n\t\tthis.deps.adaptationStore.setToolProbe(modelKey, probe, probe.probedAt);\n\t}\n\n\tprivate async resolveToolProbeModels(target?: string): Promise<Model<Api>[]> {\n\t\tconst trimmed = target?.trim();\n\t\tif (!trimmed) return this.deps.getModelRegistry().getAvailable();\n\t\tconst [provider, ...modelParts] = trimmed.split(\"/\");\n\t\tconst modelId = modelParts.join(\"/\");\n\t\tif (!provider || !modelId) throw new Error(\"Usage: /toolprobe [provider/model]\");\n\t\tconst exact = this.deps.getModelRegistry().find(provider, modelId);\n\t\tif (exact) return [exact];\n\t\tconst current = this.deps.agent.state.model;\n\t\tif (current?.provider === provider && current.id === modelId) return [current];\n\t\tthrow new Error(`Model not found: ${trimmed}`);\n\t}\n\n\tprivate maybeInjectCorrectiveSteer(variant: TextToolProtocolVariant): void {\n\t\tthis.correctiveSteerCount++;\n\t\tif (this.correctiveSteerCount !== 1 && this.correctiveSteerCount % TEXT_TOOL_PROTOCOL_STEER_INTERVAL !== 0) {\n\t\t\treturn;\n\t\t}\n\t\tconst reminder = `Reminder: to call a tool, emit exactly this envelope shape: ${formatVariantEnvelope(variant, \"TOOL\", '{\"arg\":\"value\"}')} — no other format is recognized. Reasoning may appear as prose before the envelope, never inside it.`;\n\t\tthis.deps.sendCorrectiveSteer(reminder).catch(() => {\n\t\t\t// Best-effort steer.\n\t\t});\n\t}\n\n\tprivate looksLikeTextProtocolAttempt(text: string): boolean {\n\t\treturn /<pi:call\\b|<tool_call\\b|```(?:tool|tool_call)[\\s\\S]*\"name\"\\s*:/i.test(text);\n\t}\n\n\tprivate repairSessionCount(modelKey: string, mode: ToolRepairModeName): number {\n\t\tconst key = `${modelKey}\\0${mode}`;\n\t\tconst count = (this.repairModeSessionCounts.get(key) ?? 0) + 1;\n\t\tthis.repairModeSessionCounts.set(key, count);\n\t\treturn count;\n\t}\n\n\tprivate hasFreshToolProbeVerdict(modelKey: string): boolean {\n\t\tconst probedAt = this.deps.adaptationStore.get(modelKey).toolProbe?.probedAt;\n\t\tif (!probedAt) return false;\n\t\tconst age = Date.now() - new Date(probedAt).getTime();\n\t\treturn Number.isFinite(age) && age >= 0 && age < AUTO_TOOL_PROBE_FRESHNESS_MS;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tool-protocol-controller.js","sourceRoot":"","sources":["../../src/core/tool-protocol-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EACN,qBAAqB,EACrB,8BAA8B,EAC9B,kBAAkB,EAClB,2BAA2B,GAE3B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,4BAA4B,EAA2B,MAAM,wCAAwC,CAAC;AAe/G,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC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AC;QAC7C,OAAO,KAAK,CAAC;IACd,CAAC;IAEO,wBAAwB,CAAC,QAAgB;QAChD,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,SAAS,EAAE,QAAQ,CAAC;QAC7E,IAAI,CAAC,QAAQ;YAAE,OAAO,KAAK,CAAC;QAC5B,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC,OAAO,EAAE,CAAC;QACtD,OAAO,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,GAAG,GAAG,4BAA4B,CAAC;IAC/E,CAAC;CACD","sourcesContent":["import { rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Agent, StreamFn } from \"@caupulican/pi-agent-core\";\nimport {\n\tformatVariantEnvelope,\n\tgenerateTextToolProtocolPrimer,\n\tparseTextToolCalls,\n\tTEXT_TOOL_PROTOCOL_VARIANTS,\n\ttype TextToolProtocolVariant,\n} from \"@caupulican/pi-ai/text-tool-protocol\";\nimport { formatToolRepairStandingRule, type ToolRepairModeName } from \"@caupulican/pi-ai/tool-repair-registry\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\n\tTextToolProtocolParseEvent,\n\tThinkingContent,\n\tTool,\n\tUsage,\n} from \"@caupulican/pi-ai/types\";\nimport type { ToolArgumentValidationTelemetryEvent } from \"@caupulican/pi-ai/validation\";\nimport { Type } from \"typebox\";\nimport { getProcessWorkRun } from \"../utils/work-directory.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport {\n\tMODEL_TOOL_PROTOCOL_VERSION,\n\ttype ModelToolProtocolResolution,\n\tresolveModelToolProtocol,\n} from \"./model-tool-protocol.ts\";\nimport type {\n\tModelAdaptationRule,\n\tModelAdaptationStore,\n\tModelToolProbe,\n\tModelToolProbeVerdict,\n\tNativeToolProbeGrade,\n} from \"./models/adaptation-store.ts\";\nimport type { RequestAuth } from \"./request-auth.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { ToolRecoveryLoggerStats } from \"./tool-recovery-logger.ts\";\nimport { formatToolRepairHealthReport } from \"./tool-repair-health.ts\";\nimport { resolveCurrentToolRepairSettings } from \"./tool-repair-settings.ts\";\n\nconst MODEL_ADAPTATION_REPAIR_THRESHOLD = 3;\nconst TEXT_TOOL_PROTOCOL_TRIALS_PER_VARIANT = 2;\nconst TEXT_TOOL_PROTOCOL_PARSE_FAILURE_THRESHOLD = 3;\nconst TEXT_TOOL_PROTOCOL_STEER_INTERVAL = 5;\nconst AUTO_TOOL_PROBE_FRESHNESS_MS = 15 * 60 * 1000;\nconst TEXT_TOOL_PROTOCOL_ECHO_TOOL = {\n\tname: \"echo\",\n\tdescription: \"Echo calibration data\",\n\tparameters: Type.Object({ data: Type.String() }),\n} satisfies Tool;\nconst NATIVE_TOOL_PROBE_READ_TOOL = {\n\tname: \"read\",\n\tdescription: \"Read file contents\",\n\tparameters: Type.Object({ path: Type.String() }),\n} satisfies Tool;\n\nexport type ToolProbeVerdict = \"native\" | \"text-protocol\" | \"none\";\n\nexport interface ToolProbeResult {\n\tmodel: string;\n\tverdict: ToolProbeVerdict;\n\tvariant?: TextToolProtocolVariant;\n\tnativeGrade?: NativeToolProbeGrade;\n\tdiagnostic?: string;\n}\n\nexport interface ToolProbeReport {\n\tresults: ToolProbeResult[];\n\ttable: string;\n}\n\nexport interface ToolProtocolControllerDeps {\n\tagent: Agent;\n\tagentDir: string;\n\tsettingsManager: SettingsManager;\n\tgetModelRegistry(): ModelRegistry;\n\tadaptationStore: ModelAdaptationStore;\n\tisRawStreamSimple(fn: StreamFn): boolean;\n\tgetRequiredRequestAuth(model: Model<Api>): Promise<RequestAuth>;\n\taddSpawnedUsage(usage: Usage, opts: { label?: string; reportId: string }): string | undefined;\n\temitWarning(message: string): void;\n\tsendCorrectiveSteer(message: string): Promise<void>;\n\tfindLastAssistantMessage(): AssistantMessage | undefined;\n\tisDisposed(): boolean;\n\tprobeForAuto(model: Model<Api>): Promise<ToolProbeResult>;\n}\n\n/** Owns model tool-protocol selection, probing, circuit breaking, and repair teaching. */\nexport class ToolProtocolController {\n\tprivate readonly repairModeSessionCounts = new Map<string, number>();\n\tprivate readonly parseFailures = new Map<string, { signature: string; repeats: number }>();\n\tprivate parseObservedThisTurn = false;\n\tprivate correctiveSteerCount = 0;\n\tprivate probeUsageReportSeq = 0;\n\tprivate readonly autoProbedModels = new Set<string>();\n\tprivate validationOutcomeThisTurn: TextToolProtocolParseEvent | undefined;\n\tprivate readonly deps: ToolProtocolControllerDeps;\n\n\tconstructor(deps: ToolProtocolControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tapplyRepairLayerSettings(): void {\n\t\tthis.deps.agent.toolArgumentTeachEnabled = this.getRepairSettings().teach;\n\t}\n\n\tresetTurnState(): void {\n\t\tthis.parseObservedThisTurn = false;\n\t\tthis.validationOutcomeThisTurn = undefined;\n\t}\n\n\tgetAdaptationRulesForPrompt(): ModelAdaptationRule[] {\n\t\tif (!this.getRepairSettings().teach) return [];\n\t\tconst modelKey = this.modelKey(this.deps.agent.state.model);\n\t\treturn modelKey ? this.deps.adaptationStore.get(modelKey).rules : [];\n\t}\n\n\tresolveModelToolProtocol(model: Model<Api>): ModelToolProtocolResolution {\n\t\treturn resolveModelToolProtocol({\n\t\t\tmodel,\n\t\t\tsettingsOverride: this.getRepairSettings().textProtocol,\n\t\t\tadaptation: this.deps.adaptationStore.get(this.modelRef(model)),\n\t\t});\n\t}\n\n\tasync ensureActiveModelProtocol(): Promise<void> {\n\t\tconst model = this.deps.agent.state.model;\n\t\tconst resolution = this.resolveModelToolProtocol(model);\n\t\tthis.deps.agent.textToolCallProtocol = resolution.protocol;\n\t\tif (\n\t\t\tresolution.reasonCode !== \"probe_calibration_missing\" &&\n\t\t\tresolution.reasonCode !== \"probe_calibration_failed\" &&\n\t\t\tresolution.reasonCode !== \"probe_calibration_invalid\"\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tconst modelKey = this.modelRef(model);\n\t\tthis.deps.emitWarning(\n\t\t\tresolution.reasonCode === \"probe_calibration_failed\"\n\t\t\t\t? `Text tool protocol calibration for ${modelKey} previously failed (variants tried: ${(resolution.variantsTried ?? []).join(\", \")}); falling back to native tool calls this turn. Run /toolprobe ${modelKey} to recalibrate.`\n\t\t\t\t: `Text tool protocol for ${modelKey} has no valid calibration on record; falling back to native tool calls this turn. Run /toolprobe ${modelKey} to calibrate.`,\n\t\t);\n\t}\n\n\tgetToolProbeVerdict(model: Model<Api>): ModelToolProbeVerdict | undefined {\n\t\treturn this.deps.adaptationStore.get(this.modelRef(model)).toolProbe?.status;\n\t}\n\n\tasync probeToolCalling(target?: string): Promise<ToolProbeReport> {\n\t\tconst models = await this.resolveToolProbeModels(target);\n\t\tif (models.length === 0) throw new Error(\"No available models to probe.\");\n\t\tconst results: ToolProbeResult[] = [];\n\t\tfor (const model of models) results.push(await this.probeToolCallingForModel(model));\n\t\treturn { results, table: this.formatToolProbeReport(results) };\n\t}\n\n\tasync probeToolCallingForModel(model: Model<Api>): Promise<ToolProbeResult> {\n\t\tconst modelKey = this.modelRef(model);\n\t\tconst probedAt = new Date().toISOString();\n\t\tlet nativeGrade: NativeToolProbeGrade = \"absent\";\n\t\tlet diagnostic: string | undefined;\n\t\ttry {\n\t\t\tnativeGrade = await this.gradeNativeToolCallingForModel(model, \"pi-native-probe\");\n\t\t\tif (nativeGrade === \"task\") {\n\t\t\t\tthis.storeToolProbe(modelKey, {\n\t\t\t\t\tversion: MODEL_TOOL_PROTOCOL_VERSION,\n\t\t\t\t\tstatus: \"native\",\n\t\t\t\t\tprobedAt,\n\t\t\t\t\tnativeGrade,\n\t\t\t\t});\n\t\t\t\treturn { model: modelKey, verdict: \"native\", nativeGrade };\n\t\t\t}\n\t\t\tdiagnostic =\n\t\t\t\tnativeGrade === \"echo-only\"\n\t\t\t\t\t? \"Native echo probe passed but task-scale read probe failed.\"\n\t\t\t\t\t: \"Native task-scale read and echo probes did not produce provider-native tool calls.\";\n\t\t} catch (error) {\n\t\t\tdiagnostic = error instanceof Error ? error.message : String(error);\n\t\t}\n\n\t\ttry {\n\t\t\tconst calibrated = await this.calibrateTextToolProtocolForModel(model, modelKey, { persistFailure: false });\n\t\t\tif (calibrated.status === \"calibrated\") {\n\t\t\t\tthis.storeToolProbe(modelKey, {\n\t\t\t\t\tversion: MODEL_TOOL_PROTOCOL_VERSION,\n\t\t\t\t\tstatus: \"text-protocol\",\n\t\t\t\t\tprobedAt: calibrated.calibratedAt,\n\t\t\t\t\tvariant: calibrated.variant,\n\t\t\t\t\tnativeGrade,\n\t\t\t\t\tdiagnostic,\n\t\t\t\t});\n\t\t\t\treturn { model: modelKey, verdict: \"text-protocol\", variant: calibrated.variant, nativeGrade, diagnostic };\n\t\t\t}\n\t\t\tdiagnostic = `${diagnostic ? `${diagnostic} ` : \"\"}Text protocol variants failed: ${calibrated.variantsTried.join(\", \")}`;\n\t\t} catch (error) {\n\t\t\tdiagnostic = error instanceof Error ? error.message : String(error);\n\t\t}\n\n\t\tthis.storeToolProbe(modelKey, {\n\t\t\tversion: MODEL_TOOL_PROTOCOL_VERSION,\n\t\t\tstatus: \"none\",\n\t\t\tprobedAt,\n\t\t\tnativeGrade,\n\t\t\tdiagnostic,\n\t\t});\n\t\treturn { model: modelKey, verdict: \"none\", nativeGrade, diagnostic };\n\t}\n\n\thandleTextProtocolParse(event: TextToolProtocolParseEvent): void {\n\t\tthis.parseObservedThisTurn = true;\n\t\tconst modelKey = `${event.provider}/${event.model}`;\n\t\tif (event.status === \"parsed\") return;\n\t\tthis.maybeInjectCorrectiveSteer(event.variant);\n\t\tconst signature = `${event.variant}:${event.reason ?? \"failed\"}`;\n\t\tconst previous = this.parseFailures.get(modelKey);\n\t\tconst repeats = previous?.signature === signature ? previous.repeats + 1 : 1;\n\t\tthis.parseFailures.set(modelKey, { signature, repeats });\n\t\tif (repeats < TEXT_TOOL_PROTOCOL_PARSE_FAILURE_THRESHOLD) return;\n\n\t\tconst profile = this.deps.adaptationStore.get(modelKey);\n\t\tif (profile.protocol?.version === MODEL_TOOL_PROTOCOL_VERSION && profile.protocol.status !== \"failed\") {\n\t\t\tthis.deps.adaptationStore.removeProtocol(modelKey);\n\t\t\tthis.deps.agent.textToolCallProtocol = undefined;\n\t\t}\n\t\tthis.parseFailures.delete(modelKey);\n\t\tconst probedAt = new Date().toISOString();\n\t\tthis.deps.adaptationStore.setToolProbe(\n\t\t\tmodelKey,\n\t\t\t{\n\t\t\t\tversion: MODEL_TOOL_PROTOCOL_VERSION,\n\t\t\t\tstatus: \"none\",\n\t\t\t\tprobedAt,\n\t\t\t\tnativeGrade: profile.toolProbe?.nativeGrade,\n\t\t\t\tdiagnostic: `Text protocol parsing failed ${TEXT_TOOL_PROTOCOL_PARSE_FAILURE_THRESHOLD}x in a row with signature \"${signature}\".`,\n\t\t\t},\n\t\t\tprobedAt,\n\t\t);\n\t\tthis.deps.emitWarning(\n\t\t\t`Text tool protocol for ${modelKey} stopped parsing after ${TEXT_TOOL_PROTOCOL_PARSE_FAILURE_THRESHOLD} attempts; demoted to native fallback. Run /toolprobe ${modelKey} to recalibrate.`,\n\t\t);\n\t}\n\n\thandleValidationOutcome(event: ToolArgumentValidationTelemetryEvent): void {\n\t\tif (event.source !== \"text-protocol\") return;\n\t\tconst protocol = this.deps.agent.textToolCallProtocol;\n\t\tconst variant = protocol === true ? \"tool-tag\" : protocol ? protocol.variant : undefined;\n\t\tif (!variant) return;\n\t\tconst status = event.outcome === \"bounced\" ? \"failed\" : \"parsed\";\n\t\tif (this.validationOutcomeThisTurn?.status === \"parsed\" && status === \"failed\") return;\n\t\tthis.validationOutcomeThisTurn = {\n\t\t\tprovider: event.provider ?? this.deps.agent.state.model.provider,\n\t\t\tmodel: event.model ?? this.deps.agent.state.model.id,\n\t\t\tvariant,\n\t\t\tstatus,\n\t\t\tcallCount: 1,\n\t\t\ttextLength: 0,\n\t\t\t...(status === \"failed\" && {\n\t\t\t\treason: event.errorKeywords?.includes(\"unknown_tool\") ? \"unknown-tool\" : \"validation-failed\",\n\t\t\t}),\n\t\t};\n\t}\n\n\trecordParseOutcomeFromLastAssistant(): void {\n\t\tconst validationOutcome = this.validationOutcomeThisTurn;\n\t\tthis.validationOutcomeThisTurn = undefined;\n\t\tif (validationOutcome?.status === \"parsed\") {\n\t\t\tthis.parseObservedThisTurn = true;\n\t\t\tthis.parseFailures.delete(`${validationOutcome.provider}/${validationOutcome.model}`);\n\t\t\treturn;\n\t\t}\n\t\tif (validationOutcome) {\n\t\t\tthis.handleTextProtocolParse(validationOutcome);\n\t\t\treturn;\n\t\t}\n\t\tif (this.parseObservedThisTurn) return;\n\t\tconst protocol = this.deps.agent.textToolCallProtocol;\n\t\tif (protocol === false || protocol === true || !protocol?.variant) return;\n\t\tconst response = this.deps.findLastAssistantMessage();\n\t\tif (!response) return;\n\t\tconst responseText = response.content\n\t\t\t.filter((content): content is TextContent => content.type === \"text\")\n\t\t\t.map((content) => content.text)\n\t\t\t.join(\"\\n\");\n\t\tif (!responseText) return;\n\n\t\tconst parsed = parseTextToolCalls(responseText, this.deps.agent.state.tools);\n\t\tconst attempted = parsed.attempted || this.looksLikeTextProtocolAttempt(responseText);\n\t\tif (!attempted) return;\n\t\tthis.handleTextProtocolParse({\n\t\t\tprovider: this.deps.agent.state.model.provider,\n\t\t\tmodel: this.deps.agent.state.model.id,\n\t\t\tvariant: protocol.variant,\n\t\t\tstatus: parsed.calls.length > 0 ? \"parsed\" : \"failed\",\n\t\t\treason: parsed.failure,\n\t\t\tcallCount: parsed.calls.length,\n\t\t\ttextLength: responseText.length,\n\t\t});\n\t}\n\n\ttagAdaptationRuleTeaching(event: ToolArgumentValidationTelemetryEvent): ToolArgumentValidationTelemetryEvent {\n\t\tif (!this.getRepairSettings().teach || event.taught !== \"none\") return event;\n\t\tconst modelKey =\n\t\t\tevent.provider && event.model\n\t\t\t\t? `${event.provider}/${event.model}`\n\t\t\t\t: this.modelKey(this.deps.agent.state.model);\n\t\tif (!modelKey) return event;\n\t\ttry {\n\t\t\tconst rules = this.deps.adaptationStore.get(modelKey).rules;\n\t\t\tconst modes = new Set([...event.failureModes, ...event.repairsApplied]);\n\t\t\tif (rules.some((rule) => modes.has(rule.mode as ToolRepairModeName))) return { ...event, taught: \"rule\" };\n\t\t} catch {\n\t\t\t// Best-effort telemetry tagging.\n\t\t}\n\t\treturn event;\n\t}\n\n\thandleAdaptationTelemetry(event: ToolArgumentValidationTelemetryEvent): void {\n\t\tif (!this.getRepairSettings().teach || event.outcome !== \"repaired\" || event.repairsApplied.length === 0) return;\n\t\tconst modelKey =\n\t\t\tevent.provider && event.model\n\t\t\t\t? `${event.provider}/${event.model}`\n\t\t\t\t: this.modelKey(this.deps.agent.state.model);\n\t\tif (!modelKey) return;\n\t\ttry {\n\t\t\tfor (const mode of [...new Set(event.repairsApplied)]) {\n\t\t\t\tconst profile = this.deps.adaptationStore.get(modelKey);\n\t\t\t\tconst stats = profile.teachStats[mode] ?? { taught: 0, recurrenceBefore: 0, recurrenceAfter: 0 };\n\t\t\t\tif (profile.rules.some((rule) => rule.mode === mode)) {\n\t\t\t\t\tthis.deps.adaptationStore.markRuleFired(modelKey, mode);\n\t\t\t\t\tthis.deps.adaptationStore.setTeachStats(modelKey, mode, {\n\t\t\t\t\t\t...stats,\n\t\t\t\t\t\trecurrenceAfter: stats.recurrenceAfter + 1,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst recurrenceBefore = stats.recurrenceBefore + 1;\n\t\t\t\tthis.deps.adaptationStore.setTeachStats(modelKey, mode, { ...stats, recurrenceBefore });\n\t\t\t\tconst sessionCount = this.repairSessionCount(modelKey, mode);\n\t\t\t\tif (\n\t\t\t\t\tsessionCount >= MODEL_ADAPTATION_REPAIR_THRESHOLD ||\n\t\t\t\t\trecurrenceBefore >= MODEL_ADAPTATION_REPAIR_THRESHOLD\n\t\t\t\t) {\n\t\t\t\t\tthis.deps.adaptationStore.addRule(modelKey, { mode, text: formatToolRepairStandingRule(mode) });\n\t\t\t\t\tthis.deps.adaptationStore.setTeachStats(modelKey, mode, {\n\t\t\t\t\t\t...stats,\n\t\t\t\t\t\ttaught: stats.taught + 1,\n\t\t\t\t\t\trecurrenceBefore,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Best-effort adaptation persistence.\n\t\t}\n\t}\n\n\tmaybeAutoProbe(model: Model<Api>): void {\n\t\tconst modelKey = this.modelRef(model);\n\t\tif (this.autoProbedModels.has(modelKey) || this.hasFreshToolProbeVerdict(modelKey)) return;\n\t\tthis.autoProbedModels.add(modelKey);\n\t\tvoid this.deps\n\t\t\t.probeForAuto(model)\n\t\t\t.then((result) => {\n\t\t\t\tif (this.deps.isDisposed()) return;\n\t\t\t\tconst detail =\n\t\t\t\t\tresult.verdict === \"text-protocol\"\n\t\t\t\t\t\t? ` (variant ${result.variant}); it will use the text tool protocol starting next turn`\n\t\t\t\t\t\t: result.verdict === \"none\"\n\t\t\t\t\t\t\t? \" — no working tool-call path was found; run /toolprobe for details\"\n\t\t\t\t\t\t\t: \"; native tool calls stay in use\";\n\t\t\t\tthis.deps.emitWarning(\n\t\t\t\t\t`Auto-probed ${modelKey} after repeated native tool-call validation failures: verdict \"${result.verdict}\"${detail}.`,\n\t\t\t\t);\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tif (this.deps.isDisposed()) return;\n\t\t\t\tthis.deps.emitWarning(\n\t\t\t\t\t`Auto-probe for ${modelKey} (triggered by repeated tool-call validation failures) did not complete: ${error instanceof Error ? error.message : String(error)}.`,\n\t\t\t\t);\n\t\t\t});\n\t}\n\n\tformatRepairHealth(stats?: ToolRecoveryLoggerStats): string {\n\t\treturn formatToolRepairHealthReport(this.deps.adaptationStore, new Date(), stats);\n\t}\n\n\tremoveRepairRule(model: string, mode: string): boolean {\n\t\treturn this.deps.adaptationStore.removeRule(model, mode);\n\t}\n\n\tresetProtocolCalibration(model: string): boolean {\n\t\tconst removed = this.deps.adaptationStore.removeProtocol(model);\n\t\tthis.parseFailures.delete(model);\n\t\treturn removed;\n\t}\n\n\tgetRepairSettings() {\n\t\treturn resolveCurrentToolRepairSettings(this.deps.settingsManager.settings);\n\t}\n\n\tprivate modelKey(model: Model<Api> | undefined): string | undefined {\n\t\treturn model ? this.modelRef(model) : undefined;\n\t}\n\n\tprivate modelRef(model: Model<Api>): string {\n\t\treturn `${model.provider}/${model.id}`;\n\t}\n\n\tprivate async streamForProbe(model: Model<Api>, context: Context, options: SimpleStreamOptions) {\n\t\tlet requestOptions = options;\n\t\tif (this.deps.isRawStreamSimple(this.deps.agent.streamFn)) {\n\t\t\tconst auth = await this.deps.getRequiredRequestAuth(model);\n\t\t\trequestOptions = {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\theaders: auth.headers || options.headers ? { ...auth.headers, ...options.headers } : undefined,\n\t\t\t};\n\t\t}\n\t\treturn this.deps.agent.streamFn(model, context, requestOptions);\n\t}\n\n\tprivate nextProbeUsageReportId(model: Model<Api>, kind: string): string {\n\t\treturn `tool-probe:${this.modelRef(model)}:${kind}:${this.probeUsageReportSeq++}`;\n\t}\n\n\tprivate async resolveProbeStreamCountingUsage(\n\t\tstream: AssistantMessageEventStream,\n\t\tlabel: string,\n\t\treportId: string,\n\t): Promise<AssistantMessage> {\n\t\tconst message = await stream.result();\n\t\tconst usage = message.usage;\n\t\tif (usage && (usage.cost.total > 0 || usage.totalTokens > 0)) {\n\t\t\tthis.deps.addSpawnedUsage(usage, { label, reportId });\n\t\t}\n\t\treturn message;\n\t}\n\n\tprivate textProtocolCalibrationContext(variant: TextToolProtocolVariant, token: string): Context {\n\t\tconst primer = generateTextToolProtocolPrimer([TEXT_TOOL_PROTOCOL_ECHO_TOOL], { variant });\n\t\tconst exactEnvelope = formatVariantEnvelope(variant, \"echo\", JSON.stringify({ data: token }));\n\t\tconst instruction =\n\t\t\t`Text tool protocol calibration trial. Using the protocol above, call echo with data exactly \"${token}\". ` +\n\t\t\t`Output only this exact tool-call envelope:\\n${exactEnvelope}`;\n\t\treturn {\n\t\t\tsystemPrompt: `${primer}\\n\\n${instruction}`,\n\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: instruction }], timestamp: Date.now() }],\n\t\t};\n\t}\n\n\tprivate messageHasToolCallWithStringArgument(\n\t\tmessage: AssistantMessage,\n\t\ttoolName: string,\n\t\targName: string,\n\t\targValue: string,\n\t): boolean {\n\t\treturn message.content.some((block) => {\n\t\t\tif (block.type !== \"toolCall\" || block.name !== toolName) return false;\n\t\t\tconst args = block.arguments as unknown;\n\t\t\treturn (\n\t\t\t\ttypeof args === \"object\" &&\n\t\t\t\targs !== null &&\n\t\t\t\t!Array.isArray(args) &&\n\t\t\t\t(args as Record<string, unknown>)[argName] === argValue\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate nativeToolProbeSystemPrompt(instruction: string): string {\n\t\tconst base = (this.deps.agent.state.systemPrompt ?? \"\").trim();\n\t\treturn base ? `${base}\\n\\n${instruction}` : instruction;\n\t}\n\n\tprivate async runNativeToolProbeTrial(\n\t\tmodel: Model<Api>,\n\t\tinstruction: string,\n\t\ttool: Tool,\n\t\tmaxTokens: number,\n\t\treportKind: string,\n\t\targName: string,\n\t\targValue: string,\n\t): Promise<boolean> {\n\t\tconst stream = await this.streamForProbe(\n\t\t\tmodel,\n\t\t\t{\n\t\t\t\tsystemPrompt: this.nativeToolProbeSystemPrompt(instruction),\n\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: instruction }], timestamp: Date.now() }],\n\t\t\t\ttools: [tool],\n\t\t\t},\n\t\t\t{ textToolCallProtocol: false, maxRetries: 0, temperature: 0, maxTokens },\n\t\t);\n\t\tconst message = await this.resolveProbeStreamCountingUsage(\n\t\t\tstream,\n\t\t\t\"tool-probe\",\n\t\t\tthis.nextProbeUsageReportId(model, reportKind),\n\t\t);\n\t\treturn this.messageHasToolCallWithStringArgument(message, tool.name, argName, argValue);\n\t}\n\n\tprivate async runNativeReadTaskProbeTrial(model: Model<Api>, path: string): Promise<boolean> {\n\t\tconst instruction =\n\t\t\t`Native tool-call capability probe: task-scale read. Use provider-native tool calling, not prose. ` +\n\t\t\t`Call read exactly once with path exactly \"${path}\".`;\n\t\treturn this.runNativeToolProbeTrial(\n\t\t\tmodel,\n\t\t\tinstruction,\n\t\t\tNATIVE_TOOL_PROBE_READ_TOOL,\n\t\t\t768,\n\t\t\t\"read-task\",\n\t\t\t\"path\",\n\t\t\tpath,\n\t\t);\n\t}\n\n\tprivate async runNativeEchoToolProbeTrial(model: Model<Api>, token: string): Promise<boolean> {\n\t\tconst instruction =\n\t\t\t`Native tool-call capability probe: echo-only. Use provider-native tool calling, not prose. ` +\n\t\t\t`Call echo with data exactly \"${token}\".`;\n\t\treturn this.runNativeToolProbeTrial(model, instruction, TEXT_TOOL_PROTOCOL_ECHO_TOOL, 256, \"echo\", \"data\", token);\n\t}\n\n\tprivate async gradeNativeToolCallingForModel(model: Model<Api>, token: string): Promise<NativeToolProbeGrade> {\n\t\tconst path = join(\n\t\t\tgetProcessWorkRun(this.deps.agentDir, \"probes\", \"native-tools\").path,\n\t\t\t`pi-native-probe-${process.pid}-${Date.now()}.txt`,\n\t\t);\n\t\twriteFileSync(path, token, \"utf-8\");\n\t\ttry {\n\t\t\tif (await this.runNativeReadTaskProbeTrial(model, path)) return \"task\";\n\t\t\tif (await this.runNativeEchoToolProbeTrial(model, token)) return \"echo-only\";\n\t\t\treturn \"absent\";\n\t\t} finally {\n\t\t\trmSync(path, { force: true });\n\t\t}\n\t}\n\n\tprivate async runTextProtocolTrial(\n\t\tmodel: Model<Api>,\n\t\tvariant: TextToolProtocolVariant,\n\t\ttoken: string,\n\t): Promise<boolean> {\n\t\tconst stream = await this.streamForProbe(model, this.textProtocolCalibrationContext(variant, token), {\n\t\t\ttextToolCallProtocol: false,\n\t\t\tmaxRetries: 0,\n\t\t\ttemperature: 0,\n\t\t\tmaxTokens: 256,\n\t\t});\n\t\tconst message = await this.resolveProbeStreamCountingUsage(\n\t\t\tstream,\n\t\t\t\"text-protocol-calibration\",\n\t\t\tthis.nextProbeUsageReportId(model, `text-protocol:${variant}`),\n\t\t);\n\t\tconst text = message.content\n\t\t\t.filter(\n\t\t\t\t(block): block is TextContent | ThinkingContent =>\n\t\t\t\t\tblock.type === \"text\" || (block.type === \"thinking\" && !block.redacted),\n\t\t\t)\n\t\t\t.map((block) => (block.type === \"text\" ? block.text : block.thinking))\n\t\t\t.join(\"\\n\")\n\t\t\t.trim();\n\t\tif (!text) return false;\n\t\tconst parsed = parseTextToolCalls(text, [TEXT_TOOL_PROTOCOL_ECHO_TOOL]);\n\t\treturn parsed.calls.some((call) => call.name === \"echo\" && call.arguments.data === token);\n\t}\n\n\tprivate async calibrateTextToolProtocolForModel(\n\t\tmodel: Model<Api>,\n\t\tmodelKey: string | undefined,\n\t\toptions: { persistFailure: boolean },\n\t): Promise<\n\t\t| { status: \"calibrated\"; variant: TextToolProtocolVariant; calibratedAt: string }\n\t\t| { status: \"failed\"; attemptedAt: string; variantsTried: string[] }\n\t> {\n\t\tconst variantsTried: string[] = [];\n\t\tfor (const variant of TEXT_TOOL_PROTOCOL_VARIANTS) {\n\t\t\tvariantsTried.push(variant);\n\t\t\tlet passed = true;\n\t\t\tfor (let trial = 0; trial < TEXT_TOOL_PROTOCOL_TRIALS_PER_VARIANT; trial++) {\n\t\t\t\tif (!(await this.runTextProtocolTrial(model, variant, `pi-calibration-${trial + 1}`))) {\n\t\t\t\t\tpassed = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (passed) {\n\t\t\t\tconst calibratedAt = new Date().toISOString();\n\t\t\t\tif (modelKey) {\n\t\t\t\t\tthis.deps.adaptationStore.setProtocol(\n\t\t\t\t\t\tmodelKey,\n\t\t\t\t\t\t{ version: MODEL_TOOL_PROTOCOL_VERSION, status: \"calibrated\", variant, calibratedAt },\n\t\t\t\t\t\tcalibratedAt,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn { status: \"calibrated\", variant, calibratedAt };\n\t\t\t}\n\t\t}\n\n\t\tconst attemptedAt = new Date().toISOString();\n\t\tif (modelKey && options.persistFailure) {\n\t\t\tthis.deps.adaptationStore.setProtocol(\n\t\t\t\tmodelKey,\n\t\t\t\t{ version: MODEL_TOOL_PROTOCOL_VERSION, status: \"failed\", attemptedAt, variantsTried },\n\t\t\t\tattemptedAt,\n\t\t\t);\n\t\t}\n\t\treturn { status: \"failed\", attemptedAt, variantsTried };\n\t}\n\n\tprivate formatToolProbeReport(results: readonly ToolProbeResult[]): string {\n\t\tconst lines = [\n\t\t\t\"Tool probe results:\",\n\t\t\t\"Model | Verdict | Variant | Native grade | Diagnostic\",\n\t\t\t\"--- | --- | --- | --- | ---\",\n\t\t];\n\t\tfor (const result of results) {\n\t\t\tlines.push(\n\t\t\t\t[\n\t\t\t\t\tresult.model,\n\t\t\t\t\tresult.verdict,\n\t\t\t\t\tresult.variant ?? \"-\",\n\t\t\t\t\tresult.nativeGrade ?? \"-\",\n\t\t\t\t\tresult.diagnostic ? result.diagnostic.replace(/\\s+/g, \" \").slice(0, 160) : \"-\",\n\t\t\t\t].join(\" | \"),\n\t\t\t);\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tprivate storeToolProbe(modelKey: string, probe: ModelToolProbe): void {\n\t\tthis.deps.adaptationStore.setToolProbe(modelKey, probe, probe.probedAt);\n\t}\n\n\tprivate async resolveToolProbeModels(target?: string): Promise<Model<Api>[]> {\n\t\tconst trimmed = target?.trim();\n\t\tif (!trimmed) return this.deps.getModelRegistry().getAvailable();\n\t\tconst [provider, ...modelParts] = trimmed.split(\"/\");\n\t\tconst modelId = modelParts.join(\"/\");\n\t\tif (!provider || !modelId) throw new Error(\"Usage: /toolprobe [provider/model]\");\n\t\tconst exact = this.deps.getModelRegistry().find(provider, modelId);\n\t\tif (exact) return [exact];\n\t\tconst current = this.deps.agent.state.model;\n\t\tif (current?.provider === provider && current.id === modelId) return [current];\n\t\tthrow new Error(`Model not found: ${trimmed}`);\n\t}\n\n\tprivate maybeInjectCorrectiveSteer(variant: TextToolProtocolVariant): void {\n\t\tthis.correctiveSteerCount++;\n\t\tif (this.correctiveSteerCount !== 1 && this.correctiveSteerCount % TEXT_TOOL_PROTOCOL_STEER_INTERVAL !== 0) {\n\t\t\treturn;\n\t\t}\n\t\tconst reminder = `Reminder: to call a tool, emit exactly this envelope shape: ${formatVariantEnvelope(variant, \"TOOL\", '{\"arg\":\"value\"}')} — no other format is recognized. Reasoning may appear as prose before the envelope, never inside it.`;\n\t\tthis.deps.sendCorrectiveSteer(reminder).catch(() => {\n\t\t\t// Best-effort steer.\n\t\t});\n\t}\n\n\tprivate looksLikeTextProtocolAttempt(text: string): boolean {\n\t\treturn /<pi:call\\b|<tool_call\\b|```(?:tool|tool_call)[\\s\\S]*\"name\"\\s*:/i.test(text);\n\t}\n\n\tprivate repairSessionCount(modelKey: string, mode: ToolRepairModeName): number {\n\t\tconst key = `${modelKey}\\0${mode}`;\n\t\tconst count = (this.repairModeSessionCounts.get(key) ?? 0) + 1;\n\t\tthis.repairModeSessionCounts.set(key, count);\n\t\treturn count;\n\t}\n\n\tprivate hasFreshToolProbeVerdict(modelKey: string): boolean {\n\t\tconst probedAt = this.deps.adaptationStore.get(modelKey).toolProbe?.probedAt;\n\t\tif (!probedAt) return false;\n\t\tconst age = Date.now() - new Date(probedAt).getTime();\n\t\treturn Number.isFinite(age) && age >= 0 && age < AUTO_TOOL_PROBE_FRESHNESS_MS;\n\t}\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Worker } from "node:worker_threads";
|
|
2
|
-
import { readToolFailureTelemetry } from "@caupulican/pi-agent-core";
|
|
2
|
+
import { readToolFailureTelemetry } from "@caupulican/pi-agent-core/tool-failure-memory";
|
|
3
3
|
import { createToolArgumentValidationLogRecord, createToolExecutionFailureLogRecord, } from "./tool-recovery-log-records.js";
|
|
4
4
|
const DEFAULT_MAX_QUEUE = 1000;
|
|
5
5
|
const DEFAULT_BATCH_SIZE = 50;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-recovery-logger.js","sourceRoot":"","sources":["../../src/core/tool-recovery-logger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAGrE,OAAO,EACN,qCAAqC,EACrC,mCAAmC,GAInC,MAAM,gCAAgC,CAAC;AAkCxC,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAC/B,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAC9B,MAAM,wBAAwB,GAAG,GAAG,CAAC;AAErC,SAAS,2BAA2B,CAAC,KAAc;IAClD,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACtD,MAAM,OAAO,GAAG,KAA2C,CAAC;IAC5D,OAAO,CACN,OAAO,CAAC,IAAI,KAAK,KAAK;QACtB,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ;QACnC,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ;QACnC,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ,CAClC,CAAC;AACH,CAAC;AAED,SAAS,4BAA4B;IACpC,MAAM,mBAAmB,GAAG,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC5D,OAAO,IAAI,GAAG,CACb,mBAAmB,CAAC,CAAC,CAAC,+BAA+B,CAAC,CAAC,CAAC,+BAA+B,EACvF,OAAO,IAAI,CAAC,GAAG,CACf,CAAC;AACH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AI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC;YAAE,OAAO;QAC9D,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;QAC5C,KAAK,MAAM,MAAM,IAAI,OAAO;YAAE,MAAM,EAAE,CAAC;IACxC,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { readToolFailureTelemetry } from \"@caupulican/pi-agent-core\";\nimport type { ToolArgumentValidationTelemetryEvent } from \"@caupulican/pi-ai\";\nimport type { ToolFailurePhase } from \"@caupulican/pi-ai/tool-repair-registry\";\nimport {\n\tcreateToolArgumentValidationLogRecord,\n\tcreateToolExecutionFailureLogRecord,\n\ttype ToolArgumentValidationLogRecord,\n\ttype ToolExecutionFailureLogRecord,\n\ttype ToolRecoveryLogWorkerRecord,\n} from \"./tool-recovery-log-records.ts\";\n\ninterface ToolRecoveryLogAckMessage {\n\ttype: \"ack\";\n\tbatchId: number;\n\twritten: number;\n\tfailed: number;\n}\n\nexport interface ToolRecoveryLoggerStats {\n\tenabled: boolean;\n\tqueued: number;\n\tinFlight: number;\n\tdropped: number;\n\tfailures: number;\n\tworkerStarts: number;\n\tworkerCrashes: number;\n\trespawns: number;\n\texecutionFailures: number;\n\tfailurePhases: Partial<Record<ToolFailurePhase, number>>;\n}\n\nexport interface ToolRecoveryLoggerOptions {\n\tenabled: boolean;\n\tsessionId: string;\n\teventLogPath: string;\n\tfailureCorpusPath: string;\n\tmaxQueue?: number;\n\tbatchSize?: number;\n\tnow?: () => Date;\n\tdebug?: (message: string) => void;\n\tworkerSpecifier?: string | URL;\n}\n\nconst DEFAULT_MAX_QUEUE = 1000;\nconst DEFAULT_BATCH_SIZE = 50;\nconst DEFAULT_FLUSH_TIMEOUT_MS = 200;\n\nfunction isToolRecoveryLogAckMessage(value: unknown): value is ToolRecoveryLogAckMessage {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst message = value as Partial<ToolRecoveryLogAckMessage>;\n\treturn (\n\t\tmessage.type === \"ack\" &&\n\t\ttypeof message.batchId === \"number\" &&\n\t\ttypeof message.written === \"number\" &&\n\t\ttypeof message.failed === \"number\"\n\t);\n}\n\nfunction createDefaultWorkerSpecifier(): URL {\n\tconst isTypeScriptRuntime = import.meta.url.endsWith(\".ts\");\n\treturn new URL(\n\t\tisTypeScriptRuntime ? \"./tool-recovery-log-worker.ts\" : \"./tool-recovery-log-worker.js\",\n\t\timport.meta.url,\n\t);\n}\n\nexport class ToolRecoveryLogger {\n\tprivate readonly enabled: boolean;\n\tprivate readonly sessionId: string;\n\tprivate readonly eventLogPath: string;\n\tprivate readonly failureCorpusPath: string;\n\tprivate readonly maxQueue: number;\n\tprivate readonly batchSize: number;\n\tprivate readonly now: () => Date;\n\tprivate readonly debug: (message: string) => void;\n\tprivate readonly workerSpecifier: string | URL;\n\tprivate readonly queue: ToolRecoveryLogWorkerRecord[] = [];\n\tprivate readonly flushWaiters: Array<() => void> = [];\n\tprivate worker: Worker | undefined;\n\tprivate inFlight: ToolRecoveryLogWorkerRecord[] = [];\n\tprivate inFlightBatchId: number | undefined;\n\tprivate inFlightWorker: Worker | undefined;\n\tprivate batchId = 0;\n\tprivate recordSequence = 0;\n\tprivate dropped = 0;\n\tprivate failures = 0;\n\tprivate workerStarts = 0;\n\tprivate workerCrashes = 0;\n\tprivate respawns = 0;\n\tprivate executionFailures = 0;\n\tprivate readonly failurePhases: Partial<Record<ToolFailurePhase, number>> = {};\n\tprivate respawnAttempted = false;\n\tprivate shuttingDown = false;\n\n\tconstructor(options: ToolRecoveryLoggerOptions) {\n\t\tthis.enabled = options.enabled;\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.eventLogPath = options.eventLogPath;\n\t\tthis.failureCorpusPath = options.failureCorpusPath;\n\t\tthis.maxQueue = options.maxQueue ?? DEFAULT_MAX_QUEUE;\n\t\tthis.batchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;\n\t\tthis.now = options.now ?? (() => new Date());\n\t\tthis.debug = options.debug ?? (() => {});\n\t\tthis.workerSpecifier = options.workerSpecifier ?? createDefaultWorkerSpecifier();\n\t}\n\n\trecordToolArgumentValidation(\n\t\tevent: ToolArgumentValidationTelemetryEvent,\n\t): ToolArgumentValidationLogRecord | undefined {\n\t\tif (!this.enabled || event.outcome === \"clean\") return undefined;\n\t\tconst record = createToolArgumentValidationLogRecord({\n\t\t\tevent,\n\t\t\trecordId: `${this.sessionId}:${this.recordSequence++}`,\n\t\t\tsessionId: this.sessionId,\n\t\t\tts: this.now().toISOString(),\n\t\t});\n\t\tthis.enqueue({ eventLogPath: this.eventLogPath, failureCorpusPath: this.failureCorpusPath, record });\n\t\treturn record;\n\t}\n\n\trecordToolExecutionFailure(args: {\n\t\tprovider?: string;\n\t\tmodel?: string;\n\t\ttool: string;\n\t\tdetails: unknown;\n\t}): ToolExecutionFailureLogRecord | undefined {\n\t\tif (!this.enabled) return undefined;\n\t\tconst failure = readToolFailureTelemetry(args.details);\n\t\tif (!failure) return undefined;\n\t\tconst record = createToolExecutionFailureLogRecord({\n\t\t\t...args,\n\t\t\t...failure,\n\t\t\trecordId: `${this.sessionId}:${this.recordSequence++}`,\n\t\t\tsessionId: this.sessionId,\n\t\t\tts: this.now().toISOString(),\n\t\t});\n\t\tthis.executionFailures++;\n\t\tthis.failurePhases[failure.phase] = (this.failurePhases[failure.phase] ?? 0) + 1;\n\t\tthis.enqueue({ eventLogPath: this.eventLogPath, failureCorpusPath: this.failureCorpusPath, record });\n\t\treturn record;\n\t}\n\n\tgetStats(): ToolRecoveryLoggerStats {\n\t\treturn {\n\t\t\tenabled: this.enabled,\n\t\t\tqueued: this.queue.length,\n\t\t\tinFlight: this.inFlight.length,\n\t\t\tdropped: this.dropped,\n\t\t\tfailures: this.failures,\n\t\t\tworkerStarts: this.workerStarts,\n\t\t\tworkerCrashes: this.workerCrashes,\n\t\t\trespawns: this.respawns,\n\t\t\texecutionFailures: this.executionFailures,\n\t\t\tfailurePhases: { ...this.failurePhases },\n\t\t};\n\t}\n\n\tflush(timeoutMs: number = DEFAULT_FLUSH_TIMEOUT_MS): Promise<void> {\n\t\tif (!this.enabled || (!this.worker && this.queue.length === 0 && this.inFlight.length === 0)) {\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\tthis.pump();\n\t\treturn new Promise((resolve) => {\n\t\t\tlet settled = false;\n\t\t\tlet timeout: NodeJS.Timeout;\n\t\t\tconst finish = (): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tresolve();\n\t\t\t};\n\t\t\tconst waiter = (): void => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tfinish();\n\t\t\t};\n\t\t\ttimeout = setTimeout(() => {\n\t\t\t\tconst index = this.flushWaiters.indexOf(waiter);\n\t\t\t\tif (index !== -1) this.flushWaiters.splice(index, 1);\n\t\t\t\tfinish();\n\t\t\t}, timeoutMs);\n\t\t\tthis.flushWaiters.push(waiter);\n\t\t\tthis.resolveFlushWaitersIfIdle();\n\t\t});\n\t}\n\n\tasync shutdown(timeoutMs: number = DEFAULT_FLUSH_TIMEOUT_MS): Promise<void> {\n\t\tawait this.flush(timeoutMs);\n\t\tthis.shuttingDown = true;\n\t\tconst worker = this.worker;\n\t\tthis.worker = undefined;\n\t\tif (!worker) return;\n\t\ttry {\n\t\t\tworker.postMessage({ type: \"shutdown\" });\n\t\t} catch {}\n\t\tvoid worker.terminate().catch(() => undefined);\n\t}\n\n\tprivate enqueue(record: ToolRecoveryLogWorkerRecord): void {\n\t\tif (!this.enabled) return;\n\t\tthis.queue.push(record);\n\t\twhile (this.queue.length > this.maxQueue) {\n\t\t\tthis.queue.shift();\n\t\t\tthis.dropped++;\n\t\t}\n\t\tthis.pump();\n\t}\n\n\tprivate pump(): void {\n\t\tif (!this.enabled || this.shuttingDown || this.inFlight.length > 0 || this.queue.length === 0) return;\n\t\tconst worker = this.ensureWorker();\n\t\tif (!worker) return;\n\t\tconst records = this.queue.splice(0, this.batchSize);\n\t\tthis.inFlight = records;\n\t\tconst batchId = this.batchId++;\n\t\tthis.inFlightBatchId = batchId;\n\t\tthis.inFlightWorker = worker;\n\t\ttry {\n\t\t\tworker.postMessage({ type: \"records\", batchId, records });\n\t\t} catch (error) {\n\t\t\tthis.debug(`tool recovery logger post failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\tthis.handleWorkerFailure(worker, error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t}\n\n\tprivate ensureWorker(): Worker | undefined {\n\t\tif (this.worker) return this.worker;\n\t\ttry {\n\t\t\tconst worker = new Worker(this.workerSpecifier);\n\t\t\tworker.unref();\n\t\t\tthis.worker = worker;\n\t\t\tthis.workerStarts++;\n\t\t\tworker.on(\"message\", (message: unknown) => this.handleWorkerMessage(worker, message));\n\t\t\tworker.on(\"error\", (error) => this.handleWorkerFailure(worker, error));\n\t\t\tworker.on(\"exit\", (code) => {\n\t\t\t\tif (this.shuttingDown || this.worker !== worker) return;\n\t\t\t\tthis.handleWorkerFailure(worker, new Error(`tool recovery logger worker exited with code ${code}`));\n\t\t\t});\n\t\t\treturn worker;\n\t\t} catch (error) {\n\t\t\tthis.failures++;\n\t\t\tthis.debug(\n\t\t\t\t`tool recovery logger worker start failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate handleWorkerMessage(worker: Worker, message: unknown): void {\n\t\tif (!isToolRecoveryLogAckMessage(message)) return;\n\t\tif (this.worker !== worker || this.inFlightWorker !== worker || this.inFlightBatchId !== message.batchId) {\n\t\t\treturn;\n\t\t}\n\t\tif (message.failed > 0) {\n\t\t\tthis.failures += message.failed;\n\t\t}\n\t\tthis.inFlight = [];\n\t\tthis.inFlightBatchId = undefined;\n\t\tthis.inFlightWorker = undefined;\n\t\tthis.respawnAttempted = false;\n\t\tthis.pump();\n\t\tthis.resolveFlushWaitersIfIdle();\n\t}\n\n\tprivate handleWorkerFailure(worker: Worker, error: Error): void {\n\t\tif (this.worker !== worker) return;\n\t\tthis.failures++;\n\t\tthis.workerCrashes++;\n\t\tif (this.inFlightWorker === worker) {\n\t\t\tthis.dropped += this.inFlight.length;\n\t\t\tthis.inFlight = [];\n\t\t\tthis.inFlightBatchId = undefined;\n\t\t\tthis.inFlightWorker = undefined;\n\t\t}\n\t\tthis.worker = undefined;\n\t\tthis.debug(`tool recovery logger worker failed: ${error.message}`);\n\t\tif (!this.respawnAttempted && !this.shuttingDown) {\n\t\t\tthis.respawnAttempted = true;\n\t\t\tthis.respawns++;\n\t\t\tthis.pump();\n\t\t}\n\t\tthis.resolveFlushWaitersIfIdle();\n\t}\n\n\tprivate resolveFlushWaitersIfIdle(): void {\n\t\tif (this.queue.length > 0 || this.inFlight.length > 0) return;\n\t\tconst waiters = this.flushWaiters.splice(0);\n\t\tfor (const waiter of waiters) waiter();\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tool-recovery-logger.js","sourceRoot":"","sources":["../../src/core/tool-recovery-logger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,wBAAwB,EAAE,MAAM,+CAA+C,CAAC;AAGzF,OAAO,EACN,qCAAqC,EACrC,mCAAmC,GAInC,MAAM,gCAAgC,CAAC;AAkCxC,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAC/B,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAC9B,MAAM,wBAAwB,GAAG,GAAG,CAAC;AAErC,SAAS,2BAA2B,CAAC,KAAc;IAClD,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACtD,MAAM,OAAO,GAAG,KAA2C,CAAC;IAC5D,OAAO,CACN,OAAO,CAAC,IAAI,KAAK,KAAK;QACtB,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ;QACnC,OAAO,OAAO,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,uCAAuC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QACnE,IAAI,CAAC,IAAI,CAAC,gBAAgB,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC;YAClD,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC;YAC7B,IAAI,CAAC,QAAQ,EAAE,CAAC;YAChB,IAAI,CAAC,IAAI,EAAE,CAAC;QACb,CAAC;QACD,IAAI,CAAC,yBAAyB,EAAE,CAAC;IAClC,CAAC;IAEO,yBAAyB;QAChC,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC;YAAE,OAAO;QAC9D,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;QAC5C,KAAK,MAAM,MAAM,IAAI,OAAO;YAAE,MAAM,EAAE,CAAC;IACxC,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { readToolFailureTelemetry } from \"@caupulican/pi-agent-core/tool-failure-memory\";\nimport type { ToolArgumentValidationTelemetryEvent } from \"@caupulican/pi-ai\";\nimport type { ToolFailurePhase } from \"@caupulican/pi-ai/tool-repair-registry\";\nimport {\n\tcreateToolArgumentValidationLogRecord,\n\tcreateToolExecutionFailureLogRecord,\n\ttype ToolArgumentValidationLogRecord,\n\ttype ToolExecutionFailureLogRecord,\n\ttype ToolRecoveryLogWorkerRecord,\n} from \"./tool-recovery-log-records.ts\";\n\ninterface ToolRecoveryLogAckMessage {\n\ttype: \"ack\";\n\tbatchId: number;\n\twritten: number;\n\tfailed: number;\n}\n\nexport interface ToolRecoveryLoggerStats {\n\tenabled: boolean;\n\tqueued: number;\n\tinFlight: number;\n\tdropped: number;\n\tfailures: number;\n\tworkerStarts: number;\n\tworkerCrashes: number;\n\trespawns: number;\n\texecutionFailures: number;\n\tfailurePhases: Partial<Record<ToolFailurePhase, number>>;\n}\n\nexport interface ToolRecoveryLoggerOptions {\n\tenabled: boolean;\n\tsessionId: string;\n\teventLogPath: string;\n\tfailureCorpusPath: string;\n\tmaxQueue?: number;\n\tbatchSize?: number;\n\tnow?: () => Date;\n\tdebug?: (message: string) => void;\n\tworkerSpecifier?: string | URL;\n}\n\nconst DEFAULT_MAX_QUEUE = 1000;\nconst DEFAULT_BATCH_SIZE = 50;\nconst DEFAULT_FLUSH_TIMEOUT_MS = 200;\n\nfunction isToolRecoveryLogAckMessage(value: unknown): value is ToolRecoveryLogAckMessage {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst message = value as Partial<ToolRecoveryLogAckMessage>;\n\treturn (\n\t\tmessage.type === \"ack\" &&\n\t\ttypeof message.batchId === \"number\" &&\n\t\ttypeof message.written === \"number\" &&\n\t\ttypeof message.failed === \"number\"\n\t);\n}\n\nfunction createDefaultWorkerSpecifier(): URL {\n\tconst isTypeScriptRuntime = import.meta.url.endsWith(\".ts\");\n\treturn new URL(\n\t\tisTypeScriptRuntime ? \"./tool-recovery-log-worker.ts\" : \"./tool-recovery-log-worker.js\",\n\t\timport.meta.url,\n\t);\n}\n\nexport class ToolRecoveryLogger {\n\tprivate readonly enabled: boolean;\n\tprivate readonly sessionId: string;\n\tprivate readonly eventLogPath: string;\n\tprivate readonly failureCorpusPath: string;\n\tprivate readonly maxQueue: number;\n\tprivate readonly batchSize: number;\n\tprivate readonly now: () => Date;\n\tprivate readonly debug: (message: string) => void;\n\tprivate readonly workerSpecifier: string | URL;\n\tprivate readonly queue: ToolRecoveryLogWorkerRecord[] = [];\n\tprivate readonly flushWaiters: Array<() => void> = [];\n\tprivate worker: Worker | undefined;\n\tprivate inFlight: ToolRecoveryLogWorkerRecord[] = [];\n\tprivate inFlightBatchId: number | undefined;\n\tprivate inFlightWorker: Worker | undefined;\n\tprivate batchId = 0;\n\tprivate recordSequence = 0;\n\tprivate dropped = 0;\n\tprivate failures = 0;\n\tprivate workerStarts = 0;\n\tprivate workerCrashes = 0;\n\tprivate respawns = 0;\n\tprivate executionFailures = 0;\n\tprivate readonly failurePhases: Partial<Record<ToolFailurePhase, number>> = {};\n\tprivate respawnAttempted = false;\n\tprivate shuttingDown = false;\n\n\tconstructor(options: ToolRecoveryLoggerOptions) {\n\t\tthis.enabled = options.enabled;\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.eventLogPath = options.eventLogPath;\n\t\tthis.failureCorpusPath = options.failureCorpusPath;\n\t\tthis.maxQueue = options.maxQueue ?? DEFAULT_MAX_QUEUE;\n\t\tthis.batchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;\n\t\tthis.now = options.now ?? (() => new Date());\n\t\tthis.debug = options.debug ?? (() => {});\n\t\tthis.workerSpecifier = options.workerSpecifier ?? createDefaultWorkerSpecifier();\n\t}\n\n\trecordToolArgumentValidation(\n\t\tevent: ToolArgumentValidationTelemetryEvent,\n\t): ToolArgumentValidationLogRecord | undefined {\n\t\tif (!this.enabled || event.outcome === \"clean\") return undefined;\n\t\tconst record = createToolArgumentValidationLogRecord({\n\t\t\tevent,\n\t\t\trecordId: `${this.sessionId}:${this.recordSequence++}`,\n\t\t\tsessionId: this.sessionId,\n\t\t\tts: this.now().toISOString(),\n\t\t});\n\t\tthis.enqueue({ eventLogPath: this.eventLogPath, failureCorpusPath: this.failureCorpusPath, record });\n\t\treturn record;\n\t}\n\n\trecordToolExecutionFailure(args: {\n\t\tprovider?: string;\n\t\tmodel?: string;\n\t\ttool: string;\n\t\tdetails: unknown;\n\t}): ToolExecutionFailureLogRecord | undefined {\n\t\tif (!this.enabled) return undefined;\n\t\tconst failure = readToolFailureTelemetry(args.details);\n\t\tif (!failure) return undefined;\n\t\tconst record = createToolExecutionFailureLogRecord({\n\t\t\t...args,\n\t\t\t...failure,\n\t\t\trecordId: `${this.sessionId}:${this.recordSequence++}`,\n\t\t\tsessionId: this.sessionId,\n\t\t\tts: this.now().toISOString(),\n\t\t});\n\t\tthis.executionFailures++;\n\t\tthis.failurePhases[failure.phase] = (this.failurePhases[failure.phase] ?? 0) + 1;\n\t\tthis.enqueue({ eventLogPath: this.eventLogPath, failureCorpusPath: this.failureCorpusPath, record });\n\t\treturn record;\n\t}\n\n\tgetStats(): ToolRecoveryLoggerStats {\n\t\treturn {\n\t\t\tenabled: this.enabled,\n\t\t\tqueued: this.queue.length,\n\t\t\tinFlight: this.inFlight.length,\n\t\t\tdropped: this.dropped,\n\t\t\tfailures: this.failures,\n\t\t\tworkerStarts: this.workerStarts,\n\t\t\tworkerCrashes: this.workerCrashes,\n\t\t\trespawns: this.respawns,\n\t\t\texecutionFailures: this.executionFailures,\n\t\t\tfailurePhases: { ...this.failurePhases },\n\t\t};\n\t}\n\n\tflush(timeoutMs: number = DEFAULT_FLUSH_TIMEOUT_MS): Promise<void> {\n\t\tif (!this.enabled || (!this.worker && this.queue.length === 0 && this.inFlight.length === 0)) {\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\tthis.pump();\n\t\treturn new Promise((resolve) => {\n\t\t\tlet settled = false;\n\t\t\tlet timeout: NodeJS.Timeout;\n\t\t\tconst finish = (): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tresolve();\n\t\t\t};\n\t\t\tconst waiter = (): void => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tfinish();\n\t\t\t};\n\t\t\ttimeout = setTimeout(() => {\n\t\t\t\tconst index = this.flushWaiters.indexOf(waiter);\n\t\t\t\tif (index !== -1) this.flushWaiters.splice(index, 1);\n\t\t\t\tfinish();\n\t\t\t}, timeoutMs);\n\t\t\tthis.flushWaiters.push(waiter);\n\t\t\tthis.resolveFlushWaitersIfIdle();\n\t\t});\n\t}\n\n\tasync shutdown(timeoutMs: number = DEFAULT_FLUSH_TIMEOUT_MS): Promise<void> {\n\t\tawait this.flush(timeoutMs);\n\t\tthis.shuttingDown = true;\n\t\tconst worker = this.worker;\n\t\tthis.worker = undefined;\n\t\tif (!worker) return;\n\t\ttry {\n\t\t\tworker.postMessage({ type: \"shutdown\" });\n\t\t} catch {}\n\t\tvoid worker.terminate().catch(() => undefined);\n\t}\n\n\tprivate enqueue(record: ToolRecoveryLogWorkerRecord): void {\n\t\tif (!this.enabled) return;\n\t\tthis.queue.push(record);\n\t\twhile (this.queue.length > this.maxQueue) {\n\t\t\tthis.queue.shift();\n\t\t\tthis.dropped++;\n\t\t}\n\t\tthis.pump();\n\t}\n\n\tprivate pump(): void {\n\t\tif (!this.enabled || this.shuttingDown || this.inFlight.length > 0 || this.queue.length === 0) return;\n\t\tconst worker = this.ensureWorker();\n\t\tif (!worker) return;\n\t\tconst records = this.queue.splice(0, this.batchSize);\n\t\tthis.inFlight = records;\n\t\tconst batchId = this.batchId++;\n\t\tthis.inFlightBatchId = batchId;\n\t\tthis.inFlightWorker = worker;\n\t\ttry {\n\t\t\tworker.postMessage({ type: \"records\", batchId, records });\n\t\t} catch (error) {\n\t\t\tthis.debug(`tool recovery logger post failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\tthis.handleWorkerFailure(worker, error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t}\n\n\tprivate ensureWorker(): Worker | undefined {\n\t\tif (this.worker) return this.worker;\n\t\ttry {\n\t\t\tconst worker = new Worker(this.workerSpecifier);\n\t\t\tworker.unref();\n\t\t\tthis.worker = worker;\n\t\t\tthis.workerStarts++;\n\t\t\tworker.on(\"message\", (message: unknown) => this.handleWorkerMessage(worker, message));\n\t\t\tworker.on(\"error\", (error) => this.handleWorkerFailure(worker, error));\n\t\t\tworker.on(\"exit\", (code) => {\n\t\t\t\tif (this.shuttingDown || this.worker !== worker) return;\n\t\t\t\tthis.handleWorkerFailure(worker, new Error(`tool recovery logger worker exited with code ${code}`));\n\t\t\t});\n\t\t\treturn worker;\n\t\t} catch (error) {\n\t\t\tthis.failures++;\n\t\t\tthis.debug(\n\t\t\t\t`tool recovery logger worker start failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate handleWorkerMessage(worker: Worker, message: unknown): void {\n\t\tif (!isToolRecoveryLogAckMessage(message)) return;\n\t\tif (this.worker !== worker || this.inFlightWorker !== worker || this.inFlightBatchId !== message.batchId) {\n\t\t\treturn;\n\t\t}\n\t\tif (message.failed > 0) {\n\t\t\tthis.failures += message.failed;\n\t\t}\n\t\tthis.inFlight = [];\n\t\tthis.inFlightBatchId = undefined;\n\t\tthis.inFlightWorker = undefined;\n\t\tthis.respawnAttempted = false;\n\t\tthis.pump();\n\t\tthis.resolveFlushWaitersIfIdle();\n\t}\n\n\tprivate handleWorkerFailure(worker: Worker, error: Error): void {\n\t\tif (this.worker !== worker) return;\n\t\tthis.failures++;\n\t\tthis.workerCrashes++;\n\t\tif (this.inFlightWorker === worker) {\n\t\t\tthis.dropped += this.inFlight.length;\n\t\t\tthis.inFlight = [];\n\t\t\tthis.inFlightBatchId = undefined;\n\t\t\tthis.inFlightWorker = undefined;\n\t\t}\n\t\tthis.worker = undefined;\n\t\tthis.debug(`tool recovery logger worker failed: ${error.message}`);\n\t\tif (!this.respawnAttempted && !this.shuttingDown) {\n\t\t\tthis.respawnAttempted = true;\n\t\t\tthis.respawns++;\n\t\t\tthis.pump();\n\t\t}\n\t\tthis.resolveFlushWaitersIfIdle();\n\t}\n\n\tprivate resolveFlushWaitersIfIdle(): void {\n\t\tif (this.queue.length > 0 || this.inFlight.length > 0) return;\n\t\tconst waiters = this.flushWaiters.splice(0);\n\t\tfor (const waiter of waiters) waiter();\n\t}\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { formatSize } from "@caupulican/pi-agent-core/
|
|
1
|
+
import { formatSize } from "@caupulican/pi-agent-core/truncate";
|
|
2
2
|
import { Text } from "@caupulican/pi-tui";
|
|
3
3
|
import { Type } from "typebox";
|
|
4
4
|
import { DEFAULT_RETRIEVAL_MAX_LINES, retrieveArtifactSlice, } from "../context/artifact-retrieval.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"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CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;YAC9D,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YAC/B,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;YACtD,MAAM,YAAY,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC;YAC9C,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,GAAG,QAAQ,CAAC;YAC1C,IAAI,QAAQ,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACnF,IAAI,SAAS,GAAG,CAAC;gBAAE,QAAQ,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,QAAQ,SAAS,cAAc,CAAC,EAAE,CAAC;YACzF,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;YACvB,OAAO,IAAI,CAAC;QACb,CAAC;KACD,CAAC;AACH,CAAC;AAED,MAAM,UAAU,0BAA0B,CACzC,GAAW,EACX,OAAqC;IAErC,OAAO,kBAAkB,CAAC,oCAAoC,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAC/E,CAAC","sourcesContent":["import type { AgentTool } from \"@caupulican/pi-agent-core\";\nimport { formatSize } from \"@caupulican/pi-agent-core/node\";\nimport { Text } from \"@caupulican/pi-tui\";\nimport { type Static, Type } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport {\n\ttype ArtifactRetrievalMode,\n\tDEFAULT_RETRIEVAL_MAX_LINES,\n\tretrieveArtifactSlice,\n} from \"../context/artifact-retrieval.ts\";\nimport type { ArtifactStore } from \"../context/context-artifacts.ts\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport { invalidArgText, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst ARTIFACT_ID_PREFIX = \"tool-output:\";\n\nconst artifactRetrieveSchema = Type.Object({\n\tartifactId: Type.String({\n\t\tdescription:\n\t\t\t\"Artifact id from a 'Full output: artifact tool-output:<id>' reference in a prior tool result. The 'tool-output:' prefix is optional.\",\n\t}),\n\tmode: Type.Optional(\n\t\tType.Union([Type.Literal(\"metadata\"), Type.Literal(\"head\"), Type.Literal(\"tail\")], {\n\t\t\tdescription:\n\t\t\t\t\"'metadata' for tool/path/size info only (no content); 'head' (default) for the first lines; 'tail' for the last lines.\",\n\t\t}),\n\t),\n\tmaxLines: Type.Optional(\n\t\tType.Number({ description: `Maximum lines to return for head/tail (default: ${DEFAULT_RETRIEVAL_MAX_LINES})` }),\n\t),\n});\n\nexport type ArtifactRetrieveToolInput = Static<typeof artifactRetrieveSchema>;\n\nexport interface ArtifactRetrieveToolDetails {\n\tfound: boolean;\n\tmode: ArtifactRetrievalMode;\n}\n\nexport interface ArtifactRetrieveToolOptions {\n\t/** Session-scoped artifact store to resolve ids against. Omitted: the tool reports unavailable. */\n\tartifactStore?: ArtifactStore;\n}\n\nfunction normalizeArtifactId(input: string): string {\n\treturn input.startsWith(ARTIFACT_ID_PREFIX) ? input.slice(ARTIFACT_ID_PREFIX.length) : input;\n}\n\nfunction formatMetadataText(ref: {\n\tkind: string;\n\ttoolName?: string;\n\tcommand?: string;\n\tpath?: string;\n\tbyteLength: number;\n\tlineCount?: number;\n\treproducible: boolean;\n}): string {\n\tconst lines = [\n\t\t`kind: ${ref.kind}`,\n\t\tref.toolName ? `tool: ${ref.toolName}` : undefined,\n\t\tref.command ? `command: ${ref.command}` : undefined,\n\t\tref.path ? `path: ${ref.path}` : undefined,\n\t\t`size: ${formatSize(ref.byteLength)}`,\n\t\tref.lineCount !== undefined ? `lines: ${ref.lineCount}` : undefined,\n\t\t`reproducible: ${ref.reproducible}`,\n\t];\n\treturn lines.filter((line): line is string => line !== undefined).join(\"\\n\");\n}\n\nfunction formatCall(args: { artifactId: string; mode?: string } | undefined, theme: Theme): string {\n\tconst artifactId = str(args?.artifactId);\n\tconst mode = args?.mode ?? \"head\";\n\tconst idText = artifactId === null ? invalidArgText(theme) : theme.fg(\"accent\", artifactId);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"artifact_retrieve\"))} ${idText}${theme.fg(\"toolOutput\", ` (${mode})`)}`;\n}\n\nexport function createArtifactRetrieveToolDefinition(\n\t_cwd: string,\n\toptions?: ArtifactRetrieveToolOptions,\n): ToolDefinition<typeof artifactRetrieveSchema, ArtifactRetrieveToolDetails | undefined> {\n\tconst artifactStore = options?.artifactStore;\n\treturn {\n\t\tname: \"artifact_retrieve\",\n\t\tlabel: \"artifact_retrieve\",\n\t\tdescription:\n\t\t\t\"Retrieve a bounded slice of a packed tool-output artifact by id, from a 'Full output: artifact tool-output:<id>' reference in a prior tool result. Returns metadata, or a bounded head/tail slice -- never the full raw payload in one call.\",\n\t\tpromptSnippet: \"Retrieve a bounded slice of a packed tool-output artifact\",\n\t\tparameters: artifactRetrieveSchema,\n\t\ttoolGroup: \"explore\",\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ artifactId, mode, maxLines }: { artifactId: string; mode?: ArtifactRetrievalMode; maxLines?: number },\n\t\t) {\n\t\t\tconst effectiveMode = mode ?? \"head\";\n\t\t\tif (!artifactStore) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: \"No artifact store is configured for this session.\" }],\n\t\t\t\t\tdetails: { found: false, mode: effectiveMode },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst result = retrieveArtifactSlice(artifactStore, {\n\t\t\t\tartifactId: normalizeArtifactId(artifactId),\n\t\t\t\tmode,\n\t\t\t\tmaxLines,\n\t\t\t});\n\n\t\t\tif (!result.found) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Artifact not found: ${artifactId} (${result.missingReason}). It may have been cleaned up, or the id may be incorrect.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { found: false, mode: effectiveMode },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (result.mode === \"metadata\") {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: formatMetadataText(result.ref) }],\n\t\t\t\t\tdetails: { found: true, mode: \"metadata\" },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tlet text = result.slice;\n\t\t\tif (result.truncation.truncated) {\n\t\t\t\ttext += `\\n\\n[Showing ${result.mode} ${result.truncation.outputLines} of ${result.truncation.totalLines} lines. Full artifact: ${formatSize(result.ref.byteLength)}. Retrieve again with a different mode/maxLines for another slice.]`;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\t\tdetails: { found: true, mode: result.mode },\n\t\t\t};\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst content = result.content.find((part) => part.type === \"text\");\n\t\t\tconst body = content && \"text\" in content ? content.text : \"\";\n\t\t\tconst lines = body.split(\"\\n\");\n\t\t\tconst maxLines = options.expanded ? lines.length : 20;\n\t\t\tconst displayLines = lines.slice(0, maxLines);\n\t\t\tconst remaining = lines.length - maxLines;\n\t\t\tlet rendered = displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\");\n\t\t\tif (remaining > 0) rendered += `\\n${theme.fg(\"muted\", `... (${remaining} more lines)`)}`;\n\t\t\ttext.setText(rendered);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createArtifactRetrieveTool(\n\tcwd: string,\n\toptions?: ArtifactRetrieveToolOptions,\n): AgentTool<typeof artifactRetrieveSchema> {\n\treturn wrapToolDefinition(createArtifactRetrieveToolDefinition(cwd, options));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"artifact-retrieve.js","sourceRoot":"","sources":["../../../src/core/tools/artifact-retrieve.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAChE,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EAEN,2BAA2B,EAC3B,qBAAqB,GACrB,MAAM,kCAAkC,CAAC;AAG1C,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAElE,MAAM,kBAAkB,GAAG,cAAc,CAAC;AAE1C,MAAM,sBAAsB,GAAG,IAAI,CAAC,MAAM,CAAC;IAC1C,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC;QACvB,WAAW,EACV,sIAAsI;KACvI,CAAC;IACF,IAAI,EAAE,IAAI,CAAC,QAAQ,CAClB,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,EAAE;QAClF,WAAW,EACV,wHAAwH;KACzH,CAAC,CACF;IACD,QAAQ,EAAE,IAAI,CAAC,QAAQ,CACtB,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,mDAAmD,2BAA2B,GAAG,EAAE,CAAC,CAC/G;CACD,CAAC,CAAC;AAcH,SAAS,mBAAmB,CAAC,KAAa;IACzC,OAAO,KAAK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AC/E,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC;YACpE,MAAM,IAAI,GAAG,OAAO,IAAI,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;YAC9D,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YAC/B,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;YACtD,MAAM,YAAY,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC;YAC9C,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,GAAG,QAAQ,CAAC;YAC1C,IAAI,QAAQ,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACnF,IAAI,SAAS,GAAG,CAAC;gBAAE,QAAQ,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,QAAQ,SAAS,cAAc,CAAC,EAAE,CAAC;YACzF,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;YACvB,OAAO,IAAI,CAAC;QACb,CAAC;KACD,CAAC;AACH,CAAC;AAED,MAAM,UAAU,0BAA0B,CACzC,GAAW,EACX,OAAqC;IAErC,OAAO,kBAAkB,CAAC,oCAAoC,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAC/E,CAAC","sourcesContent":["import type { AgentTool } from \"@caupulican/pi-agent-core\";\nimport { formatSize } from \"@caupulican/pi-agent-core/truncate\";\nimport { Text } from \"@caupulican/pi-tui\";\nimport { type Static, Type } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport {\n\ttype ArtifactRetrievalMode,\n\tDEFAULT_RETRIEVAL_MAX_LINES,\n\tretrieveArtifactSlice,\n} from \"../context/artifact-retrieval.ts\";\nimport type { ArtifactStore } from \"../context/context-artifacts.ts\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport { invalidArgText, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst ARTIFACT_ID_PREFIX = \"tool-output:\";\n\nconst artifactRetrieveSchema = Type.Object({\n\tartifactId: Type.String({\n\t\tdescription:\n\t\t\t\"Artifact id from a 'Full output: artifact tool-output:<id>' reference in a prior tool result. The 'tool-output:' prefix is optional.\",\n\t}),\n\tmode: Type.Optional(\n\t\tType.Union([Type.Literal(\"metadata\"), Type.Literal(\"head\"), Type.Literal(\"tail\")], {\n\t\t\tdescription:\n\t\t\t\t\"'metadata' for tool/path/size info only (no content); 'head' (default) for the first lines; 'tail' for the last lines.\",\n\t\t}),\n\t),\n\tmaxLines: Type.Optional(\n\t\tType.Number({ description: `Maximum lines to return for head/tail (default: ${DEFAULT_RETRIEVAL_MAX_LINES})` }),\n\t),\n});\n\nexport type ArtifactRetrieveToolInput = Static<typeof artifactRetrieveSchema>;\n\nexport interface ArtifactRetrieveToolDetails {\n\tfound: boolean;\n\tmode: ArtifactRetrievalMode;\n}\n\nexport interface ArtifactRetrieveToolOptions {\n\t/** Session-scoped artifact store to resolve ids against. Omitted: the tool reports unavailable. */\n\tartifactStore?: ArtifactStore;\n}\n\nfunction normalizeArtifactId(input: string): string {\n\treturn input.startsWith(ARTIFACT_ID_PREFIX) ? input.slice(ARTIFACT_ID_PREFIX.length) : input;\n}\n\nfunction formatMetadataText(ref: {\n\tkind: string;\n\ttoolName?: string;\n\tcommand?: string;\n\tpath?: string;\n\tbyteLength: number;\n\tlineCount?: number;\n\treproducible: boolean;\n}): string {\n\tconst lines = [\n\t\t`kind: ${ref.kind}`,\n\t\tref.toolName ? `tool: ${ref.toolName}` : undefined,\n\t\tref.command ? `command: ${ref.command}` : undefined,\n\t\tref.path ? `path: ${ref.path}` : undefined,\n\t\t`size: ${formatSize(ref.byteLength)}`,\n\t\tref.lineCount !== undefined ? `lines: ${ref.lineCount}` : undefined,\n\t\t`reproducible: ${ref.reproducible}`,\n\t];\n\treturn lines.filter((line): line is string => line !== undefined).join(\"\\n\");\n}\n\nfunction formatCall(args: { artifactId: string; mode?: string } | undefined, theme: Theme): string {\n\tconst artifactId = str(args?.artifactId);\n\tconst mode = args?.mode ?? \"head\";\n\tconst idText = artifactId === null ? invalidArgText(theme) : theme.fg(\"accent\", artifactId);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"artifact_retrieve\"))} ${idText}${theme.fg(\"toolOutput\", ` (${mode})`)}`;\n}\n\nexport function createArtifactRetrieveToolDefinition(\n\t_cwd: string,\n\toptions?: ArtifactRetrieveToolOptions,\n): ToolDefinition<typeof artifactRetrieveSchema, ArtifactRetrieveToolDetails | undefined> {\n\tconst artifactStore = options?.artifactStore;\n\treturn {\n\t\tname: \"artifact_retrieve\",\n\t\tlabel: \"artifact_retrieve\",\n\t\tdescription:\n\t\t\t\"Retrieve a bounded slice of a packed tool-output artifact by id, from a 'Full output: artifact tool-output:<id>' reference in a prior tool result. Returns metadata, or a bounded head/tail slice -- never the full raw payload in one call.\",\n\t\tpromptSnippet: \"Retrieve a bounded slice of a packed tool-output artifact\",\n\t\tparameters: artifactRetrieveSchema,\n\t\ttoolGroup: \"explore\",\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ artifactId, mode, maxLines }: { artifactId: string; mode?: ArtifactRetrievalMode; maxLines?: number },\n\t\t) {\n\t\t\tconst effectiveMode = mode ?? \"head\";\n\t\t\tif (!artifactStore) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: \"No artifact store is configured for this session.\" }],\n\t\t\t\t\tdetails: { found: false, mode: effectiveMode },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst result = retrieveArtifactSlice(artifactStore, {\n\t\t\t\tartifactId: normalizeArtifactId(artifactId),\n\t\t\t\tmode,\n\t\t\t\tmaxLines,\n\t\t\t});\n\n\t\t\tif (!result.found) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Artifact not found: ${artifactId} (${result.missingReason}). It may have been cleaned up, or the id may be incorrect.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { found: false, mode: effectiveMode },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (result.mode === \"metadata\") {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: formatMetadataText(result.ref) }],\n\t\t\t\t\tdetails: { found: true, mode: \"metadata\" },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tlet text = result.slice;\n\t\t\tif (result.truncation.truncated) {\n\t\t\t\ttext += `\\n\\n[Showing ${result.mode} ${result.truncation.outputLines} of ${result.truncation.totalLines} lines. Full artifact: ${formatSize(result.ref.byteLength)}. Retrieve again with a different mode/maxLines for another slice.]`;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\t\tdetails: { found: true, mode: result.mode },\n\t\t\t};\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst content = result.content.find((part) => part.type === \"text\");\n\t\t\tconst body = content && \"text\" in content ? content.text : \"\";\n\t\t\tconst lines = body.split(\"\\n\");\n\t\t\tconst maxLines = options.expanded ? lines.length : 20;\n\t\t\tconst displayLines = lines.slice(0, maxLines);\n\t\t\tconst remaining = lines.length - maxLines;\n\t\t\tlet rendered = displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\");\n\t\t\tif (remaining > 0) rendered += `\\n${theme.fg(\"muted\", `... (${remaining} more lines)`)}`;\n\t\t\ttext.setText(rendered);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createArtifactRetrieveTool(\n\tcwd: string,\n\toptions?: ArtifactRetrieveToolOptions,\n): AgentTool<typeof artifactRetrieveSchema> {\n\treturn wrapToolDefinition(createArtifactRetrieveToolDefinition(cwd, options));\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { type
|
|
2
|
-
import {
|
|
1
|
+
import { type TruncationResult } from "@caupulican/pi-agent-core/truncate";
|
|
2
|
+
import type { AgentTool } from "@caupulican/pi-agent-core/types";
|
|
3
3
|
import { type Static, Type } from "typebox";
|
|
4
4
|
import type { ToolDefinition } from "../extensions/types.ts";
|
|
5
5
|
import { type ShellOutputProjectionDetails } from "./shell-output-projection.ts";
|