@code-yeongyu/senpi 2026.8.30-3 → 2026.8.31
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 +34 -0
- package/README.md +3 -0
- package/dist/core/agent-session.d.ts +26 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +67 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry.d.ts +9 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry.js +10 -3
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/deterministic-fallback.d.ts +1 -1
- package/dist/core/extensions/builtin/compaction/deterministic-fallback.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/deterministic-fallback.js +4 -1
- package/dist/core/extensions/builtin/compaction/deterministic-fallback.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/speculative-summary.d.ts +1 -0
- package/dist/core/extensions/builtin/compaction/speculative-summary.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/speculative-summary.js +1 -0
- package/dist/core/extensions/builtin/compaction/speculative-summary.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/speculative.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/speculative.js +14 -1
- package/dist/core/extensions/builtin/compaction/speculative.js.map +1 -1
- package/dist/core/extensions/builtin/hooks/trust-state-json.d.ts +5 -0
- package/dist/core/extensions/builtin/hooks/trust-state-json.d.ts.map +1 -0
- package/dist/core/extensions/builtin/hooks/trust-state-json.js +76 -0
- package/dist/core/extensions/builtin/hooks/trust-state-json.js.map +1 -0
- package/dist/core/extensions/builtin/hooks/trust-storage.d.ts +7 -1
- package/dist/core/extensions/builtin/hooks/trust-storage.d.ts.map +1 -1
- package/dist/core/extensions/builtin/hooks/trust-storage.js +60 -8
- package/dist/core/extensions/builtin/hooks/trust-storage.js.map +1 -1
- package/dist/core/extensions/builtin/hooks/trust.d.ts +1 -2
- package/dist/core/extensions/builtin/hooks/trust.d.ts.map +1 -1
- package/dist/core/extensions/builtin/hooks/trust.js +1 -72
- package/dist/core/extensions/builtin/hooks/trust.js.map +1 -1
- package/dist/core/extensions/builtin/ttsr/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/ttsr/index.js +4 -0
- package/dist/core/extensions/builtin/ttsr/index.js.map +1 -1
- package/dist/core/extensions/builtin/ttsr/manager.d.ts +2 -0
- package/dist/core/extensions/builtin/ttsr/manager.d.ts.map +1 -1
- package/dist/core/extensions/builtin/ttsr/manager.js +28 -1
- package/dist/core/extensions/builtin/ttsr/manager.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +5 -0
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +7 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/retry-fallback/controller.d.ts +14 -0
- package/dist/core/retry-fallback/controller.d.ts.map +1 -1
- package/dist/core/retry-fallback/controller.js +33 -3
- package/dist/core/retry-fallback/controller.js.map +1 -1
- package/dist/core/retry-fallback/log.js +1 -1
- package/dist/core/retry-fallback/log.js.map +1 -1
- package/dist/core/session-activity.d.ts +47 -0
- package/dist/core/session-activity.d.ts.map +1 -0
- package/dist/core/session-activity.js +58 -0
- package/dist/core/session-activity.js.map +1 -0
- package/dist/core/session-manager.d.ts +8 -12
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +118 -7
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/session-resident-store.d.ts +8 -1
- package/dist/core/session-resident-store.d.ts.map +1 -1
- package/dist/core/session-resident-store.js +12 -5
- package/dist/core/session-resident-store.js.map +1 -1
- package/dist/modes/app-server/daemon.js +3 -3
- package/dist/modes/app-server/daemon.js.map +1 -1
- package/dist/modes/interactive/interactive-host-runtime.d.ts +3 -1
- package/dist/modes/interactive/interactive-host-runtime.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-host-runtime.js +26 -4
- package/dist/modes/interactive/interactive-host-runtime.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +24 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/connection-handler.d.ts +12 -5
- package/dist/modes/rpc/connection-handler.d.ts.map +1 -1
- package/dist/modes/rpc/connection-handler.js +149 -12
- package/dist/modes/rpc/connection-handler.js.map +1 -1
- package/dist/modes/rpc/custom-capability.d.ts +1 -0
- package/dist/modes/rpc/custom-capability.d.ts.map +1 -1
- package/dist/modes/rpc/custom-capability.js +1 -0
- package/dist/modes/rpc/custom-capability.js.map +1 -1
- package/dist/modes/rpc/host-ensure.d.ts.map +1 -1
- package/dist/modes/rpc/host-ensure.js +3 -3
- package/dist/modes/rpc/host-ensure.js.map +1 -1
- package/dist/modes/rpc/host-lifecycle.d.ts +10 -0
- package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -1
- package/dist/modes/rpc/host-lifecycle.js +15 -2
- package/dist/modes/rpc/host-lifecycle.js.map +1 -1
- package/dist/modes/rpc/multi-session-host.d.ts +38 -0
- package/dist/modes/rpc/multi-session-host.d.ts.map +1 -1
- package/dist/modes/rpc/multi-session-host.js +55 -5
- package/dist/modes/rpc/multi-session-host.js.map +1 -1
- package/dist/modes/rpc/ownership-safe-lock.d.ts +14 -0
- package/dist/modes/rpc/ownership-safe-lock.d.ts.map +1 -0
- package/dist/modes/rpc/ownership-safe-lock.js +87 -0
- package/dist/modes/rpc/ownership-safe-lock.js.map +1 -0
- package/dist/modes/rpc/rpc-client.d.ts +1 -0
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +3 -0
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +12 -1
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js +1 -0
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/modes/rpc/session-binding.d.ts +2 -1
- package/dist/modes/rpc/session-binding.d.ts.map +1 -1
- package/dist/modes/rpc/session-binding.js +1 -0
- package/dist/modes/rpc/session-binding.js.map +1 -1
- package/dist/modes/rpc/session-command-router.d.ts +54 -1
- package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
- package/dist/modes/rpc/session-command-router.js +174 -2
- package/dist/modes/rpc/session-command-router.js.map +1 -1
- package/dist/modes/rpc/session-event-writer.d.ts +18 -0
- package/dist/modes/rpc/session-event-writer.d.ts.map +1 -1
- package/dist/modes/rpc/session-event-writer.js +88 -8
- package/dist/modes/rpc/session-event-writer.js.map +1 -1
- package/dist/modes/rpc/session-registry.d.ts +11 -1
- package/dist/modes/rpc/session-registry.d.ts.map +1 -1
- package/dist/modes/rpc/session-registry.js +25 -0
- package/dist/modes/rpc/session-registry.js.map +1 -1
- package/dist/modes/rpc/widget-line-renderer.d.ts +17 -0
- package/dist/modes/rpc/widget-line-renderer.d.ts.map +1 -0
- package/dist/modes/rpc/widget-line-renderer.js +73 -0
- package/dist/modes/rpc/widget-line-renderer.js.map +1 -0
- package/dist/utils/fs-watch.d.ts.map +1 -1
- package/dist/utils/fs-watch.js +11 -2
- package/dist/utils/fs-watch.js.map +1 -1
- package/docs/app-server.md +2 -2
- package/docs/containerization.md +2 -2
- package/docs/development.md +7 -7
- package/docs/extensions.md +4 -4
- package/docs/grok-neo.md +1 -1
- package/docs/index.md +1 -1
- package/docs/packages.md +2 -2
- package/docs/quickstart.md +4 -4
- package/docs/release-guide.md +21 -21
- package/docs/rpc.md +59 -4
- package/docs/sdk.md +1 -1
- package/docs/skills.md +2 -2
- package/docs/terminal-tools.md +1 -1
- package/docs/termux.md +1 -1
- package/docs/tui.md +1 -1
- package/examples/AGENTS.md +1 -1
- package/examples/sdk/README.md +1 -1
- package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +16 -0
- package/node_modules/@code-yeongyu/senpi-codemode/README.md +2 -2
- package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
- package/node_modules/@code-yeongyu/senpi-codemode/src/extension/skill-contribution.ts +71 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/index.ts +3 -1
- package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/SKILL.md +44 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/breaking-changes.md +75 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/build.md +114 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/dev-tooling.md +34 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/http-networking.md +113 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/install.md +93 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/node-compat-platforms.md +36 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/performance.md +33 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/runtime-apis.md +156 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/security.md +52 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/test.md +103 -0
- package/node_modules/@earendil-works/pi-agent-core/README.md +3 -0
- package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
- package/node_modules/@earendil-works/pi-ai/README.md +6 -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 +15 -0
- 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.d.ts +7 -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 +316 -2
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-conversation-rotation.d.ts +4 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-conversation-rotation.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-conversation-rotation.js +23 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-conversation-rotation.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.d.ts +24 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js +20 -2
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.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/openrouter.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.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/README.md +6 -3
- package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/node_modules/@earendil-works/pi-tui/README.md +5 -4
- package/node_modules/@earendil-works/pi-tui/native/darwin/README.md +2 -2
- package/node_modules/@earendil-works/pi-tui/native/win32/README.md +2 -2
- package/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/package.json +7 -7
|
@@ -5,12 +5,12 @@ import { createConnection } from "node:net";
|
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
6
6
|
import { dirname, join, resolve } from "node:path";
|
|
7
7
|
import { fileURLToPath } from "node:url";
|
|
8
|
-
import * as properLockfile from "proper-lockfile";
|
|
9
8
|
import { ENV_AGENT_DIR, getAgentDir, isBunBinary, VERSION } from "../../config.js";
|
|
10
9
|
import { parseDaemonPidFile, processMatchesPidFile, waitForStartTime, } from "../app-server/daemon/process.js";
|
|
11
10
|
import { CUSTOM_UNSUPPORTED_CAPABILITY, EXTENSION_EVENTS_CAPABILITY, RPC_CLIENT_CAPABILITIES_ENV, } from "./custom-capability.js";
|
|
12
11
|
import { DEFAULT_HOST_IDLE_EXIT_MS, INTERNAL_SUPERVISOR_FLAG, } from "./host-lifecycle.js";
|
|
13
|
-
|
|
12
|
+
import { acquireOwnershipSafeLock } from "./ownership-safe-lock.js";
|
|
13
|
+
const lockOptions = { retries: { retries: 100, minTimeout: 20, maxTimeout: 100 } };
|
|
14
14
|
const REQUIRED_CAPABILITIES = ["multi_session", EXTENSION_EVENTS_CAPABILITY];
|
|
15
15
|
/**
|
|
16
16
|
* Every ensured host starts with this installation-wide profile, independent of
|
|
@@ -37,7 +37,7 @@ export async function ensureHost(options) {
|
|
|
37
37
|
const lockTarget = join(tmpdir(), "senpi-rpc-host-locks", createSocketLockName(socket));
|
|
38
38
|
await mkdir(dirname(lockTarget), { recursive: true });
|
|
39
39
|
await writeFile(lockTarget, "", { flag: "a", mode: 0o600 });
|
|
40
|
-
const release = await
|
|
40
|
+
const release = await acquireOwnershipSafeLock(`${lockTarget}.lock`, lockOptions);
|
|
41
41
|
try {
|
|
42
42
|
await options._test?.afterLockAcquired?.();
|
|
43
43
|
return await ensureHostLocked(paths, socket, options.agentDir ?? getAgentDir(), options.policy, options._test);
|
|
@@ -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,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,EAAE,SAAS,EAA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,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"]}
|
|
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,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AACnF,OAAO,EAEN,kBAAkB,EAClB,qBAAqB,EACrB,gBAAgB,GAChB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACN,6BAA6B,EAC7B,2BAA2B,EAC3B,2BAA2B,GAC3B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACN,yBAAyB,EAGzB,wBAAwB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAyCpE,MAAM,WAAW,GAAG,EAAE,OAAO,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,UAAU,EAAE,EAAE,EAAE,UAAU,EAAE,GAAG,EAAE,EAAW,CAAC;AAC5F,MAAM,qBAAqB,GAAG,CAAC,eAAe,EAAE,2BAA2B,CAAU,CAAC;AACtF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AAQ,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 { 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 { 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\";\nimport { acquireOwnershipSafeLock } from \"./ownership-safe-lock.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 = { 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 acquireOwnershipSafeLock(`${lockTarget}.lock`, lockOptions);\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"]}
|
|
@@ -27,6 +27,16 @@ export interface HostActivity {
|
|
|
27
27
|
readonly connections: number;
|
|
28
28
|
readonly activeTurns: number;
|
|
29
29
|
}
|
|
30
|
+
/**
|
|
31
|
+
* How the supervisor reads its child's exit. The RPC host exits 0 only through
|
|
32
|
+
* its own clean shutdown path - including its idle/empty-host policy - so that
|
|
33
|
+
* is an intentional stop, not a crash: the supervisor mirrors its own idle exit
|
|
34
|
+
* instead of reporting failure. Any non-zero code or signal stays a crash.
|
|
35
|
+
*/
|
|
36
|
+
export declare function classifyChildExit(code: number | null, signal: NodeJS.Signals | null): {
|
|
37
|
+
reason: string;
|
|
38
|
+
exitCode: number;
|
|
39
|
+
};
|
|
30
40
|
export type IdleExitDecision = "active" | "idle" | "exit";
|
|
31
41
|
/**
|
|
32
42
|
* Pure idle-window decision core. `update()` must be called with the CURRENT
|
|
@@ -1 +1 @@
|
|
|
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,C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AAE,YAAY,GAAG,gBAAgB;CAchD;AAED,MAAM,WAAW,gBAAgB;IAChC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC,kEAAkE;IAClE,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACvC,qFAAqF;IACrF,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,gGAAgG;AAChG,eAAO,MAAM,wBAAwB,mCAAmC,CAAC;AASzE;;;;;;;;;;;;;GAaG;AACH,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,MAAM,EAAE,GAAG,SAAS,CASjG;AAED,sGAAsG;AACtG,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG,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,CA0K/E"}
|
|
@@ -95,6 +95,17 @@ export function resolveHostPolicy(settings, env) {
|
|
|
95
95
|
DEFAULT_HOST_IDLE_EXIT_MS;
|
|
96
96
|
return { coldStart, idleExitMs };
|
|
97
97
|
}
|
|
98
|
+
/**
|
|
99
|
+
* How the supervisor reads its child's exit. The RPC host exits 0 only through
|
|
100
|
+
* its own clean shutdown path - including its idle/empty-host policy - so that
|
|
101
|
+
* is an intentional stop, not a crash: the supervisor mirrors its own idle exit
|
|
102
|
+
* instead of reporting failure. Any non-zero code or signal stays a crash.
|
|
103
|
+
*/
|
|
104
|
+
export function classifyChildExit(code, signal) {
|
|
105
|
+
if (code === 0 && signal === null)
|
|
106
|
+
return { reason: "rpc host exited on its own idle policy", exitCode: 0 };
|
|
107
|
+
return { reason: `rpc host process exited unexpectedly (${code ?? signal})`, exitCode: 1 };
|
|
108
|
+
}
|
|
98
109
|
/**
|
|
99
110
|
* Pure idle-window decision core. `update()` must be called with the CURRENT
|
|
100
111
|
* activity state; the window only counts continuously idle time and any
|
|
@@ -255,8 +266,10 @@ export async function runHostSupervisor(launch) {
|
|
|
255
266
|
// death notification. Errors on it must not crash the supervisor.
|
|
256
267
|
child.stdio[CHILD_WATCH_FD]?.on("error", () => { });
|
|
257
268
|
child.once("exit", (code, signal) => {
|
|
258
|
-
if (
|
|
259
|
-
|
|
269
|
+
if (shuttingDown)
|
|
270
|
+
return;
|
|
271
|
+
const { reason, exitCode } = classifyChildExit(code, signal);
|
|
272
|
+
void shutdown(reason, exitCode);
|
|
260
273
|
});
|
|
261
274
|
const server = createServer((client) => {
|
|
262
275
|
if (shuttingDown) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host-lifecycle.js","sourceRoot":"","sources":["../../../src/modes/rpc/host-lifecycle.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,OAAO,EAAqB,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC9E,OAAO,EAAE,gBAAgB,EAA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,mBAAmB,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC1D,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,eAAe,CAAC,6DAA6D,CAAC,CAAC;QAC/E,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC;IACD,KAAK,iBAAiB,CAAC,MAAM,CAAC,CAAC;AAChC,CAAC","sourcesContent":["#!/usr/bin/env node\n/**\n * Lifecycle supervisor for the shared RPC socket host started by ensureHost().\n *\n * Process tree:\n *\n * ensureHost() ──detached──▶ host-lifecycle.ts (this supervisor, owns the pidfile)\n * │ byte-proxies the public socket\n * ▼\n * cli-main --mode rpc --listen unix://<public>.internal\n *\n * The supervisor exists to enforce the host lifecycle policy without touching the\n * RPC host itself:\n *\n * - cold start: `transient` (default) means the host lives for the current login\n * session and idle-exits; `persistent` never idle-exits.\n * - idle exit: after a continuous window with zero attached client connections\n * and zero active agent turns, the supervisor tears the host down cleanly\n * (child SIGTERM first so the host flushes pending output and removes its own\n * socket, then pidfile/settings removal mirroring ensureHost's cleanupState).\n *\n * Observability without host changes: proxying the public socket yields the\n * exact connection count, and the supervisor keeps one always-on observer\n * connection to the internal socket. The multi-session host broadcasts every\n * session lifecycle/agent event to every connection, so the observer sees\n * `agent_start`/`agent_settled` for all sessions even when no client is\n * attached. If the observer connection is ever unhealthy, activity is reported\n * as unknown (non-idle), so a broken observer can only keep the host alive,\n * never kill it mid-turn.\n *\n * Lifetime binding: the host is spawned with an extra inherited pipe on fd 3\n * whose write end this supervisor holds and never writes to. The kernel closes\n * that end whenever the supervisor dies - including SIGKILL, an OOM kill, or a\n * crash, where no JS handler runs at all - so the host reads EOF and shuts down\n * cleanly, removing the private internal directory. `stopChild()` remains the\n * fast path for orderly shutdowns; the pipe is what makes an orphaned host\n * impossible. `SENPI_RPC_HOST_WATCH_PPID` is passed alongside as a belt-and-\n * braces fallback for platforms where the extra fd is not inherited.\n */\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { realpathSync, writeSync } from \"node:fs\";\nimport { access, chmod, mkdir, readFile, rm, unlink } from \"node:fs/promises\";\nimport { createConnection, createServer, type Server, type Socket } from \"node:net\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { getAgentDir, isBunBinary } from \"../../config.ts\";\nimport { createHostDaemonPaths } from \"./host-ensure.ts\";\nimport {\n\tHOST_CLEANUP_PATHS_ENV,\n\tHOST_SCRATCH_DIR_ENV,\n\tHOST_WATCH_FD_ENV,\n\tHOST_WATCH_PPID_ENV,\n} from \"./host-watchdog.ts\";\nimport { attachJsonlLineReader, MAX_RPC_LINE_CHARACTERS } from \"./jsonl.ts\";\n\nexport type HostColdStart = \"transient\" | \"persistent\";\n\n/** Environment override for the cold-start policy: `transient` or `persistent`. */\nexport const HOST_COLD_START_ENV = \"SENPI_RPC_HOST_COLD_START\";\n/** Environment override for the idle-exit window in milliseconds. */\nexport const HOST_IDLE_EXIT_MS_ENV = \"SENPI_RPC_HOST_IDLE_EXIT_MS\";\n/** Default idle-exit window: 15 minutes of continuous no-connection, no-turn idle. */\nexport const DEFAULT_HOST_IDLE_EXIT_MS = 15 * 60_000;\n\n/** The policy fields ensureHost() records in rpc-host-daemon/settings.json. */\nexport interface HostLifecyclePolicyInput {\n\treadonly coldStart?: HostColdStart;\n\treadonly idleExitMs?: number;\n}\n\nexport interface HostLifecyclePolicy {\n\treadonly coldStart: HostColdStart;\n\treadonly idleExitMs: number;\n}\n\nconst CHILD_STOP_TIMEOUT_MS = 5_000;\n\n/**\n * Child stdio slot carrying the supervisor-lifetime pipe. The supervisor holds\n * the write end open and never writes; the kernel closes it when the supervisor\n * dies for ANY reason (SIGKILL, OOM kill, crash), so the host sees EOF on this\n * fd and shuts itself down. Catchable-signal cleanup alone cannot do this.\n */\nconst CHILD_WATCH_FD = 3;\n\n/**\n * The internal hop must stay short enough for sun_path (104 bytes on macOS)\n * regardless of where the public socket lives, and private against other local\n * users, so it gets its own 0700 directory under the OS temp directory.\n */\nasync function createInternalSocketPath(): Promise<{ socket: string; dir: string }> {\n\tconst dir = join(tmpdir(), `senpi-rpc-host-internal-${randomUUID().slice(0, 8)}`);\n\tawait mkdir(dir, { recursive: false, mode: 0o700 });\n\treturn { socket: join(dir, \"host.sock\"), dir };\n}\n\nexport function parseColdStart(value: string | undefined): HostColdStart | undefined {\n\treturn value === \"transient\" || value === \"persistent\" ? value : undefined;\n}\n\nexport function parseIdleExitMs(value: string | undefined): number | undefined {\n\tif (value === undefined || !/^\\d+$/.test(value.trim())) return undefined;\n\tconst parsed = Number(value.trim());\n\treturn Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n}\n\n/**\n * Resolves the effective host policy. Precedence: environment overrides beat\n * settings.json, which beats the documented defaults (transient, 15 minutes).\n * Invalid values at either source fall through to the next source.\n */\nexport function resolveHostPolicy(\n\tsettings: unknown,\n\tenv: Readonly<Record<string, string | undefined>>,\n): HostLifecyclePolicy {\n\tconst record = isRecord(settings) ? settings : {};\n\tconst coldStart =\n\t\tparseColdStart(env[HOST_COLD_START_ENV]) ?? parseColdStart(asOptionalString(record.coldStart)) ?? \"transient\";\n\tconst idleExitMs =\n\t\tparseIdleExitMs(env[HOST_IDLE_EXIT_MS_ENV]) ??\n\t\tparseIdleExitMs(asOptionalString(record.idleExitMs)) ??\n\t\tDEFAULT_HOST_IDLE_EXIT_MS;\n\treturn { coldStart, idleExitMs };\n}\n\nexport interface HostActivity {\n\treadonly connections: number;\n\treadonly activeTurns: number;\n}\n\nexport type IdleExitDecision = \"active\" | \"idle\" | \"exit\";\n\n/**\n * Pure idle-window decision core. `update()` must be called with the CURRENT\n * activity state; the window only counts continuously idle time and any\n * activity resets it, so a busy host can never cross the threshold.\n */\nexport class IdleExitDecider {\n\tprivate idleSince: number | undefined;\n\tprivate readonly now: () => number;\n\treadonly idleExitMs: number;\n\n\tconstructor(idleExitMs: number, now: () => number = Date.now) {\n\t\tthis.idleExitMs = idleExitMs;\n\t\tthis.now = now;\n\t}\n\n\tupdate(activity: HostActivity): IdleExitDecision {\n\t\t// Any attachment or active turn both holds the host open and resets the\n\t\t// window, so only CONTINUOUS idle can ever cross the threshold.\n\t\tif (activity.connections > 0 || activity.activeTurns > 0) {\n\t\t\tthis.idleSince = undefined;\n\t\t\treturn \"active\";\n\t\t}\n\t\tif (this.idleExitMs === Number.POSITIVE_INFINITY) return \"idle\";\n\t\tif (this.idleSince === undefined) {\n\t\t\tthis.idleSince = this.now();\n\t\t\treturn \"idle\";\n\t\t}\n\t\treturn this.now() - this.idleSince >= this.idleExitMs ? \"exit\" : \"idle\";\n\t}\n}\n\nexport interface SupervisorLaunch {\n\treadonly socket: string;\n\treadonly hostArgs: readonly string[];\n\t/** Optional runtime command used by rebranded/bundled callers. */\n\treadonly childCommand?: string;\n\treadonly childArgs?: readonly string[];\n\t/** Explicit ownership directory for callers whose environment is not yet branded. */\n\treadonly agentDir?: string;\n}\n\n/** Hidden internal launch route: wire-invisible, never advertised by the public CLI surface. */\nexport const INTERNAL_SUPERVISOR_FLAG = \"--internal-rpc-host-supervisor\";\n\n/**\n * Engine-global flags a rebranded wrapper may legitimately prepend when it\n * re-dispatches this binary. `packages/omo-native` injects `--extension <dir>`\n * for every non-early command, which pushed the sentinel off argv[0].\n */\nconst INJECTABLE_PREFIX_FLAGS = new Set([\"--extension\"]);\n\n/**\n * Returns the internal supervisor payload when argv selects that route.\n *\n * The route dispatches when the sentinel is argv[0] OR is preceded only by\n * known injectable prefix flags and their values - the one perturbation\n * wrappers legitimately perform. Everything else disqualifies it: a positional\n * operand, `--`, or an unknown flag before the sentinel all return undefined,\n * so a user-supplied value that happens to equal the sentinel can never reach\n * the supervisor.\n *\n * The skipped prefix is deliberately NOT forwarded to the host: a wrapper\n * re-injects its own prefix on every re-entry, so the host child receives it\n * from the wrapper rather than twice from here.\n */\nexport function findInternalSupervisorArgs(argv: readonly string[]): readonly string[] | undefined {\n\tfor (let index = 0; index < argv.length; index++) {\n\t\tconst arg = argv[index];\n\t\tif (arg === INTERNAL_SUPERVISOR_FLAG) return argv.slice(index + 1);\n\t\t// A prefix flag only counts when its value is actually present.\n\t\tif (!INJECTABLE_PREFIX_FLAGS.has(arg) || index + 1 >= argv.length) return undefined;\n\t\tindex++;\n\t}\n\treturn undefined;\n}\n\n/** `--socket <path>` selects the public socket; every other argument is forwarded to the host CLI. */\nexport function parseSupervisorArgs(argv: readonly string[]): SupervisorLaunch | undefined {\n\tconst hostArgs: string[] = [];\n\tlet socket: string | undefined;\n\tlet childCommand: string | undefined;\n\tlet childArgs: readonly string[] | undefined;\n\tlet agentDir: string | undefined;\n\tfor (let index = 0; index < argv.length; index++) {\n\t\tconst arg = argv[index];\n\t\tif (arg === \"--socket\" && index + 1 < argv.length) {\n\t\t\tsocket = argv[++index];\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--child-command\" && index + 1 < argv.length) {\n\t\t\tchildCommand = argv[++index];\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--child-args\" && index + 1 < argv.length) {\n\t\t\ttry {\n\t\t\t\tconst parsed: unknown = JSON.parse(argv[++index]);\n\t\t\t\tif (Array.isArray(parsed) && parsed.every((value) => typeof value === \"string\")) childArgs = parsed;\n\t\t\t} catch {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--agent-dir\" && index + 1 < argv.length) {\n\t\t\tagentDir = argv[++index];\n\t\t\tcontinue;\n\t\t}\n\t\thostArgs.push(arg);\n\t}\n\treturn socket === undefined ? undefined : { socket, hostArgs, childCommand, childArgs, agentDir };\n}\n\n/** Resolves the committed CLI entry this supervisor wraps (source tree or built dist). */\nexport function resolveCliMainPath(): string {\n\tconst modulePath = fileURLToPath(import.meta.url);\n\tconst extension = modulePath.endsWith(\".ts\") ? \".ts\" : \".js\";\n\treturn resolve(dirname(modulePath), \"..\", \"..\", `cli-main${extension}`);\n}\n\n/**\n * Resolves the host child spawn. Explicit child commands (desktop launchers)\n * are forwarded untouched. The default re-enters the committed CLI entry\n * through the runtime, except in compiled standalone binaries, which always\n * boot their embedded entrypoint and would parse a script path as CLI\n * arguments - there the executable itself is the CLI, so the mode flags are\n * passed directly. Exported for tests.\n */\nexport function resolveHostChildLaunch(\n\tlaunch: SupervisorLaunch,\n\tinternalSocket: string,\n\tcompiled: boolean = isBunBinary,\n): { command: string; args: string[] } {\n\tif (launch.childCommand) {\n\t\treturn {\n\t\t\tcommand: launch.childCommand,\n\t\t\targs: [...(launch.childArgs ?? []), \"--listen\", `unix://${internalSocket}`],\n\t\t};\n\t}\n\treturn {\n\t\tcommand: process.execPath,\n\t\targs: [\n\t\t\t...(compiled ? [] : [...process.execArgv, resolveCliMainPath()]),\n\t\t\t\"--mode\",\n\t\t\t\"rpc\",\n\t\t\t\"--multi-session\",\n\t\t\t\"--listen\",\n\t\t\t`unix://${internalSocket}`,\n\t\t\t...launch.hostArgs,\n\t\t],\n\t};\n}\n\nexport async function runHostSupervisor(launch: SupervisorLaunch): Promise<void> {\n\tconst paths = createHostDaemonPaths(launch.agentDir ?? getAgentDir());\n\tconst policy = resolveHostPolicy(await readSettingsFile(paths.settingsFile), process.env);\n\tconst publicSocket = launch.socket;\n\tconst internal = await createInternalSocketPath();\n\tconst internalSocket = internal.socket;\n\tconst clientSockets = new Set<Socket>();\n\tconst busySessions = new Map<string, number>();\n\tlet observerHealthy = false;\n\tlet observerReconnectTimer: ReturnType<typeof setTimeout> | undefined;\n\tlet shuttingDown = false;\n\tlet shutdownPromise: Promise<never> | undefined;\n\n\tconst childLaunch = resolveHostChildLaunch(launch, internalSocket);\n\tconst child = spawn(childLaunch.command, childLaunch.args, {\n\t\tenv: {\n\t\t\t...process.env,\n\t\t\t...(launch.agentDir ? { SENPI_CODING_AGENT_DIR: launch.agentDir } : {}),\n\t\t\t[HOST_WATCH_FD_ENV]: String(CHILD_WATCH_FD),\n\t\t\t[HOST_WATCH_PPID_ENV]: String(process.pid),\n\t\t\t[HOST_SCRATCH_DIR_ENV]: internal.dir,\n\t\t\t[HOST_CLEANUP_PATHS_ENV]: [publicSocket, paths.pidFile, paths.settingsFile].join(\"\\n\"),\n\t\t},\n\t\t// Slot 3 is the lifetime pipe: \"pipe\" gives the child a read end it can\n\t\t// wait on and keeps the write end owned by this process alone.\n\t\tstdio: [\"ignore\", \"ignore\", \"inherit\", \"pipe\"],\n\t});\n\t// Nothing is ever written; the pipe exists purely so its EOF is a reliable\n\t// death notification. Errors on it must not crash the supervisor.\n\tchild.stdio[CHILD_WATCH_FD]?.on(\"error\", () => {});\n\tchild.once(\"exit\", (code, signal) => {\n\t\tif (!shuttingDown) void shutdown(`rpc host process exited unexpectedly (${code ?? signal})`, 1);\n\t});\n\n\tconst server = createServer((client) => {\n\t\tif (shuttingDown) {\n\t\t\tclient.destroy();\n\t\t\treturn;\n\t\t}\n\t\tconst internal = createConnection(internalSocket);\n\t\tclientSockets.add(client);\n\t\tconst detach = (): void => {\n\t\t\tclientSockets.delete(client);\n\t\t\tinternal.destroy();\n\t\t\tclient.destroy();\n\t\t};\n\t\tclient.pipe(internal);\n\t\tinternal.pipe(client);\n\t\tclient.once(\"close\", detach);\n\t\tclient.once(\"error\", detach);\n\t\tinternal.once(\"close\", detach);\n\t\tinternal.once(\"error\", detach);\n\t});\n\tserver.once(\"error\", (cause) => {\n\t\tif (!shuttingDown) void shutdown(`public socket listener failed: ${errorMessage(cause)}`, 1);\n\t});\n\n\tconst decider = new IdleExitDecider(\n\t\tpolicy.coldStart === \"persistent\" ? Number.POSITIVE_INFINITY : policy.idleExitMs,\n\t);\n\tconst tickIntervalMs = Math.max(20, Math.min(1_000, policy.idleExitMs / 4));\n\tconst ticker = setInterval(() => {\n\t\tif (decider.update(currentActivity()) === \"exit\") void shutdown(\"idle\", 0);\n\t}, tickIntervalMs);\n\n\tfunction currentActivity(): HostActivity {\n\t\treturn {\n\t\t\tconnections: clientSockets.size,\n\t\t\tactiveTurns: observerHealthy ? countBusySessions() : 1,\n\t\t};\n\t}\n\n\tfunction countBusySessions(): number {\n\t\tlet busy = 0;\n\t\tfor (const count of busySessions.values()) if (count > 0) busy++;\n\t\treturn busy;\n\t}\n\n\tfunction observeHostEvent(line: string): void {\n\t\tlet event: unknown;\n\t\ttry {\n\t\t\tevent = JSON.parse(line);\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tif (typeof event !== \"object\" || event === null) return;\n\t\tconst { type, sessionId } = event as { type?: unknown; sessionId?: unknown };\n\t\tif (typeof sessionId !== \"string\") return;\n\t\tif (type === \"agent_start\") busySessions.set(sessionId, (busySessions.get(sessionId) ?? 0) + 1);\n\t\telse if (type === \"agent_settled\")\n\t\t\tbusySessions.set(sessionId, Math.max(0, (busySessions.get(sessionId) ?? 1) - 1));\n\t}\n\n\tasync function shutdown(reason: string, exitCode: number): Promise<never> {\n\t\t// Single-flight: concurrent triggers (listener error, child exit, signals)\n\t\t// must not process.exit mid-cleanup. Late callers park on this promise while\n\t\t// the first shutdown finishes tearing down and exits.\n\t\tshutdownPromise ??= performShutdown(reason, exitCode);\n\t\treturn shutdownPromise;\n\t}\n\n\tasync function performShutdown(reason: string, exitCode: number): Promise<never> {\n\t\tif (shuttingDown) process.exit(exitCode);\n\t\tshuttingDown = true;\n\t\tclearInterval(ticker);\n\t\twriteStderrLine(`senpi rpc host supervisor: ${reason} shutdown`);\n\t\tfor (const client of clientSockets) client.destroy();\n\t\tawait closeServer(server);\n\t\t// Unlink the private directory BEFORE the child stop, which can take seconds:\n\t\t// an external SIGKILL landing during that wait (ensureHost escalates while\n\t\t// replacing a host) would otherwise leave the directory behind. The child\n\t\t// keeps serving through its already-open socket fd until it exits, and its\n\t\t// own watchdog cleanup makes the removal idempotent.\n\t\tawait rm(internal.dir, { recursive: true, force: true });\n\t\tawait stopChild(child);\n\t\tobserver?.destroy();\n\t\tif (publicSocketOwned) await rm(publicSocket, { force: true });\n\t\t// Mirror ensureHost's cleanupState: the pidfile and settings describe a\n\t\t// live host only; the stderr log stays for diagnostics.\n\t\tawait rm(paths.pidFile, { force: true });\n\t\tawait rm(paths.settingsFile, { force: true });\n\t\tprocess.exit(exitCode);\n\t}\n\n\tlet observer: Socket | undefined;\n\tlet publicSocketOwned = false;\n\t// Registered before the startup handshake, not after it: the private internal\n\t// directory already exists at this point, so a SIGTERM arriving during host\n\t// startup must run the same cleanup instead of Node's default kill, which\n\t// would leave that directory behind.\n\tregisterSupervisorSignals(shutdown);\n\ttry {\n\t\tawait waitForListener(internalSocket, 30_000);\n\t\tawait connectObserver();\n\t\tawait prepareSocketPath(publicSocket);\n\t\tawait listen(server, publicSocket);\n\t\tpublicSocketOwned = true;\n\t} catch (cause) {\n\t\tawait shutdown(`startup failed: ${errorMessage(cause)}`, 1);\n\t}\n\tasync function connectObserver(): Promise<void> {\n\t\tconst next = createConnection(internalSocket);\n\t\tawait waitForConnect(next, 5_000);\n\t\tobserver = next;\n\t\tobserverHealthy = true;\n\t\tattachJsonlLineReader(next, observeHostEvent, { maxLineLength: MAX_RPC_LINE_CHARACTERS });\n\t\tconst lost = (): void => {\n\t\t\tif (observer !== next || shuttingDown) return;\n\t\t\tobserverHealthy = false;\n\t\t\tobserver = undefined;\n\t\t\tif (observerReconnectTimer === undefined) {\n\t\t\t\tobserverReconnectTimer = setTimeout(() => {\n\t\t\t\t\tobserverReconnectTimer = undefined;\n\t\t\t\t\tvoid connectObserver().catch(() => lost());\n\t\t\t\t}, 250);\n\t\t\t\tobserverReconnectTimer.unref?.();\n\t\t\t}\n\t\t};\n\t\tnext.once(\"close\", lost);\n\t\tnext.once(\"error\", lost);\n\t}\n\n\twriteStderrLine(\n\t\t`senpi rpc host ready on unix://${publicSocket} (coldStart=${policy.coldStart}, idleExitMs=${\n\t\t\tpolicy.coldStart === \"persistent\" ? \"never\" : String(policy.idleExitMs)\n\t\t})`,\n\t);\n\tawait new Promise<never>(() => {});\n}\n\n/** External stop (ensureHost replacement, tests, QA) must clean up like idle exit. */\nfunction registerSupervisorSignals(shutdown: (reason: string, exitCode: number) => Promise<never>): void {\n\tfor (const signal of process.platform === \"win32\" ? ([\"SIGTERM\"] as const) : ([\"SIGTERM\", \"SIGHUP\"] as const)) {\n\t\tprocess.on(signal, () => {\n\t\t\tvoid shutdown(`signal:${signal}`, signal === \"SIGHUP\" ? 129 : 143);\n\t\t});\n\t}\n}\n\nasync function readSettingsFile(settingsFile: string): Promise<unknown> {\n\ttry {\n\t\treturn JSON.parse(await readFile(settingsFile, \"utf8\"));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nasync function stopChild(child: ChildProcess): Promise<void> {\n\tif (child.exitCode !== null || child.signalCode !== null) return;\n\ttry {\n\t\tchild.kill(\"SIGTERM\");\n\t} catch {\n\t\treturn;\n\t}\n\tif (await waitForChildExit(child, CHILD_STOP_TIMEOUT_MS)) return;\n\ttry {\n\t\tchild.kill(\"SIGKILL\");\n\t} catch {\n\t\treturn;\n\t}\n\tawait waitForChildExit(child, 2_000);\n}\n\nfunction waitForChildExit(child: ChildProcess, timeoutMs: number): Promise<boolean> {\n\tif (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);\n\treturn new Promise((resolve) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tchild.off(\"exit\", onExit);\n\t\t\tresolve(false);\n\t\t}, timeoutMs);\n\t\tconst onExit = (): void => {\n\t\t\tclearTimeout(timer);\n\t\t\tresolve(true);\n\t\t};\n\t\tchild.once(\"exit\", onExit);\n\t});\n}\n\nasync function waitForListener(socketPath: string, timeoutMs: number): Promise<void> {\n\tconst deadline = Date.now() + timeoutMs;\n\twhile (Date.now() <= deadline) {\n\t\tif (await canConnect(socketPath)) return;\n\t\tawait delay(50);\n\t}\n\tthrow new Error(`${socketPath}: host did not start listening within ${timeoutMs}ms`);\n}\n\nfunction canConnect(socketPath: string): Promise<boolean> {\n\treturn new Promise((resolve) => {\n\t\tconst socket = createConnection(socketPath);\n\t\tconst settle = (value: boolean): void => {\n\t\t\tsocket.destroy();\n\t\t\tresolve(value);\n\t\t};\n\t\tsocket.once(\"connect\", () => settle(true));\n\t\tsocket.once(\"error\", () => settle(false));\n\t});\n}\n\nfunction waitForConnect(socket: Socket, timeoutMs: number): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tcleanup();\n\t\t\treject(new Error(`observer connection to internal host timed out after ${timeoutMs}ms`));\n\t\t}, timeoutMs);\n\t\tconst onConnect = (): void => {\n\t\t\tcleanup();\n\t\t\tresolve();\n\t\t};\n\t\tconst onError = (cause: Error): void => {\n\t\t\tcleanup();\n\t\t\treject(cause);\n\t\t};\n\t\tconst cleanup = (): void => {\n\t\t\tclearTimeout(timer);\n\t\t\tsocket.off(\"connect\", onConnect);\n\t\t\tsocket.off(\"error\", onError);\n\t\t};\n\t\tsocket.once(\"connect\", onConnect);\n\t\tsocket.once(\"error\", onError);\n\t});\n}\n\nasync function prepareSocketPath(socketPath: string): Promise<void> {\n\tawait mkdir(dirname(socketPath), { recursive: true, mode: 0o700 });\n\ttry {\n\t\tawait access(socketPath);\n\t} catch (cause) {\n\t\tif (isNodeErrorCode(cause, \"ENOENT\")) return;\n\t\tthrow cause;\n\t}\n\tif (await canConnect(socketPath)) throw new Error(`${socketPath}: address already in use by a live server.`);\n\tawait unlink(socketPath);\n}\n\nfunction listen(server: Server, socketPath: string): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(socketPath, async () => {\n\t\t\tserver.off(\"error\", reject);\n\t\t\tif (!socketPath.startsWith(\"\\0\")) await chmod(socketPath, 0o600);\n\t\t\tresolve();\n\t\t});\n\t});\n}\n\nfunction closeServer(server: Server): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tserver.close(() => resolve());\n\t});\n}\n\nfunction writeStderrLine(text: string): void {\n\t// A detached daemon exiting right after an async stderr.write to a file can\n\t// lose the output entirely; write synchronously so diagnostics always land.\n\ttry {\n\t\twriteSync(2, `${text}\\n`);\n\t} catch {\n\t\t/* fd 2 unavailable: nothing more we can do. */\n\t}\n}\n\nfunction delay(ms: number): Promise<void> {\n\treturn new Promise((resolveDelay) => setTimeout(resolveDelay, ms));\n}\n\nfunction errorMessage(cause: unknown): string {\n\treturn cause instanceof Error ? cause.message : String(cause);\n}\n\nfunction isNodeErrorCode(cause: unknown, code: string): boolean {\n\treturn cause instanceof Error && \"code\" in cause && cause.code === code;\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 asOptionalString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : typeof value === \"number\" ? String(value) : undefined;\n}\n\nfunction isEntryScript(): boolean {\n\tconst entry = process.argv[1];\n\tif (!entry) return false;\n\ttry {\n\t\treturn fileURLToPath(import.meta.url) === realpathSync(entry);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nif (isEntryScript()) {\n\tconst launch = parseSupervisorArgs(process.argv.slice(2));\n\tif (!launch) {\n\t\twriteStderrLine(\"usage: host-lifecycle.ts --socket <path> [host cli args...]\");\n\t\tprocess.exit(2);\n\t}\n\tvoid runHostSupervisor(launch);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"host-lifecycle.js","sourceRoot":"","sources":["../../../src/modes/rpc/host-lifecycle.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,OAAO,EAAqB,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC9E,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AC,CAAC,SAAS,CAAC;AAClG,CAAC;AAED,SAAS,aAAa;IACrB,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC9B,IAAI,CAAC,KAAK;QAAE,OAAO,KAAK,CAAC;IACzB,IAAI,CAAC;QACJ,OAAO,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,YAAY,CAAC,KAAK,CAAC,CAAC;IAC/D,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,KAAK,CAAC;IACd,CAAC;AACF,CAAC;AAED,IAAI,aAAa,EAAE,EAAE,CAAC;IACrB,MAAM,MAAM,GAAG,mBAAmB,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC1D,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,eAAe,CAAC,6DAA6D,CAAC,CAAC;QAC/E,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC;IACD,KAAK,iBAAiB,CAAC,MAAM,CAAC,CAAC;AAChC,CAAC","sourcesContent":["#!/usr/bin/env node\n/**\n * Lifecycle supervisor for the shared RPC socket host started by ensureHost().\n *\n * Process tree:\n *\n * ensureHost() ──detached──▶ host-lifecycle.ts (this supervisor, owns the pidfile)\n * │ byte-proxies the public socket\n * ▼\n * cli-main --mode rpc --listen unix://<public>.internal\n *\n * The supervisor exists to enforce the host lifecycle policy without touching the\n * RPC host itself:\n *\n * - cold start: `transient` (default) means the host lives for the current login\n * session and idle-exits; `persistent` never idle-exits.\n * - idle exit: after a continuous window with zero attached client connections\n * and zero active agent turns, the supervisor tears the host down cleanly\n * (child SIGTERM first so the host flushes pending output and removes its own\n * socket, then pidfile/settings removal mirroring ensureHost's cleanupState).\n *\n * Observability without host changes: proxying the public socket yields the\n * exact connection count, and the supervisor keeps one always-on observer\n * connection to the internal socket. The multi-session host broadcasts every\n * session lifecycle/agent event to every connection, so the observer sees\n * `agent_start`/`agent_settled` for all sessions even when no client is\n * attached. If the observer connection is ever unhealthy, activity is reported\n * as unknown (non-idle), so a broken observer can only keep the host alive,\n * never kill it mid-turn.\n *\n * Lifetime binding: the host is spawned with an extra inherited pipe on fd 3\n * whose write end this supervisor holds and never writes to. The kernel closes\n * that end whenever the supervisor dies - including SIGKILL, an OOM kill, or a\n * crash, where no JS handler runs at all - so the host reads EOF and shuts down\n * cleanly, removing the private internal directory. `stopChild()` remains the\n * fast path for orderly shutdowns; the pipe is what makes an orphaned host\n * impossible. `SENPI_RPC_HOST_WATCH_PPID` is passed alongside as a belt-and-\n * braces fallback for platforms where the extra fd is not inherited.\n */\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { realpathSync, writeSync } from \"node:fs\";\nimport { access, chmod, mkdir, readFile, rm, unlink } from \"node:fs/promises\";\nimport { createConnection, createServer, type Server, type Socket } from \"node:net\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { getAgentDir, isBunBinary } from \"../../config.ts\";\nimport { createHostDaemonPaths } from \"./host-ensure.ts\";\nimport {\n\tHOST_CLEANUP_PATHS_ENV,\n\tHOST_SCRATCH_DIR_ENV,\n\tHOST_WATCH_FD_ENV,\n\tHOST_WATCH_PPID_ENV,\n} from \"./host-watchdog.ts\";\nimport { attachJsonlLineReader, MAX_RPC_LINE_CHARACTERS } from \"./jsonl.ts\";\n\nexport type HostColdStart = \"transient\" | \"persistent\";\n\n/** Environment override for the cold-start policy: `transient` or `persistent`. */\nexport const HOST_COLD_START_ENV = \"SENPI_RPC_HOST_COLD_START\";\n/** Environment override for the idle-exit window in milliseconds. */\nexport const HOST_IDLE_EXIT_MS_ENV = \"SENPI_RPC_HOST_IDLE_EXIT_MS\";\n/** Default idle-exit window: 15 minutes of continuous no-connection, no-turn idle. */\nexport const DEFAULT_HOST_IDLE_EXIT_MS = 15 * 60_000;\n\n/** The policy fields ensureHost() records in rpc-host-daemon/settings.json. */\nexport interface HostLifecyclePolicyInput {\n\treadonly coldStart?: HostColdStart;\n\treadonly idleExitMs?: number;\n}\n\nexport interface HostLifecyclePolicy {\n\treadonly coldStart: HostColdStart;\n\treadonly idleExitMs: number;\n}\n\nconst CHILD_STOP_TIMEOUT_MS = 5_000;\n\n/**\n * Child stdio slot carrying the supervisor-lifetime pipe. The supervisor holds\n * the write end open and never writes; the kernel closes it when the supervisor\n * dies for ANY reason (SIGKILL, OOM kill, crash), so the host sees EOF on this\n * fd and shuts itself down. Catchable-signal cleanup alone cannot do this.\n */\nconst CHILD_WATCH_FD = 3;\n\n/**\n * The internal hop must stay short enough for sun_path (104 bytes on macOS)\n * regardless of where the public socket lives, and private against other local\n * users, so it gets its own 0700 directory under the OS temp directory.\n */\nasync function createInternalSocketPath(): Promise<{ socket: string; dir: string }> {\n\tconst dir = join(tmpdir(), `senpi-rpc-host-internal-${randomUUID().slice(0, 8)}`);\n\tawait mkdir(dir, { recursive: false, mode: 0o700 });\n\treturn { socket: join(dir, \"host.sock\"), dir };\n}\n\nexport function parseColdStart(value: string | undefined): HostColdStart | undefined {\n\treturn value === \"transient\" || value === \"persistent\" ? value : undefined;\n}\n\nexport function parseIdleExitMs(value: string | undefined): number | undefined {\n\tif (value === undefined || !/^\\d+$/.test(value.trim())) return undefined;\n\tconst parsed = Number(value.trim());\n\treturn Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n}\n\n/**\n * Resolves the effective host policy. Precedence: environment overrides beat\n * settings.json, which beats the documented defaults (transient, 15 minutes).\n * Invalid values at either source fall through to the next source.\n */\nexport function resolveHostPolicy(\n\tsettings: unknown,\n\tenv: Readonly<Record<string, string | undefined>>,\n): HostLifecyclePolicy {\n\tconst record = isRecord(settings) ? settings : {};\n\tconst coldStart =\n\t\tparseColdStart(env[HOST_COLD_START_ENV]) ?? parseColdStart(asOptionalString(record.coldStart)) ?? \"transient\";\n\tconst idleExitMs =\n\t\tparseIdleExitMs(env[HOST_IDLE_EXIT_MS_ENV]) ??\n\t\tparseIdleExitMs(asOptionalString(record.idleExitMs)) ??\n\t\tDEFAULT_HOST_IDLE_EXIT_MS;\n\treturn { coldStart, idleExitMs };\n}\n\nexport interface HostActivity {\n\treadonly connections: number;\n\treadonly activeTurns: number;\n}\n\n/**\n * How the supervisor reads its child's exit. The RPC host exits 0 only through\n * its own clean shutdown path - including its idle/empty-host policy - so that\n * is an intentional stop, not a crash: the supervisor mirrors its own idle exit\n * instead of reporting failure. Any non-zero code or signal stays a crash.\n */\nexport function classifyChildExit(\n\tcode: number | null,\n\tsignal: NodeJS.Signals | null,\n): { reason: string; exitCode: number } {\n\tif (code === 0 && signal === null) return { reason: \"rpc host exited on its own idle policy\", exitCode: 0 };\n\treturn { reason: `rpc host process exited unexpectedly (${code ?? signal})`, exitCode: 1 };\n}\n\nexport type IdleExitDecision = \"active\" | \"idle\" | \"exit\";\n\n/**\n * Pure idle-window decision core. `update()` must be called with the CURRENT\n * activity state; the window only counts continuously idle time and any\n * activity resets it, so a busy host can never cross the threshold.\n */\nexport class IdleExitDecider {\n\tprivate idleSince: number | undefined;\n\tprivate readonly now: () => number;\n\treadonly idleExitMs: number;\n\n\tconstructor(idleExitMs: number, now: () => number = Date.now) {\n\t\tthis.idleExitMs = idleExitMs;\n\t\tthis.now = now;\n\t}\n\n\tupdate(activity: HostActivity): IdleExitDecision {\n\t\t// Any attachment or active turn both holds the host open and resets the\n\t\t// window, so only CONTINUOUS idle can ever cross the threshold.\n\t\tif (activity.connections > 0 || activity.activeTurns > 0) {\n\t\t\tthis.idleSince = undefined;\n\t\t\treturn \"active\";\n\t\t}\n\t\tif (this.idleExitMs === Number.POSITIVE_INFINITY) return \"idle\";\n\t\tif (this.idleSince === undefined) {\n\t\t\tthis.idleSince = this.now();\n\t\t\treturn \"idle\";\n\t\t}\n\t\treturn this.now() - this.idleSince >= this.idleExitMs ? \"exit\" : \"idle\";\n\t}\n}\n\nexport interface SupervisorLaunch {\n\treadonly socket: string;\n\treadonly hostArgs: readonly string[];\n\t/** Optional runtime command used by rebranded/bundled callers. */\n\treadonly childCommand?: string;\n\treadonly childArgs?: readonly string[];\n\t/** Explicit ownership directory for callers whose environment is not yet branded. */\n\treadonly agentDir?: string;\n}\n\n/** Hidden internal launch route: wire-invisible, never advertised by the public CLI surface. */\nexport const INTERNAL_SUPERVISOR_FLAG = \"--internal-rpc-host-supervisor\";\n\n/**\n * Engine-global flags a rebranded wrapper may legitimately prepend when it\n * re-dispatches this binary. `packages/omo-native` injects `--extension <dir>`\n * for every non-early command, which pushed the sentinel off argv[0].\n */\nconst INJECTABLE_PREFIX_FLAGS = new Set([\"--extension\"]);\n\n/**\n * Returns the internal supervisor payload when argv selects that route.\n *\n * The route dispatches when the sentinel is argv[0] OR is preceded only by\n * known injectable prefix flags and their values - the one perturbation\n * wrappers legitimately perform. Everything else disqualifies it: a positional\n * operand, `--`, or an unknown flag before the sentinel all return undefined,\n * so a user-supplied value that happens to equal the sentinel can never reach\n * the supervisor.\n *\n * The skipped prefix is deliberately NOT forwarded to the host: a wrapper\n * re-injects its own prefix on every re-entry, so the host child receives it\n * from the wrapper rather than twice from here.\n */\nexport function findInternalSupervisorArgs(argv: readonly string[]): readonly string[] | undefined {\n\tfor (let index = 0; index < argv.length; index++) {\n\t\tconst arg = argv[index];\n\t\tif (arg === INTERNAL_SUPERVISOR_FLAG) return argv.slice(index + 1);\n\t\t// A prefix flag only counts when its value is actually present.\n\t\tif (!INJECTABLE_PREFIX_FLAGS.has(arg) || index + 1 >= argv.length) return undefined;\n\t\tindex++;\n\t}\n\treturn undefined;\n}\n\n/** `--socket <path>` selects the public socket; every other argument is forwarded to the host CLI. */\nexport function parseSupervisorArgs(argv: readonly string[]): SupervisorLaunch | undefined {\n\tconst hostArgs: string[] = [];\n\tlet socket: string | undefined;\n\tlet childCommand: string | undefined;\n\tlet childArgs: readonly string[] | undefined;\n\tlet agentDir: string | undefined;\n\tfor (let index = 0; index < argv.length; index++) {\n\t\tconst arg = argv[index];\n\t\tif (arg === \"--socket\" && index + 1 < argv.length) {\n\t\t\tsocket = argv[++index];\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--child-command\" && index + 1 < argv.length) {\n\t\t\tchildCommand = argv[++index];\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--child-args\" && index + 1 < argv.length) {\n\t\t\ttry {\n\t\t\t\tconst parsed: unknown = JSON.parse(argv[++index]);\n\t\t\t\tif (Array.isArray(parsed) && parsed.every((value) => typeof value === \"string\")) childArgs = parsed;\n\t\t\t} catch {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--agent-dir\" && index + 1 < argv.length) {\n\t\t\tagentDir = argv[++index];\n\t\t\tcontinue;\n\t\t}\n\t\thostArgs.push(arg);\n\t}\n\treturn socket === undefined ? undefined : { socket, hostArgs, childCommand, childArgs, agentDir };\n}\n\n/** Resolves the committed CLI entry this supervisor wraps (source tree or built dist). */\nexport function resolveCliMainPath(): string {\n\tconst modulePath = fileURLToPath(import.meta.url);\n\tconst extension = modulePath.endsWith(\".ts\") ? \".ts\" : \".js\";\n\treturn resolve(dirname(modulePath), \"..\", \"..\", `cli-main${extension}`);\n}\n\n/**\n * Resolves the host child spawn. Explicit child commands (desktop launchers)\n * are forwarded untouched. The default re-enters the committed CLI entry\n * through the runtime, except in compiled standalone binaries, which always\n * boot their embedded entrypoint and would parse a script path as CLI\n * arguments - there the executable itself is the CLI, so the mode flags are\n * passed directly. Exported for tests.\n */\nexport function resolveHostChildLaunch(\n\tlaunch: SupervisorLaunch,\n\tinternalSocket: string,\n\tcompiled: boolean = isBunBinary,\n): { command: string; args: string[] } {\n\tif (launch.childCommand) {\n\t\treturn {\n\t\t\tcommand: launch.childCommand,\n\t\t\targs: [...(launch.childArgs ?? []), \"--listen\", `unix://${internalSocket}`],\n\t\t};\n\t}\n\treturn {\n\t\tcommand: process.execPath,\n\t\targs: [\n\t\t\t...(compiled ? [] : [...process.execArgv, resolveCliMainPath()]),\n\t\t\t\"--mode\",\n\t\t\t\"rpc\",\n\t\t\t\"--multi-session\",\n\t\t\t\"--listen\",\n\t\t\t`unix://${internalSocket}`,\n\t\t\t...launch.hostArgs,\n\t\t],\n\t};\n}\n\nexport async function runHostSupervisor(launch: SupervisorLaunch): Promise<void> {\n\tconst paths = createHostDaemonPaths(launch.agentDir ?? getAgentDir());\n\tconst policy = resolveHostPolicy(await readSettingsFile(paths.settingsFile), process.env);\n\tconst publicSocket = launch.socket;\n\tconst internal = await createInternalSocketPath();\n\tconst internalSocket = internal.socket;\n\tconst clientSockets = new Set<Socket>();\n\tconst busySessions = new Map<string, number>();\n\tlet observerHealthy = false;\n\tlet observerReconnectTimer: ReturnType<typeof setTimeout> | undefined;\n\tlet shuttingDown = false;\n\tlet shutdownPromise: Promise<never> | undefined;\n\n\tconst childLaunch = resolveHostChildLaunch(launch, internalSocket);\n\tconst child = spawn(childLaunch.command, childLaunch.args, {\n\t\tenv: {\n\t\t\t...process.env,\n\t\t\t...(launch.agentDir ? { SENPI_CODING_AGENT_DIR: launch.agentDir } : {}),\n\t\t\t[HOST_WATCH_FD_ENV]: String(CHILD_WATCH_FD),\n\t\t\t[HOST_WATCH_PPID_ENV]: String(process.pid),\n\t\t\t[HOST_SCRATCH_DIR_ENV]: internal.dir,\n\t\t\t[HOST_CLEANUP_PATHS_ENV]: [publicSocket, paths.pidFile, paths.settingsFile].join(\"\\n\"),\n\t\t},\n\t\t// Slot 3 is the lifetime pipe: \"pipe\" gives the child a read end it can\n\t\t// wait on and keeps the write end owned by this process alone.\n\t\tstdio: [\"ignore\", \"ignore\", \"inherit\", \"pipe\"],\n\t});\n\t// Nothing is ever written; the pipe exists purely so its EOF is a reliable\n\t// death notification. Errors on it must not crash the supervisor.\n\tchild.stdio[CHILD_WATCH_FD]?.on(\"error\", () => {});\n\tchild.once(\"exit\", (code, signal) => {\n\t\tif (shuttingDown) return;\n\t\tconst { reason, exitCode } = classifyChildExit(code, signal);\n\t\tvoid shutdown(reason, exitCode);\n\t});\n\n\tconst server = createServer((client) => {\n\t\tif (shuttingDown) {\n\t\t\tclient.destroy();\n\t\t\treturn;\n\t\t}\n\t\tconst internal = createConnection(internalSocket);\n\t\tclientSockets.add(client);\n\t\tconst detach = (): void => {\n\t\t\tclientSockets.delete(client);\n\t\t\tinternal.destroy();\n\t\t\tclient.destroy();\n\t\t};\n\t\tclient.pipe(internal);\n\t\tinternal.pipe(client);\n\t\tclient.once(\"close\", detach);\n\t\tclient.once(\"error\", detach);\n\t\tinternal.once(\"close\", detach);\n\t\tinternal.once(\"error\", detach);\n\t});\n\tserver.once(\"error\", (cause) => {\n\t\tif (!shuttingDown) void shutdown(`public socket listener failed: ${errorMessage(cause)}`, 1);\n\t});\n\n\tconst decider = new IdleExitDecider(\n\t\tpolicy.coldStart === \"persistent\" ? Number.POSITIVE_INFINITY : policy.idleExitMs,\n\t);\n\tconst tickIntervalMs = Math.max(20, Math.min(1_000, policy.idleExitMs / 4));\n\tconst ticker = setInterval(() => {\n\t\tif (decider.update(currentActivity()) === \"exit\") void shutdown(\"idle\", 0);\n\t}, tickIntervalMs);\n\n\tfunction currentActivity(): HostActivity {\n\t\treturn {\n\t\t\tconnections: clientSockets.size,\n\t\t\tactiveTurns: observerHealthy ? countBusySessions() : 1,\n\t\t};\n\t}\n\n\tfunction countBusySessions(): number {\n\t\tlet busy = 0;\n\t\tfor (const count of busySessions.values()) if (count > 0) busy++;\n\t\treturn busy;\n\t}\n\n\tfunction observeHostEvent(line: string): void {\n\t\tlet event: unknown;\n\t\ttry {\n\t\t\tevent = JSON.parse(line);\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tif (typeof event !== \"object\" || event === null) return;\n\t\tconst { type, sessionId } = event as { type?: unknown; sessionId?: unknown };\n\t\tif (typeof sessionId !== \"string\") return;\n\t\tif (type === \"agent_start\") busySessions.set(sessionId, (busySessions.get(sessionId) ?? 0) + 1);\n\t\telse if (type === \"agent_settled\")\n\t\t\tbusySessions.set(sessionId, Math.max(0, (busySessions.get(sessionId) ?? 1) - 1));\n\t}\n\n\tasync function shutdown(reason: string, exitCode: number): Promise<never> {\n\t\t// Single-flight: concurrent triggers (listener error, child exit, signals)\n\t\t// must not process.exit mid-cleanup. Late callers park on this promise while\n\t\t// the first shutdown finishes tearing down and exits.\n\t\tshutdownPromise ??= performShutdown(reason, exitCode);\n\t\treturn shutdownPromise;\n\t}\n\n\tasync function performShutdown(reason: string, exitCode: number): Promise<never> {\n\t\tif (shuttingDown) process.exit(exitCode);\n\t\tshuttingDown = true;\n\t\tclearInterval(ticker);\n\t\twriteStderrLine(`senpi rpc host supervisor: ${reason} shutdown`);\n\t\tfor (const client of clientSockets) client.destroy();\n\t\tawait closeServer(server);\n\t\t// Unlink the private directory BEFORE the child stop, which can take seconds:\n\t\t// an external SIGKILL landing during that wait (ensureHost escalates while\n\t\t// replacing a host) would otherwise leave the directory behind. The child\n\t\t// keeps serving through its already-open socket fd until it exits, and its\n\t\t// own watchdog cleanup makes the removal idempotent.\n\t\tawait rm(internal.dir, { recursive: true, force: true });\n\t\tawait stopChild(child);\n\t\tobserver?.destroy();\n\t\tif (publicSocketOwned) await rm(publicSocket, { force: true });\n\t\t// Mirror ensureHost's cleanupState: the pidfile and settings describe a\n\t\t// live host only; the stderr log stays for diagnostics.\n\t\tawait rm(paths.pidFile, { force: true });\n\t\tawait rm(paths.settingsFile, { force: true });\n\t\tprocess.exit(exitCode);\n\t}\n\n\tlet observer: Socket | undefined;\n\tlet publicSocketOwned = false;\n\t// Registered before the startup handshake, not after it: the private internal\n\t// directory already exists at this point, so a SIGTERM arriving during host\n\t// startup must run the same cleanup instead of Node's default kill, which\n\t// would leave that directory behind.\n\tregisterSupervisorSignals(shutdown);\n\ttry {\n\t\tawait waitForListener(internalSocket, 30_000);\n\t\tawait connectObserver();\n\t\tawait prepareSocketPath(publicSocket);\n\t\tawait listen(server, publicSocket);\n\t\tpublicSocketOwned = true;\n\t} catch (cause) {\n\t\tawait shutdown(`startup failed: ${errorMessage(cause)}`, 1);\n\t}\n\tasync function connectObserver(): Promise<void> {\n\t\tconst next = createConnection(internalSocket);\n\t\tawait waitForConnect(next, 5_000);\n\t\tobserver = next;\n\t\tobserverHealthy = true;\n\t\tattachJsonlLineReader(next, observeHostEvent, { maxLineLength: MAX_RPC_LINE_CHARACTERS });\n\t\tconst lost = (): void => {\n\t\t\tif (observer !== next || shuttingDown) return;\n\t\t\tobserverHealthy = false;\n\t\t\tobserver = undefined;\n\t\t\tif (observerReconnectTimer === undefined) {\n\t\t\t\tobserverReconnectTimer = setTimeout(() => {\n\t\t\t\t\tobserverReconnectTimer = undefined;\n\t\t\t\t\tvoid connectObserver().catch(() => lost());\n\t\t\t\t}, 250);\n\t\t\t\tobserverReconnectTimer.unref?.();\n\t\t\t}\n\t\t};\n\t\tnext.once(\"close\", lost);\n\t\tnext.once(\"error\", lost);\n\t}\n\n\twriteStderrLine(\n\t\t`senpi rpc host ready on unix://${publicSocket} (coldStart=${policy.coldStart}, idleExitMs=${\n\t\t\tpolicy.coldStart === \"persistent\" ? \"never\" : String(policy.idleExitMs)\n\t\t})`,\n\t);\n\tawait new Promise<never>(() => {});\n}\n\n/** External stop (ensureHost replacement, tests, QA) must clean up like idle exit. */\nfunction registerSupervisorSignals(shutdown: (reason: string, exitCode: number) => Promise<never>): void {\n\tfor (const signal of process.platform === \"win32\" ? ([\"SIGTERM\"] as const) : ([\"SIGTERM\", \"SIGHUP\"] as const)) {\n\t\tprocess.on(signal, () => {\n\t\t\tvoid shutdown(`signal:${signal}`, signal === \"SIGHUP\" ? 129 : 143);\n\t\t});\n\t}\n}\n\nasync function readSettingsFile(settingsFile: string): Promise<unknown> {\n\ttry {\n\t\treturn JSON.parse(await readFile(settingsFile, \"utf8\"));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nasync function stopChild(child: ChildProcess): Promise<void> {\n\tif (child.exitCode !== null || child.signalCode !== null) return;\n\ttry {\n\t\tchild.kill(\"SIGTERM\");\n\t} catch {\n\t\treturn;\n\t}\n\tif (await waitForChildExit(child, CHILD_STOP_TIMEOUT_MS)) return;\n\ttry {\n\t\tchild.kill(\"SIGKILL\");\n\t} catch {\n\t\treturn;\n\t}\n\tawait waitForChildExit(child, 2_000);\n}\n\nfunction waitForChildExit(child: ChildProcess, timeoutMs: number): Promise<boolean> {\n\tif (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);\n\treturn new Promise((resolve) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tchild.off(\"exit\", onExit);\n\t\t\tresolve(false);\n\t\t}, timeoutMs);\n\t\tconst onExit = (): void => {\n\t\t\tclearTimeout(timer);\n\t\t\tresolve(true);\n\t\t};\n\t\tchild.once(\"exit\", onExit);\n\t});\n}\n\nasync function waitForListener(socketPath: string, timeoutMs: number): Promise<void> {\n\tconst deadline = Date.now() + timeoutMs;\n\twhile (Date.now() <= deadline) {\n\t\tif (await canConnect(socketPath)) return;\n\t\tawait delay(50);\n\t}\n\tthrow new Error(`${socketPath}: host did not start listening within ${timeoutMs}ms`);\n}\n\nfunction canConnect(socketPath: string): Promise<boolean> {\n\treturn new Promise((resolve) => {\n\t\tconst socket = createConnection(socketPath);\n\t\tconst settle = (value: boolean): void => {\n\t\t\tsocket.destroy();\n\t\t\tresolve(value);\n\t\t};\n\t\tsocket.once(\"connect\", () => settle(true));\n\t\tsocket.once(\"error\", () => settle(false));\n\t});\n}\n\nfunction waitForConnect(socket: Socket, timeoutMs: number): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tcleanup();\n\t\t\treject(new Error(`observer connection to internal host timed out after ${timeoutMs}ms`));\n\t\t}, timeoutMs);\n\t\tconst onConnect = (): void => {\n\t\t\tcleanup();\n\t\t\tresolve();\n\t\t};\n\t\tconst onError = (cause: Error): void => {\n\t\t\tcleanup();\n\t\t\treject(cause);\n\t\t};\n\t\tconst cleanup = (): void => {\n\t\t\tclearTimeout(timer);\n\t\t\tsocket.off(\"connect\", onConnect);\n\t\t\tsocket.off(\"error\", onError);\n\t\t};\n\t\tsocket.once(\"connect\", onConnect);\n\t\tsocket.once(\"error\", onError);\n\t});\n}\n\nasync function prepareSocketPath(socketPath: string): Promise<void> {\n\tawait mkdir(dirname(socketPath), { recursive: true, mode: 0o700 });\n\ttry {\n\t\tawait access(socketPath);\n\t} catch (cause) {\n\t\tif (isNodeErrorCode(cause, \"ENOENT\")) return;\n\t\tthrow cause;\n\t}\n\tif (await canConnect(socketPath)) throw new Error(`${socketPath}: address already in use by a live server.`);\n\tawait unlink(socketPath);\n}\n\nfunction listen(server: Server, socketPath: string): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(socketPath, async () => {\n\t\t\tserver.off(\"error\", reject);\n\t\t\tif (!socketPath.startsWith(\"\\0\")) await chmod(socketPath, 0o600);\n\t\t\tresolve();\n\t\t});\n\t});\n}\n\nfunction closeServer(server: Server): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tserver.close(() => resolve());\n\t});\n}\n\nfunction writeStderrLine(text: string): void {\n\t// A detached daemon exiting right after an async stderr.write to a file can\n\t// lose the output entirely; write synchronously so diagnostics always land.\n\ttry {\n\t\twriteSync(2, `${text}\\n`);\n\t} catch {\n\t\t/* fd 2 unavailable: nothing more we can do. */\n\t}\n}\n\nfunction delay(ms: number): Promise<void> {\n\treturn new Promise((resolveDelay) => setTimeout(resolveDelay, ms));\n}\n\nfunction errorMessage(cause: unknown): string {\n\treturn cause instanceof Error ? cause.message : String(cause);\n}\n\nfunction isNodeErrorCode(cause: unknown, code: string): boolean {\n\treturn cause instanceof Error && \"code\" in cause && cause.code === code;\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 asOptionalString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : typeof value === \"number\" ? String(value) : undefined;\n}\n\nfunction isEntryScript(): boolean {\n\tconst entry = process.argv[1];\n\tif (!entry) return false;\n\ttry {\n\t\treturn fileURLToPath(import.meta.url) === realpathSync(entry);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nif (isEntryScript()) {\n\tconst launch = parseSupervisorArgs(process.argv.slice(2));\n\tif (!launch) {\n\t\twriteStderrLine(\"usage: host-lifecycle.ts --socket <path> [host cli args...]\");\n\t\tprocess.exit(2);\n\t}\n\tvoid runHostSupervisor(launch);\n}\n"]}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type { CreateAgentSessionRuntimeFactory } from "../../core/agent-session-runtime.ts";
|
|
2
|
+
import { type RpcBindingFactory, SessionCommandRouter } from "./session-command-router.ts";
|
|
3
|
+
import { SessionEventWriter } from "./session-event-writer.ts";
|
|
2
4
|
export interface MultiSessionHostOptions {
|
|
3
5
|
agentDir: string;
|
|
4
6
|
createRuntime: CreateAgentSessionRuntimeFactory;
|
|
@@ -10,7 +12,39 @@ export interface MultiSessionHostOptions {
|
|
|
10
12
|
};
|
|
11
13
|
initialThinkingLevel?: string;
|
|
12
14
|
listen?: string;
|
|
15
|
+
/** Test seam: defaults to the real shared-session binding. */
|
|
16
|
+
createBinding?: RpcBindingFactory;
|
|
13
17
|
}
|
|
18
|
+
/** Environment override for the idle-session eviction window, in milliseconds. */
|
|
19
|
+
export declare const RPC_SESSION_IDLE_EVICTION_MS_ENV = "SENPI_RPC_SESSION_IDLE_EVICTION_MS";
|
|
20
|
+
/** Environment override for the concurrent open-session cap. */
|
|
21
|
+
export declare const RPC_MAX_SESSIONS_ENV = "SENPI_RPC_MAX_SESSIONS";
|
|
22
|
+
/** Environment override for the empty-host exit window, in milliseconds. */
|
|
23
|
+
export declare const RPC_HOST_EMPTY_EXIT_MS_ENV = "SENPI_RPC_HOST_EMPTY_EXIT_MS";
|
|
24
|
+
/** Default idle-eviction window: 30 minutes after a session's last routed command or settled turn. */
|
|
25
|
+
export declare const DEFAULT_SESSION_IDLE_EVICTION_MS: number;
|
|
26
|
+
/** Default session cap: an idle session holds a full runtime (~340-510 MB RSS measured). */
|
|
27
|
+
export declare const DEFAULT_MAX_SESSIONS = 8;
|
|
28
|
+
/** Default empty-host exit: 15 minutes with zero open sessions, matching the supervisor's idle window. */
|
|
29
|
+
export declare const DEFAULT_HOST_EMPTY_EXIT_MS: number;
|
|
30
|
+
/** Explicit occupancy-policy overrides for createHostCore; tests inject clocks and hooks here. */
|
|
31
|
+
export interface HostIdleOverrides {
|
|
32
|
+
now?: () => number;
|
|
33
|
+
idleEvictionMs?: number;
|
|
34
|
+
emptyExitMs?: number;
|
|
35
|
+
maxSessions?: number;
|
|
36
|
+
/** Shutdown hook the empty-exit window invokes; hosts pass their exit path. */
|
|
37
|
+
onEmptyExit?: () => void;
|
|
38
|
+
/** Gate consulted before the empty-exit window advances (connected clients block it). */
|
|
39
|
+
canExitWhenEmpty?: () => boolean;
|
|
40
|
+
}
|
|
41
|
+
/** Precedence: explicit overrides beat environment variables beat documented defaults. */
|
|
42
|
+
export declare function resolveHostIdlePolicy(env: Readonly<Record<string, string | undefined>>, overrides?: HostIdleOverrides): {
|
|
43
|
+
now: () => number;
|
|
44
|
+
idleEvictionMs: number;
|
|
45
|
+
emptyExitMs: number;
|
|
46
|
+
maxSessions: number;
|
|
47
|
+
};
|
|
14
48
|
/**
|
|
15
49
|
* Socket event visibility is an all-sessions broadcast: every connected client
|
|
16
50
|
* receives every session lifecycle/agent event, tagged with its routing
|
|
@@ -18,4 +52,8 @@ export interface MultiSessionHostOptions {
|
|
|
18
52
|
* keeps observers stateless while preventing correlated replies from leaking.
|
|
19
53
|
*/
|
|
20
54
|
export declare function runMultiSessionHost(options: MultiSessionHostOptions): Promise<never>;
|
|
55
|
+
export declare function createHostCore(options: MultiSessionHostOptions, writer: SessionEventWriter, capabilities?: string[], idle?: HostIdleOverrides): {
|
|
56
|
+
router: SessionCommandRouter;
|
|
57
|
+
handle: (line: string) => Promise<void>;
|
|
58
|
+
};
|
|
21
59
|
//# sourceMappingURL=multi-session-host.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"multi-session-host.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/multi-session-host.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,qCAAqC,CAAC;
|
|
1
|
+
{"version":3,"file":"multi-session-host.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/multi-session-host.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,qCAAqC,CAAC;AAgB5F,OAAO,EAAE,KAAK,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AAC3F,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAG/D,MAAM,WAAW,uBAAuB;IACvC,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,gCAAgC,CAAC;IAChD,GAAG,EAAE,MAAM,CAAC;IACZ,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,aAAa,CAAC,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;IACtD,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,8DAA8D;IAC9D,aAAa,CAAC,EAAE,iBAAiB,CAAC;CAClC;AAED,kFAAkF;AAClF,eAAO,MAAM,gCAAgC,uCAAuC,CAAC;AACrF,gEAAgE;AAChE,eAAO,MAAM,oBAAoB,2BAA2B,CAAC;AAC7D,4EAA4E;AAC5E,eAAO,MAAM,0BAA0B,iCAAiC,CAAC;AACzE,sGAAsG;AACtG,eAAO,MAAM,gCAAgC,QAAc,CAAC;AAC5D,4FAA4F;AAC5F,eAAO,MAAM,oBAAoB,IAAI,CAAC;AACtC,0GAA0G;AAC1G,eAAO,MAAM,0BAA0B,QAAc,CAAC;AAEtD,kGAAkG;AAClG,MAAM,WAAW,iBAAiB;IACjC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,+EAA+E;IAC/E,WAAW,CAAC,EAAE,MAAM,IAAI,CAAC;IACzB,yFAAyF;IACzF,gBAAgB,CAAC,EAAE,MAAM,OAAO,CAAC;CACjC;AAQD,0FAA0F;AAC1F,wBAAgB,qBAAqB,CACpC,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,EACjD,SAAS,GAAE,iBAAsB,GAC/B;IAAE,GAAG,EAAE,MAAM,MAAM,CAAC;IAAC,cAAc,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,CAWzF;AASD;;;;;GAKG;AACH,wBAAsB,mBAAmB,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,KAAK,CAAC,CAG1F;AAED,wBAAgB,cAAc,CAC7B,OAAO,EAAE,uBAAuB,EAChC,MAAM,EAAE,kBAAkB,EAC1B,YAAY,WAA+D,EAC3E,IAAI,GAAE,iBAAsB;;mBAsBA,MAAM,KAAG,OAAO,CAAC,IAAI,CAAC;EAiBlD"}
|
|
@@ -5,12 +5,42 @@ import { envValue } from "../../core/brand.js";
|
|
|
5
5
|
import { flushRawStdout, takeOverStdout, waitForRawStdoutBackpressure, writeRawStdout, } from "../../core/output-guard.js";
|
|
6
6
|
import { killTrackedDetachedChildren } from "../../utils/shell.js";
|
|
7
7
|
import { parseClientCapabilities } from "./custom-capability.js";
|
|
8
|
+
import { parseIdleExitMs } from "./host-lifecycle.js";
|
|
8
9
|
import { armHostWatchdog, readHostWatchdogConfigFromBrandEnv } from "./host-watchdog.js";
|
|
9
10
|
import { attachJsonlLineReader, MAX_RPC_LINE_CHARACTERS } from "./jsonl.js";
|
|
10
11
|
import { rpcCommandShapeError } from "./rpc-input-validation.js";
|
|
11
12
|
import { SessionCommandRouter } from "./session-command-router.js";
|
|
12
13
|
import { SessionEventWriter } from "./session-event-writer.js";
|
|
13
14
|
import { RpcSessionRegistry } from "./session-registry.js";
|
|
15
|
+
/** Environment override for the idle-session eviction window, in milliseconds. */
|
|
16
|
+
export const RPC_SESSION_IDLE_EVICTION_MS_ENV = "SENPI_RPC_SESSION_IDLE_EVICTION_MS";
|
|
17
|
+
/** Environment override for the concurrent open-session cap. */
|
|
18
|
+
export const RPC_MAX_SESSIONS_ENV = "SENPI_RPC_MAX_SESSIONS";
|
|
19
|
+
/** Environment override for the empty-host exit window, in milliseconds. */
|
|
20
|
+
export const RPC_HOST_EMPTY_EXIT_MS_ENV = "SENPI_RPC_HOST_EMPTY_EXIT_MS";
|
|
21
|
+
/** Default idle-eviction window: 30 minutes after a session's last routed command or settled turn. */
|
|
22
|
+
export const DEFAULT_SESSION_IDLE_EVICTION_MS = 30 * 60_000;
|
|
23
|
+
/** Default session cap: an idle session holds a full runtime (~340-510 MB RSS measured). */
|
|
24
|
+
export const DEFAULT_MAX_SESSIONS = 8;
|
|
25
|
+
/** Default empty-host exit: 15 minutes with zero open sessions, matching the supervisor's idle window. */
|
|
26
|
+
export const DEFAULT_HOST_EMPTY_EXIT_MS = 15 * 60_000;
|
|
27
|
+
function parseSessionCap(value) {
|
|
28
|
+
if (value === undefined || !/^\d+$/.test(value.trim()))
|
|
29
|
+
return undefined;
|
|
30
|
+
const parsed = Number(value.trim());
|
|
31
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
|
|
32
|
+
}
|
|
33
|
+
/** Precedence: explicit overrides beat environment variables beat documented defaults. */
|
|
34
|
+
export function resolveHostIdlePolicy(env, overrides = {}) {
|
|
35
|
+
return {
|
|
36
|
+
now: overrides.now ?? Date.now,
|
|
37
|
+
idleEvictionMs: overrides.idleEvictionMs ??
|
|
38
|
+
parseIdleExitMs(env[RPC_SESSION_IDLE_EVICTION_MS_ENV]) ??
|
|
39
|
+
DEFAULT_SESSION_IDLE_EVICTION_MS,
|
|
40
|
+
emptyExitMs: overrides.emptyExitMs ?? parseIdleExitMs(env[RPC_HOST_EMPTY_EXIT_MS_ENV]) ?? DEFAULT_HOST_EMPTY_EXIT_MS,
|
|
41
|
+
maxSessions: overrides.maxSessions ?? parseSessionCap(env[RPC_MAX_SESSIONS_ENV]) ?? DEFAULT_MAX_SESSIONS,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
14
44
|
/**
|
|
15
45
|
* Socket event visibility is an all-sessions broadcast: every connected client
|
|
16
46
|
* receives every session lifecycle/agent event, tagged with its routing
|
|
@@ -22,9 +52,20 @@ export async function runMultiSessionHost(options) {
|
|
|
22
52
|
return runStdioHost(options);
|
|
23
53
|
return runSocketHost(options, resolveSocketPath(options.listen, options.agentDir));
|
|
24
54
|
}
|
|
25
|
-
function createHostCore(options, writer) {
|
|
26
|
-
const
|
|
27
|
-
const router = new SessionCommandRouter(new RpcSessionRegistry({
|
|
55
|
+
export function createHostCore(options, writer, capabilities = parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")), idle = {}) {
|
|
56
|
+
const policy = resolveHostIdlePolicy(process.env, idle);
|
|
57
|
+
const router = new SessionCommandRouter(new RpcSessionRegistry({
|
|
58
|
+
agentDir: options.agentDir,
|
|
59
|
+
createRuntime: options.createRuntime,
|
|
60
|
+
now: policy.now,
|
|
61
|
+
maxSessions: policy.maxSessions,
|
|
62
|
+
}), writer, options, options.createBinding, { capabilities }, {
|
|
63
|
+
now: policy.now,
|
|
64
|
+
idleEvictionMs: policy.idleEvictionMs,
|
|
65
|
+
emptyExitMs: policy.emptyExitMs,
|
|
66
|
+
onEmptyExit: idle.onEmptyExit,
|
|
67
|
+
canExitWhenEmpty: idle.canExitWhenEmpty,
|
|
68
|
+
});
|
|
28
69
|
const handle = async (line) => {
|
|
29
70
|
let parsed;
|
|
30
71
|
try {
|
|
@@ -50,7 +91,11 @@ async function runStdioHost(options) {
|
|
|
50
91
|
takeOverStdout();
|
|
51
92
|
const sink = { writeRaw: writeRawStdout, waitForBackpressure: waitForRawStdoutBackpressure };
|
|
52
93
|
const writer = new SessionEventWriter(sink.writeRaw, sink.waitForBackpressure);
|
|
53
|
-
|
|
94
|
+
// An empty host (no session ever opened, or all closed) must not stay resident
|
|
95
|
+
// forever: exit through the normal shutdown path once the window elapses.
|
|
96
|
+
const { router, handle } = createHostCore(options, writer, undefined, {
|
|
97
|
+
onEmptyExit: () => void shutdown(0),
|
|
98
|
+
});
|
|
54
99
|
let shuttingDown = false;
|
|
55
100
|
const shutdown = async (exitCode = 0) => {
|
|
56
101
|
if (shuttingDown)
|
|
@@ -78,8 +123,13 @@ async function runStdioHost(options) {
|
|
|
78
123
|
async function runSocketHost(options, socketPath) {
|
|
79
124
|
await prepareSocketPath(socketPath);
|
|
80
125
|
const writer = new SessionEventWriter(() => { });
|
|
81
|
-
const { router, handle } = createHostCore(options, writer);
|
|
82
126
|
const connections = new Map();
|
|
127
|
+
const { router, handle } = createHostCore(options, writer, parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")).filter((capability) => capability !== "rendered_components"),
|
|
128
|
+
// Supervised hosts idle-exit via the supervisor, but a socket host that
|
|
129
|
+
// outlives its supervisor (or is started bare) still self-exits when empty.
|
|
130
|
+
// A connected client counts as occupancy even with no session open: exiting
|
|
131
|
+
// under it would drop its socket and read as a crash to the supervisor.
|
|
132
|
+
{ onEmptyExit: () => void shutdown(0), canExitWhenEmpty: () => connections.size === 0 });
|
|
83
133
|
let nextConnection = 0;
|
|
84
134
|
let shuttingDown = false;
|
|
85
135
|
const server = createServer((socket) => {
|