@caupulican/pi-adaptative 0.81.32 → 0.81.37
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 +46 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/README.md +69 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +53 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +1282 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +1453 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/templates/builder-validator.json +14 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/templates/claude-trio.json +32 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/templates/full-provider-review.json +15 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/templates/provider-prompt-smoke.json +14 -0
- package/dist/bundled-resources/prompts/extensionify.md +5 -4
- package/dist/bundled-resources/prompts/skillify.md +5 -5
- package/dist/bundled-resources/skills/pi-harness-learning/SKILL.md +6 -3
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +10 -8
- package/dist/cli/args.js.map +1 -1
- package/dist/config.d.ts +5 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +10 -2
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session.d.ts +12 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +42 -2
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
- package/dist/core/autonomy/approval-gate.js +2 -0
- package/dist/core/autonomy/approval-gate.js.map +1 -1
- package/dist/core/autonomy/foreground-envelope.d.ts.map +1 -1
- package/dist/core/autonomy/foreground-envelope.js +2 -0
- package/dist/core/autonomy/foreground-envelope.js.map +1 -1
- package/dist/core/autonomy/gates.d.ts.map +1 -1
- package/dist/core/autonomy/gates.js +9 -2
- package/dist/core/autonomy/gates.js.map +1 -1
- package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
- package/dist/core/autonomy/risk-assessment.js +2 -0
- package/dist/core/autonomy/risk-assessment.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +12 -3
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +67 -26
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/bash-execution-controller.d.ts +9 -4
- package/dist/core/bash-execution-controller.d.ts.map +1 -1
- package/dist/core/bash-execution-controller.js +7 -6
- package/dist/core/bash-execution-controller.js.map +1 -1
- package/dist/core/bash-executor.d.ts +2 -0
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +10 -5
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/context/context-store-retention.d.ts +4 -1
- package/dist/core/context/context-store-retention.d.ts.map +1 -1
- package/dist/core/context/context-store-retention.js +42 -151
- package/dist/core/context/context-store-retention.js.map +1 -1
- package/dist/core/context-pipeline.d.ts.map +1 -1
- package/dist/core/context-pipeline.js +6 -6
- package/dist/core/context-pipeline.js.map +1 -1
- package/dist/core/default-tool-surface.d.ts +7 -0
- package/dist/core/default-tool-surface.d.ts.map +1 -1
- package/dist/core/default-tool-surface.js +29 -10
- package/dist/core/default-tool-surface.js.map +1 -1
- package/dist/core/doctor.d.ts +10 -10
- package/dist/core/doctor.d.ts.map +1 -1
- package/dist/core/doctor.js +30 -20
- package/dist/core/doctor.js.map +1 -1
- package/dist/core/exec.d.ts +2 -0
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js +26 -39
- package/dist/core/exec.js.map +1 -1
- package/dist/core/extensions/loader.d.ts +9 -2
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +105 -21
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/types.d.ts +13 -3
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js +3 -0
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/footer-data-provider.d.ts.map +1 -1
- package/dist/core/footer-data-provider.js +2 -0
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/goals/goal-state.d.ts +10 -0
- package/dist/core/goals/goal-state.d.ts.map +1 -1
- package/dist/core/goals/goal-state.js +37 -0
- package/dist/core/goals/goal-state.js.map +1 -1
- package/dist/core/goals/goal-tool-core.d.ts +11 -0
- package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
- package/dist/core/goals/goal-tool-core.js +51 -1
- package/dist/core/goals/goal-tool-core.js.map +1 -1
- package/dist/core/improvement-loop.d.ts.map +1 -1
- package/dist/core/improvement-loop.js +26 -5
- package/dist/core/improvement-loop.js.map +1 -1
- package/dist/core/memory/memory-manager.d.ts.map +1 -1
- package/dist/core/memory/memory-manager.js +1 -0
- package/dist/core/memory/memory-manager.js.map +1 -1
- package/dist/core/model-capability.d.ts.map +1 -1
- package/dist/core/model-capability.js +2 -0
- package/dist/core/model-capability.js.map +1 -1
- package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
- package/dist/core/model-router/tool-escalation.js +17 -3
- package/dist/core/model-router/tool-escalation.js.map +1 -1
- package/dist/core/models/fitness-store.d.ts.map +1 -1
- package/dist/core/models/fitness-store.js +1 -1
- package/dist/core/models/fitness-store.js.map +1 -1
- package/dist/core/models/local-runtime.d.ts +6 -4
- package/dist/core/models/local-runtime.d.ts.map +1 -1
- package/dist/core/models/local-runtime.js +108 -36
- package/dist/core/models/local-runtime.js.map +1 -1
- package/dist/core/output-guard.d.ts.map +1 -1
- package/dist/core/output-guard.js +23 -8
- package/dist/core/output-guard.js.map +1 -1
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +44 -59
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/profile-resource-selection.d.ts +16 -0
- package/dist/core/profile-resource-selection.d.ts.map +1 -1
- package/dist/core/profile-resource-selection.js +41 -0
- package/dist/core/profile-resource-selection.js.map +1 -1
- package/dist/core/python-runtime.d.ts +46 -0
- package/dist/core/python-runtime.d.ts.map +1 -0
- package/dist/core/python-runtime.js +157 -0
- package/dist/core/python-runtime.js.map +1 -0
- package/dist/core/reflection-controller.d.ts.map +1 -1
- package/dist/core/reflection-controller.js +18 -1
- package/dist/core/reflection-controller.js.map +1 -1
- package/dist/core/reload-blockers.d.ts +1 -0
- package/dist/core/reload-blockers.d.ts.map +1 -1
- package/dist/core/reload-blockers.js +6 -2
- package/dist/core/reload-blockers.js.map +1 -1
- package/dist/core/resource-loader.d.ts +2 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +50 -28
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +4 -0
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +31 -9
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/security/untrusted-boundary.d.ts +2 -2
- package/dist/core/security/untrusted-boundary.d.ts.map +1 -1
- package/dist/core/security/untrusted-boundary.js +4 -3
- package/dist/core/security/untrusted-boundary.js.map +1 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +3 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +9 -1
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +13 -2
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tasks/session-task-state.d.ts +10 -0
- package/dist/core/tasks/session-task-state.d.ts.map +1 -0
- package/dist/core/tasks/session-task-state.js +29 -0
- package/dist/core/tasks/session-task-state.js.map +1 -0
- package/dist/core/tasks/task-command.d.ts +30 -0
- package/dist/core/tasks/task-command.d.ts.map +1 -0
- package/dist/core/tasks/task-command.js +79 -0
- package/dist/core/tasks/task-command.js.map +1 -0
- package/dist/core/tasks/task-state.d.ts +71 -0
- package/dist/core/tasks/task-state.d.ts.map +1 -0
- package/dist/core/tasks/task-state.js +372 -0
- package/dist/core/tasks/task-state.js.map +1 -0
- package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -1
- package/dist/core/tool-selection/tool-selection-controller.js +1 -1
- package/dist/core/tool-selection/tool-selection-controller.js.map +1 -1
- package/dist/core/toolkit/script-runner.d.ts.map +1 -1
- package/dist/core/toolkit/script-runner.js +58 -24
- package/dist/core/toolkit/script-runner.js.map +1 -1
- package/dist/core/tools/bash.d.ts +20 -2
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +132 -220
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/extensionify.d.ts +2 -1
- package/dist/core/tools/extensionify.d.ts.map +1 -1
- package/dist/core/tools/extensionify.js +11 -8
- package/dist/core/tools/extensionify.js.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +57 -48
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/git-filter.d.ts.map +1 -1
- package/dist/core/tools/git-filter.js +20 -32
- package/dist/core/tools/git-filter.js.map +1 -1
- package/dist/core/tools/goal.d.ts +1 -1
- package/dist/core/tools/goal.d.ts.map +1 -1
- package/dist/core/tools/goal.js +10 -3
- package/dist/core/tools/goal.js.map +1 -1
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +92 -80
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/index.d.ts +9 -6
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +24 -9
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts +2 -0
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +7 -4
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/python.d.ts +64 -0
- package/dist/core/tools/python.d.ts.map +1 -0
- package/dist/core/tools/python.js +241 -0
- package/dist/core/tools/python.js.map +1 -0
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +4 -3
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/shell-contract-router.d.ts +13 -0
- package/dist/core/tools/shell-contract-router.d.ts.map +1 -0
- package/dist/core/tools/shell-contract-router.js +295 -0
- package/dist/core/tools/shell-contract-router.js.map +1 -0
- package/dist/core/tools/task-steps.d.ts +46 -0
- package/dist/core/tools/task-steps.d.ts.map +1 -0
- package/dist/core/tools/task-steps.js +160 -0
- package/dist/core/tools/task-steps.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- 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 +23 -4
- package/dist/main.js.map +1 -1
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +18 -4
- package/dist/migrations.js.map +1 -1
- package/dist/modes/interactive/auth-dialogs-controller.d.ts +10 -0
- package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -1
- package/dist/modes/interactive/auth-dialogs-controller.js +94 -27
- package/dist/modes/interactive/auth-dialogs-controller.js.map +1 -1
- package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
- package/dist/modes/interactive/auto-learn-controller.js +2 -1
- package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
- package/dist/modes/interactive/components/bordered-loader.d.ts +1 -0
- package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
- package/dist/modes/interactive/components/bordered-loader.js +8 -0
- package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
- package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-editor.js +6 -15
- package/dist/modes/interactive/components/extension-editor.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +3 -1
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +20 -8
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/profile-resource-editor.d.ts +4 -1
- package/dist/modes/interactive/components/profile-resource-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/profile-resource-editor.js +22 -39
- package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +1 -1
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/config-backup.d.ts +1 -0
- package/dist/modes/interactive/config-backup.d.ts.map +1 -1
- package/dist/modes/interactive/config-backup.js +14 -3
- package/dist/modes/interactive/config-backup.js.map +1 -1
- package/dist/modes/interactive/editor-overlay-host.d.ts +12 -0
- package/dist/modes/interactive/editor-overlay-host.d.ts.map +1 -1
- package/dist/modes/interactive/editor-overlay-host.js +55 -0
- package/dist/modes/interactive/editor-overlay-host.js.map +1 -1
- package/dist/modes/interactive/extension-ui-host.d.ts +2 -1
- package/dist/modes/interactive/extension-ui-host.d.ts.map +1 -1
- package/dist/modes/interactive/extension-ui-host.js +161 -96
- package/dist/modes/interactive/extension-ui-host.js.map +1 -1
- package/dist/modes/interactive/external-editor.d.ts.map +1 -1
- package/dist/modes/interactive/external-editor.js +23 -28
- package/dist/modes/interactive/external-editor.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +26 -8
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/profile-menu-controller.d.ts +5 -1
- package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -1
- package/dist/modes/interactive/profile-menu-controller.js +118 -24
- package/dist/modes/interactive/profile-menu-controller.js.map +1 -1
- package/dist/modes/interactive/resource-shell-commands.d.ts +1 -0
- package/dist/modes/interactive/resource-shell-commands.d.ts.map +1 -1
- package/dist/modes/interactive/resource-shell-commands.js +5 -1
- package/dist/modes/interactive/resource-shell-commands.js.map +1 -1
- package/dist/modes/interactive/session-flow-commands.d.ts +10 -0
- package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
- package/dist/modes/interactive/session-flow-commands.js +143 -7
- package/dist/modes/interactive/session-flow-commands.js.map +1 -1
- package/dist/modes/interactive/session-io-commands.d.ts.map +1 -1
- package/dist/modes/interactive/session-io-commands.js +80 -50
- package/dist/modes/interactive/session-io-commands.js.map +1 -1
- package/dist/modes/interactive/startup-checks.d.ts.map +1 -1
- package/dist/modes/interactive/startup-checks.js +14 -17
- package/dist/modes/interactive/startup-checks.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +20 -19
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +10 -19
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/child-process.d.ts +13 -7
- package/dist/utils/child-process.d.ts.map +1 -1
- package/dist/utils/child-process.js +56 -3
- package/dist/utils/child-process.js.map +1 -1
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +3 -2
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/clipboard.d.ts.map +1 -1
- package/dist/utils/clipboard.js +17 -10
- package/dist/utils/clipboard.js.map +1 -1
- package/dist/utils/external-editor-command.d.ts +8 -0
- package/dist/utils/external-editor-command.d.ts.map +1 -0
- package/dist/utils/external-editor-command.js +60 -0
- package/dist/utils/external-editor-command.js.map +1 -0
- package/dist/utils/paths.d.ts.map +1 -1
- package/dist/utils/paths.js +10 -2
- package/dist/utils/paths.js.map +1 -1
- package/dist/utils/shell.d.ts +6 -8
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +61 -70
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/tools-manager.d.ts +23 -3
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +117 -21
- package/dist/utils/tools-manager.js.map +1 -1
- package/dist/utils/work-directory.d.ts +36 -0
- package/dist/utils/work-directory.d.ts.map +1 -0
- package/dist/utils/work-directory.js +462 -0
- package/dist/utils/work-directory.js.map +1 -0
- package/docs/index.md +4 -0
- package/docs/python.md +43 -0
- package/docs/resources.md +2 -2
- package/docs/rpc.md +1 -1
- package/docs/settings.md +7 -3
- package/docs/task-steps.md +90 -0
- package/docs/termux.md +7 -0
- package/docs/tmux-agent-manager.md +48 -0
- package/docs/usage.md +5 -6
- package/docs/windows.md +104 -8
- package/docs/work-directory.md +41 -0
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +32 -37
- package/package.json +9 -7
- package/scripts/postinstall-python-runtime.mjs +20 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash-executor.d.ts","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;
|
|
1
|
+
{"version":3,"file":"bash-executor.d.ts","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAWH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAOtD,MAAM,WAAW,mBAAmB;IACnC,+DAA+D;IAC/D,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,mCAAmC;IACnC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,2FAA2F;IAC3F,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,wHAAwH;IACxH,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,UAAU;IAC1B,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,mDAAmD;IACnD,SAAS,EAAE,OAAO,CAAC;IACnB,uCAAuC;IACvC,SAAS,EAAE,OAAO,CAAC;IACnB,yFAAyF;IACzF,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAUD;;;GAGG;AACH,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,cAAc,EAC1B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,UAAU,CAAC,CAiKrB","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport type { WriteStream } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { sanitizeBinaryOutput } from \"@caupulican/pi-agent-core\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"@caupulican/pi-agent-core/node\";\nimport { getAgentDir } from \"../config.ts\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { createSafeWriteStream, endWriteStream } from \"../utils/safe-write-stream.ts\";\nimport { getProcessWorkRun } from \"../utils/work-directory.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./tools/git-filter.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\t/** Enable conservative pi-native git output filtering for local default execution paths */\n\tenableGitFilter?: boolean;\n\t/** Wall-clock timeout in seconds. Direct interactive/RPC callers provide the same bounded default as the agent tool. */\n\ttimeout?: number;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\nfunction getBashOutputPath(id: string): string {\n\treturn join(getProcessWorkRun(getAgentDir(), \"outputs\", \"bash\").path, `pi-bash-${id}.log`);\n}\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tif (options?.enableGitFilter) {\n\t\tconst classification = classifyGitCommand(command, process.env);\n\t\tif (classification.eligible && classification.subcommand) {\n\t\t\tconst res = await executeFilteredGit(\n\t\t\t\tcwd,\n\t\t\t\tclassification.subcommand,\n\t\t\t\tclassification.globalOptions || [],\n\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t{ signal: options.signal, timeout: options.timeout },\n\t\t\t);\n\t\t\tif (res.exitCode !== -100) {\n\t\t\t\tconst rawBytes = res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\");\n\t\t\t\t// The filter already spills oversized output to a temp file; reuse it\n\t\t\t\t// instead of materializing another full copy here.\n\t\t\t\tlet fullOutputPath = res.fullOutputPath;\n\t\t\t\tif (fullOutputPath === undefined && rawBytes.length > DEFAULT_MAX_BYTES) {\n\t\t\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\t\t\tconst spillPath = getBashOutputPath(id);\n\t\t\t\t\tfullOutputPath = spillPath;\n\t\t\t\t\t// On stream failure (e.g. disk full), drop the advertised path instead of\n\t\t\t\t\t// pointing at a partial/missing file.\n\t\t\t\t\tconst tempFileStream = createSafeWriteStream(spillPath, () => {\n\t\t\t\t\t\tfullOutputPath = undefined;\n\t\t\t\t\t});\n\t\t\t\t\ttempFileStream.write(rawBytes);\n\t\t\t\t\t// Await the flush so the returned path points at a COMPLETE file, not one mid-write.\n\t\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t\t}\n\t\t\t\toptions.onChunk?.(res.output);\n\t\t\t\treturn {\n\t\t\t\t\toutput: res.output,\n\t\t\t\t\texitCode: res.exitCode,\n\t\t\t\t\tcancelled: options.signal?.aborted ?? false,\n\t\t\t\t\ttruncated: res.fullOutputPath !== undefined || rawBytes.length > DEFAULT_MAX_BYTES,\n\t\t\t\t\tfullOutputPath,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = getBashOutputPath(id);\n\t\t// On stream failure (e.g. disk full), drop the artifact instead of\n\t\t// crashing the process; the rolling in-memory output is still returned.\n\t\ttempFileStream = createSafeWriteStream(tempFilePath, () => {\n\t\t\ttempFileStream = undefined;\n\t\t\ttempFilePath = undefined;\n\t\t});\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\t// Guard writableEnded: custom BashOperations may deliver late onData\n\t\t// callbacks after an abort path has already ended the stream.\n\t\tif (tempFileStream && !tempFileStream.writableEnded) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t\ttimeout: options?.timeout,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\t// Await the flush so fullOutputPath refers to a fully-written file on return, not one still\n\t\t\t// draining its buffer — otherwise a fast reader can see partial/empty content.\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\n\t\t// The silence watchdog (see tools/bash.ts) throws a raw `silence:<secs>` sentinel.\n\t\t// Map it to the same user-facing message the interactive bash tool shows, instead of\n\t\t// leaking the sentinel to callers of this path (interactive !cmd, RPC).\n\t\tif (err instanceof Error && err.message.startsWith(\"silence:\")) {\n\t\t\tconst secs = err.message.split(\":\")[1];\n\t\t\tthrow new Error(\n\t\t\t\t`Command killed after ${secs}s of silence (no output). If the command is legitimately quiet for long stretches, re-run it with an explicit timeout.`,\n\t\t\t);\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
|
|
@@ -6,16 +6,20 @@
|
|
|
6
6
|
* - Direct calls from modes that need bash execution
|
|
7
7
|
*/
|
|
8
8
|
import { randomBytes } from "node:crypto";
|
|
9
|
-
import { tmpdir } from "node:os";
|
|
10
9
|
import { join } from "node:path";
|
|
11
10
|
import { sanitizeBinaryOutput } from "@caupulican/pi-agent-core";
|
|
12
11
|
import { DEFAULT_MAX_BYTES, truncateTail } from "@caupulican/pi-agent-core/node";
|
|
12
|
+
import { getAgentDir } from "../config.js";
|
|
13
13
|
import { stripAnsi } from "../utils/ansi.js";
|
|
14
14
|
import { createSafeWriteStream, endWriteStream } from "../utils/safe-write-stream.js";
|
|
15
|
+
import { getProcessWorkRun } from "../utils/work-directory.js";
|
|
15
16
|
import { classifyGitCommand, executeFilteredGit } from "./tools/git-filter.js";
|
|
16
17
|
// ============================================================================
|
|
17
18
|
// Implementation
|
|
18
19
|
// ============================================================================
|
|
20
|
+
function getBashOutputPath(id) {
|
|
21
|
+
return join(getProcessWorkRun(getAgentDir(), "outputs", "bash").path, `pi-bash-${id}.log`);
|
|
22
|
+
}
|
|
19
23
|
/**
|
|
20
24
|
* Execute a bash command using custom BashOperations.
|
|
21
25
|
* Used for remote execution (SSH, containers, etc.).
|
|
@@ -24,7 +28,7 @@ export async function executeBashWithOperations(command, cwd, operations, option
|
|
|
24
28
|
if (options?.enableGitFilter) {
|
|
25
29
|
const classification = classifyGitCommand(command, process.env);
|
|
26
30
|
if (classification.eligible && classification.subcommand) {
|
|
27
|
-
const res = await executeFilteredGit(cwd, classification.subcommand, classification.globalOptions || [], classification.subcommandArgs || [], { signal: options.signal });
|
|
31
|
+
const res = await executeFilteredGit(cwd, classification.subcommand, classification.globalOptions || [], classification.subcommandArgs || [], { signal: options.signal, timeout: options.timeout });
|
|
28
32
|
if (res.exitCode !== -100) {
|
|
29
33
|
const rawBytes = res.rawBytes ?? Buffer.from(res.rawOut, "utf-8");
|
|
30
34
|
// The filter already spills oversized output to a temp file; reuse it
|
|
@@ -32,7 +36,7 @@ export async function executeBashWithOperations(command, cwd, operations, option
|
|
|
32
36
|
let fullOutputPath = res.fullOutputPath;
|
|
33
37
|
if (fullOutputPath === undefined && rawBytes.length > DEFAULT_MAX_BYTES) {
|
|
34
38
|
const id = randomBytes(8).toString("hex");
|
|
35
|
-
const spillPath =
|
|
39
|
+
const spillPath = getBashOutputPath(id);
|
|
36
40
|
fullOutputPath = spillPath;
|
|
37
41
|
// On stream failure (e.g. disk full), drop the advertised path instead of
|
|
38
42
|
// pointing at a partial/missing file.
|
|
@@ -65,7 +69,7 @@ export async function executeBashWithOperations(command, cwd, operations, option
|
|
|
65
69
|
return;
|
|
66
70
|
}
|
|
67
71
|
const id = randomBytes(8).toString("hex");
|
|
68
|
-
tempFilePath =
|
|
72
|
+
tempFilePath = getBashOutputPath(id);
|
|
69
73
|
// On stream failure (e.g. disk full), drop the artifact instead of
|
|
70
74
|
// crashing the process; the rolling in-memory output is still returned.
|
|
71
75
|
tempFileStream = createSafeWriteStream(tempFilePath, () => {
|
|
@@ -106,6 +110,7 @@ export async function executeBashWithOperations(command, cwd, operations, option
|
|
|
106
110
|
const result = await operations.exec(command, cwd, {
|
|
107
111
|
onData,
|
|
108
112
|
signal: options?.signal,
|
|
113
|
+
timeout: options?.timeout,
|
|
109
114
|
});
|
|
110
115
|
const fullOutput = outputChunks.join("");
|
|
111
116
|
const truncationResult = truncateTail(fullOutput);
|
|
@@ -153,7 +158,7 @@ export async function executeBashWithOperations(command, cwd, operations, option
|
|
|
153
158
|
// leaking the sentinel to callers of this path (interactive !cmd, RPC).
|
|
154
159
|
if (err instanceof Error && err.message.startsWith("silence:")) {
|
|
155
160
|
const secs = err.message.split(":")[1];
|
|
156
|
-
throw new Error(`Command killed after ${secs}s of silence (no output). If the command is legitimately quiet for long stretches, re-run it with an explicit timeout
|
|
161
|
+
throw new Error(`Command killed after ${secs}s of silence (no output). If the command is legitimately quiet for long stretches, re-run it with an explicit timeout.`);
|
|
157
162
|
}
|
|
158
163
|
throw err;
|
|
159
164
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash-executor.js","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAEtF,OAA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BAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU;gBAC1E,QAAQ,EAAE,SAAS;gBACnB,SAAS,EAAE,IAAI;gBACf,SAAS,EAAE,gBAAgB,CAAC,SAAS;gBACrC,cAAc,EAAE,YAAY;aAC5B,CAAC;QACH,CAAC;QAED,IAAI,cAAc,EAAE,CAAC;YACpB,MAAM,cAAc,CAAC,cAAc,CAAC,CAAC;QACtC,CAAC;QAED,mFAAmF;QACnF,qFAAqF;QACrF,wEAAwE;QACxE,IAAI,GAAG,YAAY,KAAK,IAAI,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;YAChE,MAAM,IAAI,GAAG,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YACvC,MAAM,IAAI,KAAK,CACd,wBAAwB,IAAI,8JAA8J,CAC1L,CAAC;QACH,CAAC;QAED,MAAM,GAAG,CAAC;IACX,CAAC;AAAA,CACD","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport type { WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { sanitizeBinaryOutput } from \"@caupulican/pi-agent-core\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"@caupulican/pi-agent-core/node\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { createSafeWriteStream, endWriteStream } from \"../utils/safe-write-stream.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./tools/git-filter.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\t/** Enable conservative pi-native git output filtering for local default execution paths */\n\tenableGitFilter?: boolean;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tif (options?.enableGitFilter) {\n\t\tconst classification = classifyGitCommand(command, process.env);\n\t\tif (classification.eligible && classification.subcommand) {\n\t\t\tconst res = await executeFilteredGit(\n\t\t\t\tcwd,\n\t\t\t\tclassification.subcommand,\n\t\t\t\tclassification.globalOptions || [],\n\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t{ signal: options.signal },\n\t\t\t);\n\t\t\tif (res.exitCode !== -100) {\n\t\t\t\tconst rawBytes = res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\");\n\t\t\t\t// The filter already spills oversized output to a temp file; reuse it\n\t\t\t\t// instead of materializing another full copy here.\n\t\t\t\tlet fullOutputPath = res.fullOutputPath;\n\t\t\t\tif (fullOutputPath === undefined && rawBytes.length > DEFAULT_MAX_BYTES) {\n\t\t\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\t\t\tconst spillPath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t\t\t\tfullOutputPath = spillPath;\n\t\t\t\t\t// On stream failure (e.g. disk full), drop the advertised path instead of\n\t\t\t\t\t// pointing at a partial/missing file.\n\t\t\t\t\tconst tempFileStream = createSafeWriteStream(spillPath, () => {\n\t\t\t\t\t\tfullOutputPath = undefined;\n\t\t\t\t\t});\n\t\t\t\t\ttempFileStream.write(rawBytes);\n\t\t\t\t\t// Await the flush so the returned path points at a COMPLETE file, not one mid-write.\n\t\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t\t}\n\t\t\t\toptions.onChunk?.(res.output);\n\t\t\t\treturn {\n\t\t\t\t\toutput: res.output,\n\t\t\t\t\texitCode: res.exitCode,\n\t\t\t\t\tcancelled: options.signal?.aborted ?? false,\n\t\t\t\t\ttruncated: res.fullOutputPath !== undefined || rawBytes.length > DEFAULT_MAX_BYTES,\n\t\t\t\t\tfullOutputPath,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t// On stream failure (e.g. disk full), drop the artifact instead of\n\t\t// crashing the process; the rolling in-memory output is still returned.\n\t\ttempFileStream = createSafeWriteStream(tempFilePath, () => {\n\t\t\ttempFileStream = undefined;\n\t\t\ttempFilePath = undefined;\n\t\t});\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\t// Guard writableEnded: custom BashOperations may deliver late onData\n\t\t// callbacks after an abort path has already ended the stream.\n\t\tif (tempFileStream && !tempFileStream.writableEnded) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\t// Await the flush so fullOutputPath refers to a fully-written file on return, not one still\n\t\t\t// draining its buffer — otherwise a fast reader can see partial/empty content.\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\n\t\t// The silence watchdog (see tools/bash.ts) throws a raw `silence:<secs>` sentinel.\n\t\t// Map it to the same user-facing message the interactive bash tool shows, instead of\n\t\t// leaking the sentinel to callers of this path (interactive !cmd, RPC).\n\t\tif (err instanceof Error && err.message.startsWith(\"silence:\")) {\n\t\t\tconst secs = err.message.split(\":\")[1];\n\t\t\tthrow new Error(\n\t\t\t\t`Command killed after ${secs}s of silence (no output). If the command is legitimately quiet for long stretches, re-run it with an explicit timeout, or run it in the background with '&'.`,\n\t\t\t);\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bash-executor.js","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AACtF,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAE/D,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AA8B/E,+EAA+E;AAC/E,iBAAiB;AACjB,+EAA+E;AAE/E,SAAS,iBAAiB,CAAC,EAAU,EAAU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,MAAM,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU;gBAC1E,QAAQ,EAAE,SAAS;gBACnB,SAAS,EAAE,IAAI;gBACf,SAAS,EAAE,gBAAgB,CAAC,SAAS;gBACrC,cAAc,EAAE,YAAY;aAC5B,CAAC;QACH,CAAC;QAED,IAAI,cAAc,EAAE,CAAC;YACpB,MAAM,cAAc,CAAC,cAAc,CAAC,CAAC;QACtC,CAAC;QAED,mFAAmF;QACnF,qFAAqF;QACrF,wEAAwE;QACxE,IAAI,GAAG,YAAY,KAAK,IAAI,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;YAChE,MAAM,IAAI,GAAG,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YACvC,MAAM,IAAI,KAAK,CACd,wBAAwB,IAAI,wHAAwH,CACpJ,CAAC;QACH,CAAC;QAED,MAAM,GAAG,CAAC;IACX,CAAC;AAAA,CACD","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport type { WriteStream } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { sanitizeBinaryOutput } from \"@caupulican/pi-agent-core\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"@caupulican/pi-agent-core/node\";\nimport { getAgentDir } from \"../config.ts\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { createSafeWriteStream, endWriteStream } from \"../utils/safe-write-stream.ts\";\nimport { getProcessWorkRun } from \"../utils/work-directory.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./tools/git-filter.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\t/** Enable conservative pi-native git output filtering for local default execution paths */\n\tenableGitFilter?: boolean;\n\t/** Wall-clock timeout in seconds. Direct interactive/RPC callers provide the same bounded default as the agent tool. */\n\ttimeout?: number;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\nfunction getBashOutputPath(id: string): string {\n\treturn join(getProcessWorkRun(getAgentDir(), \"outputs\", \"bash\").path, `pi-bash-${id}.log`);\n}\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tif (options?.enableGitFilter) {\n\t\tconst classification = classifyGitCommand(command, process.env);\n\t\tif (classification.eligible && classification.subcommand) {\n\t\t\tconst res = await executeFilteredGit(\n\t\t\t\tcwd,\n\t\t\t\tclassification.subcommand,\n\t\t\t\tclassification.globalOptions || [],\n\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t{ signal: options.signal, timeout: options.timeout },\n\t\t\t);\n\t\t\tif (res.exitCode !== -100) {\n\t\t\t\tconst rawBytes = res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\");\n\t\t\t\t// The filter already spills oversized output to a temp file; reuse it\n\t\t\t\t// instead of materializing another full copy here.\n\t\t\t\tlet fullOutputPath = res.fullOutputPath;\n\t\t\t\tif (fullOutputPath === undefined && rawBytes.length > DEFAULT_MAX_BYTES) {\n\t\t\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\t\t\tconst spillPath = getBashOutputPath(id);\n\t\t\t\t\tfullOutputPath = spillPath;\n\t\t\t\t\t// On stream failure (e.g. disk full), drop the advertised path instead of\n\t\t\t\t\t// pointing at a partial/missing file.\n\t\t\t\t\tconst tempFileStream = createSafeWriteStream(spillPath, () => {\n\t\t\t\t\t\tfullOutputPath = undefined;\n\t\t\t\t\t});\n\t\t\t\t\ttempFileStream.write(rawBytes);\n\t\t\t\t\t// Await the flush so the returned path points at a COMPLETE file, not one mid-write.\n\t\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t\t}\n\t\t\t\toptions.onChunk?.(res.output);\n\t\t\t\treturn {\n\t\t\t\t\toutput: res.output,\n\t\t\t\t\texitCode: res.exitCode,\n\t\t\t\t\tcancelled: options.signal?.aborted ?? false,\n\t\t\t\t\ttruncated: res.fullOutputPath !== undefined || rawBytes.length > DEFAULT_MAX_BYTES,\n\t\t\t\t\tfullOutputPath,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = getBashOutputPath(id);\n\t\t// On stream failure (e.g. disk full), drop the artifact instead of\n\t\t// crashing the process; the rolling in-memory output is still returned.\n\t\ttempFileStream = createSafeWriteStream(tempFilePath, () => {\n\t\t\ttempFileStream = undefined;\n\t\t\ttempFilePath = undefined;\n\t\t});\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\t// Guard writableEnded: custom BashOperations may deliver late onData\n\t\t// callbacks after an abort path has already ended the stream.\n\t\tif (tempFileStream && !tempFileStream.writableEnded) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t\ttimeout: options?.timeout,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\t// Await the flush so fullOutputPath refers to a fully-written file on return, not one still\n\t\t\t// draining its buffer — otherwise a fast reader can see partial/empty content.\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\n\t\t// The silence watchdog (see tools/bash.ts) throws a raw `silence:<secs>` sentinel.\n\t\t// Map it to the same user-facing message the interactive bash tool shows, instead of\n\t\t// leaking the sentinel to callers of this path (interactive !cmd, RPC).\n\t\tif (err instanceof Error && err.message.startsWith(\"silence:\")) {\n\t\t\tconst secs = err.message.split(\":\")[1];\n\t\t\tthrow new Error(\n\t\t\t\t`Command killed after ${secs}s of silence (no output). If the command is legitimately quiet for long stretches, re-run it with an explicit timeout.`,\n\t\t\t);\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
|
|
@@ -5,8 +5,11 @@ export interface ContextStoreRetentionOptions {
|
|
|
5
5
|
now?: number;
|
|
6
6
|
}
|
|
7
7
|
export interface ContextStoreRetentionLease {
|
|
8
|
+
readonly gcDir: string;
|
|
9
|
+
readonly artifactsDir: string;
|
|
8
10
|
release(): void;
|
|
9
11
|
}
|
|
10
|
-
export declare function
|
|
12
|
+
export declare function pruneContextStores(agentDir: string, tenant: "gc" | "artifacts", options?: ContextStoreRetentionOptions): string[];
|
|
13
|
+
export declare function getContextStoreDir(agentDir: string, tenant: "gc" | "artifacts", sessionId: string): string;
|
|
11
14
|
export declare function acquireContextStoreRetention(agentDir: string, sessionId: string, options?: ContextStoreRetentionOptions): ContextStoreRetentionLease;
|
|
12
15
|
//# sourceMappingURL=context-store-retention.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-store-retention.d.ts","sourceRoot":"","sources":["../../../src/core/context/context-store-retention.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"context-store-retention.d.ts","sourceRoot":"","sources":["../../../src/core/context/context-store-retention.ts"],"names":[],"mappings":"AAYA,MAAM,WAAW,4BAA4B;IAC5C,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,GAAG,CAAC,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,0BAA0B;IAC1C,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,OAAO,IAAI,IAAI,CAAC;CAChB;AAWD,wBAAgB,kBAAkB,CACjC,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,IAAI,GAAG,WAAW,EAC1B,OAAO,GAAE,4BAAiC,GACxC,MAAM,EAAE,CAEV;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,GAAG,WAAW,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAE1G;AAED,wBAAgB,4BAA4B,CAC3C,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,OAAO,GAAE,4BAAiC,GACxC,0BAA0B,CA4B5B","sourcesContent":["import {\n\tacquireWorkRun,\n\tgetWorkRunDir,\n\tpruneWorkTenant,\n\ttype WorkRetentionOptions,\n\ttype WorkRunLease,\n} from \"../../utils/work-directory.ts\";\n\nconst DEFAULT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;\nconst DEFAULT_MAX_SESSION_DIRS = 64;\nconst DEFAULT_MAX_TOTAL_BYTES = 512 * 1024 * 1024;\n\nexport interface ContextStoreRetentionOptions {\n\tmaxAgeMs?: number;\n\tmaxSessionDirs?: number;\n\tmaxTotalBytes?: number;\n\tnow?: number;\n}\n\nexport interface ContextStoreRetentionLease {\n\treadonly gcDir: string;\n\treadonly artifactsDir: string;\n\trelease(): void;\n}\n\nfunction toWorkRetention(options: ContextStoreRetentionOptions): WorkRetentionOptions {\n\treturn {\n\t\tmaxAgeMs: options.maxAgeMs ?? DEFAULT_MAX_AGE_MS,\n\t\tmaxRuns: options.maxSessionDirs ?? DEFAULT_MAX_SESSION_DIRS,\n\t\tmaxTotalBytes: options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,\n\t\tnow: options.now,\n\t};\n}\n\nexport function pruneContextStores(\n\tagentDir: string,\n\ttenant: \"gc\" | \"artifacts\",\n\toptions: ContextStoreRetentionOptions = {},\n): string[] {\n\treturn pruneWorkTenant(agentDir, \"context\", tenant, toWorkRetention(options));\n}\n\nexport function getContextStoreDir(agentDir: string, tenant: \"gc\" | \"artifacts\", sessionId: string): string {\n\treturn getWorkRunDir(agentDir, \"context\", tenant, sessionId);\n}\n\nexport function acquireContextStoreRetention(\n\tagentDir: string,\n\tsessionId: string,\n\toptions: ContextStoreRetentionOptions = {},\n): ContextStoreRetentionLease {\n\tconst retention = toWorkRetention(options);\n\tconst leases: WorkRunLease[] = [];\n\ttry {\n\t\tconst gc = acquireWorkRun({ agentDir, category: \"context\", tenant: \"gc\", runId: sessionId, retention });\n\t\tleases.push(gc);\n\t\tconst artifacts = acquireWorkRun({\n\t\t\tagentDir,\n\t\t\tcategory: \"context\",\n\t\t\ttenant: \"artifacts\",\n\t\t\trunId: sessionId,\n\t\t\tretention,\n\t\t});\n\t\tleases.push(artifacts);\n\t\tlet released = false;\n\t\treturn {\n\t\t\tgcDir: gc.path,\n\t\t\tartifactsDir: artifacts.path,\n\t\t\trelease(): void {\n\t\t\t\tif (released) return;\n\t\t\t\treleased = true;\n\t\t\t\tfor (const lease of leases) lease.release();\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tfor (const lease of leases) lease.release();\n\t\tthrow error;\n\t}\n}\n"]}
|
|
@@ -1,161 +1,52 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
3
|
-
import { dirname, join } from "node:path";
|
|
4
|
-
const LEASES_DIRECTORY = ".leases";
|
|
5
|
-
const ACTIVE_MARKER_PREFIX = "active-";
|
|
6
|
-
const ACTIVE_MARKER_SUFFIX = ".json";
|
|
1
|
+
import { acquireWorkRun, getWorkRunDir, pruneWorkTenant, } from "../../utils/work-directory.js";
|
|
7
2
|
const DEFAULT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
|
|
8
3
|
const DEFAULT_MAX_SESSION_DIRS = 64;
|
|
9
4
|
const DEFAULT_MAX_TOTAL_BYTES = 512 * 1024 * 1024;
|
|
10
|
-
function
|
|
11
|
-
return
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
try {
|
|
18
|
-
if (entry.isDirectory())
|
|
19
|
-
total += directoryBytes(child);
|
|
20
|
-
else
|
|
21
|
-
total += lstatSync(child).size;
|
|
22
|
-
}
|
|
23
|
-
catch {
|
|
24
|
-
// Concurrent cleanup or an unreadable entry is ignored by best-effort retention.
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
return total;
|
|
28
|
-
}
|
|
29
|
-
function markerProcessIsAlive(path) {
|
|
30
|
-
try {
|
|
31
|
-
const parsed = JSON.parse(readFileSync(path, "utf-8"));
|
|
32
|
-
if (typeof parsed.pid !== "number" || !Number.isSafeInteger(parsed.pid) || parsed.pid <= 0)
|
|
33
|
-
return false;
|
|
34
|
-
try {
|
|
35
|
-
process.kill(parsed.pid, 0);
|
|
36
|
-
return true;
|
|
37
|
-
}
|
|
38
|
-
catch (error) {
|
|
39
|
-
return error.code === "EPERM";
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
catch {
|
|
43
|
-
return false;
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
function cleanupStaleLeases(rootDir) {
|
|
47
|
-
const leasesRoot = join(rootDir, LEASES_DIRECTORY);
|
|
48
|
-
if (!existsSync(leasesRoot))
|
|
49
|
-
return;
|
|
50
|
-
for (const entry of readdirSync(leasesRoot, { withFileTypes: true })) {
|
|
51
|
-
if (!entry.isDirectory())
|
|
52
|
-
continue;
|
|
53
|
-
const leaseDir = join(leasesRoot, entry.name);
|
|
54
|
-
try {
|
|
55
|
-
for (const marker of readdirSync(leaseDir)) {
|
|
56
|
-
const markerPath = join(leaseDir, marker);
|
|
57
|
-
if (!markerProcessIsAlive(markerPath))
|
|
58
|
-
unlinkSync(markerPath);
|
|
59
|
-
}
|
|
60
|
-
rmdirSync(leaseDir);
|
|
61
|
-
}
|
|
62
|
-
catch {
|
|
63
|
-
// A live marker or concurrent lease keeps the directory in place.
|
|
64
|
-
}
|
|
65
|
-
}
|
|
5
|
+
function toWorkRetention(options) {
|
|
6
|
+
return {
|
|
7
|
+
maxAgeMs: options.maxAgeMs ?? DEFAULT_MAX_AGE_MS,
|
|
8
|
+
maxRuns: options.maxSessionDirs ?? DEFAULT_MAX_SESSION_DIRS,
|
|
9
|
+
maxTotalBytes: options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,
|
|
10
|
+
now: options.now,
|
|
11
|
+
};
|
|
66
12
|
}
|
|
67
|
-
function
|
|
68
|
-
|
|
69
|
-
return [];
|
|
70
|
-
cleanupStaleLeases(rootDir);
|
|
71
|
-
const directories = [];
|
|
72
|
-
for (const entry of readdirSync(rootDir, { withFileTypes: true })) {
|
|
73
|
-
if (!entry.isDirectory() || entry.name === LEASES_DIRECTORY)
|
|
74
|
-
continue;
|
|
75
|
-
const path = join(rootDir, entry.name);
|
|
76
|
-
try {
|
|
77
|
-
const leaseDir = join(rootDir, LEASES_DIRECTORY, entry.name);
|
|
78
|
-
const markerPaths = existsSync(leaseDir)
|
|
79
|
-
? readdirSync(leaseDir)
|
|
80
|
-
.filter((name) => name.startsWith(ACTIVE_MARKER_PREFIX) && name.endsWith(ACTIVE_MARKER_SUFFIX))
|
|
81
|
-
.map((name) => join(leaseDir, name))
|
|
82
|
-
: [];
|
|
83
|
-
directories.push({
|
|
84
|
-
path,
|
|
85
|
-
mtimeMs: Math.max(statSync(path).mtimeMs, ...markerPaths.map((markerPath) => statSync(markerPath).mtimeMs)),
|
|
86
|
-
bytes: directoryBytes(path),
|
|
87
|
-
active: markerPaths.some(markerProcessIsAlive),
|
|
88
|
-
});
|
|
89
|
-
}
|
|
90
|
-
catch {
|
|
91
|
-
// Ignore a directory that disappeared or became unreadable during the scan.
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
return directories;
|
|
13
|
+
export function pruneContextStores(agentDir, tenant, options = {}) {
|
|
14
|
+
return pruneWorkTenant(agentDir, "context", tenant, toWorkRetention(options));
|
|
95
15
|
}
|
|
96
|
-
export function
|
|
97
|
-
|
|
98
|
-
const maxAgeMs = positiveLimit(options.maxAgeMs, DEFAULT_MAX_AGE_MS);
|
|
99
|
-
const maxSessionDirs = positiveLimit(options.maxSessionDirs, DEFAULT_MAX_SESSION_DIRS);
|
|
100
|
-
const maxTotalBytes = positiveLimit(options.maxTotalBytes, DEFAULT_MAX_TOTAL_BYTES);
|
|
101
|
-
const directories = inspectSessionDirectories(rootDir);
|
|
102
|
-
const removed = [];
|
|
103
|
-
let retainedCount = directories.length;
|
|
104
|
-
let retainedBytes = directories.reduce((sum, directory) => sum + directory.bytes, 0);
|
|
105
|
-
for (const directory of directories.sort((left, right) => left.mtimeMs - right.mtimeMs)) {
|
|
106
|
-
if (directory.active)
|
|
107
|
-
continue;
|
|
108
|
-
const expired = now - directory.mtimeMs > maxAgeMs;
|
|
109
|
-
const overCount = retainedCount > maxSessionDirs;
|
|
110
|
-
const overBytes = retainedBytes > maxTotalBytes;
|
|
111
|
-
if (!expired && !overCount && !overBytes)
|
|
112
|
-
continue;
|
|
113
|
-
try {
|
|
114
|
-
rmSync(directory.path, { recursive: true, force: true });
|
|
115
|
-
removed.push(directory.path);
|
|
116
|
-
retainedCount--;
|
|
117
|
-
retainedBytes -= directory.bytes;
|
|
118
|
-
}
|
|
119
|
-
catch {
|
|
120
|
-
// Retention is best-effort and must never block a live session.
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
return removed;
|
|
16
|
+
export function getContextStoreDir(agentDir, tenant, sessionId) {
|
|
17
|
+
return getWorkRunDir(agentDir, "context", tenant, sessionId);
|
|
124
18
|
}
|
|
125
19
|
export function acquireContextStoreRetention(agentDir, sessionId, options = {}) {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
const
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
20
|
+
const retention = toWorkRetention(options);
|
|
21
|
+
const leases = [];
|
|
22
|
+
try {
|
|
23
|
+
const gc = acquireWorkRun({ agentDir, category: "context", tenant: "gc", runId: sessionId, retention });
|
|
24
|
+
leases.push(gc);
|
|
25
|
+
const artifacts = acquireWorkRun({
|
|
26
|
+
agentDir,
|
|
27
|
+
category: "context",
|
|
28
|
+
tenant: "artifacts",
|
|
29
|
+
runId: sessionId,
|
|
30
|
+
retention,
|
|
31
|
+
});
|
|
32
|
+
leases.push(artifacts);
|
|
33
|
+
let released = false;
|
|
34
|
+
return {
|
|
35
|
+
gcDir: gc.path,
|
|
36
|
+
artifactsDir: artifacts.path,
|
|
37
|
+
release() {
|
|
38
|
+
if (released)
|
|
39
|
+
return;
|
|
40
|
+
released = true;
|
|
41
|
+
for (const lease of leases)
|
|
42
|
+
lease.release();
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
for (const lease of leases)
|
|
48
|
+
lease.release();
|
|
49
|
+
throw error;
|
|
144
50
|
}
|
|
145
|
-
let released = false;
|
|
146
|
-
return {
|
|
147
|
-
release() {
|
|
148
|
-
if (released)
|
|
149
|
-
return;
|
|
150
|
-
released = true;
|
|
151
|
-
for (const markerPath of markerPaths) {
|
|
152
|
-
try {
|
|
153
|
-
unlinkSync(markerPath);
|
|
154
|
-
rmdirSync(dirname(markerPath));
|
|
155
|
-
}
|
|
156
|
-
catch { }
|
|
157
|
-
}
|
|
158
|
-
},
|
|
159
|
-
};
|
|
160
51
|
}
|
|
161
52
|
//# sourceMappingURL=context-store-retention.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-store-retention.js","sourceRoot":"","sources":["../../../src/core/context/context-store-retention.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACN,UAAU,EACV,SAAS,EACT,SAAS,EACT,WAAW,EACX,YAAY,EACZ,SAAS,EACT,MAAM,EACN,QAAQ,EACR,UAAU,EACV,aAAa,GACb,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAE1C,MAAM,gBAAgB,GAAG,SAAS,CAAC;AACnC,MAAM,oBAAoB,GAAG,SAAS,CAAC;AACvC,MAAM,oBAAoB,GAAG,OAAO,CAAC;AACrC,MAAM,kBAAkB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AACpD,MAAM,wBAAwB,GAAG,EAAE,CAAC;AACpC,MAAM,uBAAuB,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,CAAC;AAoBlD,SAAS,aAAa,CAAC,KAAyB,EAAE,QAAgB,EAAU;IAC3E,OAAO,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,QAAQ,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QACN,OAAO,GAAS;YACf,IAAI,QAAQ;gBAAE,OAAO;YACrB,QAAQ,GAAG,IAAI,CAAC;YAChB,KAAK,MAAM,UAAU,IAAI,WAAW,EAAE,CAAC;gBACtC,IAAI,CAAC;oBACJ,UAAU,CAAC,UAAU,CAAC,CAAC;oBACvB,SAAS,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;gBAChC,CAAC;gBAAC,MAAM,CAAC,CAAA,CAAC;YACX,CAAC;QAAA,CACD;KACD,CAAC;AAAA,CACF","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n\texistsSync,\n\tlstatSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trmdirSync,\n\trmSync,\n\tstatSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nconst LEASES_DIRECTORY = \".leases\";\nconst ACTIVE_MARKER_PREFIX = \"active-\";\nconst ACTIVE_MARKER_SUFFIX = \".json\";\nconst DEFAULT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;\nconst DEFAULT_MAX_SESSION_DIRS = 64;\nconst DEFAULT_MAX_TOTAL_BYTES = 512 * 1024 * 1024;\n\nexport interface ContextStoreRetentionOptions {\n\tmaxAgeMs?: number;\n\tmaxSessionDirs?: number;\n\tmaxTotalBytes?: number;\n\tnow?: number;\n}\n\nexport interface ContextStoreRetentionLease {\n\trelease(): void;\n}\n\ninterface SessionDirectory {\n\tpath: string;\n\tmtimeMs: number;\n\tbytes: number;\n\tactive: boolean;\n}\n\nfunction positiveLimit(value: number | undefined, fallback: number): number {\n\treturn value !== undefined && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;\n}\n\nfunction directoryBytes(path: string): number {\n\tlet total = 0;\n\tfor (const entry of readdirSync(path, { withFileTypes: true })) {\n\t\tconst child = join(path, entry.name);\n\t\ttry {\n\t\t\tif (entry.isDirectory()) total += directoryBytes(child);\n\t\t\telse total += lstatSync(child).size;\n\t\t} catch {\n\t\t\t// Concurrent cleanup or an unreadable entry is ignored by best-effort retention.\n\t\t}\n\t}\n\treturn total;\n}\n\nfunction markerProcessIsAlive(path: string): boolean {\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(path, \"utf-8\")) as { pid?: unknown };\n\t\tif (typeof parsed.pid !== \"number\" || !Number.isSafeInteger(parsed.pid) || parsed.pid <= 0) return false;\n\t\ttry {\n\t\t\tprocess.kill(parsed.pid, 0);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\treturn (error as NodeJS.ErrnoException).code === \"EPERM\";\n\t\t}\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction cleanupStaleLeases(rootDir: string): void {\n\tconst leasesRoot = join(rootDir, LEASES_DIRECTORY);\n\tif (!existsSync(leasesRoot)) return;\n\tfor (const entry of readdirSync(leasesRoot, { withFileTypes: true })) {\n\t\tif (!entry.isDirectory()) continue;\n\t\tconst leaseDir = join(leasesRoot, entry.name);\n\t\ttry {\n\t\t\tfor (const marker of readdirSync(leaseDir)) {\n\t\t\t\tconst markerPath = join(leaseDir, marker);\n\t\t\t\tif (!markerProcessIsAlive(markerPath)) unlinkSync(markerPath);\n\t\t\t}\n\t\t\trmdirSync(leaseDir);\n\t\t} catch {\n\t\t\t// A live marker or concurrent lease keeps the directory in place.\n\t\t}\n\t}\n}\n\nfunction inspectSessionDirectories(rootDir: string): SessionDirectory[] {\n\tif (!existsSync(rootDir)) return [];\n\tcleanupStaleLeases(rootDir);\n\tconst directories: SessionDirectory[] = [];\n\tfor (const entry of readdirSync(rootDir, { withFileTypes: true })) {\n\t\tif (!entry.isDirectory() || entry.name === LEASES_DIRECTORY) continue;\n\t\tconst path = join(rootDir, entry.name);\n\t\ttry {\n\t\t\tconst leaseDir = join(rootDir, LEASES_DIRECTORY, entry.name);\n\t\t\tconst markerPaths = existsSync(leaseDir)\n\t\t\t\t? readdirSync(leaseDir)\n\t\t\t\t\t\t.filter((name) => name.startsWith(ACTIVE_MARKER_PREFIX) && name.endsWith(ACTIVE_MARKER_SUFFIX))\n\t\t\t\t\t\t.map((name) => join(leaseDir, name))\n\t\t\t\t: [];\n\t\t\tdirectories.push({\n\t\t\t\tpath,\n\t\t\t\tmtimeMs: Math.max(statSync(path).mtimeMs, ...markerPaths.map((markerPath) => statSync(markerPath).mtimeMs)),\n\t\t\t\tbytes: directoryBytes(path),\n\t\t\t\tactive: markerPaths.some(markerProcessIsAlive),\n\t\t\t});\n\t\t} catch {\n\t\t\t// Ignore a directory that disappeared or became unreadable during the scan.\n\t\t}\n\t}\n\treturn directories;\n}\n\nexport function pruneContextStoreRoot(rootDir: string, options: ContextStoreRetentionOptions = {}): string[] {\n\tconst now = options.now ?? Date.now();\n\tconst maxAgeMs = positiveLimit(options.maxAgeMs, DEFAULT_MAX_AGE_MS);\n\tconst maxSessionDirs = positiveLimit(options.maxSessionDirs, DEFAULT_MAX_SESSION_DIRS);\n\tconst maxTotalBytes = positiveLimit(options.maxTotalBytes, DEFAULT_MAX_TOTAL_BYTES);\n\tconst directories = inspectSessionDirectories(rootDir);\n\tconst removed: string[] = [];\n\tlet retainedCount = directories.length;\n\tlet retainedBytes = directories.reduce((sum, directory) => sum + directory.bytes, 0);\n\tfor (const directory of directories.sort((left, right) => left.mtimeMs - right.mtimeMs)) {\n\t\tif (directory.active) continue;\n\t\tconst expired = now - directory.mtimeMs > maxAgeMs;\n\t\tconst overCount = retainedCount > maxSessionDirs;\n\t\tconst overBytes = retainedBytes > maxTotalBytes;\n\t\tif (!expired && !overCount && !overBytes) continue;\n\t\ttry {\n\t\t\trmSync(directory.path, { recursive: true, force: true });\n\t\t\tremoved.push(directory.path);\n\t\t\tretainedCount--;\n\t\t\tretainedBytes -= directory.bytes;\n\t\t} catch {\n\t\t\t// Retention is best-effort and must never block a live session.\n\t\t}\n\t}\n\treturn removed;\n}\n\nexport function acquireContextStoreRetention(\n\tagentDir: string,\n\tsessionId: string,\n\toptions: ContextStoreRetentionOptions = {},\n): ContextStoreRetentionLease {\n\tif (!/^[A-Za-z0-9_-]+$/.test(sessionId)) return { release: () => {} };\n\tconst roots = [join(agentDir, \"context-gc\"), join(agentDir, \"context-artifacts\")];\n\tconst markerPaths: string[] = [];\n\tfor (const root of roots) {\n\t\tconst sessionDir = join(root, sessionId);\n\t\ttry {\n\t\t\tmkdirSync(sessionDir, { recursive: true });\n\t\t\tconst leaseDir = join(root, LEASES_DIRECTORY, sessionId);\n\t\t\tmkdirSync(leaseDir, { recursive: true });\n\t\t\tconst markerPath = join(\n\t\t\t\tleaseDir,\n\t\t\t\t`${ACTIVE_MARKER_PREFIX}${process.pid}-${randomUUID()}${ACTIVE_MARKER_SUFFIX}`,\n\t\t\t);\n\t\t\twriteFileSync(markerPath, JSON.stringify({ pid: process.pid, touchedAt: Date.now() }), \"utf-8\");\n\t\t\tmarkerPaths.push(markerPath);\n\t\t\tpruneContextStoreRoot(root, options);\n\t\t} catch {\n\t\t\t// Retention is best-effort; the caller can still use its normal store path.\n\t\t}\n\t}\n\tlet released = false;\n\treturn {\n\t\trelease(): void {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tfor (const markerPath of markerPaths) {\n\t\t\t\ttry {\n\t\t\t\t\tunlinkSync(markerPath);\n\t\t\t\t\trmdirSync(dirname(markerPath));\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t},\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"context-store-retention.js","sourceRoot":"","sources":["../../../src/core/context/context-store-retention.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,cAAc,EACd,aAAa,EACb,eAAe,GAGf,MAAM,+BAA+B,CAAC;AAEvC,MAAM,kBAAkB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AACpD,MAAM,wBAAwB,GAAG,EAAE,CAAC;AACpC,MAAM,uBAAuB,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,CAAC;AAelD,SAAS,eAAe,CAAC,OAAqC,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AO;YACN,KAAK,EAAE,EAAE,CAAC,IAAI;YACd,YAAY,EAAE,SAAS,CAAC,IAAI;YAC5B,OAAO,GAAS;gBACf,IAAI,QAAQ;oBAAE,OAAO;gBACrB,QAAQ,GAAG,IAAI,CAAC;gBAChB,KAAK,MAAM,KAAK,IAAI,MAAM;oBAAE,KAAK,CAAC,OAAO,EAAE,CAAC;YAAA,CAC5C;SACD,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,KAAK,MAAM,KAAK,IAAI,MAAM;YAAE,KAAK,CAAC,OAAO,EAAE,CAAC;QAC5C,MAAM,KAAK,CAAC;IACb,CAAC;AAAA,CACD","sourcesContent":["import {\n\tacquireWorkRun,\n\tgetWorkRunDir,\n\tpruneWorkTenant,\n\ttype WorkRetentionOptions,\n\ttype WorkRunLease,\n} from \"../../utils/work-directory.ts\";\n\nconst DEFAULT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;\nconst DEFAULT_MAX_SESSION_DIRS = 64;\nconst DEFAULT_MAX_TOTAL_BYTES = 512 * 1024 * 1024;\n\nexport interface ContextStoreRetentionOptions {\n\tmaxAgeMs?: number;\n\tmaxSessionDirs?: number;\n\tmaxTotalBytes?: number;\n\tnow?: number;\n}\n\nexport interface ContextStoreRetentionLease {\n\treadonly gcDir: string;\n\treadonly artifactsDir: string;\n\trelease(): void;\n}\n\nfunction toWorkRetention(options: ContextStoreRetentionOptions): WorkRetentionOptions {\n\treturn {\n\t\tmaxAgeMs: options.maxAgeMs ?? DEFAULT_MAX_AGE_MS,\n\t\tmaxRuns: options.maxSessionDirs ?? DEFAULT_MAX_SESSION_DIRS,\n\t\tmaxTotalBytes: options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,\n\t\tnow: options.now,\n\t};\n}\n\nexport function pruneContextStores(\n\tagentDir: string,\n\ttenant: \"gc\" | \"artifacts\",\n\toptions: ContextStoreRetentionOptions = {},\n): string[] {\n\treturn pruneWorkTenant(agentDir, \"context\", tenant, toWorkRetention(options));\n}\n\nexport function getContextStoreDir(agentDir: string, tenant: \"gc\" | \"artifacts\", sessionId: string): string {\n\treturn getWorkRunDir(agentDir, \"context\", tenant, sessionId);\n}\n\nexport function acquireContextStoreRetention(\n\tagentDir: string,\n\tsessionId: string,\n\toptions: ContextStoreRetentionOptions = {},\n): ContextStoreRetentionLease {\n\tconst retention = toWorkRetention(options);\n\tconst leases: WorkRunLease[] = [];\n\ttry {\n\t\tconst gc = acquireWorkRun({ agentDir, category: \"context\", tenant: \"gc\", runId: sessionId, retention });\n\t\tleases.push(gc);\n\t\tconst artifacts = acquireWorkRun({\n\t\t\tagentDir,\n\t\t\tcategory: \"context\",\n\t\t\ttenant: \"artifacts\",\n\t\t\trunId: sessionId,\n\t\t\tretention,\n\t\t});\n\t\tleases.push(artifacts);\n\t\tlet released = false;\n\t\treturn {\n\t\t\tgcDir: gc.path,\n\t\t\tartifactsDir: artifacts.path,\n\t\t\trelease(): void {\n\t\t\t\tif (released) return;\n\t\t\t\treleased = true;\n\t\t\t\tfor (const lease of leases) lease.release();\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tfor (const lease of leases) lease.release();\n\t\tthrow error;\n\t}\n}\n"]}
|