@code-yeongyu/senpi 2026.8.29 → 2026.8.30-2
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 +122 -0
- package/dist/core/agent-session.d.ts +45 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +329 -29
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +155 -37
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/compaction/compaction-execution.d.ts +14 -0
- package/dist/core/compaction/compaction-execution.d.ts.map +1 -0
- package/dist/core/compaction/compaction-execution.js +121 -0
- package/dist/core/compaction/compaction-execution.js.map +1 -0
- package/dist/core/compaction/compaction-settings.d.ts +17 -0
- package/dist/core/compaction/compaction-settings.d.ts.map +1 -0
- package/dist/core/compaction/compaction-settings.js +17 -0
- package/dist/core/compaction/compaction-settings.js.map +1 -0
- package/dist/core/compaction/compaction.d.ts +13 -26
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +7 -136
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/compaction/ideal-compaction-settings.d.ts +9 -0
- package/dist/core/compaction/ideal-compaction-settings.d.ts.map +1 -0
- package/dist/core/compaction/ideal-compaction-settings.js +7 -0
- package/dist/core/compaction/ideal-compaction-settings.js.map +1 -0
- package/dist/core/compaction-settings-access.d.ts +19 -0
- package/dist/core/compaction-settings-access.d.ts.map +1 -0
- package/dist/core/compaction-settings-access.js +10 -0
- package/dist/core/compaction-settings-access.js.map +1 -0
- package/dist/core/compaction-settings-resolver.d.ts +22 -0
- package/dist/core/compaction-settings-resolver.d.ts.map +1 -0
- package/dist/core/compaction-settings-resolver.js +46 -0
- package/dist/core/compaction-settings-resolver.js.map +1 -0
- package/dist/core/credential-accounts.d.ts.map +1 -1
- package/dist/core/credential-accounts.js +23 -9
- package/dist/core/credential-accounts.js.map +1 -1
- package/dist/core/credential-pool/env-slots.d.ts.map +1 -1
- package/dist/core/credential-pool/env-slots.js +2 -0
- package/dist/core/credential-pool/env-slots.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/context-pipeline.d.ts +17 -0
- package/dist/core/extensions/builtin/compaction/context-pipeline.d.ts.map +1 -0
- package/dist/core/extensions/builtin/compaction/context-pipeline.js +28 -0
- package/dist/core/extensions/builtin/compaction/context-pipeline.js.map +1 -0
- package/dist/core/extensions/builtin/compaction/deterministic-fallback.d.ts +8 -2
- package/dist/core/extensions/builtin/compaction/deterministic-fallback.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/deterministic-fallback.js +163 -48
- package/dist/core/extensions/builtin/compaction/deterministic-fallback.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/emergency-prune.d.ts +17 -0
- package/dist/core/extensions/builtin/compaction/emergency-prune.d.ts.map +1 -0
- package/dist/core/extensions/builtin/compaction/emergency-prune.js +64 -0
- package/dist/core/extensions/builtin/compaction/emergency-prune.js.map +1 -0
- package/dist/core/extensions/builtin/compaction/extension-wiring.d.ts +27 -0
- package/dist/core/extensions/builtin/compaction/extension-wiring.d.ts.map +1 -0
- package/dist/core/extensions/builtin/compaction/extension-wiring.js +84 -0
- package/dist/core/extensions/builtin/compaction/extension-wiring.js.map +1 -0
- package/dist/core/extensions/builtin/compaction/idle.d.ts +1 -0
- package/dist/core/extensions/builtin/compaction/idle.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/idle.js +13 -2
- package/dist/core/extensions/builtin/compaction/idle.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/index.d.ts +1 -1
- package/dist/core/extensions/builtin/compaction/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/index.js +121 -147
- package/dist/core/extensions/builtin/compaction/index.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/log.d.ts +1 -1
- package/dist/core/extensions/builtin/compaction/log.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/log.js +2 -0
- package/dist/core/extensions/builtin/compaction/log.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/model-selection.d.ts +14 -0
- package/dist/core/extensions/builtin/compaction/model-selection.d.ts.map +1 -0
- package/dist/core/extensions/builtin/compaction/model-selection.js +37 -0
- package/dist/core/extensions/builtin/compaction/model-selection.js.map +1 -0
- package/dist/core/extensions/builtin/compaction/openai-remote-dependencies.d.ts +9 -0
- package/dist/core/extensions/builtin/compaction/openai-remote-dependencies.d.ts.map +1 -0
- package/dist/core/extensions/builtin/compaction/openai-remote-dependencies.js +2 -0
- package/dist/core/extensions/builtin/compaction/openai-remote-dependencies.js.map +1 -0
- package/dist/core/extensions/builtin/compaction/openai-remote.d.ts +3 -6
- package/dist/core/extensions/builtin/compaction/openai-remote.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/openai-remote.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/orchestration.d.ts +56 -0
- package/dist/core/extensions/builtin/compaction/orchestration.d.ts.map +1 -0
- package/dist/core/extensions/builtin/compaction/orchestration.js +136 -0
- package/dist/core/extensions/builtin/compaction/orchestration.js.map +1 -0
- package/dist/core/extensions/builtin/compaction/policy.d.ts +5 -2
- package/dist/core/extensions/builtin/compaction/policy.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/policy.js +43 -26
- package/dist/core/extensions/builtin/compaction/policy.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/retained-message-safety.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/retained-message-safety.js +31 -8
- package/dist/core/extensions/builtin/compaction/retained-message-safety.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/speculation-lead.d.ts +8 -0
- package/dist/core/extensions/builtin/compaction/speculation-lead.d.ts.map +1 -0
- package/dist/core/extensions/builtin/compaction/speculation-lead.js +17 -0
- package/dist/core/extensions/builtin/compaction/speculation-lead.js.map +1 -0
- package/dist/core/extensions/builtin/compaction/speculative-job.d.ts +22 -0
- package/dist/core/extensions/builtin/compaction/speculative-job.d.ts.map +1 -0
- package/dist/core/extensions/builtin/compaction/speculative-job.js +16 -0
- package/dist/core/extensions/builtin/compaction/speculative-job.js.map +1 -0
- package/dist/core/extensions/builtin/compaction/speculative-summary.d.ts +22 -0
- package/dist/core/extensions/builtin/compaction/speculative-summary.d.ts.map +1 -0
- package/dist/core/extensions/builtin/compaction/speculative-summary.js +131 -0
- package/dist/core/extensions/builtin/compaction/speculative-summary.js.map +1 -0
- package/dist/core/extensions/builtin/compaction/speculative.d.ts +8 -13
- package/dist/core/extensions/builtin/compaction/speculative.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/speculative.js +7 -196
- package/dist/core/extensions/builtin/compaction/speculative.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/token-budget-reminder.d.ts +18 -0
- package/dist/core/extensions/builtin/compaction/token-budget-reminder.d.ts.map +1 -0
- package/dist/core/extensions/builtin/compaction/token-budget-reminder.js +18 -0
- package/dist/core/extensions/builtin/compaction/token-budget-reminder.js.map +1 -0
- package/dist/core/extensions/builtin/compaction/tool-admission.d.ts +36 -0
- package/dist/core/extensions/builtin/compaction/tool-admission.d.ts.map +1 -0
- package/dist/core/extensions/builtin/compaction/tool-admission.js +92 -0
- package/dist/core/extensions/builtin/compaction/tool-admission.js.map +1 -0
- package/dist/core/extensions/builtin/cursor-cli-oauth/stream.d.ts.map +1 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/stream.js +8 -28
- package/dist/core/extensions/builtin/cursor-cli-oauth/stream.js.map +1 -1
- package/dist/core/extensions/builtin/permission-system/external-dir.d.ts.map +1 -1
- package/dist/core/extensions/builtin/permission-system/external-dir.js +15 -5
- package/dist/core/extensions/builtin/permission-system/external-dir.js.map +1 -1
- package/dist/core/extensions/builtin/permission-system/parsers.d.ts.map +1 -1
- package/dist/core/extensions/builtin/permission-system/parsers.js +16 -1
- package/dist/core/extensions/builtin/permission-system/parsers.js.map +1 -1
- package/dist/core/extensions/builtin/terminal/manager.d.ts +5 -0
- package/dist/core/extensions/builtin/terminal/manager.d.ts.map +1 -1
- package/dist/core/extensions/builtin/terminal/manager.js +31 -3
- package/dist/core/extensions/builtin/terminal/manager.js.map +1 -1
- package/dist/core/extensions/builtin/terminal/monitor-permission.d.ts +8 -0
- package/dist/core/extensions/builtin/terminal/monitor-permission.d.ts.map +1 -0
- package/dist/core/extensions/builtin/terminal/monitor-permission.js +16 -0
- package/dist/core/extensions/builtin/terminal/monitor-permission.js.map +1 -0
- package/dist/core/extensions/builtin/terminal/monitor-registry.d.ts +13 -0
- package/dist/core/extensions/builtin/terminal/monitor-registry.d.ts.map +1 -1
- package/dist/core/extensions/builtin/terminal/monitor-registry.js +403 -3
- package/dist/core/extensions/builtin/terminal/monitor-registry.js.map +1 -1
- package/dist/core/extensions/builtin/terminal/session-bundle.d.ts.map +1 -1
- package/dist/core/extensions/builtin/terminal/session-bundle.js +1 -0
- package/dist/core/extensions/builtin/terminal/session-bundle.js.map +1 -1
- package/dist/core/extensions/builtin/terminal/tools/kill-bash.d.ts.map +1 -1
- package/dist/core/extensions/builtin/terminal/tools/kill-bash.js +5 -2
- package/dist/core/extensions/builtin/terminal/tools/kill-bash.js.map +1 -1
- package/dist/core/extensions/builtin/terminal/tools/monitor.d.ts +4 -0
- package/dist/core/extensions/builtin/terminal/tools/monitor.d.ts.map +1 -1
- package/dist/core/extensions/builtin/terminal/tools/monitor.js +40 -2
- package/dist/core/extensions/builtin/terminal/tools/monitor.js.map +1 -1
- package/dist/core/model-resolver.js +2 -2
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +10 -1
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +15 -85
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +15 -17
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-public-types.d.ts +11 -0
- package/dist/core/settings-public-types.d.ts.map +1 -0
- package/dist/core/settings-public-types.js +2 -0
- package/dist/core/settings-public-types.js.map +1 -0
- package/dist/core/settings-shapes.d.ts +36 -0
- package/dist/core/settings-shapes.d.ts.map +1 -0
- package/dist/core/settings-shapes.js +2 -0
- package/dist/core/settings-shapes.js.map +1 -0
- package/dist/core/shared-host-policy.d.ts +6 -0
- package/dist/core/shared-host-policy.d.ts.map +1 -0
- package/dist/core/shared-host-policy.js +7 -0
- package/dist/core/shared-host-policy.js.map +1 -0
- package/dist/core/terminal-settings.d.ts +22 -0
- package/dist/core/terminal-settings.d.ts.map +1 -0
- package/dist/core/terminal-settings.js +2 -0
- package/dist/core/terminal-settings.js.map +1 -0
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +97 -15
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/index.d.ts +1 -0
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +8 -0
- package/dist/core/tools/index.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 +76 -34
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +17 -5
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts +7 -0
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +34 -8
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/grok/chrome.d.ts +2 -0
- package/dist/modes/interactive/grok/chrome.d.ts.map +1 -1
- package/dist/modes/interactive/grok/chrome.js.map +1 -1
- package/dist/modes/interactive/interactive-host-runtime.d.ts +121 -1
- package/dist/modes/interactive/interactive-host-runtime.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-host-runtime.js +336 -65
- package/dist/modes/interactive/interactive-host-runtime.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +7 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +114 -2
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/connection-handler.d.ts +8 -1
- package/dist/modes/rpc/connection-handler.d.ts.map +1 -1
- package/dist/modes/rpc/connection-handler.js +145 -49
- package/dist/modes/rpc/connection-handler.js.map +1 -1
- package/dist/modes/rpc/host-ensure.d.ts +19 -0
- package/dist/modes/rpc/host-ensure.d.ts.map +1 -1
- package/dist/modes/rpc/host-ensure.js +79 -15
- package/dist/modes/rpc/host-ensure.js.map +1 -1
- package/dist/modes/rpc/host-lifecycle.d.ts +29 -0
- package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -1
- package/dist/modes/rpc/host-lifecycle.js +96 -25
- package/dist/modes/rpc/host-lifecycle.js.map +1 -1
- package/dist/modes/rpc/host-watchdog.d.ts +2 -0
- package/dist/modes/rpc/host-watchdog.d.ts.map +1 -1
- package/dist/modes/rpc/host-watchdog.js +23 -12
- package/dist/modes/rpc/host-watchdog.js.map +1 -1
- package/dist/modes/rpc/multi-session-host.js +6 -4
- package/dist/modes/rpc/multi-session-host.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +10 -4
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +47 -10
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-input-validation.d.ts +1 -0
- package/dist/modes/rpc/rpc-input-validation.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-input-validation.js +66 -0
- package/dist/modes/rpc/rpc-input-validation.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +86 -1
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/modes/rpc/session-binding.d.ts +1 -0
- package/dist/modes/rpc/session-binding.d.ts.map +1 -1
- package/dist/modes/rpc/session-binding.js +21 -1
- package/dist/modes/rpc/session-binding.js.map +1 -1
- package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
- package/dist/modes/rpc/session-command-router.js +1 -0
- package/dist/modes/rpc/session-command-router.js.map +1 -1
- package/dist/modes/rpc/session-event-writer.d.ts +2 -0
- package/dist/modes/rpc/session-event-writer.d.ts.map +1 -1
- package/dist/modes/rpc/session-event-writer.js +54 -7
- package/dist/modes/rpc/session-event-writer.js.map +1 -1
- package/dist/modes/rpc/session-extension-ui-requests.d.ts +1 -0
- package/dist/modes/rpc/session-extension-ui-requests.d.ts.map +1 -1
- package/dist/modes/rpc/session-extension-ui-requests.js +5 -0
- package/dist/modes/rpc/session-extension-ui-requests.js.map +1 -1
- package/dist/modes/rpc/session-registry.d.ts +10 -2
- package/dist/modes/rpc/session-registry.d.ts.map +1 -1
- package/dist/modes/rpc/session-registry.js +58 -4
- package/dist/modes/rpc/session-registry.js.map +1 -1
- package/dist/modes/rpc/socket-event-fanout.d.ts +22 -0
- package/dist/modes/rpc/socket-event-fanout.d.ts.map +1 -0
- package/dist/modes/rpc/socket-event-fanout.js +84 -0
- package/dist/modes/rpc/socket-event-fanout.js.map +1 -0
- package/docs/rpc.md +18 -2
- package/docs/settings.md +34 -0
- package/docs/windows.md +2 -0
- package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +50 -0
- package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-indirect-eval.js +139 -90
- package/node_modules/@code-yeongyu/senpi-codemode/src/prompt/eval-prompt.ts +4 -4
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/env/nodejs.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/env/nodejs.js +40 -20
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/env/nodejs.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/types.d.ts +3 -3
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/types.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/types.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/shell-output.d.ts +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/shell-output.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/shell-output.js +28 -9
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/shell-output.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +67 -38
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent/measure.d.ts +20 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent/measure.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent/measure.js +443 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent/measure.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.d.ts +2 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.js +2 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/index.d.ts +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/index.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/index.js +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/index.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai-coding-cn.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai.json +1 -1
- package/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/node_modules/@earendil-works/pi-pty/package.json +1 -1
- package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/components/editor.d.ts +7 -0
- package/node_modules/@earendil-works/pi-tui/dist/components/editor.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/components/editor.js +5 -0
- package/node_modules/@earendil-works/pi-tui/dist/components/editor.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/mux.d.ts +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/mux.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/mux.js +2 -2
- package/node_modules/@earendil-works/pi-tui/dist/mux.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts +1 -0
- package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/terminal.js +19 -0
- package/node_modules/@earendil-works/pi-tui/dist/terminal.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/package.json +7 -7
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
2
3
|
import { mkdir, open, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
4
|
import { createConnection } from "node:net";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
4
6
|
import { dirname, join, resolve } from "node:path";
|
|
5
7
|
import { fileURLToPath } from "node:url";
|
|
6
8
|
import * as properLockfile from "proper-lockfile";
|
|
7
|
-
import { ENV_AGENT_DIR, getAgentDir, VERSION } from "../../config.js";
|
|
9
|
+
import { ENV_AGENT_DIR, getAgentDir, isBunBinary, VERSION } from "../../config.js";
|
|
8
10
|
import { parseDaemonPidFile, processMatchesPidFile, waitForStartTime, } from "../app-server/daemon/process.js";
|
|
9
11
|
import { CUSTOM_UNSUPPORTED_CAPABILITY, EXTENSION_EVENTS_CAPABILITY, RPC_CLIENT_CAPABILITIES_ENV, } from "./custom-capability.js";
|
|
10
|
-
import { DEFAULT_HOST_IDLE_EXIT_MS } from "./host-lifecycle.js";
|
|
12
|
+
import { DEFAULT_HOST_IDLE_EXIT_MS, INTERNAL_SUPERVISOR_FLAG, } from "./host-lifecycle.js";
|
|
11
13
|
const lockOptions = { stale: 60_000, retries: { retries: 100, minTimeout: 20, maxTimeout: 100 } };
|
|
12
14
|
const REQUIRED_CAPABILITIES = ["multi_session", EXTENSION_EVENTS_CAPABILITY];
|
|
13
15
|
/**
|
|
@@ -30,8 +32,14 @@ export async function ensureHost(options) {
|
|
|
30
32
|
const socket = normalizeSocketPath(options.socket);
|
|
31
33
|
const paths = createHostDaemonPaths(options.agentDir);
|
|
32
34
|
await mkdir(paths.dir, { recursive: true });
|
|
33
|
-
|
|
35
|
+
// The public socket is the shared resource; agent directories are not a
|
|
36
|
+
// sufficient lock scope when two installations target the same endpoint.
|
|
37
|
+
const lockTarget = join(tmpdir(), "senpi-rpc-host-locks", createSocketLockName(socket));
|
|
38
|
+
await mkdir(dirname(lockTarget), { recursive: true });
|
|
39
|
+
await writeFile(lockTarget, "", { flag: "a", mode: 0o600 });
|
|
40
|
+
const release = await properLockfile.lock(lockTarget, { ...lockOptions, lockfilePath: `${lockTarget}.lock` });
|
|
34
41
|
try {
|
|
42
|
+
await options._test?.afterLockAcquired?.();
|
|
35
43
|
return await ensureHostLocked(paths, socket, options.agentDir ?? getAgentDir(), options.policy, options._test);
|
|
36
44
|
}
|
|
37
45
|
finally {
|
|
@@ -67,9 +75,12 @@ async function startHost(paths, socket, agentDir, policy, testOptions) {
|
|
|
67
75
|
})}\n`, { mode: 0o600 });
|
|
68
76
|
const stderr = await open(paths.stderrLog, "w", 0o600);
|
|
69
77
|
let pidFile;
|
|
78
|
+
let child;
|
|
79
|
+
let exitedEarly;
|
|
80
|
+
let childExit;
|
|
70
81
|
try {
|
|
71
82
|
const launch = testOptions?.spawn ?? defaultHostLaunch(socket, testOptions?.hostArgs ?? []);
|
|
72
|
-
|
|
83
|
+
child = spawn(launch.command, [...launch.args], {
|
|
73
84
|
detached: true,
|
|
74
85
|
env: {
|
|
75
86
|
...process.env,
|
|
@@ -79,23 +90,49 @@ async function startHost(paths, socket, agentDir, policy, testOptions) {
|
|
|
79
90
|
},
|
|
80
91
|
stdio: ["ignore", "ignore", stderr.fd],
|
|
81
92
|
});
|
|
93
|
+
childExit = new Promise((resolveExit) => {
|
|
94
|
+
child.once("exit", (code, signal) => {
|
|
95
|
+
exitedEarly = { code, signal };
|
|
96
|
+
resolveExit(exitedEarly);
|
|
97
|
+
});
|
|
98
|
+
});
|
|
82
99
|
child.unref();
|
|
83
100
|
if (child.pid === undefined)
|
|
84
101
|
throw new Error("failed to spawn RPC socket host");
|
|
85
|
-
|
|
102
|
+
const processStartTime = await Promise.race([
|
|
103
|
+
waitForStartTime(child.pid, 2_000),
|
|
104
|
+
childExit.then(() => {
|
|
105
|
+
throw new Error("RPC socket host exited before its start time could be read");
|
|
106
|
+
}),
|
|
107
|
+
]);
|
|
108
|
+
pidFile = { pid: child.pid, processStartTime };
|
|
86
109
|
await writeFile(paths.pidFile, `${JSON.stringify(pidFile)}\n`, { mode: 0o600 });
|
|
87
110
|
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
if (!exitedEarly)
|
|
113
|
+
throw error;
|
|
114
|
+
const diagnostic = await appendStderr(paths, `RPC socket host exited with code ${exitedEarly.code ?? "null"}${exitedEarly.signal ? ` (${exitedEarly.signal})` : ""} before answering get_protocol_info`);
|
|
115
|
+
await cleanupState(paths);
|
|
116
|
+
throw new Error(diagnostic);
|
|
117
|
+
}
|
|
88
118
|
finally {
|
|
89
119
|
await stderr.close();
|
|
90
120
|
}
|
|
91
121
|
const readinessTimeoutMs = testOptions?.readinessTimeoutMs ?? 10_000;
|
|
92
|
-
const
|
|
93
|
-
if (isCompatible(protocol))
|
|
122
|
+
const result = await pollProtocolInfo(socket, readinessTimeoutMs, childExit);
|
|
123
|
+
if (isCompatible(result.protocol))
|
|
94
124
|
return { pid: pidFile.pid, socket, reused: false };
|
|
95
125
|
await stopManagedHost(pidFile, testOptions?.stopTimeoutMs ?? 10_000);
|
|
96
|
-
const
|
|
126
|
+
const message = result.protocol
|
|
127
|
+
? `RPC socket host answered get_protocol_info with serverVersion ${result.protocol.serverVersion} and capabilities ${JSON.stringify(result.protocol.capabilities)}, but is incompatible with serverVersion ${VERSION} and required capabilities ${JSON.stringify(REQUIRED_CAPABILITIES)}`
|
|
128
|
+
: result.exited
|
|
129
|
+
? `RPC socket host exited with code ${result.exited.code ?? "null"}${result.exited.signal ? ` (${result.exited.signal})` : ""} before answering get_protocol_info`
|
|
130
|
+
: `spawned RPC socket host did not answer get_protocol_info within ${readinessTimeoutMs}ms`;
|
|
131
|
+
const diagnostic = await appendStderr(paths, message);
|
|
97
132
|
await cleanupState(paths);
|
|
98
|
-
|
|
133
|
+
// The supervisor may have failed before binding, or another owner may have
|
|
134
|
+
// appeared while readiness was being checked. Never unlink an endpoint we
|
|
135
|
+
// cannot prove this start owned.
|
|
99
136
|
throw new Error(diagnostic);
|
|
100
137
|
}
|
|
101
138
|
async function stopManagedHost(pidFile, termTimeoutMs) {
|
|
@@ -127,15 +164,25 @@ async function waitForGone(pidFile, timeoutMs) {
|
|
|
127
164
|
}
|
|
128
165
|
return false;
|
|
129
166
|
}
|
|
130
|
-
async function pollProtocolInfo(socket, timeoutMs) {
|
|
167
|
+
async function pollProtocolInfo(socket, timeoutMs, childExit) {
|
|
131
168
|
const deadline = Date.now() + timeoutMs;
|
|
169
|
+
let lastProtocol;
|
|
132
170
|
while (Date.now() <= deadline) {
|
|
133
|
-
const
|
|
134
|
-
|
|
135
|
-
|
|
171
|
+
const probe = probeProtocolInfo(socket, Math.min(500, Math.max(1, deadline - Date.now())));
|
|
172
|
+
const info = childExit ? await Promise.race([probe, childExit]) : await probe;
|
|
173
|
+
if (isChildExit(info))
|
|
174
|
+
return { protocol: lastProtocol, exited: info };
|
|
175
|
+
if (info) {
|
|
176
|
+
lastProtocol = info;
|
|
177
|
+
if (isCompatible(info))
|
|
178
|
+
return { protocol: info };
|
|
179
|
+
}
|
|
136
180
|
await delay(50);
|
|
137
181
|
}
|
|
138
|
-
return
|
|
182
|
+
return { protocol: lastProtocol };
|
|
183
|
+
}
|
|
184
|
+
function isChildExit(value) {
|
|
185
|
+
return !!value && "code" in value && "signal" in value;
|
|
139
186
|
}
|
|
140
187
|
function probeProtocolInfo(socketPath, timeoutMs) {
|
|
141
188
|
return new Promise((resolveProbe) => {
|
|
@@ -212,6 +259,9 @@ async function appendStderr(paths, message) {
|
|
|
212
259
|
throw error;
|
|
213
260
|
}
|
|
214
261
|
}
|
|
262
|
+
function createSocketLockName(socket) {
|
|
263
|
+
return createHash("sha256").update(socket).digest("hex").slice(0, 32);
|
|
264
|
+
}
|
|
215
265
|
function normalizeSocketPath(value) {
|
|
216
266
|
if (value.startsWith("unix://"))
|
|
217
267
|
return value.slice("unix://".length);
|
|
@@ -221,8 +271,22 @@ function normalizeSocketPath(value) {
|
|
|
221
271
|
* Default launch: the host-lifecycle supervisor owns the public socket and the
|
|
222
272
|
* idle-exit policy; it spawns the committed RPC socket host itself. Any extra
|
|
223
273
|
* hostArgs are forwarded verbatim to the host CLI (e.g. provider pinning).
|
|
274
|
+
*
|
|
275
|
+
* A compiled standalone binary cannot re-enter itself through a script path:
|
|
276
|
+
* bun executables always boot their embedded entrypoint and parse the whole
|
|
277
|
+
* argv as CLI arguments, so `host-lifecycle.ts --socket <path>` dies with
|
|
278
|
+
* "Unknown option: --socket" before the host ever answers get_protocol_info.
|
|
279
|
+
* Compiled binaries therefore re-enter through the hidden
|
|
280
|
+
* `--internal-rpc-host-supervisor` route that main() dispatches before
|
|
281
|
+
* argument parsing. Exported for tests.
|
|
224
282
|
*/
|
|
225
|
-
function defaultHostLaunch(socket, hostArgs) {
|
|
283
|
+
export function defaultHostLaunch(socket, hostArgs, compiled = isBunBinary) {
|
|
284
|
+
if (compiled) {
|
|
285
|
+
return {
|
|
286
|
+
command: process.execPath,
|
|
287
|
+
args: [INTERNAL_SUPERVISOR_FLAG, "--socket", socket, ...hostArgs],
|
|
288
|
+
};
|
|
289
|
+
}
|
|
226
290
|
return {
|
|
227
291
|
command: process.execPath,
|
|
228
292
|
args: [...process.execArgv, resolveHostLifecycleEntryPath(), "--socket", socket, ...hostArgs],
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host-ensure.js","sourceRoot":"","sources":["../../../src/modes/rpc/host-ensure.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,KAAK,cAAc,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,WAAW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;;;;GAIG;AACH,SAAS,iBAAiB,CACzB,MAAc,EACd,QAA2B;IAK3B,OAAO;QACN,OAAO,EAAE,OAAO,CAAC,QAAQ;QACzB,IAAI,EAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,EAAE,6BAA6B,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,GAAG,QAAQ,CAAC;KAC7F,CAAC;AACH,CAAC;AAED,SAAS,6BAA6B;IACrC,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAClD,MAAM,SAAS,GAAG,UAAU,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC;IAC7D,OAAO,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,iBAAiB,SAAS,EAAE,CAAC,CAAC;AACnE,CAAC;AAED,SAAS,KAAK,CAAC,EAAU;IACxB,OAAO,IAAI,OAAO,CAAC,CAAC,YAAY,EAAE,EAAE,CAAC,UAAU,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC,CAAC;AACpE,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAED,SAAS,eAAe,CAAC,KAAc,EAAE,IAAY;IACpD,OAAO,KAAK,YAAY,KAAK,IAAI,MAAM,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC;AACzE,CAAC","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { mkdir, open, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { createConnection } from \"node:net\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport * as properLockfile from \"proper-lockfile\";\nimport { ENV_AGENT_DIR, getAgentDir, VERSION } from \"../../config.ts\";\nimport {\n\ttype DaemonPidFile,\n\tparseDaemonPidFile,\n\tprocessMatchesPidFile,\n\twaitForStartTime,\n} from \"../app-server/daemon/process.ts\";\nimport {\n\tCUSTOM_UNSUPPORTED_CAPABILITY,\n\tEXTENSION_EVENTS_CAPABILITY,\n\tRPC_CLIENT_CAPABILITIES_ENV,\n} from \"./custom-capability.ts\";\nimport { DEFAULT_HOST_IDLE_EXIT_MS, type HostColdStart, type HostLifecyclePolicyInput } from \"./host-lifecycle.ts\";\n\nexport type { HostColdStart, HostLifecyclePolicyInput };\n\nexport interface HostDaemonPaths {\n\treadonly dir: string;\n\treadonly pidFile: string;\n\treadonly lockFile: string;\n\treadonly settingsFile: string;\n\treadonly stderrLog: string;\n}\n\nexport interface EnsureHostOptions {\n\treadonly socket: string;\n\treadonly agentDir?: string;\n\t/** Host lifecycle policy recorded in settings.json (env overrides win at runtime). */\n\treadonly policy?: HostLifecyclePolicyInput;\n\treadonly _test?: {\n\t\treadonly readinessTimeoutMs?: number;\n\t\treadonly stopTimeoutMs?: number;\n\t\treadonly spawn?: { readonly command: string; readonly args: readonly string[] };\n\t\t/** Extra env merged over process.env for the spawned host (hermetic test/QA wiring). */\n\t\treadonly env?: Readonly<Record<string, string>>;\n\t\t/** Extra CLI args forwarded through the supervisor to the host process. */\n\t\treadonly hostArgs?: readonly string[];\n\t};\n}\n\nexport interface EnsuredHost {\n\treadonly pid: number;\n\treadonly socket: string;\n\treadonly reused: boolean;\n}\n\ntype ProtocolInfo = {\n\treadonly serverVersion: string;\n\treadonly capabilities: readonly string[];\n};\n\nconst lockOptions = { stale: 60_000, retries: { retries: 100, minTimeout: 20, maxTimeout: 100 } } as const;\nconst REQUIRED_CAPABILITIES = [\"multi_session\", EXTENSION_EVENTS_CAPABILITY] as const;\n/**\n * Every ensured host starts with this installation-wide profile, independent of\n * the first caller. In particular, extension_events must remain available when\n * a terminal client starts the shared host before the desktop connects.\n */\nexport const PINNED_HOST_CLIENT_CAPABILITIES = [EXTENSION_EVENTS_CAPABILITY, CUSTOM_UNSUPPORTED_CAPABILITY] as const;\n\nexport function createHostDaemonPaths(agentDir = getAgentDir()): HostDaemonPaths {\n\tconst dir = join(agentDir, \"rpc-host-daemon\");\n\treturn {\n\t\tdir,\n\t\tpidFile: join(dir, \"host.pid\"),\n\t\tlockFile: join(dir, \"daemon.lock\"),\n\t\tsettingsFile: join(dir, \"settings.json\"),\n\t\tstderrLog: join(dir, \"stderr.log\"),\n\t};\n}\n\nexport async function ensureHost(options: EnsureHostOptions): Promise<EnsuredHost> {\n\tconst socket = normalizeSocketPath(options.socket);\n\tconst paths = createHostDaemonPaths(options.agentDir);\n\tawait mkdir(paths.dir, { recursive: true });\n\tconst release = await properLockfile.lock(paths.dir, { ...lockOptions, lockfilePath: paths.lockFile });\n\ttry {\n\t\treturn await ensureHostLocked(paths, socket, options.agentDir ?? getAgentDir(), options.policy, options._test);\n\t} finally {\n\t\tawait release();\n\t}\n}\n\nasync function ensureHostLocked(\n\tpaths: HostDaemonPaths,\n\tsocket: string,\n\tagentDir: string,\n\tpolicy: HostLifecyclePolicyInput | undefined,\n\ttestOptions: EnsureHostOptions[\"_test\"],\n): Promise<EnsuredHost> {\n\tconst pidFile = await readPidFile(paths);\n\tconst protocol = await probeProtocolInfo(socket, 1_000);\n\tconst pidMatches = pidFile ? await processMatchesPidFile(pidFile) : false;\n\tif (isCompatible(protocol)) {\n\t\t// A compatible socket is attachable even when another client surface\n\t\t// started it. Only hosts we spawned are eligible for lifecycle management.\n\t\treturn { pid: pidFile?.pid ?? 0, socket, reused: true };\n\t}\n\tif (protocol && !pidMatches) {\n\t\tthrow new Error(`RPC socket ${socket} is owned by an unmanaged host`);\n\t}\n\tif (pidFile && pidMatches) {\n\t\tawait stopManagedHost(pidFile, testOptions?.stopTimeoutMs ?? 10_000);\n\t}\n\tawait cleanupState(paths);\n\treturn startHost(paths, socket, agentDir, policy, testOptions);\n}\n\nasync function startHost(\n\tpaths: HostDaemonPaths,\n\tsocket: string,\n\tagentDir: string,\n\tpolicy: HostLifecyclePolicyInput | undefined,\n\ttestOptions: EnsureHostOptions[\"_test\"],\n): Promise<EnsuredHost> {\n\t// The settings file must exist before the supervisor reads it at boot, so it\n\t// records the policy before the spawn instead of beside the pidfile.\n\tawait writeFile(\n\t\tpaths.settingsFile,\n\t\t`${JSON.stringify({\n\t\t\tsocket,\n\t\t\tcapabilities: PINNED_HOST_CLIENT_CAPABILITIES,\n\t\t\tcoldStart: policy?.coldStart ?? \"transient\",\n\t\t\tidleExitMs: policy?.idleExitMs ?? DEFAULT_HOST_IDLE_EXIT_MS,\n\t\t})}\\n`,\n\t\t{ mode: 0o600 },\n\t);\n\tconst stderr = await open(paths.stderrLog, \"w\", 0o600);\n\tlet pidFile: DaemonPidFile | undefined;\n\ttry {\n\t\tconst launch = testOptions?.spawn ?? defaultHostLaunch(socket, testOptions?.hostArgs ?? []);\n\t\tconst child = spawn(launch.command, [...launch.args], {\n\t\t\tdetached: true,\n\t\t\tenv: {\n\t\t\t\t...process.env,\n\t\t\t\t...(testOptions?.env ?? {}),\n\t\t\t\t[ENV_AGENT_DIR]: agentDir,\n\t\t\t\t[RPC_CLIENT_CAPABILITIES_ENV]: PINNED_HOST_CLIENT_CAPABILITIES.join(\",\"),\n\t\t\t},\n\t\t\tstdio: [\"ignore\", \"ignore\", stderr.fd],\n\t\t});\n\t\tchild.unref();\n\t\tif (child.pid === undefined) throw new Error(\"failed to spawn RPC socket host\");\n\t\tpidFile = { pid: child.pid, processStartTime: await waitForStartTime(child.pid, 2_000) };\n\t\tawait writeFile(paths.pidFile, `${JSON.stringify(pidFile)}\\n`, { mode: 0o600 });\n\t} finally {\n\t\tawait stderr.close();\n\t}\n\tconst readinessTimeoutMs = testOptions?.readinessTimeoutMs ?? 10_000;\n\tconst protocol = await pollProtocolInfo(socket, readinessTimeoutMs);\n\tif (isCompatible(protocol)) return { pid: pidFile.pid, socket, reused: false };\n\tawait stopManagedHost(pidFile, testOptions?.stopTimeoutMs ?? 10_000);\n\tconst diagnostic = await appendStderr(\n\t\tpaths,\n\t\t`spawned RPC socket host did not answer get_protocol_info within ${readinessTimeoutMs}ms`,\n\t);\n\tawait cleanupState(paths);\n\tawait rm(socket, { force: true });\n\tthrow new Error(diagnostic);\n}\n\nasync function stopManagedHost(pidFile: DaemonPidFile, termTimeoutMs: number): Promise<void> {\n\tawait signalValidated(pidFile, \"SIGTERM\");\n\tif (await waitForGone(pidFile, termTimeoutMs)) return;\n\tawait signalValidated(pidFile, \"SIGKILL\");\n\tif (!(await waitForGone(pidFile, 2_000))) {\n\t\tthrow new Error(`RPC socket host pid ${pidFile.pid} remained alive after SIGKILL`);\n\t}\n}\n\nasync function signalValidated(pidFile: DaemonPidFile, signal: NodeJS.Signals): Promise<void> {\n\tif (!(await processMatchesPidFile(pidFile))) return;\n\ttry {\n\t\tprocess.kill(pidFile.pid, signal);\n\t} catch (error: unknown) {\n\t\tif (!isNodeErrorCode(error, \"ESRCH\")) throw error;\n\t}\n}\n\nasync function waitForGone(pidFile: DaemonPidFile, timeoutMs: number): Promise<boolean> {\n\tconst deadline = Date.now() + timeoutMs;\n\twhile (Date.now() <= deadline) {\n\t\tif (!(await processMatchesPidFile(pidFile))) return true;\n\t\tawait delay(50);\n\t}\n\treturn false;\n}\n\nasync function pollProtocolInfo(socket: string, timeoutMs: number): Promise<ProtocolInfo | undefined> {\n\tconst deadline = Date.now() + timeoutMs;\n\twhile (Date.now() <= deadline) {\n\t\tconst info = await probeProtocolInfo(socket, Math.min(500, Math.max(1, deadline - Date.now())));\n\t\tif (info) return info;\n\t\tawait delay(50);\n\t}\n\treturn undefined;\n}\n\nfunction probeProtocolInfo(socketPath: string, timeoutMs: number): Promise<ProtocolInfo | undefined> {\n\treturn new Promise((resolveProbe) => {\n\t\tconst socket = createConnection(socketPath);\n\t\tlet buffer = \"\";\n\t\tlet settled = false;\n\t\tconst finish = (value?: ProtocolInfo): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tclearTimeout(timeout);\n\t\t\tsocket.destroy();\n\t\t\tresolveProbe(value);\n\t\t};\n\t\tconst timeout = setTimeout(() => finish(), timeoutMs);\n\t\tsocket.once(\"connect\", () => {\n\t\t\tsocket.write('{\"id\":\"ensure-host-probe\",\"type\":\"get_protocol_info\"}\\n');\n\t\t});\n\t\tsocket.on(\"data\", (chunk) => {\n\t\t\tbuffer += chunk.toString(\"utf8\");\n\t\t\tconst newline = buffer.indexOf(\"\\n\");\n\t\t\tif (newline === -1) return;\n\t\t\tfinish(readProtocolInfo(buffer.slice(0, newline)));\n\t\t});\n\t\tsocket.once(\"error\", () => finish());\n\t\tsocket.once(\"close\", () => finish());\n\t});\n}\n\nfunction readProtocolInfo(text: string): ProtocolInfo | undefined {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(text);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!isRecord(parsed) || parsed.id !== \"ensure-host-probe\" || parsed.success !== true || !isRecord(parsed.data)) {\n\t\treturn undefined;\n\t}\n\tconst { serverVersion, capabilities } = parsed.data;\n\tif (typeof serverVersion !== \"string\" || !Array.isArray(capabilities)) return undefined;\n\tif (!capabilities.every((capability) => typeof capability === \"string\")) return undefined;\n\treturn { serverVersion, capabilities };\n}\n\nfunction isCompatible(protocol: ProtocolInfo | undefined): boolean {\n\treturn (\n\t\tprotocol?.serverVersion === VERSION &&\n\t\tREQUIRED_CAPABILITIES.every((capability) => protocol.capabilities.includes(capability))\n\t);\n}\n\nasync function readPidFile(paths: HostDaemonPaths): Promise<DaemonPidFile | undefined> {\n\ttry {\n\t\treturn parseDaemonPidFile(await readFile(paths.pidFile, \"utf8\"));\n\t} catch (error: unknown) {\n\t\tif (isNodeErrorCode(error, \"ENOENT\")) return undefined;\n\t\tthrow error;\n\t}\n}\n\nasync function cleanupState(paths: HostDaemonPaths): Promise<void> {\n\tawait rm(paths.pidFile, { force: true });\n\tawait rm(paths.settingsFile, { force: true });\n}\n\nasync function appendStderr(paths: HostDaemonPaths, message: string): Promise<string> {\n\ttry {\n\t\tconst stderr = (await readFile(paths.stderrLog, \"utf8\")).trim();\n\t\treturn stderr ? `${message}\\n${stderr}` : message;\n\t} catch (error: unknown) {\n\t\tif (isNodeErrorCode(error, \"ENOENT\")) return message;\n\t\tthrow error;\n\t}\n}\n\nfunction normalizeSocketPath(value: string): string {\n\tif (value.startsWith(\"unix://\")) return value.slice(\"unix://\".length);\n\treturn value;\n}\n\n/**\n * Default launch: the host-lifecycle supervisor owns the public socket and the\n * idle-exit policy; it spawns the committed RPC socket host itself. Any extra\n * hostArgs are forwarded verbatim to the host CLI (e.g. provider pinning).\n */\nfunction defaultHostLaunch(\n\tsocket: string,\n\thostArgs: readonly string[],\n): {\n\tcommand: string;\n\targs: string[];\n} {\n\treturn {\n\t\tcommand: process.execPath,\n\t\targs: [...process.execArgv, resolveHostLifecycleEntryPath(), \"--socket\", socket, ...hostArgs],\n\t};\n}\n\nfunction resolveHostLifecycleEntryPath(): string {\n\tconst modulePath = fileURLToPath(import.meta.url);\n\tconst extension = modulePath.endsWith(\".ts\") ? \".ts\" : \".js\";\n\treturn resolve(dirname(modulePath), `host-lifecycle${extension}`);\n}\n\nfunction delay(ms: number): Promise<void> {\n\treturn new Promise((resolveDelay) => setTimeout(resolveDelay, ms));\n}\n\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isNodeErrorCode(error: unknown, code: string): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === code;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"host-ensure.js","sourceRoot":"","sources":["../../../src/modes/rpc/host-ensure.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,EAA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,CAAC,CAAC;AACnE,CAAC;AAED,SAAS,KAAK,CAAC,EAAU;IACxB,OAAO,IAAI,OAAO,CAAC,CAAC,YAAY,EAAE,EAAE,CAAC,UAAU,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC,CAAC;AACpE,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAED,SAAS,eAAe,CAAC,KAAc,EAAE,IAAY;IACpD,OAAO,KAAK,YAAY,KAAK,IAAI,MAAM,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC;AACzE,CAAC","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { mkdir, open, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { createConnection } from \"node:net\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport * as properLockfile from \"proper-lockfile\";\nimport { ENV_AGENT_DIR, getAgentDir, isBunBinary, VERSION } from \"../../config.ts\";\nimport {\n\ttype DaemonPidFile,\n\tparseDaemonPidFile,\n\tprocessMatchesPidFile,\n\twaitForStartTime,\n} from \"../app-server/daemon/process.ts\";\nimport {\n\tCUSTOM_UNSUPPORTED_CAPABILITY,\n\tEXTENSION_EVENTS_CAPABILITY,\n\tRPC_CLIENT_CAPABILITIES_ENV,\n} from \"./custom-capability.ts\";\nimport {\n\tDEFAULT_HOST_IDLE_EXIT_MS,\n\ttype HostColdStart,\n\ttype HostLifecyclePolicyInput,\n\tINTERNAL_SUPERVISOR_FLAG,\n} from \"./host-lifecycle.ts\";\n\nexport type { HostColdStart, HostLifecyclePolicyInput };\n\nexport interface HostDaemonPaths {\n\treadonly dir: string;\n\treadonly pidFile: string;\n\treadonly lockFile: string;\n\treadonly settingsFile: string;\n\treadonly stderrLog: string;\n}\n\nexport interface EnsureHostOptions {\n\treadonly socket: string;\n\treadonly agentDir?: string;\n\t/** Host lifecycle policy recorded in settings.json (env overrides win at runtime). */\n\treadonly policy?: HostLifecyclePolicyInput;\n\treadonly _test?: {\n\t\treadonly readinessTimeoutMs?: number;\n\t\treadonly stopTimeoutMs?: number;\n\t\treadonly spawn?: { readonly command: string; readonly args: readonly string[] };\n\t\t/** Extra env merged over process.env for the spawned host (hermetic test/QA wiring). */\n\t\treadonly env?: Readonly<Record<string, string>>;\n\t\t/** Extra CLI args forwarded through the supervisor to the host process. */\n\t\treadonly hostArgs?: readonly string[];\n\t\t/** Runs after endpoint ownership is locked; deterministic concurrency-test gate. */\n\t\treadonly afterLockAcquired?: () => Promise<void>;\n\t};\n}\n\nexport interface EnsuredHost {\n\treadonly pid: number;\n\treadonly socket: string;\n\treadonly reused: boolean;\n}\n\ntype ProtocolInfo = {\n\treadonly serverVersion: string;\n\treadonly capabilities: readonly string[];\n};\n\nconst lockOptions = { stale: 60_000, retries: { retries: 100, minTimeout: 20, maxTimeout: 100 } } as const;\nconst REQUIRED_CAPABILITIES = [\"multi_session\", EXTENSION_EVENTS_CAPABILITY] as const;\n/**\n * Every ensured host starts with this installation-wide profile, independent of\n * the first caller. In particular, extension_events must remain available when\n * a terminal client starts the shared host before the desktop connects.\n */\nexport const PINNED_HOST_CLIENT_CAPABILITIES = [EXTENSION_EVENTS_CAPABILITY, CUSTOM_UNSUPPORTED_CAPABILITY] as const;\n\nexport function createHostDaemonPaths(agentDir = getAgentDir()): HostDaemonPaths {\n\tconst dir = join(agentDir, \"rpc-host-daemon\");\n\treturn {\n\t\tdir,\n\t\tpidFile: join(dir, \"host.pid\"),\n\t\tlockFile: join(dir, \"daemon.lock\"),\n\t\tsettingsFile: join(dir, \"settings.json\"),\n\t\tstderrLog: join(dir, \"stderr.log\"),\n\t};\n}\n\nexport async function ensureHost(options: EnsureHostOptions): Promise<EnsuredHost> {\n\tconst socket = normalizeSocketPath(options.socket);\n\tconst paths = createHostDaemonPaths(options.agentDir);\n\tawait mkdir(paths.dir, { recursive: true });\n\t// The public socket is the shared resource; agent directories are not a\n\t// sufficient lock scope when two installations target the same endpoint.\n\tconst lockTarget = join(tmpdir(), \"senpi-rpc-host-locks\", createSocketLockName(socket));\n\tawait mkdir(dirname(lockTarget), { recursive: true });\n\tawait writeFile(lockTarget, \"\", { flag: \"a\", mode: 0o600 });\n\tconst release = await properLockfile.lock(lockTarget, { ...lockOptions, lockfilePath: `${lockTarget}.lock` });\n\ttry {\n\t\tawait options._test?.afterLockAcquired?.();\n\t\treturn await ensureHostLocked(paths, socket, options.agentDir ?? getAgentDir(), options.policy, options._test);\n\t} finally {\n\t\tawait release();\n\t}\n}\n\nasync function ensureHostLocked(\n\tpaths: HostDaemonPaths,\n\tsocket: string,\n\tagentDir: string,\n\tpolicy: HostLifecyclePolicyInput | undefined,\n\ttestOptions: EnsureHostOptions[\"_test\"],\n): Promise<EnsuredHost> {\n\tconst pidFile = await readPidFile(paths);\n\tconst protocol = await probeProtocolInfo(socket, 1_000);\n\tconst pidMatches = pidFile ? await processMatchesPidFile(pidFile) : false;\n\tif (isCompatible(protocol)) {\n\t\t// A compatible socket is attachable even when another client surface\n\t\t// started it. Only hosts we spawned are eligible for lifecycle management.\n\t\treturn { pid: pidFile?.pid ?? 0, socket, reused: true };\n\t}\n\tif (protocol && !pidMatches) {\n\t\tthrow new Error(`RPC socket ${socket} is owned by an unmanaged host`);\n\t}\n\tif (pidFile && pidMatches) {\n\t\tawait stopManagedHost(pidFile, testOptions?.stopTimeoutMs ?? 10_000);\n\t}\n\tawait cleanupState(paths);\n\treturn startHost(paths, socket, agentDir, policy, testOptions);\n}\n\nasync function startHost(\n\tpaths: HostDaemonPaths,\n\tsocket: string,\n\tagentDir: string,\n\tpolicy: HostLifecyclePolicyInput | undefined,\n\ttestOptions: EnsureHostOptions[\"_test\"],\n): Promise<EnsuredHost> {\n\t// The settings file must exist before the supervisor reads it at boot, so it\n\t// records the policy before the spawn instead of beside the pidfile.\n\tawait writeFile(\n\t\tpaths.settingsFile,\n\t\t`${JSON.stringify({\n\t\t\tsocket,\n\t\t\tcapabilities: PINNED_HOST_CLIENT_CAPABILITIES,\n\t\t\tcoldStart: policy?.coldStart ?? \"transient\",\n\t\t\tidleExitMs: policy?.idleExitMs ?? DEFAULT_HOST_IDLE_EXIT_MS,\n\t\t})}\\n`,\n\t\t{ mode: 0o600 },\n\t);\n\tconst stderr = await open(paths.stderrLog, \"w\", 0o600);\n\tlet pidFile: DaemonPidFile | undefined;\n\tlet child: ReturnType<typeof spawn> | undefined;\n\tlet exitedEarly: ChildExit | undefined;\n\tlet childExit: Promise<ChildExit> | undefined;\n\ttry {\n\t\tconst launch = testOptions?.spawn ?? defaultHostLaunch(socket, testOptions?.hostArgs ?? []);\n\t\tchild = spawn(launch.command, [...launch.args], {\n\t\t\tdetached: true,\n\t\t\tenv: {\n\t\t\t\t...process.env,\n\t\t\t\t...(testOptions?.env ?? {}),\n\t\t\t\t[ENV_AGENT_DIR]: agentDir,\n\t\t\t\t[RPC_CLIENT_CAPABILITIES_ENV]: PINNED_HOST_CLIENT_CAPABILITIES.join(\",\"),\n\t\t\t},\n\t\t\tstdio: [\"ignore\", \"ignore\", stderr.fd],\n\t\t});\n\t\tchildExit = new Promise((resolveExit) => {\n\t\t\tchild!.once(\"exit\", (code, signal) => {\n\t\t\t\texitedEarly = { code, signal };\n\t\t\t\tresolveExit(exitedEarly);\n\t\t\t});\n\t\t});\n\t\tchild.unref();\n\t\tif (child.pid === undefined) throw new Error(\"failed to spawn RPC socket host\");\n\t\tconst processStartTime = await Promise.race([\n\t\t\twaitForStartTime(child.pid, 2_000),\n\t\t\tchildExit.then(() => {\n\t\t\t\tthrow new Error(\"RPC socket host exited before its start time could be read\");\n\t\t\t}),\n\t\t]);\n\t\tpidFile = { pid: child.pid, processStartTime };\n\t\tawait writeFile(paths.pidFile, `${JSON.stringify(pidFile)}\\n`, { mode: 0o600 });\n\t} catch (error: unknown) {\n\t\tif (!exitedEarly) throw error;\n\t\tconst diagnostic = await appendStderr(\n\t\t\tpaths,\n\t\t\t`RPC socket host exited with code ${exitedEarly.code ?? \"null\"}${exitedEarly.signal ? ` (${exitedEarly.signal})` : \"\"} before answering get_protocol_info`,\n\t\t);\n\t\tawait cleanupState(paths);\n\t\tthrow new Error(diagnostic);\n\t} finally {\n\t\tawait stderr.close();\n\t}\n\tconst readinessTimeoutMs = testOptions?.readinessTimeoutMs ?? 10_000;\n\tconst result = await pollProtocolInfo(socket, readinessTimeoutMs, childExit);\n\tif (isCompatible(result.protocol)) return { pid: pidFile.pid, socket, reused: false };\n\tawait stopManagedHost(pidFile, testOptions?.stopTimeoutMs ?? 10_000);\n\tconst message = result.protocol\n\t\t? `RPC socket host answered get_protocol_info with serverVersion ${result.protocol.serverVersion} and capabilities ${JSON.stringify(result.protocol.capabilities)}, but is incompatible with serverVersion ${VERSION} and required capabilities ${JSON.stringify(REQUIRED_CAPABILITIES)}`\n\t\t: result.exited\n\t\t\t? `RPC socket host exited with code ${result.exited.code ?? \"null\"}${result.exited.signal ? ` (${result.exited.signal})` : \"\"} before answering get_protocol_info`\n\t\t\t: `spawned RPC socket host did not answer get_protocol_info within ${readinessTimeoutMs}ms`;\n\tconst diagnostic = await appendStderr(paths, message);\n\tawait cleanupState(paths);\n\t// The supervisor may have failed before binding, or another owner may have\n\t// appeared while readiness was being checked. Never unlink an endpoint we\n\t// cannot prove this start owned.\n\tthrow new Error(diagnostic);\n}\n\nasync function stopManagedHost(pidFile: DaemonPidFile, termTimeoutMs: number): Promise<void> {\n\tawait signalValidated(pidFile, \"SIGTERM\");\n\tif (await waitForGone(pidFile, termTimeoutMs)) return;\n\tawait signalValidated(pidFile, \"SIGKILL\");\n\tif (!(await waitForGone(pidFile, 2_000))) {\n\t\tthrow new Error(`RPC socket host pid ${pidFile.pid} remained alive after SIGKILL`);\n\t}\n}\n\nasync function signalValidated(pidFile: DaemonPidFile, signal: NodeJS.Signals): Promise<void> {\n\tif (!(await processMatchesPidFile(pidFile))) return;\n\ttry {\n\t\tprocess.kill(pidFile.pid, signal);\n\t} catch (error: unknown) {\n\t\tif (!isNodeErrorCode(error, \"ESRCH\")) throw error;\n\t}\n}\n\nasync function waitForGone(pidFile: DaemonPidFile, timeoutMs: number): Promise<boolean> {\n\tconst deadline = Date.now() + timeoutMs;\n\twhile (Date.now() <= deadline) {\n\t\tif (!(await processMatchesPidFile(pidFile))) return true;\n\t\tawait delay(50);\n\t}\n\treturn false;\n}\n\ntype ChildExit = { readonly code: number | null; readonly signal: NodeJS.Signals | null };\n\ntype ProtocolPollResult = { readonly protocol?: ProtocolInfo; readonly exited?: ChildExit };\n\nasync function pollProtocolInfo(\n\tsocket: string,\n\ttimeoutMs: number,\n\tchildExit?: Promise<ChildExit>,\n): Promise<ProtocolPollResult> {\n\tconst deadline = Date.now() + timeoutMs;\n\tlet lastProtocol: ProtocolInfo | undefined;\n\twhile (Date.now() <= deadline) {\n\t\tconst probe = probeProtocolInfo(socket, Math.min(500, Math.max(1, deadline - Date.now())));\n\t\tconst info = childExit ? await Promise.race([probe, childExit]) : await probe;\n\t\tif (isChildExit(info)) return { protocol: lastProtocol, exited: info };\n\t\tif (info) {\n\t\t\tlastProtocol = info;\n\t\t\tif (isCompatible(info)) return { protocol: info };\n\t\t}\n\t\tawait delay(50);\n\t}\n\treturn { protocol: lastProtocol };\n}\n\nfunction isChildExit(value: ProtocolInfo | ChildExit | undefined): value is ChildExit {\n\treturn !!value && \"code\" in value && \"signal\" in value;\n}\n\nfunction probeProtocolInfo(socketPath: string, timeoutMs: number): Promise<ProtocolInfo | undefined> {\n\treturn new Promise((resolveProbe) => {\n\t\tconst socket = createConnection(socketPath);\n\t\tlet buffer = \"\";\n\t\tlet settled = false;\n\t\tconst finish = (value?: ProtocolInfo): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tclearTimeout(timeout);\n\t\t\tsocket.destroy();\n\t\t\tresolveProbe(value);\n\t\t};\n\t\tconst timeout = setTimeout(() => finish(), timeoutMs);\n\t\tsocket.once(\"connect\", () => {\n\t\t\tsocket.write('{\"id\":\"ensure-host-probe\",\"type\":\"get_protocol_info\"}\\n');\n\t\t});\n\t\tsocket.on(\"data\", (chunk) => {\n\t\t\tbuffer += chunk.toString(\"utf8\");\n\t\t\tconst newline = buffer.indexOf(\"\\n\");\n\t\t\tif (newline === -1) return;\n\t\t\tfinish(readProtocolInfo(buffer.slice(0, newline)));\n\t\t});\n\t\tsocket.once(\"error\", () => finish());\n\t\tsocket.once(\"close\", () => finish());\n\t});\n}\n\nfunction readProtocolInfo(text: string): ProtocolInfo | undefined {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(text);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!isRecord(parsed) || parsed.id !== \"ensure-host-probe\" || parsed.success !== true || !isRecord(parsed.data)) {\n\t\treturn undefined;\n\t}\n\tconst { serverVersion, capabilities } = parsed.data;\n\tif (typeof serverVersion !== \"string\" || !Array.isArray(capabilities)) return undefined;\n\tif (!capabilities.every((capability) => typeof capability === \"string\")) return undefined;\n\treturn { serverVersion, capabilities };\n}\n\nfunction isCompatible(protocol: ProtocolInfo | undefined): boolean {\n\treturn (\n\t\tprotocol?.serverVersion === VERSION &&\n\t\tREQUIRED_CAPABILITIES.every((capability) => protocol.capabilities.includes(capability))\n\t);\n}\n\nasync function readPidFile(paths: HostDaemonPaths): Promise<DaemonPidFile | undefined> {\n\ttry {\n\t\treturn parseDaemonPidFile(await readFile(paths.pidFile, \"utf8\"));\n\t} catch (error: unknown) {\n\t\tif (isNodeErrorCode(error, \"ENOENT\")) return undefined;\n\t\tthrow error;\n\t}\n}\n\nasync function cleanupState(paths: HostDaemonPaths): Promise<void> {\n\tawait rm(paths.pidFile, { force: true });\n\tawait rm(paths.settingsFile, { force: true });\n}\n\nasync function appendStderr(paths: HostDaemonPaths, message: string): Promise<string> {\n\ttry {\n\t\tconst stderr = (await readFile(paths.stderrLog, \"utf8\")).trim();\n\t\treturn stderr ? `${message}\\n${stderr}` : message;\n\t} catch (error: unknown) {\n\t\tif (isNodeErrorCode(error, \"ENOENT\")) return message;\n\t\tthrow error;\n\t}\n}\n\nfunction createSocketLockName(socket: string): string {\n\treturn createHash(\"sha256\").update(socket).digest(\"hex\").slice(0, 32);\n}\n\nfunction normalizeSocketPath(value: string): string {\n\tif (value.startsWith(\"unix://\")) return value.slice(\"unix://\".length);\n\treturn value;\n}\n\n/**\n * Default launch: the host-lifecycle supervisor owns the public socket and the\n * idle-exit policy; it spawns the committed RPC socket host itself. Any extra\n * hostArgs are forwarded verbatim to the host CLI (e.g. provider pinning).\n *\n * A compiled standalone binary cannot re-enter itself through a script path:\n * bun executables always boot their embedded entrypoint and parse the whole\n * argv as CLI arguments, so `host-lifecycle.ts --socket <path>` dies with\n * \"Unknown option: --socket\" before the host ever answers get_protocol_info.\n * Compiled binaries therefore re-enter through the hidden\n * `--internal-rpc-host-supervisor` route that main() dispatches before\n * argument parsing. Exported for tests.\n */\nexport function defaultHostLaunch(\n\tsocket: string,\n\thostArgs: readonly string[],\n\tcompiled: boolean = isBunBinary,\n): {\n\tcommand: string;\n\targs: string[];\n} {\n\tif (compiled) {\n\t\treturn {\n\t\t\tcommand: process.execPath,\n\t\t\targs: [INTERNAL_SUPERVISOR_FLAG, \"--socket\", socket, ...hostArgs],\n\t\t};\n\t}\n\treturn {\n\t\tcommand: process.execPath,\n\t\targs: [...process.execArgv, resolveHostLifecycleEntryPath(), \"--socket\", socket, ...hostArgs],\n\t};\n}\n\nfunction resolveHostLifecycleEntryPath(): string {\n\tconst modulePath = fileURLToPath(import.meta.url);\n\tconst extension = modulePath.endsWith(\".ts\") ? \".ts\" : \".js\";\n\treturn resolve(dirname(modulePath), `host-lifecycle${extension}`);\n}\n\nfunction delay(ms: number): Promise<void> {\n\treturn new Promise((resolveDelay) => setTimeout(resolveDelay, ms));\n}\n\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isNodeErrorCode(error: unknown, code: string): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === code;\n}\n"]}
|
|
@@ -49,9 +49,38 @@ export interface SupervisorLaunch {
|
|
|
49
49
|
/** Explicit ownership directory for callers whose environment is not yet branded. */
|
|
50
50
|
readonly agentDir?: string;
|
|
51
51
|
}
|
|
52
|
+
/** Hidden internal launch route: wire-invisible, never advertised by the public CLI surface. */
|
|
53
|
+
export declare const INTERNAL_SUPERVISOR_FLAG = "--internal-rpc-host-supervisor";
|
|
54
|
+
/**
|
|
55
|
+
* Returns the internal supervisor payload when argv selects that route.
|
|
56
|
+
*
|
|
57
|
+
* The route dispatches when the sentinel is argv[0] OR is preceded only by
|
|
58
|
+
* known injectable prefix flags and their values - the one perturbation
|
|
59
|
+
* wrappers legitimately perform. Everything else disqualifies it: a positional
|
|
60
|
+
* operand, `--`, or an unknown flag before the sentinel all return undefined,
|
|
61
|
+
* so a user-supplied value that happens to equal the sentinel can never reach
|
|
62
|
+
* the supervisor.
|
|
63
|
+
*
|
|
64
|
+
* The skipped prefix is deliberately NOT forwarded to the host: a wrapper
|
|
65
|
+
* re-injects its own prefix on every re-entry, so the host child receives it
|
|
66
|
+
* from the wrapper rather than twice from here.
|
|
67
|
+
*/
|
|
68
|
+
export declare function findInternalSupervisorArgs(argv: readonly string[]): readonly string[] | undefined;
|
|
52
69
|
/** `--socket <path>` selects the public socket; every other argument is forwarded to the host CLI. */
|
|
53
70
|
export declare function parseSupervisorArgs(argv: readonly string[]): SupervisorLaunch | undefined;
|
|
54
71
|
/** Resolves the committed CLI entry this supervisor wraps (source tree or built dist). */
|
|
55
72
|
export declare function resolveCliMainPath(): string;
|
|
73
|
+
/**
|
|
74
|
+
* Resolves the host child spawn. Explicit child commands (desktop launchers)
|
|
75
|
+
* are forwarded untouched. The default re-enters the committed CLI entry
|
|
76
|
+
* through the runtime, except in compiled standalone binaries, which always
|
|
77
|
+
* boot their embedded entrypoint and would parse a script path as CLI
|
|
78
|
+
* arguments - there the executable itself is the CLI, so the mode flags are
|
|
79
|
+
* passed directly. Exported for tests.
|
|
80
|
+
*/
|
|
81
|
+
export declare function resolveHostChildLaunch(launch: SupervisorLaunch, internalSocket: string, compiled?: boolean): {
|
|
82
|
+
command: string;
|
|
83
|
+
args: string[];
|
|
84
|
+
};
|
|
56
85
|
export declare function runHostSupervisor(launch: SupervisorLaunch): Promise<void>;
|
|
57
86
|
//# sourceMappingURL=host-lifecycle.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host-lifecycle.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/host-lifecycle.ts"],"names":[],"mappings":";
|
|
1
|
+
{"version":3,"file":"host-lifecycle.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/host-lifecycle.ts"],"names":[],"mappings":";AAyDA,MAAM,MAAM,aAAa,GAAG,WAAW,GAAG,YAAY,CAAC;AAEvD,mFAAmF;AACnF,eAAO,MAAM,mBAAmB,8BAA8B,CAAC;AAC/D,qEAAqE;AACrE,eAAO,MAAM,qBAAqB,gCAAgC,CAAC;AACnE,sFAAsF;AACtF,eAAO,MAAM,yBAAyB,QAAc,CAAC;AAErD,+EAA+E;AAC/E,MAAM,WAAW,wBAAwB;IACxC,QAAQ,CAAC,SAAS,CAAC,EAAE,aAAa,CAAC;IACnC,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,MAAM,WAAW,mBAAmB;IACnC,QAAQ,CAAC,SAAS,EAAE,aAAa,CAAC;IAClC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC5B;AAuBD,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,aAAa,GAAG,SAAS,CAEnF;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG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AG,gBAAgB,GAAG,SAAS,CAgCzF;AAED,0FAA0F;AAC1F,wBAAgB,kBAAkB,IAAI,MAAM,CAI3C;AAED;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACrC,MAAM,EAAE,gBAAgB,EACxB,cAAc,EAAE,MAAM,EACtB,QAAQ,GAAE,OAAqB,GAC7B;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,EAAE,CAAA;CAAE,CAmBrC;AAED,wBAAsB,iBAAiB,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAwK/E"}
|
|
@@ -45,9 +45,9 @@ import { createConnection, createServer } from "node:net";
|
|
|
45
45
|
import { tmpdir } from "node:os";
|
|
46
46
|
import { dirname, join, resolve } from "node:path";
|
|
47
47
|
import { fileURLToPath } from "node:url";
|
|
48
|
-
import { getAgentDir } from "../../config.js";
|
|
48
|
+
import { getAgentDir, isBunBinary } from "../../config.js";
|
|
49
49
|
import { createHostDaemonPaths } from "./host-ensure.js";
|
|
50
|
-
import { HOST_SCRATCH_DIR_ENV, HOST_WATCH_FD_ENV, HOST_WATCH_PPID_ENV } from "./host-watchdog.js";
|
|
50
|
+
import { HOST_CLEANUP_PATHS_ENV, HOST_SCRATCH_DIR_ENV, HOST_WATCH_FD_ENV, HOST_WATCH_PPID_ENV, } from "./host-watchdog.js";
|
|
51
51
|
import { attachJsonlLineReader, MAX_RPC_LINE_CHARACTERS } from "./jsonl.js";
|
|
52
52
|
/** Environment override for the cold-start policy: `transient` or `persistent`. */
|
|
53
53
|
export const HOST_COLD_START_ENV = "SENPI_RPC_HOST_COLD_START";
|
|
@@ -121,6 +121,40 @@ export class IdleExitDecider {
|
|
|
121
121
|
return this.now() - this.idleSince >= this.idleExitMs ? "exit" : "idle";
|
|
122
122
|
}
|
|
123
123
|
}
|
|
124
|
+
/** Hidden internal launch route: wire-invisible, never advertised by the public CLI surface. */
|
|
125
|
+
export const INTERNAL_SUPERVISOR_FLAG = "--internal-rpc-host-supervisor";
|
|
126
|
+
/**
|
|
127
|
+
* Engine-global flags a rebranded wrapper may legitimately prepend when it
|
|
128
|
+
* re-dispatches this binary. `packages/omo-native` injects `--extension <dir>`
|
|
129
|
+
* for every non-early command, which pushed the sentinel off argv[0].
|
|
130
|
+
*/
|
|
131
|
+
const INJECTABLE_PREFIX_FLAGS = new Set(["--extension"]);
|
|
132
|
+
/**
|
|
133
|
+
* Returns the internal supervisor payload when argv selects that route.
|
|
134
|
+
*
|
|
135
|
+
* The route dispatches when the sentinel is argv[0] OR is preceded only by
|
|
136
|
+
* known injectable prefix flags and their values - the one perturbation
|
|
137
|
+
* wrappers legitimately perform. Everything else disqualifies it: a positional
|
|
138
|
+
* operand, `--`, or an unknown flag before the sentinel all return undefined,
|
|
139
|
+
* so a user-supplied value that happens to equal the sentinel can never reach
|
|
140
|
+
* the supervisor.
|
|
141
|
+
*
|
|
142
|
+
* The skipped prefix is deliberately NOT forwarded to the host: a wrapper
|
|
143
|
+
* re-injects its own prefix on every re-entry, so the host child receives it
|
|
144
|
+
* from the wrapper rather than twice from here.
|
|
145
|
+
*/
|
|
146
|
+
export function findInternalSupervisorArgs(argv) {
|
|
147
|
+
for (let index = 0; index < argv.length; index++) {
|
|
148
|
+
const arg = argv[index];
|
|
149
|
+
if (arg === INTERNAL_SUPERVISOR_FLAG)
|
|
150
|
+
return argv.slice(index + 1);
|
|
151
|
+
// A prefix flag only counts when its value is actually present.
|
|
152
|
+
if (!INJECTABLE_PREFIX_FLAGS.has(arg) || index + 1 >= argv.length)
|
|
153
|
+
return undefined;
|
|
154
|
+
index++;
|
|
155
|
+
}
|
|
156
|
+
return undefined;
|
|
157
|
+
}
|
|
124
158
|
/** `--socket <path>` selects the public socket; every other argument is forwarded to the host CLI. */
|
|
125
159
|
export function parseSupervisorArgs(argv) {
|
|
126
160
|
const hostArgs = [];
|
|
@@ -163,6 +197,34 @@ export function resolveCliMainPath() {
|
|
|
163
197
|
const extension = modulePath.endsWith(".ts") ? ".ts" : ".js";
|
|
164
198
|
return resolve(dirname(modulePath), "..", "..", `cli-main${extension}`);
|
|
165
199
|
}
|
|
200
|
+
/**
|
|
201
|
+
* Resolves the host child spawn. Explicit child commands (desktop launchers)
|
|
202
|
+
* are forwarded untouched. The default re-enters the committed CLI entry
|
|
203
|
+
* through the runtime, except in compiled standalone binaries, which always
|
|
204
|
+
* boot their embedded entrypoint and would parse a script path as CLI
|
|
205
|
+
* arguments - there the executable itself is the CLI, so the mode flags are
|
|
206
|
+
* passed directly. Exported for tests.
|
|
207
|
+
*/
|
|
208
|
+
export function resolveHostChildLaunch(launch, internalSocket, compiled = isBunBinary) {
|
|
209
|
+
if (launch.childCommand) {
|
|
210
|
+
return {
|
|
211
|
+
command: launch.childCommand,
|
|
212
|
+
args: [...(launch.childArgs ?? []), "--listen", `unix://${internalSocket}`],
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
return {
|
|
216
|
+
command: process.execPath,
|
|
217
|
+
args: [
|
|
218
|
+
...(compiled ? [] : [...process.execArgv, resolveCliMainPath()]),
|
|
219
|
+
"--mode",
|
|
220
|
+
"rpc",
|
|
221
|
+
"--multi-session",
|
|
222
|
+
"--listen",
|
|
223
|
+
`unix://${internalSocket}`,
|
|
224
|
+
...launch.hostArgs,
|
|
225
|
+
],
|
|
226
|
+
};
|
|
227
|
+
}
|
|
166
228
|
export async function runHostSupervisor(launch) {
|
|
167
229
|
const paths = createHostDaemonPaths(launch.agentDir ?? getAgentDir());
|
|
168
230
|
const policy = resolveHostPolicy(await readSettingsFile(paths.settingsFile), process.env);
|
|
@@ -172,25 +234,18 @@ export async function runHostSupervisor(launch) {
|
|
|
172
234
|
const clientSockets = new Set();
|
|
173
235
|
const busySessions = new Map();
|
|
174
236
|
let observerHealthy = false;
|
|
237
|
+
let observerReconnectTimer;
|
|
175
238
|
let shuttingDown = false;
|
|
176
239
|
let shutdownPromise;
|
|
177
|
-
const
|
|
178
|
-
|
|
179
|
-
: [
|
|
180
|
-
...process.execArgv,
|
|
181
|
-
resolveCliMainPath(),
|
|
182
|
-
"--mode",
|
|
183
|
-
"rpc",
|
|
184
|
-
"--multi-session",
|
|
185
|
-
"--listen",
|
|
186
|
-
`unix://${internalSocket}`,
|
|
187
|
-
...launch.hostArgs,
|
|
188
|
-
], {
|
|
240
|
+
const childLaunch = resolveHostChildLaunch(launch, internalSocket);
|
|
241
|
+
const child = spawn(childLaunch.command, childLaunch.args, {
|
|
189
242
|
env: {
|
|
190
243
|
...process.env,
|
|
244
|
+
...(launch.agentDir ? { SENPI_CODING_AGENT_DIR: launch.agentDir } : {}),
|
|
191
245
|
[HOST_WATCH_FD_ENV]: String(CHILD_WATCH_FD),
|
|
192
246
|
[HOST_WATCH_PPID_ENV]: String(process.pid),
|
|
193
247
|
[HOST_SCRATCH_DIR_ENV]: internal.dir,
|
|
248
|
+
[HOST_CLEANUP_PATHS_ENV]: [publicSocket, paths.pidFile, paths.settingsFile].join("\n"),
|
|
194
249
|
},
|
|
195
250
|
// Slot 3 is the lifetime pipe: "pipe" gives the child a read end it can
|
|
196
251
|
// wait on and keeps the write end owned by this process alone.
|
|
@@ -287,7 +342,8 @@ export async function runHostSupervisor(launch) {
|
|
|
287
342
|
await rm(internal.dir, { recursive: true, force: true });
|
|
288
343
|
await stopChild(child);
|
|
289
344
|
observer?.destroy();
|
|
290
|
-
|
|
345
|
+
if (publicSocketOwned)
|
|
346
|
+
await rm(publicSocket, { force: true });
|
|
291
347
|
// Mirror ensureHost's cleanupState: the pidfile and settings describe a
|
|
292
348
|
// live host only; the stderr log stays for diagnostics.
|
|
293
349
|
await rm(paths.pidFile, { force: true });
|
|
@@ -295,6 +351,7 @@ export async function runHostSupervisor(launch) {
|
|
|
295
351
|
process.exit(exitCode);
|
|
296
352
|
}
|
|
297
353
|
let observer;
|
|
354
|
+
let publicSocketOwned = false;
|
|
298
355
|
// Registered before the startup handshake, not after it: the private internal
|
|
299
356
|
// directory already exists at this point, so a SIGTERM arriving during host
|
|
300
357
|
// startup must run the same cleanup instead of Node's default kill, which
|
|
@@ -302,22 +359,36 @@ export async function runHostSupervisor(launch) {
|
|
|
302
359
|
registerSupervisorSignals(shutdown);
|
|
303
360
|
try {
|
|
304
361
|
await waitForListener(internalSocket, 30_000);
|
|
305
|
-
|
|
306
|
-
await waitForConnect(observer, 5_000);
|
|
307
|
-
observerHealthy = true;
|
|
308
|
-
attachJsonlLineReader(observer, observeHostEvent, { maxLineLength: MAX_RPC_LINE_CHARACTERS });
|
|
309
|
-
observer.once("close", () => {
|
|
310
|
-
observerHealthy = false;
|
|
311
|
-
});
|
|
312
|
-
observer.once("error", () => {
|
|
313
|
-
observerHealthy = false;
|
|
314
|
-
});
|
|
362
|
+
await connectObserver();
|
|
315
363
|
await prepareSocketPath(publicSocket);
|
|
316
364
|
await listen(server, publicSocket);
|
|
365
|
+
publicSocketOwned = true;
|
|
317
366
|
}
|
|
318
367
|
catch (cause) {
|
|
319
368
|
await shutdown(`startup failed: ${errorMessage(cause)}`, 1);
|
|
320
369
|
}
|
|
370
|
+
async function connectObserver() {
|
|
371
|
+
const next = createConnection(internalSocket);
|
|
372
|
+
await waitForConnect(next, 5_000);
|
|
373
|
+
observer = next;
|
|
374
|
+
observerHealthy = true;
|
|
375
|
+
attachJsonlLineReader(next, observeHostEvent, { maxLineLength: MAX_RPC_LINE_CHARACTERS });
|
|
376
|
+
const lost = () => {
|
|
377
|
+
if (observer !== next || shuttingDown)
|
|
378
|
+
return;
|
|
379
|
+
observerHealthy = false;
|
|
380
|
+
observer = undefined;
|
|
381
|
+
if (observerReconnectTimer === undefined) {
|
|
382
|
+
observerReconnectTimer = setTimeout(() => {
|
|
383
|
+
observerReconnectTimer = undefined;
|
|
384
|
+
void connectObserver().catch(() => lost());
|
|
385
|
+
}, 250);
|
|
386
|
+
observerReconnectTimer.unref?.();
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
next.once("close", lost);
|
|
390
|
+
next.once("error", lost);
|
|
391
|
+
}
|
|
321
392
|
writeStderrLine(`senpi rpc host ready on unix://${publicSocket} (coldStart=${policy.coldStart}, idleExitMs=${policy.coldStart === "persistent" ? "never" : String(policy.idleExitMs)})`);
|
|
322
393
|
await new Promise(() => { });
|
|
323
394
|
}
|