@code-yeongyu/senpi 2026.9.8 → 2026.9.9

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.
Files changed (114) hide show
  1. package/CHANGELOG.md +23 -4
  2. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  3. package/dist/core/agent-session-runtime.js +2 -0
  4. package/dist/core/agent-session-runtime.js.map +1 -1
  5. package/dist/core/compaction/compaction-execution.d.ts.map +1 -1
  6. package/dist/core/compaction/compaction-execution.js +5 -5
  7. package/dist/core/compaction/compaction-execution.js.map +1 -1
  8. package/dist/core/compaction/compaction-settings.d.ts +2 -0
  9. package/dist/core/compaction/compaction-settings.d.ts.map +1 -1
  10. package/dist/core/compaction/compaction-settings.js.map +1 -1
  11. package/dist/core/compaction/compaction.d.ts +3 -3
  12. package/dist/core/compaction/compaction.d.ts.map +1 -1
  13. package/dist/core/compaction/compaction.js +12 -7
  14. package/dist/core/compaction/compaction.js.map +1 -1
  15. package/dist/core/compaction/stream-watchdog.d.ts +29 -0
  16. package/dist/core/compaction/stream-watchdog.d.ts.map +1 -1
  17. package/dist/core/compaction/stream-watchdog.js +35 -0
  18. package/dist/core/compaction/stream-watchdog.js.map +1 -1
  19. package/dist/core/compaction-settings-access.d.ts +6 -0
  20. package/dist/core/compaction-settings-access.d.ts.map +1 -1
  21. package/dist/core/compaction-settings-access.js.map +1 -1
  22. package/dist/core/compaction-settings-resolver.d.ts +2 -0
  23. package/dist/core/compaction-settings-resolver.d.ts.map +1 -1
  24. package/dist/core/compaction-settings-resolver.js +5 -0
  25. package/dist/core/compaction-settings-resolver.js.map +1 -1
  26. package/dist/core/extensions/builtin/compaction/model-usability-budget.d.ts +1 -1
  27. package/dist/core/extensions/builtin/compaction/model-usability-budget.d.ts.map +1 -1
  28. package/dist/core/extensions/builtin/compaction/model-usability-budget.js +23 -3
  29. package/dist/core/extensions/builtin/compaction/model-usability-budget.js.map +1 -1
  30. package/dist/core/extensions/builtin/compaction/speculative-summary.d.ts +2 -0
  31. package/dist/core/extensions/builtin/compaction/speculative-summary.d.ts.map +1 -1
  32. package/dist/core/extensions/builtin/compaction/speculative-summary.js +5 -2
  33. package/dist/core/extensions/builtin/compaction/speculative-summary.js.map +1 -1
  34. package/dist/core/extensions/builtin/compaction/speculative.d.ts.map +1 -1
  35. package/dist/core/extensions/builtin/compaction/speculative.js +9 -3
  36. package/dist/core/extensions/builtin/compaction/speculative.js.map +1 -1
  37. package/dist/core/extensions/builtin/compaction/summarization-retry.d.ts +10 -4
  38. package/dist/core/extensions/builtin/compaction/summarization-retry.d.ts.map +1 -1
  39. package/dist/core/extensions/builtin/compaction/summarization-retry.js +14 -5
  40. package/dist/core/extensions/builtin/compaction/summarization-retry.js.map +1 -1
  41. package/dist/core/session-manager.d.ts.map +1 -1
  42. package/dist/core/session-manager.js +11 -1
  43. package/dist/core/session-manager.js.map +1 -1
  44. package/dist/core/session-write-reservation.d.ts +4 -0
  45. package/dist/core/session-write-reservation.d.ts.map +1 -0
  46. package/dist/core/session-write-reservation.js +12 -0
  47. package/dist/core/session-write-reservation.js.map +1 -0
  48. package/dist/main.d.ts +14 -0
  49. package/dist/main.d.ts.map +1 -1
  50. package/dist/main.js +162 -147
  51. package/dist/main.js.map +1 -1
  52. package/dist/modes/rpc/connection-handler.d.ts +2 -0
  53. package/dist/modes/rpc/connection-handler.d.ts.map +1 -1
  54. package/dist/modes/rpc/connection-handler.js +1 -1
  55. package/dist/modes/rpc/connection-handler.js.map +1 -1
  56. package/dist/modes/rpc/multi-session-host.d.ts +2 -0
  57. package/dist/modes/rpc/multi-session-host.d.ts.map +1 -1
  58. package/dist/modes/rpc/multi-session-host.js +18 -8
  59. package/dist/modes/rpc/multi-session-host.js.map +1 -1
  60. package/dist/modes/rpc/session-binding.d.ts.map +1 -1
  61. package/dist/modes/rpc/session-binding.js +3 -0
  62. package/dist/modes/rpc/session-binding.js.map +1 -1
  63. package/dist/modes/rpc/session-command-router.d.ts +1 -1
  64. package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
  65. package/dist/modes/rpc/session-command-router.js +57 -25
  66. package/dist/modes/rpc/session-command-router.js.map +1 -1
  67. package/dist/modes/rpc/session-event-writer.d.ts +23 -1
  68. package/dist/modes/rpc/session-event-writer.d.ts.map +1 -1
  69. package/dist/modes/rpc/session-event-writer.js +108 -1
  70. package/dist/modes/rpc/session-event-writer.js.map +1 -1
  71. package/dist/modes/rpc/session-registry.d.ts +4 -2
  72. package/dist/modes/rpc/session-registry.d.ts.map +1 -1
  73. package/dist/modes/rpc/session-registry.js +1 -1
  74. package/dist/modes/rpc/session-registry.js.map +1 -1
  75. package/dist/modes/rpc/session-worker-client.d.ts +47 -0
  76. package/dist/modes/rpc/session-worker-client.d.ts.map +1 -0
  77. package/dist/modes/rpc/session-worker-client.js +226 -0
  78. package/dist/modes/rpc/session-worker-client.js.map +1 -0
  79. package/dist/modes/rpc/session-worker-protocol.d.ts +103 -0
  80. package/dist/modes/rpc/session-worker-protocol.d.ts.map +1 -0
  81. package/dist/modes/rpc/session-worker-protocol.js +12 -0
  82. package/dist/modes/rpc/session-worker-protocol.js.map +1 -0
  83. package/dist/modes/rpc/session-worker-requests.d.ts +24 -0
  84. package/dist/modes/rpc/session-worker-requests.d.ts.map +1 -0
  85. package/dist/modes/rpc/session-worker-requests.js +71 -0
  86. package/dist/modes/rpc/session-worker-requests.js.map +1 -0
  87. package/dist/modes/rpc/session-worker.d.ts +2 -0
  88. package/dist/modes/rpc/session-worker.d.ts.map +1 -0
  89. package/dist/modes/rpc/session-worker.js +229 -0
  90. package/dist/modes/rpc/session-worker.js.map +1 -0
  91. package/dist/modes/rpc/worker-session-registry.d.ts +37 -0
  92. package/dist/modes/rpc/worker-session-registry.d.ts.map +1 -0
  93. package/dist/modes/rpc/worker-session-registry.js +207 -0
  94. package/dist/modes/rpc/worker-session-registry.js.map +1 -0
  95. package/docs/rpc.md +70 -9
  96. package/docs/settings.md +1 -0
  97. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +12 -0
  98. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  99. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  100. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +23 -5
  101. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js.map +1 -1
  102. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts +30 -0
  103. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts.map +1 -1
  104. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +30 -0
  105. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js.map +1 -1
  106. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  107. package/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  108. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  109. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  110. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  111. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  112. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  113. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  114. package/package.json +7 -7
@@ -14,6 +14,7 @@ import { SessionEventWriter } from "./session-event-writer.js";
14
14
  import { RpcSessionRegistry } from "./session-registry.js";
15
15
  import { PUBLIC_SOCKET_IDENTITY_FILE, readSocketIdentityFile, shieldSocketDuringClose, statSocketIdentity, unlinkOwnedSocket, waitForSocketIdentityFile, } from "./socket-ownership.js";
16
16
  import { authenticateSocket, ensureSocketSecret, resolveSocketTransportAddress, SOCKET_SECRET_FILE_ENV, socketSecretPath, } from "./socket-transport.js";
17
+ import { WorkerSessionRegistry } from "./worker-session-registry.js";
17
18
  /** Environment override for the idle-session eviction window, in milliseconds. */
18
19
  export const RPC_SESSION_IDLE_EVICTION_MS_ENV = "SENPI_RPC_SESSION_IDLE_EVICTION_MS";
19
20
  /** Environment override for the empty-host exit window, in milliseconds. */
@@ -51,12 +52,18 @@ export async function runMultiSessionHost(options) {
51
52
  }
52
53
  export function createHostCore(options, writer, capabilities = parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")), idle = {}) {
53
54
  const policy = resolveHostIdlePolicy(process.env, idle);
54
- const router = new SessionCommandRouter(new RpcSessionRegistry({
55
- agentDir: options.agentDir,
56
- createRuntime: options.createRuntime,
57
- now: policy.now,
58
- closeGraceMs: idle.closeGraceMs ?? parseIdleExitMs(process.env[RPC_CLOSE_GRACE_MS_ENV]) ?? 10_000,
59
- }), writer, options, options.createBinding, { capabilities }, {
55
+ const router = new SessionCommandRouter(options.workerConfiguration
56
+ ? new WorkerSessionRegistry({
57
+ configuration: options.workerConfiguration,
58
+ now: policy.now,
59
+ closeGraceMs: idle.closeGraceMs ?? parseIdleExitMs(process.env[RPC_CLOSE_GRACE_MS_ENV]) ?? 10_000,
60
+ })
61
+ : new RpcSessionRegistry({
62
+ agentDir: options.agentDir,
63
+ createRuntime: options.createRuntime,
64
+ now: policy.now,
65
+ closeGraceMs: idle.closeGraceMs ?? parseIdleExitMs(process.env[RPC_CLOSE_GRACE_MS_ENV]) ?? 10_000,
66
+ }), writer, options, options.createBinding, { capabilities }, {
60
67
  now: policy.now,
61
68
  idleEvictionMs: policy.idleEvictionMs,
62
69
  emptyExitMs: policy.emptyExitMs,
@@ -106,9 +113,12 @@ async function runStdioHost(options) {
106
113
  };
107
114
  const onEnd = () => void shutdown();
108
115
  process.stdin.on("end", onEnd);
109
- const detachReader = attachJsonlLineReader(process.stdin, (line) => void handle(line), {
116
+ const reportInputFailure = (cause) => {
117
+ process.stderr.write(`senpi rpc stdio request failed: ${errorMessage(cause)}\n`);
118
+ };
119
+ const detachReader = attachJsonlLineReader(process.stdin, (line) => void handle(line).catch(reportInputFailure), {
110
120
  maxLineLength: MAX_RPC_LINE_CHARACTERS,
111
- onOversizedLine: () => void writer.enqueueControl(parseError(oversizedLineError())),
121
+ onOversizedLine: () => void writer.enqueueControl(parseError(oversizedLineError())).catch(reportInputFailure),
112
122
  });
113
123
  const detach = () => {
114
124
  detachReader();
@@ -1 +1 @@
1
- {"version":3,"file":"multi-session-host.js","sourceRoot":"","sources":["../../../src/modes/rpc/multi-session-host.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAA4B,MAAM,UAAU,CAAC;AACpF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAE1C,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/C,OAAO,EACN,cAAc,EACd,cAAc,EACd,4BAA4B,EAC5B,cAAc,GACd,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,2BAA2B,EAAE,MAAM,sBAAsB,CAAC;AAEnE,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,kCAAkC,EAAE,MAAM,oBAAoB,CAAC;AACzF,OAAO,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAC5E,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAEjE,OAAO,EAA0B,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AAC3F,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EACN,2BAA2B,EAC3B,sBAAsB,EAEtB,uBAAuB,EACvB,kBAAkB,EAClB,iBAAiB,EACjB,yBAAyB,GACzB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,E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AE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;IAC9D,CAAC,CAAC,CAAC;AACJ,CAAC;AAED,SAAS,OAAO,CAAC,OAAe;IAC/B,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,mBAAmB,OAAO,IAAI,CAAC,CAAC;AACtD,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;AAED,SAAS,uBAAuB,CAAC,QAA+C;IAC/E,KAAK,MAAM,MAAM,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAE,CAAC,SAAS,CAAW,CAAC,CAAC,CAAE,CAAC,SAAS,EAAE,QAAQ,CAAW,EAAE,CAAC;QAC/G,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE;YACvB,2BAA2B,EAAE,CAAC;YAC9B,KAAK,QAAQ,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAChD,CAAC,CAAC,CAAC;IACJ,CAAC;AACF,CAAC","sourcesContent":["import { access, chmod, mkdir, unlink } from \"node:fs/promises\";\nimport { createConnection, createServer, type Server, type Socket } from \"node:net\";\nimport { dirname, join } from \"node:path\";\nimport type { CreateAgentSessionRuntimeFactory } from \"../../core/agent-session-runtime.ts\";\nimport { envValue } from \"../../core/brand.ts\";\nimport {\n\tflushRawStdout,\n\ttakeOverStdout,\n\twaitForRawStdoutBackpressure,\n\twriteRawStdout,\n} from \"../../core/output-guard.ts\";\nimport { killTrackedDetachedChildren } from \"../../utils/shell.ts\";\nimport type { RpcConnectionSink } from \"./connection-handler.ts\";\nimport { parseClientCapabilities } from \"./custom-capability.ts\";\nimport { parseIdleExitMs } from \"./host-lifecycle.ts\";\nimport { armHostWatchdog, readHostWatchdogConfigFromBrandEnv } from \"./host-watchdog.ts\";\nimport { attachJsonlLineReader, MAX_RPC_LINE_CHARACTERS } from \"./jsonl.ts\";\nimport { rpcCommandShapeError } from \"./rpc-input-validation.ts\";\nimport type { RpcCommand, RpcResponse } from \"./rpc-types.ts\";\nimport { type RpcBindingFactory, SessionCommandRouter } from \"./session-command-router.ts\";\nimport { SessionEventWriter } from \"./session-event-writer.ts\";\nimport { RpcSessionRegistry } from \"./session-registry.ts\";\nimport {\n\tPUBLIC_SOCKET_IDENTITY_FILE,\n\treadSocketIdentityFile,\n\ttype SocketFileIdentity,\n\tshieldSocketDuringClose,\n\tstatSocketIdentity,\n\tunlinkOwnedSocket,\n\twaitForSocketIdentityFile,\n} from \"./socket-ownership.ts\";\nimport {\n\tauthenticateSocket,\n\tensureSocketSecret,\n\tresolveSocketTransportAddress,\n\tSOCKET_SECRET_FILE_ENV,\n\tsocketSecretPath,\n} from \"./socket-transport.ts\";\n\nexport interface MultiSessionHostOptions {\n\tagentDir: string;\n\tcreateRuntime: CreateAgentSessionRuntimeFactory;\n\tcwd: string;\n\tpermissionPreset?: string;\n\tcreationModel?: { provider: string; modelId: string };\n\tinitialThinkingLevel?: string;\n\tlisten?: string;\n\t/** Test seam: defaults to the real shared-session binding. */\n\tcreateBinding?: RpcBindingFactory;\n}\n\n/** Environment override for the idle-session eviction window, in milliseconds. */\nexport const RPC_SESSION_IDLE_EVICTION_MS_ENV = \"SENPI_RPC_SESSION_IDLE_EVICTION_MS\";\n/** Environment override for the empty-host exit window, in milliseconds. */\nexport const RPC_HOST_EMPTY_EXIT_MS_ENV = \"SENPI_RPC_HOST_EMPTY_EXIT_MS\";\n/** Environment override for the graceful close_session teardown window, in milliseconds. */\nexport const RPC_CLOSE_GRACE_MS_ENV = \"SENPI_RPC_CLOSE_GRACE_MS\";\n/** Default idle-eviction window: 30 minutes after a session's last routed command or settled turn. */\nexport const DEFAULT_SESSION_IDLE_EVICTION_MS = 30 * 60_000;\n/** Default empty-host exit: 15 minutes with zero open sessions, matching the supervisor's idle window. */\nexport const DEFAULT_HOST_EMPTY_EXIT_MS = 15 * 60_000;\n/** Win32 named-pipe close can leave libuv's server callback pending after handles are destroyed. */\nconst WINDOWS_SHUTDOWN_HARD_EXIT_MS = 2_000;\n\n/** Explicit occupancy-policy overrides for createHostCore; tests inject clocks and hooks here. */\nexport interface HostIdleOverrides {\n\tnow?: () => number;\n\tidleEvictionMs?: number;\n\temptyExitMs?: number;\n\tcloseGraceMs?: number;\n\t/** Shutdown hook the empty-exit window invokes; hosts pass their exit path. */\n\tonEmptyExit?: () => void;\n\t/** Gate consulted before the empty-exit window advances (connected clients block it). */\n\tcanExitWhenEmpty?: () => boolean;\n}\n\n/**\n * Resolve the host's idle lifecycle policy.\n */\nexport function resolveHostIdlePolicy(\n\tenv: Readonly<Record<string, string | undefined>>,\n\toverrides: HostIdleOverrides = {},\n): { now: () => number; idleEvictionMs: number; emptyExitMs: number } {\n\treturn {\n\t\tnow: overrides.now ?? Date.now,\n\t\tidleEvictionMs:\n\t\t\toverrides.idleEvictionMs ??\n\t\t\tparseIdleExitMs(env[RPC_SESSION_IDLE_EVICTION_MS_ENV]) ??\n\t\t\tDEFAULT_SESSION_IDLE_EVICTION_MS,\n\t\temptyExitMs:\n\t\t\toverrides.emptyExitMs ?? parseIdleExitMs(env[RPC_HOST_EMPTY_EXIT_MS_ENV]) ?? DEFAULT_HOST_EMPTY_EXIT_MS,\n\t};\n}\n\ninterface Connection {\n\treadonly id: string;\n\treadonly sink: RpcConnectionSink;\n\treadonly detach: () => void;\n\treadonly close: () => void;\n}\n\n/**\n * Socket agent events are delivered only to connections attached to their\n * session, tagged with its routing sessionId. Content-free session lifecycle\n * events remain visible to every connection. Responses and extension UI\n * requests remain requester-only; foreign observation uses attach-on-open.\n */\nexport async function runMultiSessionHost(options: MultiSessionHostOptions): Promise<never> {\n\tif (options.listen === undefined || options.listen === \"stdio://\") return runStdioHost(options);\n\treturn runSocketHost(options, resolveSocketPath(options.listen, options.agentDir));\n}\n\nexport function createHostCore(\n\toptions: MultiSessionHostOptions,\n\twriter: SessionEventWriter,\n\tcapabilities = parseClientCapabilities(envValue(\"RPC_CLIENT_CAPABILITIES\")),\n\tidle: HostIdleOverrides = {},\n) {\n\tconst policy = resolveHostIdlePolicy(process.env, idle);\n\tconst router = new SessionCommandRouter(\n\t\tnew RpcSessionRegistry({\n\t\t\tagentDir: options.agentDir,\n\t\t\tcreateRuntime: options.createRuntime,\n\t\t\tnow: policy.now,\n\t\t\tcloseGraceMs: idle.closeGraceMs ?? parseIdleExitMs(process.env[RPC_CLOSE_GRACE_MS_ENV]) ?? 10_000,\n\t\t}),\n\t\twriter,\n\t\toptions,\n\t\toptions.createBinding,\n\t\t{ capabilities },\n\t\t{\n\t\t\tnow: policy.now,\n\t\t\tidleEvictionMs: policy.idleEvictionMs,\n\t\t\temptyExitMs: policy.emptyExitMs,\n\t\t\tonEmptyExit: idle.onEmptyExit,\n\t\t\tcanExitWhenEmpty: idle.canExitWhenEmpty,\n\t\t},\n\t);\n\tconst handle = async (line: string): Promise<void> => {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(line);\n\t\t} catch (cause) {\n\t\t\tawait writer.enqueueControl(parseError(`Failed to parse command: ${errorMessage(cause)}`));\n\t\t\treturn;\n\t\t}\n\t\tconst shapeError = rpcCommandShapeError(parsed);\n\t\tif (shapeError) {\n\t\t\tawait writer.enqueueControl(parseError(shapeError));\n\t\t\treturn;\n\t\t}\n\t\tconst response = await router.handle(parsed as RpcCommand);\n\t\tif (response) await writer.enqueueControl(response);\n\t};\n\treturn { router, handle };\n}\n\n/** Plain-stdio host with no eagerly-created AgentSessionRuntime. */\nasync function runStdioHost(options: MultiSessionHostOptions): Promise<never> {\n\ttakeOverStdout();\n\tconst sink: RpcConnectionSink = { writeRaw: writeRawStdout, waitForBackpressure: waitForRawStdoutBackpressure };\n\tconst writer = new SessionEventWriter(sink.writeRaw, sink.waitForBackpressure);\n\t// An empty host (no session ever opened, or all closed) must not stay resident\n\t// forever: exit through the normal shutdown path once the window elapses.\n\tconst { router, handle } = createHostCore(options, writer, undefined, {\n\t\tonEmptyExit: () => void shutdown(0),\n\t});\n\tlet shuttingDown = false;\n\tconst shutdown = async (exitCode = 0): Promise<never> => {\n\t\tif (shuttingDown) process.exit(exitCode);\n\t\tshuttingDown = true;\n\t\tdetach();\n\t\tawait router.dispose();\n\t\tawait writer.flush();\n\t\tawait flushRawStdout();\n\t\tprocess.exit(exitCode);\n\t};\n\tconst onEnd = () => void shutdown();\n\tprocess.stdin.on(\"end\", onEnd);\n\tconst detachReader = attachJsonlLineReader(process.stdin, (line) => void handle(line), {\n\t\tmaxLineLength: MAX_RPC_LINE_CHARACTERS,\n\t\tonOversizedLine: () => void writer.enqueueControl(parseError(oversizedLineError())),\n\t});\n\tconst detach = () => {\n\t\tdetachReader();\n\t\tprocess.stdin.off(\"end\", onEnd);\n\t};\n\tregisterShutdownSignals(shutdown);\n\treturn new Promise(() => {});\n}\n\nasync function runSocketHost(options: MultiSessionHostOptions, socketPath: string): Promise<never> {\n\tawait prepareSocketPath(socketPath);\n\tconst writer = new SessionEventWriter(() => {});\n\tconst connections = new Map<string, Connection>();\n\tconst { router, handle } = createHostCore(\n\t\toptions,\n\t\twriter,\n\t\tparseClientCapabilities(envValue(\"RPC_CLIENT_CAPABILITIES\")).filter(\n\t\t\t(capability) => capability !== \"rendered_components\",\n\t\t),\n\t\t// Supervised hosts idle-exit via the supervisor, but a socket host that\n\t\t// outlives its supervisor (or is started bare) still self-exits when empty.\n\t\t// A connected client counts as occupancy even with no session open: exiting\n\t\t// under it would drop its socket and read as a crash to the supervisor.\n\t\t{ onEmptyExit: () => void shutdown(0), canExitWhenEmpty: () => connections.size === 0 },\n\t);\n\tlet nextConnection = 0;\n\tlet shuttingDown = false;\n\tconst secret =\n\t\tprocess.platform === \"win32\"\n\t\t\t? await ensureSocketSecret(process.env[SOCKET_SECRET_FILE_ENV] ?? socketSecretPath(socketPath))\n\t\t\t: undefined;\n\tconst watchdogConfig = readHostWatchdogConfigFromBrandEnv();\n\t// Crash-path ownership for the supervisor's PUBLIC socket: the supervisor\n\t// records the identity of the entry it bound (inside its private scratch\n\t// directory, which no replacement supervisor writes) right after its listen,\n\t// and this host removes that path only while the identity still matches. A\n\t// blind path removal here would unlink a newer host's freshly published\n\t// entry after a takeover - the startup path already refuses to touch a\n\t// socket owned by a live server; teardown follows the same rule.\n\tconst supervisorPublicSocketPath =\n\t\tprocess.platform === \"win32\" || socketPath.startsWith(\"\\0\") ? undefined : watchdogConfig?.publicSocket;\n\tconst supervisorPublicOwnerFile =\n\t\tsupervisorPublicSocketPath && watchdogConfig?.scratchDir\n\t\t\t? join(watchdogConfig.scratchDir, PUBLIC_SOCKET_IDENTITY_FILE)\n\t\t\t: undefined;\n\tlet boundIdentity: SocketFileIdentity | undefined;\n\tlet supervisorPublicIdentity: SocketFileIdentity | undefined;\n\tconst server = createServer((socket) => {\n\t\tconst accept = (): void => {\n\t\t\tconst id = `socket-${++nextConnection}`;\n\t\t\tconst sink = socketSink(socket);\n\t\t\twriter.registerConnection(id, sink);\n\t\t\tconst detachReader = attachJsonlLineReader(\n\t\t\t\tsocket,\n\t\t\t\t(line) => {\n\t\t\t\t\t// Do not serialize awaited commands: extension_ui_response and other\n\t\t\t\t\t// re-entrant frames must be able to resolve a command already awaiting them.\n\t\t\t\t\tvoid writer\n\t\t\t\t\t\t.withConnection(id, () => handle(line))\n\t\t\t\t\t\t.catch((cause) => {\n\t\t\t\t\t\t\tprocess.stderr.write(`senpi rpc connection ${id} failed: ${errorMessage(cause)}\\n`);\n\t\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tmaxLineLength: MAX_RPC_LINE_CHARACTERS,\n\t\t\t\t\tonOversizedLine: () => {\n\t\t\t\t\t\tvoid writer\n\t\t\t\t\t\t\t.withConnection(id, () => writer.enqueueControl(parseError(oversizedLineError())))\n\t\t\t\t\t\t\t.catch((cause) =>\n\t\t\t\t\t\t\t\tprocess.stderr.write(`senpi rpc connection ${id} failed: ${errorMessage(cause)}\\n`),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\tlet detached = false;\n\t\t\tconst detach = () => {\n\t\t\t\tif (detached) return;\n\t\t\t\tdetached = true;\n\t\t\t\tdetachReader();\n\t\t\t\twriter.unregisterConnection(id);\n\t\t\t\tconnections.delete(id);\n\t\t\t\t// A socket that dies without close_session still owns its sessions' attachments\n\t\t\t\t// and path reservations. Release them on the command chain so this runs after any\n\t\t\t\t// in-flight command for this connection settles, otherwise the path stays pinned\n\t\t\t\t// by a runtime whose client is gone and later resumes attach to that orphan.\n\t\t\t\tvoid router.releaseConnection(id).catch((cause) => {\n\t\t\t\t\tprocess.stderr.write(`senpi rpc connection ${id} release failed: ${errorMessage(cause)}\\n`);\n\t\t\t\t});\n\t\t\t};\n\t\t\tconnections.set(id, { id, sink, detach, close: () => socket.destroy() });\n\t\t\tsocket.once(\"close\", detach);\n\t\t\tsocket.once(\"error\", () => detach());\n\t\t};\n\t\tif (secret) authenticateSocket(socket, secret, accept);\n\t\telse accept();\n\t});\n\tserver.on(\"error\", (cause) => {\n\t\tif (!shuttingDown) process.stderr.write(`senpi rpc socket listener failed: ${errorMessage(cause)}\\n`);\n\t});\n\tconst shutdown = async (exitCode = 0, watchdogCleanup?: Promise<void>): Promise<never> => {\n\t\tif (shuttingDown) process.exit(exitCode);\n\t\tshuttingDown = true;\n\t\t// On Windows, destroying named-pipe sockets does not always make libuv's\n\t\t// server.close callback fire: connected pipe instances can remain in the\n\t\t// kernel after the JavaScript handles are destroyed. Keep the normal drain\n\t\t// path, but never let that platform-specific close stall orphan the host.\n\t\ttry {\n\t\t\tfor (const connection of connections.values()) {\n\t\t\t\tconnection.detach();\n\t\t\t\tconnection.close();\n\t\t\t}\n\t\t\t// libuv unlinks the bound NAME when the listening handle closes - which\n\t\t\t// would delete a newer host's entry renamed over this path. Shield the\n\t\t\t// current entry for the close, then let the ownership check decide.\n\t\t\tawait shieldSocketDuringClose(socketPath, () =>\n\t\t\t\tprocess.platform === \"win32\"\n\t\t\t\t\t? Promise.race([closeServer(server), delay(WINDOWS_SHUTDOWN_HARD_EXIT_MS)])\n\t\t\t\t\t: closeServer(server),\n\t\t\t);\n\t\t\tawait router.dispose();\n\t\t\tawait writer.flush();\n\t\t\t// Ownership-checked: unlink only the entry THIS process bound. After a\n\t\t\t// takeover renamed a newer host's socket over the same path, the\n\t\t\t// identity no longer matches and the replacement stays published.\n\t\t\tawait unlinkOwnedSocket(socketPath, boundIdentity, hostLog);\n\t\t\tif (supervisorPublicSocketPath) {\n\t\t\t\tawait unlinkOwnedSocket(supervisorPublicSocketPath, supervisorPublicIdentity, hostLog);\n\t\t\t}\n\t\t\tif (watchdogCleanup) await watchdogCleanup;\n\t\t} finally {\n\t\t\t// Explicitly terminate after every shutdown trigger. Windows named-pipe\n\t\t\t// handles are not fully controllable from JS, and an unresolved cleanup\n\t\t\t// must not leave this daemon or its public endpoint alive.\n\t\t\tprocess.exit(exitCode);\n\t\t}\n\t};\n\tregisterShutdownSignals(shutdown);\n\t// Arm before listen: a supervisor death during the listen transition must\n\t// still close the child and clean its private endpoint.\n\tconst watchdog =\n\t\twatchdogConfig && supervisorPublicOwnerFile\n\t\t\t? {\n\t\t\t\t\t...watchdogConfig,\n\t\t\t\t\t// The supervisor may die while this host is still waiting for the token\n\t\t\t\t\t// below; read it before the watchdog removes the scratch directory, or the\n\t\t\t\t\t// shutdown's ownership check has nothing to prove with and leaves the\n\t\t\t\t\t// public socket behind.\n\t\t\t\t\tbeforeCleanup: async () => {\n\t\t\t\t\t\tsupervisorPublicIdentity ??= await readSocketIdentityFile(supervisorPublicOwnerFile);\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: watchdogConfig;\n\tarmHostWatchdog(watchdog, (reason, cleanup) => {\n\t\tprocess.stderr.write(`senpi rpc host: ${reason}; shutting down\\n`);\n\t\t// Enter shutdown before killing session-owned child processes. The Windows\n\t\t// tree killer is synchronous, while the shutdown fallback must be armed\n\t\t// before any such cleanup can delay the event loop.\n\t\tvoid shutdown(0, cleanup);\n\t\tsetImmediate(killTrackedDetachedChildren);\n\t});\n\tboundIdentity = await listen(server, socketPath, secret);\n\tif (supervisorPublicOwnerFile) {\n\t\t// The supervisor publishes its public-socket token after this internal\n\t\t// listener is ready, so a short bounded wait keeps the lifecycles in step\n\t\t// without delaying unsupervised hosts.\n\t\tsupervisorPublicIdentity = await waitForSocketIdentityFile(supervisorPublicOwnerFile);\n\t}\n\tprocess.stderr.write(`senpi rpc listening on ${formatSocketAddress(socketPath)}\\n`);\n\n\t// Opt-in only: set by the lifecycle supervisor so this host can never outlive\n\t// it, including when the supervisor is SIGKILLed and runs no handler at all.\n\treturn new Promise(() => {});\n}\n\nfunction delay(ms: number): Promise<void> {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction parseError(error: string): RpcResponse {\n\treturn { type: \"response\", command: \"parse\", success: false, error };\n}\n\nfunction oversizedLineError(): string {\n\treturn `RPC input line exceeds ${MAX_RPC_LINE_CHARACTERS} characters.`;\n}\n\nfunction errorMessage(cause: unknown): string {\n\treturn cause instanceof Error ? cause.message : String(cause);\n}\n\nfunction resolveSocketPath(value: string, agentDir: string): string {\n\tif (value === \"unix://\") return join(agentDir, \"rpc\", \"rpc.sock\");\n\tif (value.startsWith(\"unix://\")) {\n\t\tconst path = value.slice(\"unix://\".length);\n\t\tif (path.length === 0) return join(agentDir, \"rpc\", \"rpc.sock\");\n\t\tif (path.startsWith(\"@\") && process.platform === \"linux\") return `\\0${path.slice(1)}`;\n\t\treturn path;\n\t}\n\treturn value;\n}\n\nfunction formatSocketAddress(socketPath: string): string {\n\treturn socketPath.startsWith(\"\\0\") ? `unix://@${socketPath.slice(1)}` : `unix://${socketPath}`;\n}\n\nfunction socketSink(socket: Socket): RpcConnectionSink {\n\tlet needsDrain = false;\n\treturn {\n\t\twriteRaw(chunk) {\n\t\t\tif (!socket.destroyed) needsDrain = !socket.write(chunk);\n\t\t},\n\t\tclose() {\n\t\t\tsocket.destroy();\n\t\t},\n\t\twaitForBackpressure() {\n\t\t\tif (socket.destroyed || !needsDrain) return Promise.resolve();\n\t\t\tneedsDrain = false;\n\t\t\treturn new Promise<void>((resolve) => {\n\t\t\t\tconst done = () => {\n\t\t\t\t\tsocket.off(\"drain\", done);\n\t\t\t\t\tsocket.off(\"close\", done);\n\t\t\t\t\tresolve();\n\t\t\t\t};\n\t\t\t\tsocket.once(\"drain\", done);\n\t\t\t\tsocket.once(\"close\", done);\n\t\t\t});\n\t\t},\n\t};\n}\n\nasync function prepareSocketPath(socketPath: string): Promise<void> {\n\tif (process.platform === \"win32\" || socketPath.startsWith(\"\\0\")) return;\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 probeSocket(socketPath)) throw new Error(`${socketPath}: address already in use by a live server.`);\n\tawait unlink(socketPath);\n}\n\nfunction probeSocket(socketPath: string): Promise<boolean> {\n\treturn new Promise((resolve) => {\n\t\tconst socket = createConnection(resolveSocketTransportAddress(socketPath, process.platform));\n\t\tconst settle = (live: boolean) => {\n\t\t\tsocket.destroy();\n\t\t\tresolve(live);\n\t\t};\n\t\tsocket.once(\"connect\", () => settle(true));\n\t\tsocket.once(\"error\", () => settle(false));\n\t\tsocket.setTimeout(1_000, () => settle(false));\n\t});\n}\n\nfunction listen(server: Server, socketPath: string, secret?: Uint8Array): Promise<SocketFileIdentity | undefined> {\n\treturn new Promise((resolve, reject) => {\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(resolveSocketTransportAddress(socketPath, process.platform, secret), async () => {\n\t\t\tserver.off(\"error\", reject);\n\t\t\ttry {\n\t\t\t\tif (process.platform !== \"win32\" && !socketPath.startsWith(\"\\0\")) {\n\t\t\t\t\tawait chmod(socketPath, 0o600);\n\t\t\t\t\t// Record which filesystem entry THIS listener created; shutdown\n\t\t\t\t\t// removes the path only while this identity still matches.\n\t\t\t\t\treturn resolve(await statSocketIdentity(socketPath));\n\t\t\t\t}\n\t\t\t\tresolve(undefined);\n\t\t\t} catch (cause) {\n\t\t\t\treject(cause);\n\t\t\t}\n\t\t});\n\t});\n}\n\nfunction closeServer(server: Server): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tserver.close((cause) => (cause ? reject(cause) : resolve()));\n\t});\n}\n\nfunction hostLog(message: string): void {\n\tprocess.stderr.write(`senpi rpc host: ${message}\\n`);\n}\n\nfunction isNodeErrorCode(cause: unknown, code: string): boolean {\n\treturn cause instanceof Error && \"code\" in cause && cause.code === code;\n}\n\nfunction registerShutdownSignals(shutdown: (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\tkillTrackedDetachedChildren();\n\t\t\tvoid shutdown(signal === \"SIGHUP\" ? 129 : 143);\n\t\t});\n\t}\n}\n"]}
1
+ {"version":3,"file":"multi-session-host.js","sourceRoot":"","sources":["../../../src/modes/rpc/multi-session-host.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAA4B,MAAM,UAAU,CAAC;AACpF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAE1C,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/C,OAAO,EACN,cAAc,EACd,cAAc,EACd,4BAA4B,EAC5B,cA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EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;IAC9D,CAAC,CAAC,CAAC;AACJ,CAAC;AAED,SAAS,OAAO,CAAC,OAAe;IAC/B,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,mBAAmB,OAAO,IAAI,CAAC,CAAC;AACtD,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;AAED,SAAS,uBAAuB,CAAC,QAA+C;IAC/E,KAAK,MAAM,MAAM,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAE,CAAC,SAAS,CAAW,CAAC,CAAC,CAAE,CAAC,SAAS,EAAE,QAAQ,CAAW,EAAE,CAAC;QAC/G,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE;YACvB,2BAA2B,EAAE,CAAC;YAC9B,KAAK,QAAQ,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAChD,CAAC,CAAC,CAAC;IACJ,CAAC;AACF,CAAC","sourcesContent":["import { access, chmod, mkdir, unlink } from \"node:fs/promises\";\nimport { createConnection, createServer, type Server, type Socket } from \"node:net\";\nimport { dirname, join } from \"node:path\";\nimport type { CreateAgentSessionRuntimeFactory } from \"../../core/agent-session-runtime.ts\";\nimport { envValue } from \"../../core/brand.ts\";\nimport {\n\tflushRawStdout,\n\ttakeOverStdout,\n\twaitForRawStdoutBackpressure,\n\twriteRawStdout,\n} from \"../../core/output-guard.ts\";\nimport type { CliRuntimeConfiguration } from \"../../main.ts\";\nimport { killTrackedDetachedChildren } from \"../../utils/shell.ts\";\nimport type { RpcConnectionSink } from \"./connection-handler.ts\";\nimport { parseClientCapabilities } from \"./custom-capability.ts\";\nimport { parseIdleExitMs } from \"./host-lifecycle.ts\";\nimport { armHostWatchdog, readHostWatchdogConfigFromBrandEnv } from \"./host-watchdog.ts\";\nimport { attachJsonlLineReader, MAX_RPC_LINE_CHARACTERS } from \"./jsonl.ts\";\nimport { rpcCommandShapeError } from \"./rpc-input-validation.ts\";\nimport type { RpcCommand, RpcResponse } from \"./rpc-types.ts\";\nimport { type RpcBindingFactory, SessionCommandRouter } from \"./session-command-router.ts\";\nimport { SessionEventWriter } from \"./session-event-writer.ts\";\nimport { RpcSessionRegistry } from \"./session-registry.ts\";\nimport {\n\tPUBLIC_SOCKET_IDENTITY_FILE,\n\treadSocketIdentityFile,\n\ttype SocketFileIdentity,\n\tshieldSocketDuringClose,\n\tstatSocketIdentity,\n\tunlinkOwnedSocket,\n\twaitForSocketIdentityFile,\n} from \"./socket-ownership.ts\";\nimport {\n\tauthenticateSocket,\n\tensureSocketSecret,\n\tresolveSocketTransportAddress,\n\tSOCKET_SECRET_FILE_ENV,\n\tsocketSecretPath,\n} from \"./socket-transport.ts\";\nimport { WorkerSessionRegistry } from \"./worker-session-registry.ts\";\n\nexport interface MultiSessionHostOptions {\n\tagentDir: string;\n\tcreateRuntime: CreateAgentSessionRuntimeFactory;\n\tworkerConfiguration?: CliRuntimeConfiguration;\n\tcwd: string;\n\tpermissionPreset?: string;\n\tcreationModel?: { provider: string; modelId: string };\n\tinitialThinkingLevel?: string;\n\tlisten?: string;\n\t/** Test seam: defaults to the real shared-session binding. */\n\tcreateBinding?: RpcBindingFactory;\n}\n\n/** Environment override for the idle-session eviction window, in milliseconds. */\nexport const RPC_SESSION_IDLE_EVICTION_MS_ENV = \"SENPI_RPC_SESSION_IDLE_EVICTION_MS\";\n/** Environment override for the empty-host exit window, in milliseconds. */\nexport const RPC_HOST_EMPTY_EXIT_MS_ENV = \"SENPI_RPC_HOST_EMPTY_EXIT_MS\";\n/** Environment override for the graceful close_session teardown window, in milliseconds. */\nexport const RPC_CLOSE_GRACE_MS_ENV = \"SENPI_RPC_CLOSE_GRACE_MS\";\n/** Default idle-eviction window: 30 minutes after a session's last routed command or settled turn. */\nexport const DEFAULT_SESSION_IDLE_EVICTION_MS = 30 * 60_000;\n/** Default empty-host exit: 15 minutes with zero open sessions, matching the supervisor's idle window. */\nexport const DEFAULT_HOST_EMPTY_EXIT_MS = 15 * 60_000;\n/** Win32 named-pipe close can leave libuv's server callback pending after handles are destroyed. */\nconst WINDOWS_SHUTDOWN_HARD_EXIT_MS = 2_000;\n\n/** Explicit occupancy-policy overrides for createHostCore; tests inject clocks and hooks here. */\nexport interface HostIdleOverrides {\n\tnow?: () => number;\n\tidleEvictionMs?: number;\n\temptyExitMs?: number;\n\tcloseGraceMs?: number;\n\t/** Shutdown hook the empty-exit window invokes; hosts pass their exit path. */\n\tonEmptyExit?: () => void;\n\t/** Gate consulted before the empty-exit window advances (connected clients block it). */\n\tcanExitWhenEmpty?: () => boolean;\n}\n\n/**\n * Resolve the host's idle lifecycle policy.\n */\nexport function resolveHostIdlePolicy(\n\tenv: Readonly<Record<string, string | undefined>>,\n\toverrides: HostIdleOverrides = {},\n): { now: () => number; idleEvictionMs: number; emptyExitMs: number } {\n\treturn {\n\t\tnow: overrides.now ?? Date.now,\n\t\tidleEvictionMs:\n\t\t\toverrides.idleEvictionMs ??\n\t\t\tparseIdleExitMs(env[RPC_SESSION_IDLE_EVICTION_MS_ENV]) ??\n\t\t\tDEFAULT_SESSION_IDLE_EVICTION_MS,\n\t\temptyExitMs:\n\t\t\toverrides.emptyExitMs ?? parseIdleExitMs(env[RPC_HOST_EMPTY_EXIT_MS_ENV]) ?? DEFAULT_HOST_EMPTY_EXIT_MS,\n\t};\n}\n\ninterface Connection {\n\treadonly id: string;\n\treadonly sink: RpcConnectionSink;\n\treadonly detach: () => void;\n\treadonly close: () => void;\n}\n\n/**\n * Socket agent events are delivered only to connections attached to their\n * session, tagged with its routing sessionId. Content-free session lifecycle\n * events remain visible to every connection. Responses and extension UI\n * requests remain requester-only; foreign observation uses attach-on-open.\n */\nexport async function runMultiSessionHost(options: MultiSessionHostOptions): Promise<never> {\n\tif (options.listen === undefined || options.listen === \"stdio://\") return runStdioHost(options);\n\treturn runSocketHost(options, resolveSocketPath(options.listen, options.agentDir));\n}\n\nexport function createHostCore(\n\toptions: MultiSessionHostOptions,\n\twriter: SessionEventWriter,\n\tcapabilities = parseClientCapabilities(envValue(\"RPC_CLIENT_CAPABILITIES\")),\n\tidle: HostIdleOverrides = {},\n) {\n\tconst policy = resolveHostIdlePolicy(process.env, idle);\n\tconst router = new SessionCommandRouter(\n\t\toptions.workerConfiguration\n\t\t\t? new WorkerSessionRegistry({\n\t\t\t\t\tconfiguration: options.workerConfiguration,\n\t\t\t\t\tnow: policy.now,\n\t\t\t\t\tcloseGraceMs: idle.closeGraceMs ?? parseIdleExitMs(process.env[RPC_CLOSE_GRACE_MS_ENV]) ?? 10_000,\n\t\t\t\t})\n\t\t\t: new RpcSessionRegistry({\n\t\t\t\t\tagentDir: options.agentDir,\n\t\t\t\t\tcreateRuntime: options.createRuntime,\n\t\t\t\t\tnow: policy.now,\n\t\t\t\t\tcloseGraceMs: idle.closeGraceMs ?? parseIdleExitMs(process.env[RPC_CLOSE_GRACE_MS_ENV]) ?? 10_000,\n\t\t\t\t}),\n\t\twriter,\n\t\toptions,\n\t\toptions.createBinding,\n\t\t{ capabilities },\n\t\t{\n\t\t\tnow: policy.now,\n\t\t\tidleEvictionMs: policy.idleEvictionMs,\n\t\t\temptyExitMs: policy.emptyExitMs,\n\t\t\tonEmptyExit: idle.onEmptyExit,\n\t\t\tcanExitWhenEmpty: idle.canExitWhenEmpty,\n\t\t},\n\t);\n\tconst handle = async (line: string): Promise<void> => {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(line);\n\t\t} catch (cause) {\n\t\t\tawait writer.enqueueControl(parseError(`Failed to parse command: ${errorMessage(cause)}`));\n\t\t\treturn;\n\t\t}\n\t\tconst shapeError = rpcCommandShapeError(parsed);\n\t\tif (shapeError) {\n\t\t\tawait writer.enqueueControl(parseError(shapeError));\n\t\t\treturn;\n\t\t}\n\t\tconst response = await router.handle(parsed as RpcCommand);\n\t\tif (response) await writer.enqueueControl(response);\n\t};\n\treturn { router, handle };\n}\n\n/** Plain-stdio host with no eagerly-created AgentSessionRuntime. */\nasync function runStdioHost(options: MultiSessionHostOptions): Promise<never> {\n\ttakeOverStdout();\n\tconst sink: RpcConnectionSink = { writeRaw: writeRawStdout, waitForBackpressure: waitForRawStdoutBackpressure };\n\tconst writer = new SessionEventWriter(sink.writeRaw, sink.waitForBackpressure);\n\t// An empty host (no session ever opened, or all closed) must not stay resident\n\t// forever: exit through the normal shutdown path once the window elapses.\n\tconst { router, handle } = createHostCore(options, writer, undefined, {\n\t\tonEmptyExit: () => void shutdown(0),\n\t});\n\tlet shuttingDown = false;\n\tconst shutdown = async (exitCode = 0): Promise<never> => {\n\t\tif (shuttingDown) process.exit(exitCode);\n\t\tshuttingDown = true;\n\t\tdetach();\n\t\tawait router.dispose();\n\t\tawait writer.flush();\n\t\tawait flushRawStdout();\n\t\tprocess.exit(exitCode);\n\t};\n\tconst onEnd = () => void shutdown();\n\tprocess.stdin.on(\"end\", onEnd);\n\tconst reportInputFailure = (cause: unknown): void => {\n\t\tprocess.stderr.write(`senpi rpc stdio request failed: ${errorMessage(cause)}\\n`);\n\t};\n\tconst detachReader = attachJsonlLineReader(process.stdin, (line) => void handle(line).catch(reportInputFailure), {\n\t\tmaxLineLength: MAX_RPC_LINE_CHARACTERS,\n\t\tonOversizedLine: () => void writer.enqueueControl(parseError(oversizedLineError())).catch(reportInputFailure),\n\t});\n\tconst detach = () => {\n\t\tdetachReader();\n\t\tprocess.stdin.off(\"end\", onEnd);\n\t};\n\tregisterShutdownSignals(shutdown);\n\treturn new Promise(() => {});\n}\n\nasync function runSocketHost(options: MultiSessionHostOptions, socketPath: string): Promise<never> {\n\tawait prepareSocketPath(socketPath);\n\tconst writer = new SessionEventWriter(() => {});\n\tconst connections = new Map<string, Connection>();\n\tconst { router, handle } = createHostCore(\n\t\toptions,\n\t\twriter,\n\t\tparseClientCapabilities(envValue(\"RPC_CLIENT_CAPABILITIES\")).filter(\n\t\t\t(capability) => capability !== \"rendered_components\",\n\t\t),\n\t\t// Supervised hosts idle-exit via the supervisor, but a socket host that\n\t\t// outlives its supervisor (or is started bare) still self-exits when empty.\n\t\t// A connected client counts as occupancy even with no session open: exiting\n\t\t// under it would drop its socket and read as a crash to the supervisor.\n\t\t{ onEmptyExit: () => void shutdown(0), canExitWhenEmpty: () => connections.size === 0 },\n\t);\n\tlet nextConnection = 0;\n\tlet shuttingDown = false;\n\tconst secret =\n\t\tprocess.platform === \"win32\"\n\t\t\t? await ensureSocketSecret(process.env[SOCKET_SECRET_FILE_ENV] ?? socketSecretPath(socketPath))\n\t\t\t: undefined;\n\tconst watchdogConfig = readHostWatchdogConfigFromBrandEnv();\n\t// Crash-path ownership for the supervisor's PUBLIC socket: the supervisor\n\t// records the identity of the entry it bound (inside its private scratch\n\t// directory, which no replacement supervisor writes) right after its listen,\n\t// and this host removes that path only while the identity still matches. A\n\t// blind path removal here would unlink a newer host's freshly published\n\t// entry after a takeover - the startup path already refuses to touch a\n\t// socket owned by a live server; teardown follows the same rule.\n\tconst supervisorPublicSocketPath =\n\t\tprocess.platform === \"win32\" || socketPath.startsWith(\"\\0\") ? undefined : watchdogConfig?.publicSocket;\n\tconst supervisorPublicOwnerFile =\n\t\tsupervisorPublicSocketPath && watchdogConfig?.scratchDir\n\t\t\t? join(watchdogConfig.scratchDir, PUBLIC_SOCKET_IDENTITY_FILE)\n\t\t\t: undefined;\n\tlet boundIdentity: SocketFileIdentity | undefined;\n\tlet supervisorPublicIdentity: SocketFileIdentity | undefined;\n\tconst server = createServer((socket) => {\n\t\tconst accept = (): void => {\n\t\t\tconst id = `socket-${++nextConnection}`;\n\t\t\tconst sink = socketSink(socket);\n\t\t\twriter.registerConnection(id, sink);\n\t\t\tconst detachReader = attachJsonlLineReader(\n\t\t\t\tsocket,\n\t\t\t\t(line) => {\n\t\t\t\t\t// Do not serialize awaited commands: extension_ui_response and other\n\t\t\t\t\t// re-entrant frames must be able to resolve a command already awaiting them.\n\t\t\t\t\tvoid writer\n\t\t\t\t\t\t.withConnection(id, () => handle(line))\n\t\t\t\t\t\t.catch((cause) => {\n\t\t\t\t\t\t\tprocess.stderr.write(`senpi rpc connection ${id} failed: ${errorMessage(cause)}\\n`);\n\t\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tmaxLineLength: MAX_RPC_LINE_CHARACTERS,\n\t\t\t\t\tonOversizedLine: () => {\n\t\t\t\t\t\tvoid writer\n\t\t\t\t\t\t\t.withConnection(id, () => writer.enqueueControl(parseError(oversizedLineError())))\n\t\t\t\t\t\t\t.catch((cause) =>\n\t\t\t\t\t\t\t\tprocess.stderr.write(`senpi rpc connection ${id} failed: ${errorMessage(cause)}\\n`),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\tlet detached = false;\n\t\t\tconst detach = () => {\n\t\t\t\tif (detached) return;\n\t\t\t\tdetached = true;\n\t\t\t\tdetachReader();\n\t\t\t\twriter.unregisterConnection(id);\n\t\t\t\tconnections.delete(id);\n\t\t\t\t// A socket that dies without close_session still owns its sessions' attachments\n\t\t\t\t// and path reservations. Release them on the command chain so this runs after any\n\t\t\t\t// in-flight command for this connection settles, otherwise the path stays pinned\n\t\t\t\t// by a runtime whose client is gone and later resumes attach to that orphan.\n\t\t\t\tvoid router.releaseConnection(id).catch((cause) => {\n\t\t\t\t\tprocess.stderr.write(`senpi rpc connection ${id} release failed: ${errorMessage(cause)}\\n`);\n\t\t\t\t});\n\t\t\t};\n\t\t\tconnections.set(id, { id, sink, detach, close: () => socket.destroy() });\n\t\t\tsocket.once(\"close\", detach);\n\t\t\tsocket.once(\"error\", () => detach());\n\t\t};\n\t\tif (secret) authenticateSocket(socket, secret, accept);\n\t\telse accept();\n\t});\n\tserver.on(\"error\", (cause) => {\n\t\tif (!shuttingDown) process.stderr.write(`senpi rpc socket listener failed: ${errorMessage(cause)}\\n`);\n\t});\n\tconst shutdown = async (exitCode = 0, watchdogCleanup?: Promise<void>): Promise<never> => {\n\t\tif (shuttingDown) process.exit(exitCode);\n\t\tshuttingDown = true;\n\t\t// On Windows, destroying named-pipe sockets does not always make libuv's\n\t\t// server.close callback fire: connected pipe instances can remain in the\n\t\t// kernel after the JavaScript handles are destroyed. Keep the normal drain\n\t\t// path, but never let that platform-specific close stall orphan the host.\n\t\ttry {\n\t\t\tfor (const connection of connections.values()) {\n\t\t\t\tconnection.detach();\n\t\t\t\tconnection.close();\n\t\t\t}\n\t\t\t// libuv unlinks the bound NAME when the listening handle closes - which\n\t\t\t// would delete a newer host's entry renamed over this path. Shield the\n\t\t\t// current entry for the close, then let the ownership check decide.\n\t\t\tawait shieldSocketDuringClose(socketPath, () =>\n\t\t\t\tprocess.platform === \"win32\"\n\t\t\t\t\t? Promise.race([closeServer(server), delay(WINDOWS_SHUTDOWN_HARD_EXIT_MS)])\n\t\t\t\t\t: closeServer(server),\n\t\t\t);\n\t\t\tawait router.dispose();\n\t\t\tawait writer.flush();\n\t\t\t// Ownership-checked: unlink only the entry THIS process bound. After a\n\t\t\t// takeover renamed a newer host's socket over the same path, the\n\t\t\t// identity no longer matches and the replacement stays published.\n\t\t\tawait unlinkOwnedSocket(socketPath, boundIdentity, hostLog);\n\t\t\tif (supervisorPublicSocketPath) {\n\t\t\t\tawait unlinkOwnedSocket(supervisorPublicSocketPath, supervisorPublicIdentity, hostLog);\n\t\t\t}\n\t\t\tif (watchdogCleanup) await watchdogCleanup;\n\t\t} finally {\n\t\t\t// Explicitly terminate after every shutdown trigger. Windows named-pipe\n\t\t\t// handles are not fully controllable from JS, and an unresolved cleanup\n\t\t\t// must not leave this daemon or its public endpoint alive.\n\t\t\tprocess.exit(exitCode);\n\t\t}\n\t};\n\tregisterShutdownSignals(shutdown);\n\t// Arm before listen: a supervisor death during the listen transition must\n\t// still close the child and clean its private endpoint.\n\tconst watchdog =\n\t\twatchdogConfig && supervisorPublicOwnerFile\n\t\t\t? {\n\t\t\t\t\t...watchdogConfig,\n\t\t\t\t\t// The supervisor may die while this host is still waiting for the token\n\t\t\t\t\t// below; read it before the watchdog removes the scratch directory, or the\n\t\t\t\t\t// shutdown's ownership check has nothing to prove with and leaves the\n\t\t\t\t\t// public socket behind.\n\t\t\t\t\tbeforeCleanup: async () => {\n\t\t\t\t\t\tsupervisorPublicIdentity ??= await readSocketIdentityFile(supervisorPublicOwnerFile);\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: watchdogConfig;\n\tarmHostWatchdog(watchdog, (reason, cleanup) => {\n\t\tprocess.stderr.write(`senpi rpc host: ${reason}; shutting down\\n`);\n\t\t// Enter shutdown before killing session-owned child processes. The Windows\n\t\t// tree killer is synchronous, while the shutdown fallback must be armed\n\t\t// before any such cleanup can delay the event loop.\n\t\tvoid shutdown(0, cleanup);\n\t\tsetImmediate(killTrackedDetachedChildren);\n\t});\n\tboundIdentity = await listen(server, socketPath, secret);\n\tif (supervisorPublicOwnerFile) {\n\t\t// The supervisor publishes its public-socket token after this internal\n\t\t// listener is ready, so a short bounded wait keeps the lifecycles in step\n\t\t// without delaying unsupervised hosts.\n\t\tsupervisorPublicIdentity = await waitForSocketIdentityFile(supervisorPublicOwnerFile);\n\t}\n\tprocess.stderr.write(`senpi rpc listening on ${formatSocketAddress(socketPath)}\\n`);\n\n\t// Opt-in only: set by the lifecycle supervisor so this host can never outlive\n\t// it, including when the supervisor is SIGKILLed and runs no handler at all.\n\treturn new Promise(() => {});\n}\n\nfunction delay(ms: number): Promise<void> {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction parseError(error: string): RpcResponse {\n\treturn { type: \"response\", command: \"parse\", success: false, error };\n}\n\nfunction oversizedLineError(): string {\n\treturn `RPC input line exceeds ${MAX_RPC_LINE_CHARACTERS} characters.`;\n}\n\nfunction errorMessage(cause: unknown): string {\n\treturn cause instanceof Error ? cause.message : String(cause);\n}\n\nfunction resolveSocketPath(value: string, agentDir: string): string {\n\tif (value === \"unix://\") return join(agentDir, \"rpc\", \"rpc.sock\");\n\tif (value.startsWith(\"unix://\")) {\n\t\tconst path = value.slice(\"unix://\".length);\n\t\tif (path.length === 0) return join(agentDir, \"rpc\", \"rpc.sock\");\n\t\tif (path.startsWith(\"@\") && process.platform === \"linux\") return `\\0${path.slice(1)}`;\n\t\treturn path;\n\t}\n\treturn value;\n}\n\nfunction formatSocketAddress(socketPath: string): string {\n\treturn socketPath.startsWith(\"\\0\") ? `unix://@${socketPath.slice(1)}` : `unix://${socketPath}`;\n}\n\nfunction socketSink(socket: Socket): RpcConnectionSink {\n\tlet needsDrain = false;\n\treturn {\n\t\twriteRaw(chunk) {\n\t\t\tif (!socket.destroyed) needsDrain = !socket.write(chunk);\n\t\t},\n\t\tclose() {\n\t\t\tsocket.destroy();\n\t\t},\n\t\twaitForBackpressure() {\n\t\t\tif (socket.destroyed || !needsDrain) return Promise.resolve();\n\t\t\tneedsDrain = false;\n\t\t\treturn new Promise<void>((resolve) => {\n\t\t\t\tconst done = () => {\n\t\t\t\t\tsocket.off(\"drain\", done);\n\t\t\t\t\tsocket.off(\"close\", done);\n\t\t\t\t\tresolve();\n\t\t\t\t};\n\t\t\t\tsocket.once(\"drain\", done);\n\t\t\t\tsocket.once(\"close\", done);\n\t\t\t});\n\t\t},\n\t};\n}\n\nasync function prepareSocketPath(socketPath: string): Promise<void> {\n\tif (process.platform === \"win32\" || socketPath.startsWith(\"\\0\")) return;\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 probeSocket(socketPath)) throw new Error(`${socketPath}: address already in use by a live server.`);\n\tawait unlink(socketPath);\n}\n\nfunction probeSocket(socketPath: string): Promise<boolean> {\n\treturn new Promise((resolve) => {\n\t\tconst socket = createConnection(resolveSocketTransportAddress(socketPath, process.platform));\n\t\tconst settle = (live: boolean) => {\n\t\t\tsocket.destroy();\n\t\t\tresolve(live);\n\t\t};\n\t\tsocket.once(\"connect\", () => settle(true));\n\t\tsocket.once(\"error\", () => settle(false));\n\t\tsocket.setTimeout(1_000, () => settle(false));\n\t});\n}\n\nfunction listen(server: Server, socketPath: string, secret?: Uint8Array): Promise<SocketFileIdentity | undefined> {\n\treturn new Promise((resolve, reject) => {\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(resolveSocketTransportAddress(socketPath, process.platform, secret), async () => {\n\t\t\tserver.off(\"error\", reject);\n\t\t\ttry {\n\t\t\t\tif (process.platform !== \"win32\" && !socketPath.startsWith(\"\\0\")) {\n\t\t\t\t\tawait chmod(socketPath, 0o600);\n\t\t\t\t\t// Record which filesystem entry THIS listener created; shutdown\n\t\t\t\t\t// removes the path only while this identity still matches.\n\t\t\t\t\treturn resolve(await statSocketIdentity(socketPath));\n\t\t\t\t}\n\t\t\t\tresolve(undefined);\n\t\t\t} catch (cause) {\n\t\t\t\treject(cause);\n\t\t\t}\n\t\t});\n\t});\n}\n\nfunction closeServer(server: Server): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tserver.close((cause) => (cause ? reject(cause) : resolve()));\n\t});\n}\n\nfunction hostLog(message: string): void {\n\tprocess.stderr.write(`senpi rpc host: ${message}\\n`);\n}\n\nfunction isNodeErrorCode(cause: unknown, code: string): boolean {\n\treturn cause instanceof Error && \"code\" in cause && cause.code === code;\n}\n\nfunction registerShutdownSignals(shutdown: (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\tkillTrackedDetachedChildren();\n\t\t\tvoid shutdown(signal === \"SIGHUP\" ? 129 : 143);\n\t\t});\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"session-binding.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/session-binding.ts"],"names":[],"mappings":"AAEA,OAAO,EAGN,KAAK,oBAAoB,EAEzB,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAE7D,kFAAkF;AAClF,MAAM,WAAW,iBAAiB;IACjC,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACvC,gCAAgC,CAAC,IAAI,IAAI,CAAC;IAC1C,kBAAkB,CAAC,IAAI,IAAI,CAAC;IAC5B,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACzB;AAQD;;;GAGG;AACH,wBAAsB,uBAAuB,CAC5C,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,eAAe,EACtB,MAAM,EAAE,kBAAkB,EAC1B,YAAY,EAAE,MAAM,IAAI,EACxB,OAAO,GAAE,IAAI,CAAC,oBAAoB,EAAE,cAAc,GAAG,aAAa,CAAM,GACtE,OAAO,CAAC,iBAAiB,CAAC,CAuC5B"}
1
+ {"version":3,"file":"session-binding.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/session-binding.ts"],"names":[],"mappings":"AAEA,OAAO,EAGN,KAAK,oBAAoB,EAEzB,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAE7D,kFAAkF;AAClF,MAAM,WAAW,iBAAiB;IACjC,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACvC,gCAAgC,CAAC,IAAI,IAAI,CAAC;IAC1C,kBAAkB,CAAC,IAAI,IAAI,CAAC;IAC5B,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACzB;AAQD;;;GAGG;AACH,wBAAsB,uBAAuB,CAC5C,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,eAAe,EACtB,MAAM,EAAE,kBAAkB,EAC1B,YAAY,EAAE,MAAM,IAAI,EACxB,OAAO,GAAE,IAAI,CAAC,oBAAoB,EAAE,cAAc,GAAG,aAAa,CAAM,GACtE,OAAO,CAAC,iBAAiB,CAAC,CAyC5B"}
@@ -11,6 +11,8 @@ function enqueueRecords(writer, sessionId, chunk) {
11
11
  * scope. The classic handler remains the single source of command semantics.
12
12
  */
13
13
  export async function createRpcSessionBinding(sessionId, entry, writer, requestClose, options = {}) {
14
+ if (entry.worker)
15
+ return entry.worker.bind(sessionId, writer, requestClose, options);
14
16
  if (!entry.runtime)
15
17
  throw new Error("Session runtime was not created");
16
18
  // Attachments share one entry, so resolve the host from the live runtime. In
@@ -41,6 +43,7 @@ export async function createRpcSessionBinding(sessionId, entry, writer, requestC
41
43
  sessionId,
42
44
  shutdownHandler: bindToProviderScope(requestClose),
43
45
  disposeRuntime: false,
46
+ eventFlushScheduler: (flush) => flush(),
44
47
  ...options,
45
48
  });
46
49
  });
@@ -1 +1 @@
1
- {"version":3,"file":"session-binding.js","sourceRoot":"","sources":["../../../src/modes/rpc/session-binding.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAEtG,OAAO,EACN,0BAA0B,GAI1B,MAAM,yBAAyB,CAAC;AAYjC,SAAS,cAAc,CAAC,MAA0B,EAAE,SAAiB,EAAE,KAAa;IACnF,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;QACtC,IAAI,IAAI;YAAE,MAAM,CAAC,OAAO,CAAC,SAAS,EAAE,IAAI,C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,EAAE,EAAE,CAAC,cAAc,CAAC,MAAM,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;YAC1F,mBAAmB,EAAE,mBAAmB,CAAC,KAAK,IAAI,EAAE,GAAE,CAAC,CAAC;SACxD,CAAC;QACF,OAAO,0BAA0B,CAAC,WAAW,EAAE,UAAU,EAAE;YAC1D,SAAS;YACT,eAAe,EAAE,mBAAmB,CAAC,YAAY,CAAC;YAClD,cAAc,EAAE,KAAK;YACrB,GAAG,OAAO;SACV,CAAC,CAAC;IACJ,CAAC,CAAC,CAAC;IACH,MAAM,OAAO,CAAC,KAAK,CAAC;IACpB,OAAO;QACN,MAAM,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,oBAAoB,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,eAAe,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC;QAC9G,gCAAgC,EAAE,GAAG,EAAE,CACtC,oBAAoB,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,gCAAgC,EAAE,CAAC;QACpF,kBAAkB,EAAE,GAAG,EAAE,CAAC,oBAAoB,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,kBAAkB,EAAE,CAAC;QAC/F,OAAO,EAAE,GAAG,EAAE,CAAC,oBAAoB,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;KACzE,CAAC;AACH,CAAC","sourcesContent":["import { bindToProviderScope, runWithProviderScope } from \"@earendil-works/pi-ai/node/provider-scope\";\nimport type { AgentSessionRuntime } from \"../../core/agent-session-runtime.ts\";\nimport {\n\tcreateRpcConnectionHandler,\n\ttype RpcConnectionHandler,\n\ttype RpcConnectionOptions,\n\ttype RpcConnectionSink,\n} from \"./connection-handler.ts\";\nimport type { SessionEventWriter } from \"./session-event-writer.ts\";\nimport type { RpcSessionEntry } from \"./session-registry.ts\";\n\n/** A session-owned adapter around the classic command and extension-UI wiring. */\nexport interface RpcSessionBinding {\n\thandle(command: object): Promise<void>;\n\tcancelPendingExtensionUiRequests?(): void;\n\trerenderComponents?(): void;\n\tdispose(): Promise<void>;\n}\n\nfunction enqueueRecords(writer: SessionEventWriter, sessionId: string, chunk: string): void {\n\tfor (const line of chunk.split(\"\\n\")) {\n\t\tif (line) writer.enqueue(sessionId, JSON.parse(line) as object);\n\t}\n}\n\n/**\n * Creates the extension UI bridge and subscriptions within the entry's provider\n * scope. The classic handler remains the single source of command semantics.\n */\nexport async function createRpcSessionBinding(\n\tsessionId: string,\n\tentry: RpcSessionEntry,\n\twriter: SessionEventWriter,\n\trequestClose: () => void,\n\toptions: Pick<RpcConnectionOptions, \"capabilities\" | \"sharedWidth\"> = {},\n): Promise<RpcSessionBinding> {\n\tif (!entry.runtime) throw new Error(\"Session runtime was not created\");\n\t// Attachments share one entry, so resolve the host from the live runtime. In\n\t// particular, switch_session must use the entry's replacement-aware method\n\t// instead of a runtime captured during open_session.\n\tconst runtimeHost = new Proxy({} as AgentSessionRuntime, {\n\t\tget(_target, property) {\n\t\t\tif (property === \"switchSession\" && entry.switchSession) return entry.switchSession;\n\t\t\tif (property === \"setRebindSession\")\n\t\t\t\treturn (callback?: Parameters<AgentSessionRuntime[\"setRebindSession\"]>[0]) => {\n\t\t\t\t\tentry.rebindSession = callback;\n\t\t\t\t\tentry.runtime?.setRebindSession(callback);\n\t\t\t\t};\n\t\t\tconst runtime = entry.runtime;\n\t\t\tif (!runtime) throw new Error(\"Session runtime was not created\");\n\t\t\tconst value = Reflect.get(runtime, property, runtime);\n\t\t\treturn typeof value === \"function\" ? value.bind(runtime) : value;\n\t\t},\n\t});\n\tconst handler: RpcConnectionHandler = await runWithProviderScope(entry.scope, async () => {\n\t\tconst taggedSink: RpcConnectionSink = {\n\t\t\twriteRaw: bindToProviderScope((chunk: string) => enqueueRecords(writer, sessionId, chunk)),\n\t\t\twaitForBackpressure: bindToProviderScope(async () => {}),\n\t\t};\n\t\treturn createRpcConnectionHandler(runtimeHost, taggedSink, {\n\t\t\tsessionId,\n\t\t\tshutdownHandler: bindToProviderScope(requestClose),\n\t\t\tdisposeRuntime: false,\n\t\t\t...options,\n\t\t});\n\t});\n\tawait handler.ready;\n\treturn {\n\t\thandle: (command) => runWithProviderScope(entry.scope, () => handler.handleInputLine(JSON.stringify(command))),\n\t\tcancelPendingExtensionUiRequests: () =>\n\t\t\trunWithProviderScope(entry.scope, () => handler.cancelPendingExtensionUiRequests()),\n\t\trerenderComponents: () => runWithProviderScope(entry.scope, () => handler.rerenderComponents()),\n\t\tdispose: () => runWithProviderScope(entry.scope, () => handler.dispose()),\n\t};\n}\n"]}
1
+ {"version":3,"file":"session-binding.js","sourceRoot":"","sources":["../../../src/modes/rpc/session-binding.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAEtG,OAAO,EACN,0BAA0B,GAI1B,MAAM,yBAAyB,CAAC;AAYjC,SAAS,cAAc,CAAC,MAA0B,EAAE,SAAiB,EAAE,KAAa;IACnF,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;QACtC,IAAI,IAAI;YAAE,MAAM,CAAC,OAAO,CAAC,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAW,CAAC,CAAC;IACjE,CAAC;AACF,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC5C,SAAiB,EACjB,KAAsB,EACtB,MAA0B,EAC1B,YAAwB,EACxB,UAAsE,EAAE;IAExE,IAAI,KAAK,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC;IACrF,IAAI,CAAC,KAAK,CAAC,OAAO;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eAAe,EAAE,mBAAmB,CAAC,YAAY,CAAC;YAClD,cAAc,EAAE,KAAK;YACrB,mBAAmB,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,EAAE;YACvC,GAAG,OAAO;SACV,CAAC,CAAC;IACJ,CAAC,CAAC,CAAC;IACH,MAAM,OAAO,CAAC,KAAK,CAAC;IACpB,OAAO;QACN,MAAM,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,oBAAoB,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,eAAe,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC;QAC9G,gCAAgC,EAAE,GAAG,EAAE,CACtC,oBAAoB,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,gCAAgC,EAAE,CAAC;QACpF,kBAAkB,EAAE,GAAG,EAAE,CAAC,oBAAoB,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,kBAAkB,EAAE,CAAC;QAC/F,OAAO,EAAE,GAAG,EAAE,CAAC,oBAAoB,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;KACzE,CAAC;AACH,CAAC","sourcesContent":["import { bindToProviderScope, runWithProviderScope } from \"@earendil-works/pi-ai/node/provider-scope\";\nimport type { AgentSessionRuntime } from \"../../core/agent-session-runtime.ts\";\nimport {\n\tcreateRpcConnectionHandler,\n\ttype RpcConnectionHandler,\n\ttype RpcConnectionOptions,\n\ttype RpcConnectionSink,\n} from \"./connection-handler.ts\";\nimport type { SessionEventWriter } from \"./session-event-writer.ts\";\nimport type { RpcSessionEntry } from \"./session-registry.ts\";\n\n/** A session-owned adapter around the classic command and extension-UI wiring. */\nexport interface RpcSessionBinding {\n\thandle(command: object): Promise<void>;\n\tcancelPendingExtensionUiRequests?(): void;\n\trerenderComponents?(): void;\n\tdispose(): Promise<void>;\n}\n\nfunction enqueueRecords(writer: SessionEventWriter, sessionId: string, chunk: string): void {\n\tfor (const line of chunk.split(\"\\n\")) {\n\t\tif (line) writer.enqueue(sessionId, JSON.parse(line) as object);\n\t}\n}\n\n/**\n * Creates the extension UI bridge and subscriptions within the entry's provider\n * scope. The classic handler remains the single source of command semantics.\n */\nexport async function createRpcSessionBinding(\n\tsessionId: string,\n\tentry: RpcSessionEntry,\n\twriter: SessionEventWriter,\n\trequestClose: () => void,\n\toptions: Pick<RpcConnectionOptions, \"capabilities\" | \"sharedWidth\"> = {},\n): Promise<RpcSessionBinding> {\n\tif (entry.worker) return entry.worker.bind(sessionId, writer, requestClose, options);\n\tif (!entry.runtime) throw new Error(\"Session runtime was not created\");\n\t// Attachments share one entry, so resolve the host from the live runtime. In\n\t// particular, switch_session must use the entry's replacement-aware method\n\t// instead of a runtime captured during open_session.\n\tconst runtimeHost = new Proxy({} as AgentSessionRuntime, {\n\t\tget(_target, property) {\n\t\t\tif (property === \"switchSession\" && entry.switchSession) return entry.switchSession;\n\t\t\tif (property === \"setRebindSession\")\n\t\t\t\treturn (callback?: Parameters<AgentSessionRuntime[\"setRebindSession\"]>[0]) => {\n\t\t\t\t\tentry.rebindSession = callback;\n\t\t\t\t\tentry.runtime?.setRebindSession(callback);\n\t\t\t\t};\n\t\t\tconst runtime = entry.runtime;\n\t\t\tif (!runtime) throw new Error(\"Session runtime was not created\");\n\t\t\tconst value = Reflect.get(runtime, property, runtime);\n\t\t\treturn typeof value === \"function\" ? value.bind(runtime) : value;\n\t\t},\n\t});\n\tconst handler: RpcConnectionHandler = await runWithProviderScope(entry.scope, async () => {\n\t\tconst taggedSink: RpcConnectionSink = {\n\t\t\twriteRaw: bindToProviderScope((chunk: string) => enqueueRecords(writer, sessionId, chunk)),\n\t\t\twaitForBackpressure: bindToProviderScope(async () => {}),\n\t\t};\n\t\treturn createRpcConnectionHandler(runtimeHost, taggedSink, {\n\t\t\tsessionId,\n\t\t\tshutdownHandler: bindToProviderScope(requestClose),\n\t\t\tdisposeRuntime: false,\n\t\t\teventFlushScheduler: (flush) => flush(),\n\t\t\t...options,\n\t\t});\n\t});\n\tawait handler.ready;\n\treturn {\n\t\thandle: (command) => runWithProviderScope(entry.scope, () => handler.handleInputLine(JSON.stringify(command))),\n\t\tcancelPendingExtensionUiRequests: () =>\n\t\t\trunWithProviderScope(entry.scope, () => handler.cancelPendingExtensionUiRequests()),\n\t\trerenderComponents: () => runWithProviderScope(entry.scope, () => handler.rerenderComponents()),\n\t\tdispose: () => runWithProviderScope(entry.scope, () => handler.dispose()),\n\t};\n}\n"]}
@@ -49,7 +49,7 @@ export declare class SessionCommandRouter {
49
49
  private readonly canExitWhenEmpty?;
50
50
  private sweepTimer;
51
51
  private emptySince;
52
- constructor(registry: RpcSessionRegistry, writer: SessionEventWriter, defaults: Pick<RpcSessionLaunchProfile, "cwd" | "permissionPreset" | "creationModel" | "initialThinkingLevel">, createBinding?: typeof createRpcSessionBinding, connectionOptions?: Parameters<typeof createRpcSessionBinding>[4], idle?: RpcSessionIdlePolicy);
52
+ constructor(registry: Pick<RpcSessionRegistry, "openSession" | "peek" | "getForCommand" | "beginClose" | "close" | "closeMarked" | "list" | "size">, writer: SessionEventWriter, defaults: Pick<RpcSessionLaunchProfile, "cwd" | "permissionPreset" | "creationModel" | "initialThinkingLevel">, createBinding?: typeof createRpcSessionBinding, connectionOptions?: Parameters<typeof createRpcSessionBinding>[4], idle?: RpcSessionIdlePolicy);
53
53
  handle(command: RpcCommand): Promise<RpcResponse | undefined>;
54
54
  dispose(): Promise<void>;
55
55
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"session-command-router.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/session-command-router.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAO9D,OAAO,EAAE,uBAAuB,EAA0B,MAAM,sBAAsB,CAAC;AACvF,OAAO,KAAK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G;IACH,OAAO,CAAC,UAAU;IAYlB,kFAAkF;IAClF,OAAO,CAAC,aAAa;YAWP,KAAK;IAoCnB,qGAAqG;IACrG,OAAO,CAAC,sBAAsB;IAkB9B;;;;;;OAMG;YACW,aAAa;IA0B3B,OAAO,CAAC,kBAAkB;IAQ1B,OAAO,CAAC,IAAI;CAWZ"}
@@ -127,7 +127,7 @@ export class SessionCommandRouter {
127
127
  const entry = this.registry.peek(sessionId);
128
128
  if (!entry)
129
129
  continue;
130
- if (entry.runtime?.session.isSessionBusy) {
130
+ if (entry.worker?.busy || entry.runtime?.session.isSessionBusy) {
131
131
  // Session-owned work defers eviction; the window restarts when it settles.
132
132
  entry.lastCommandAt = now;
133
133
  continue;
@@ -279,11 +279,23 @@ export class SessionCommandRouter {
279
279
  },
280
280
  },
281
281
  }));
282
+ if (entry.worker)
283
+ entry.worker.bindingReady = true;
284
+ if (entry.worker)
285
+ void entry.worker.exited.then(async () => {
286
+ await this.finalizations.get(openedSession.sessionId)?.promise;
287
+ this.bindings.delete(openedSession.sessionId);
288
+ this.forgetSessionOwnership(openedSession.sessionId);
289
+ this.writer.forgetSession(openedSession.sessionId);
290
+ });
282
291
  }
283
292
  if (owner !== undefined && this.releasedConnections.has(owner)) {
293
+ this.releaseOwnerAttachment(owner, openedSession.sessionId);
284
294
  await this.releaseOwnedSession(openedSession.sessionId);
285
295
  }
286
- const state = entry.runtime.session;
296
+ const state = entry.worker?.snapshot?.state ?? (entry.runtime ? buildRpcSessionState(entry.runtime.session) : undefined);
297
+ if (!state)
298
+ throw new Error("Session state was not created");
287
299
  this.writer.enqueue(opened.sessionId, {
288
300
  id: command.id,
289
301
  type: "response",
@@ -291,7 +303,7 @@ export class SessionCommandRouter {
291
303
  success: true,
292
304
  data: {
293
305
  sessionId: opened.sessionId,
294
- state: buildRpcSessionState(state),
306
+ state,
295
307
  ...(opened.attached ? { attached: true } : {}),
296
308
  },
297
309
  });
@@ -324,15 +336,15 @@ export class SessionCommandRouter {
324
336
  for (const binding of this.bindings.values())
325
337
  binding.rerenderComponents?.();
326
338
  const opens = this.opensByConnection.get(connectionId);
327
- if (opens)
328
- await Promise.all([...opens]);
329
339
  const owned = this.sessionsByConnection.get(connectionId);
330
340
  this.sessionsByConnection.delete(connectionId);
331
341
  if (owned === undefined) {
342
+ if (opens)
343
+ await Promise.all([...opens]);
332
344
  this.releasedConnections.delete(connectionId);
333
345
  return;
334
346
  }
335
- for (const [sessionId, count] of owned) {
347
+ await Promise.all([...owned].map(async ([sessionId, count]) => {
336
348
  this.bindings.get(sessionId)?.cancelPendingExtensionUiRequests?.();
337
349
  for (let attachment = 0; attachment < count; attachment++) {
338
350
  // Headless completion contract: a turn survives its client's death and
@@ -344,6 +356,15 @@ export class SessionCommandRouter {
344
356
  // so the dropped owner's reservation still frees afterwards.
345
357
  const live = this.registry.peek(sessionId);
346
358
  const session = live?.state === "open" ? live.runtime?.session : undefined;
359
+ if (live?.state === "open" && live.worker?.snapshot?.streaming) {
360
+ const unsubscribe = live.worker.subscribeSettled(() => {
361
+ unsubscribe();
362
+ void this.releaseOwnedSession(sessionId).catch((cause) => {
363
+ process.stderr.write(`senpi rpc deferred worker release ${sessionId} failed: ${String(cause)}\n`);
364
+ });
365
+ });
366
+ continue;
367
+ }
347
368
  if (session?.isStreaming) {
348
369
  let released = false;
349
370
  const unsubscribe = session.subscribe((event) => {
@@ -361,7 +382,9 @@ export class SessionCommandRouter {
361
382
  }
362
383
  await this.releaseOwnedSession(sessionId);
363
384
  }
364
- }
385
+ }));
386
+ if (opens)
387
+ await Promise.all([...opens]);
365
388
  this.releasedConnections.delete(connectionId);
366
389
  }
367
390
  /**
@@ -411,15 +434,6 @@ export class SessionCommandRouter {
411
434
  }
412
435
  }
413
436
  async close(command) {
414
- // This must be the first operation: binding.dispose() awaits teardown and
415
- // otherwise leaves a window where commands can enter the old handler.
416
- let claim;
417
- try {
418
- claim = this.claimClose(command.sessionId, { drainAttachments: false });
419
- }
420
- catch (cause) {
421
- return error(command.id, "close_session", this.code(cause));
422
- }
423
437
  const response = {
424
438
  id: command.id,
425
439
  type: "response",
@@ -427,17 +441,35 @@ export class SessionCommandRouter {
427
441
  success: true,
428
442
  data: {},
429
443
  };
430
- const owner = this.writer.currentConnection();
431
- if (owner !== undefined)
432
- this.releaseOwnerAttachment(owner, command.sessionId);
433
- if (claim.finalizer) {
434
- await this.finalizeClose(command.sessionId, this.bindings.get(command.sessionId), () => this.writer.closeSession(command.sessionId, response));
444
+ const reply = this.writer.reserveCloseResponse(command.sessionId, response);
445
+ if (!reply)
446
+ return undefined;
447
+ // Admission and claiming are synchronous, before any teardown await. A
448
+ // saturated requester neither releases an attachment nor joins a promise.
449
+ let claim;
450
+ try {
451
+ claim = this.claimClose(command.sessionId, { drainAttachments: false });
435
452
  }
436
- else {
437
- await this.finalizations.get(command.sessionId)?.promise;
438
- this.writer.enqueueClosedResponse(command.sessionId, response);
453
+ catch (cause) {
454
+ reply.release();
455
+ return error(command.id, "close_session", this.code(cause));
456
+ }
457
+ try {
458
+ const owner = this.writer.currentConnection();
459
+ if (owner !== undefined)
460
+ this.releaseOwnerAttachment(owner, command.sessionId);
461
+ if (claim.finalizer) {
462
+ await this.finalizeClose(command.sessionId, this.bindings.get(command.sessionId), () => reply.complete(true));
463
+ }
464
+ else {
465
+ await this.finalizations.get(command.sessionId)?.promise;
466
+ reply.complete(false);
467
+ }
468
+ return undefined;
469
+ }
470
+ finally {
471
+ reply.release();
439
472
  }
440
- return undefined;
441
473
  }
442
474
  /** Detaches the closing connection's UI/width state; a rerender failure must not abort the close. */
443
475
  releaseOwnerAttachment(owner, sessionId) {