@code-yeongyu/senpi 2026.8.27 → 2026.8.28

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 (103) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/core/credential-accounts.d.ts +31 -0
  3. package/dist/core/credential-accounts.d.ts.map +1 -0
  4. package/dist/core/credential-accounts.js +125 -0
  5. package/dist/core/credential-accounts.js.map +1 -0
  6. package/dist/core/extensions/builtin/account/index.d.ts +9 -0
  7. package/dist/core/extensions/builtin/account/index.d.ts.map +1 -0
  8. package/dist/core/extensions/builtin/account/index.js +69 -0
  9. package/dist/core/extensions/builtin/account/index.js.map +1 -0
  10. package/dist/core/extensions/builtin/imagegen/index.d.ts.map +1 -1
  11. package/dist/core/extensions/builtin/imagegen/index.js +10 -3
  12. package/dist/core/extensions/builtin/imagegen/index.js.map +1 -1
  13. package/dist/core/extensions/builtin/index.d.ts.map +1 -1
  14. package/dist/core/extensions/builtin/index.js +4 -0
  15. package/dist/core/extensions/builtin/index.js.map +1 -1
  16. package/dist/main.d.ts.map +1 -1
  17. package/dist/main.js +12 -1
  18. package/dist/main.js.map +1 -1
  19. package/dist/modes/app-server/server/account.d.ts.map +1 -1
  20. package/dist/modes/app-server/server/account.js +5 -5
  21. package/dist/modes/app-server/server/account.js.map +1 -1
  22. package/dist/modes/interactive/components/footer.d.ts +11 -3
  23. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  24. package/dist/modes/interactive/components/footer.js +31 -1
  25. package/dist/modes/interactive/components/footer.js.map +1 -1
  26. package/dist/modes/interactive/grok/chrome.d.ts +4 -4
  27. package/dist/modes/interactive/grok/chrome.d.ts.map +1 -1
  28. package/dist/modes/interactive/grok/chrome.js.map +1 -1
  29. package/dist/modes/interactive/grok/footer.d.ts +3 -3
  30. package/dist/modes/interactive/grok/footer.d.ts.map +1 -1
  31. package/dist/modes/interactive/grok/footer.js.map +1 -1
  32. package/dist/modes/interactive/interactive-host-runtime.d.ts +16 -1
  33. package/dist/modes/interactive/interactive-host-runtime.d.ts.map +1 -1
  34. package/dist/modes/interactive/interactive-host-runtime.js +36 -9
  35. package/dist/modes/interactive/interactive-host-runtime.js.map +1 -1
  36. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  37. package/dist/modes/interactive/interactive-mode.js +19 -13
  38. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  39. package/dist/modes/rpc/connection-handler.d.ts.map +1 -1
  40. package/dist/modes/rpc/connection-handler.js +12 -5
  41. package/dist/modes/rpc/connection-handler.js.map +1 -1
  42. package/dist/modes/rpc/rpc-client.d.ts +16 -3
  43. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  44. package/dist/modes/rpc/rpc-client.js +43 -5
  45. package/dist/modes/rpc/rpc-client.js.map +1 -1
  46. package/dist/modes/rpc/rpc-types.d.ts +4 -1
  47. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  48. package/dist/modes/rpc/rpc-types.js.map +1 -1
  49. package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
  50. package/dist/modes/rpc/session-command-router.js +12 -4
  51. package/dist/modes/rpc/session-command-router.js.map +1 -1
  52. package/dist/modes/rpc/session-registry.d.ts +9 -0
  53. package/dist/modes/rpc/session-registry.d.ts.map +1 -1
  54. package/dist/modes/rpc/session-registry.js +31 -3
  55. package/dist/modes/rpc/session-registry.js.map +1 -1
  56. package/docs/providers.md +48 -0
  57. package/docs/rpc.md +6 -4
  58. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +14 -0
  59. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  60. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/context-manager.ts +13 -1
  61. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/inline-worker.ts +15 -1
  62. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/py/transport.ts +14 -1
  63. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.d.ts.map +1 -1
  64. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.js +20 -4
  65. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.js.map +1 -1
  66. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/index.d.ts +1 -1
  67. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/index.d.ts.map +1 -1
  68. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/index.js.map +1 -1
  69. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/post-mutate.d.ts +21 -0
  70. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/post-mutate.d.ts.map +1 -0
  71. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/post-mutate.js +27 -0
  72. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/post-mutate.js.map +1 -0
  73. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/tool-context.d.ts +24 -0
  74. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/tool-context.d.ts.map +1 -1
  75. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/tool-context.js.map +1 -1
  76. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/write.d.ts.map +1 -1
  77. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/write.js +7 -2
  78. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/write.js.map +1 -1
  79. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  80. package/node_modules/@earendil-works/pi-ai/dist/auth/credential-store.d.ts +2 -1
  81. package/node_modules/@earendil-works/pi-ai/dist/auth/credential-store.d.ts.map +1 -1
  82. package/node_modules/@earendil-works/pi-ai/dist/auth/credential-store.js +2 -1
  83. package/node_modules/@earendil-works/pi-ai/dist/auth/credential-store.js.map +1 -1
  84. package/node_modules/@earendil-works/pi-ai/dist/auth/types.d.ts +3 -2
  85. package/node_modules/@earendil-works/pi-ai/dist/auth/types.d.ts.map +1 -1
  86. package/node_modules/@earendil-works/pi-ai/dist/auth/types.js.map +1 -1
  87. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  88. package/node_modules/@earendil-works/pi-ai/dist/providers/data/alibaba-token-plan.json +1 -1
  89. package/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  90. package/node_modules/@earendil-works/pi-ai/dist/providers/data/github-copilot.json +1 -1
  91. package/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
  92. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openai-codex.json +1 -1
  93. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openai.json +1 -1
  94. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  95. package/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan-cn.json +1 -1
  96. package/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan.json +1 -1
  97. package/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
  98. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  99. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  100. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  101. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  102. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  103. package/package.json +7 -7
@@ -63,8 +63,9 @@ export class SessionCommandRouter {
63
63
  }
64
64
  async dispose() {
65
65
  await Promise.all([...this.bindings.entries()].map(async ([sessionId, binding]) => {
66
+ let entry;
66
67
  try {
67
- this.registry.beginClose(sessionId);
68
+ entry = this.registry.beginClose(sessionId);
68
69
  }
69
70
  catch {
70
71
  return;
@@ -74,7 +75,10 @@ export class SessionCommandRouter {
74
75
  }
75
76
  finally {
76
77
  this.bindings.delete(sessionId);
77
- await this.registry.closeMarked(sessionId);
78
+ // Attached sessions outlive this connection: only the last
79
+ // attachment's close transitions the entry to "closing".
80
+ if (entry.state === "closing")
81
+ await this.registry.closeMarked(sessionId);
78
82
  }
79
83
  }));
80
84
  this.bindings.clear();
@@ -103,6 +107,7 @@ export class SessionCommandRouter {
103
107
  data: {
104
108
  sessionId: opened.sessionId,
105
109
  state: buildRpcSessionState(state),
110
+ ...(opened.attached ? { attached: true } : {}),
106
111
  },
107
112
  });
108
113
  return undefined;
@@ -123,13 +128,16 @@ export class SessionCommandRouter {
123
128
  try {
124
129
  // This must be the first operation: binding.dispose() awaits teardown and
125
130
  // otherwise leaves a window where commands can enter the old handler.
126
- this.registry.beginClose(command.sessionId);
131
+ const entry = this.registry.beginClose(command.sessionId);
127
132
  try {
128
133
  await this.bindings.get(command.sessionId)?.dispose();
129
134
  }
130
135
  finally {
131
136
  this.bindings.delete(command.sessionId);
132
- await this.registry.closeMarked(command.sessionId);
137
+ // Other attachments may still own the live session; only the last
138
+ // close finalizes the runtime teardown.
139
+ if (entry.state === "closing")
140
+ await this.registry.closeMarked(command.sessionId);
133
141
  }
134
142
  this.writer.closeSession(command.sessionId, {
135
143
  id: command.id,
@@ -1 +1 @@
1
- {"version":3,"file":"session-command-router.js","sourceRoot":"","sources":["../../../src/modes/rpc/session-command-router.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAE/D,OAAO,EACN,4BAA4B,EAC5B,qBAAqB,EACrB,yBAAyB,EACzB,yBAAyB,GACzB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,uBAAuB,EAA0B,MAAM,sBAAsB,CAAC;AAGvF,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAEhE,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,CAAC,mBAAmB,EAAE,cAAc,EAAE,eAAe,EAAE,eAAe,CAAC,CAAC,CAAC;AAElG,SAAS,KAAK,CAAC,EAAsB,EAAE,OAAe,EAAE,IAAY;IACnE,O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AC,CAAC,GAAG,qBAAqB,KAAK,KAAK,CAAC,OAAO,EAAE;YAC9C,CAAC,CAAC,yBAAyB,CAAC;IAC9B,CAAC;CACD","sourcesContent":["import { VERSION } from \"../../config.ts\";\nimport { buildRpcSessionState } from \"./connection-handler.ts\";\nimport type { RpcCommand, RpcResponse } from \"./rpc-types.ts\";\nimport {\n\tRPC_ERROR_MISSING_SESSION_ID,\n\tRPC_ERROR_OPEN_FAILED,\n\tRPC_ERROR_SESSION_CLOSING,\n\tRPC_ERROR_UNKNOWN_SESSION,\n} from \"./rpc-types.ts\";\nimport { createRpcSessionBinding, type RpcSessionBinding } from \"./session-binding.ts\";\nimport type { SessionEventWriter } from \"./session-event-writer.ts\";\nimport type { RpcSessionLaunchProfile, RpcSessionRegistry } from \"./session-registry.ts\";\nimport { RpcSessionRegistryError } from \"./session-registry.ts\";\n\nconst controls = new Set([\"get_protocol_info\", \"open_session\", \"close_session\", \"list_sessions\"]);\n\nfunction error(id: string | undefined, command: string, code: string): RpcResponse {\n\treturn { id, type: \"response\", command, success: false, error: code };\n}\n\n/** Routes control messages and enforces a routing handle for every session command. */\nexport class SessionCommandRouter {\n\tprivate readonly bindings = new Map<string, RpcSessionBinding>();\n\tprivate readonly registry: RpcSessionRegistry;\n\tprivate readonly writer: SessionEventWriter;\n\tprivate readonly defaults: Pick<\n\t\tRpcSessionLaunchProfile,\n\t\t\"cwd\" | \"permissionPreset\" | \"creationModel\" | \"initialThinkingLevel\"\n\t>;\n\tprivate readonly createBinding: typeof createRpcSessionBinding;\n\tprivate readonly connectionOptions: Parameters<typeof createRpcSessionBinding>[4];\n\n\tconstructor(\n\t\tregistry: RpcSessionRegistry,\n\t\twriter: SessionEventWriter,\n\t\tdefaults: Pick<RpcSessionLaunchProfile, \"cwd\" | \"permissionPreset\" | \"creationModel\" | \"initialThinkingLevel\">,\n\t\tcreateBinding: typeof createRpcSessionBinding = createRpcSessionBinding,\n\t\tconnectionOptions: Parameters<typeof createRpcSessionBinding>[4] = {},\n\t) {\n\t\tthis.registry = registry;\n\t\tthis.writer = writer;\n\t\tthis.defaults = defaults;\n\t\tthis.createBinding = createBinding;\n\t\tthis.connectionOptions = connectionOptions;\n\t}\n\n\tasync handle(command: RpcCommand): Promise<RpcResponse | undefined> {\n\t\tif (command.type === \"get_protocol_info\") {\n\t\t\tconst capabilities = new Set([\"multi_session\", ...(this.connectionOptions?.capabilities ?? [])]);\n\t\t\treturn {\n\t\t\t\tid: command.id,\n\t\t\t\ttype: \"response\",\n\t\t\t\tcommand: \"get_protocol_info\",\n\t\t\t\tsuccess: true,\n\t\t\t\tdata: {\n\t\t\t\t\tprotocolVersion: 1,\n\t\t\t\t\tserverVersion: VERSION,\n\t\t\t\t\tcapabilities: [...capabilities],\n\t\t\t\t\tmode: \"multi\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (command.type === \"list_sessions\")\n\t\t\treturn {\n\t\t\t\tid: command.id,\n\t\t\t\ttype: \"response\",\n\t\t\t\tcommand: \"list_sessions\",\n\t\t\t\tsuccess: true,\n\t\t\t\tdata: { sessions: this.registry.list() },\n\t\t\t};\n\t\tif (command.type === \"open_session\") return this.open(command);\n\t\tif (command.type === \"close_session\") return this.close(command);\n\t\tif (controls.has(command.type)) return undefined;\n\t\tif (!command.sessionId) return error(command.id, command.type, RPC_ERROR_MISSING_SESSION_ID);\n\t\ttry {\n\t\t\tthis.registry.getForCommand(command.sessionId, command.type);\n\t\t\tconst binding = this.bindings.get(command.sessionId);\n\t\t\tif (!binding) return error(command.id, command.type, RPC_ERROR_UNKNOWN_SESSION);\n\t\t\tawait binding.handle(command);\n\t\t\treturn undefined;\n\t\t} catch (cause) {\n\t\t\treturn error(command.id, command.type, this.code(cause));\n\t\t}\n\t}\n\n\tasync dispose(): Promise<void> {\n\t\tawait Promise.all(\n\t\t\t[...this.bindings.entries()].map(async ([sessionId, binding]) => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.registry.beginClose(sessionId);\n\t\t\t\t} catch {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tawait binding.dispose();\n\t\t\t\t} finally {\n\t\t\t\t\tthis.bindings.delete(sessionId);\n\t\t\t\t\tawait this.registry.closeMarked(sessionId);\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t\tthis.bindings.clear();\n\t}\n\n\tprivate async open(command: Extract<RpcCommand, { type: \"open_session\" }>): Promise<RpcResponse | undefined> {\n\t\tlet opened: { sessionId: string } | undefined;\n\t\ttry {\n\t\t\topened = await this.registry.openSession({\n\t\t\t\tcwd: command.cwd ?? this.defaults.cwd,\n\t\t\t\tsessionPath: command.sessionPath,\n\t\t\t\tpermissionPreset: command.permissionPreset ?? this.defaults.permissionPreset,\n\t\t\t\tcreationModel:\n\t\t\t\t\tcommand.provider && command.modelId\n\t\t\t\t\t\t? { provider: command.provider, modelId: command.modelId }\n\t\t\t\t\t\t: this.defaults.creationModel,\n\t\t\t\tinitialThinkingLevel: command.thinkingLevel ?? this.defaults.initialThinkingLevel,\n\t\t\t});\n\t\t\tconst openedSession = opened;\n\t\t\tconst entry = this.registry.getForCommand(openedSession.sessionId, \"open_session\");\n\t\t\tthis.bindings.set(\n\t\t\t\topenedSession.sessionId,\n\t\t\t\tawait this.createBinding(\n\t\t\t\t\topenedSession.sessionId,\n\t\t\t\t\tentry,\n\t\t\t\t\tthis.writer,\n\t\t\t\t\t() => void this.close({ type: \"close_session\", sessionId: openedSession.sessionId }),\n\t\t\t\t\tthis.connectionOptions,\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst state = entry.runtime!.session;\n\t\t\tthis.writer.enqueue(opened.sessionId, {\n\t\t\t\tid: command.id,\n\t\t\t\ttype: \"response\",\n\t\t\t\tcommand: \"open_session\",\n\t\t\t\tsuccess: true,\n\t\t\t\tdata: {\n\t\t\t\t\tsessionId: opened.sessionId,\n\t\t\t\t\tstate: buildRpcSessionState(state),\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn undefined;\n\t\t} catch (cause) {\n\t\t\tif (opened) {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.registry.close(opened.sessionId);\n\t\t\t\t} catch {\n\t\t\t\t\t/* The open rollback has already removed the entry. */\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn error(command.id, \"open_session\", this.code(cause));\n\t\t}\n\t}\n\n\tprivate async close(command: Extract<RpcCommand, { type: \"close_session\" }>): Promise<RpcResponse | undefined> {\n\t\ttry {\n\t\t\t// This must be the first operation: binding.dispose() awaits teardown and\n\t\t\t// otherwise leaves a window where commands can enter the old handler.\n\t\t\tthis.registry.beginClose(command.sessionId);\n\t\t\ttry {\n\t\t\t\tawait this.bindings.get(command.sessionId)?.dispose();\n\t\t\t} finally {\n\t\t\t\tthis.bindings.delete(command.sessionId);\n\t\t\t\tawait this.registry.closeMarked(command.sessionId);\n\t\t\t}\n\t\t\tthis.writer.closeSession(command.sessionId, {\n\t\t\t\tid: command.id,\n\t\t\t\ttype: \"response\",\n\t\t\t\tcommand: \"close_session\",\n\t\t\t\tsuccess: true,\n\t\t\t\tdata: {},\n\t\t\t});\n\t\t\treturn undefined;\n\t\t} catch (cause) {\n\t\t\treturn error(command.id, \"close_session\", this.code(cause));\n\t\t}\n\t}\n\n\tprivate code(cause: unknown): string {\n\t\tif (cause instanceof RpcSessionRegistryError) {\n\t\t\treturn cause.code === RPC_ERROR_OPEN_FAILED ? cause.message : cause.code;\n\t\t}\n\t\tif (cause instanceof Error && [RPC_ERROR_UNKNOWN_SESSION, RPC_ERROR_SESSION_CLOSING].includes(cause.message)) {\n\t\t\treturn cause.message;\n\t\t}\n\t\treturn cause instanceof Error && cause.message\n\t\t\t? `${RPC_ERROR_OPEN_FAILED}: ${cause.message}`\n\t\t\t: RPC_ERROR_UNKNOWN_SESSION;\n\t}\n}\n"]}
1
+ {"version":3,"file":"session-command-router.js","sourceRoot":"","sources":["../../../src/modes/rpc/session-command-router.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAA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E,EAAE,OAAO,CAAC,EAAE;gBACd,IAAI,EAAE,UAAU;gBAChB,OAAO,EAAE,eAAe;gBACxB,OAAO,EAAE,IAAI;gBACb,IAAI,EAAE,EAAE;aACR,CAAC,CAAC;YACH,OAAO,SAAS,CAAC;QAClB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,OAAO,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,eAAe,EAAE,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;QAC7D,CAAC;IACF,CAAC;IAEO,IAAI,CAAC,KAAc;QAC1B,IAAI,KAAK,YAAY,uBAAuB,EAAE,CAAC;YAC9C,OAAO,KAAK,CAAC,IAAI,KAAK,qBAAqB,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC;QAC1E,CAAC;QACD,IAAI,KAAK,YAAY,KAAK,IAAI,CAAC,yBAAyB,EAAE,yBAAyB,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;YAC9G,OAAO,KAAK,CAAC,OAAO,CAAC;QACtB,CAAC;QACD,OAAO,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,OAAO;YAC7C,CAAC,CAAC,GAAG,qBAAqB,KAAK,KAAK,CAAC,OAAO,EAAE;YAC9C,CAAC,CAAC,yBAAyB,CAAC;IAC9B,CAAC;CACD","sourcesContent":["import { VERSION } from \"../../config.ts\";\nimport { buildRpcSessionState } from \"./connection-handler.ts\";\nimport type { RpcCommand, RpcResponse } from \"./rpc-types.ts\";\nimport {\n\tRPC_ERROR_MISSING_SESSION_ID,\n\tRPC_ERROR_OPEN_FAILED,\n\tRPC_ERROR_SESSION_CLOSING,\n\tRPC_ERROR_UNKNOWN_SESSION,\n} from \"./rpc-types.ts\";\nimport { createRpcSessionBinding, type RpcSessionBinding } from \"./session-binding.ts\";\nimport type { SessionEventWriter } from \"./session-event-writer.ts\";\nimport type {\n\tOpenRpcSession,\n\tRpcSessionEntry,\n\tRpcSessionLaunchProfile,\n\tRpcSessionRegistry,\n} from \"./session-registry.ts\";\nimport { RpcSessionRegistryError } from \"./session-registry.ts\";\n\nconst controls = new Set([\"get_protocol_info\", \"open_session\", \"close_session\", \"list_sessions\"]);\n\nfunction error(id: string | undefined, command: string, code: string): RpcResponse {\n\treturn { id, type: \"response\", command, success: false, error: code };\n}\n\n/** Routes control messages and enforces a routing handle for every session command. */\nexport class SessionCommandRouter {\n\tprivate readonly bindings = new Map<string, RpcSessionBinding>();\n\tprivate readonly registry: RpcSessionRegistry;\n\tprivate readonly writer: SessionEventWriter;\n\tprivate readonly defaults: Pick<\n\t\tRpcSessionLaunchProfile,\n\t\t\"cwd\" | \"permissionPreset\" | \"creationModel\" | \"initialThinkingLevel\"\n\t>;\n\tprivate readonly createBinding: typeof createRpcSessionBinding;\n\tprivate readonly connectionOptions: Parameters<typeof createRpcSessionBinding>[4];\n\n\tconstructor(\n\t\tregistry: RpcSessionRegistry,\n\t\twriter: SessionEventWriter,\n\t\tdefaults: Pick<RpcSessionLaunchProfile, \"cwd\" | \"permissionPreset\" | \"creationModel\" | \"initialThinkingLevel\">,\n\t\tcreateBinding: typeof createRpcSessionBinding = createRpcSessionBinding,\n\t\tconnectionOptions: Parameters<typeof createRpcSessionBinding>[4] = {},\n\t) {\n\t\tthis.registry = registry;\n\t\tthis.writer = writer;\n\t\tthis.defaults = defaults;\n\t\tthis.createBinding = createBinding;\n\t\tthis.connectionOptions = connectionOptions;\n\t}\n\n\tasync handle(command: RpcCommand): Promise<RpcResponse | undefined> {\n\t\tif (command.type === \"get_protocol_info\") {\n\t\t\tconst capabilities = new Set([\"multi_session\", ...(this.connectionOptions?.capabilities ?? [])]);\n\t\t\treturn {\n\t\t\t\tid: command.id,\n\t\t\t\ttype: \"response\",\n\t\t\t\tcommand: \"get_protocol_info\",\n\t\t\t\tsuccess: true,\n\t\t\t\tdata: {\n\t\t\t\t\tprotocolVersion: 1,\n\t\t\t\t\tserverVersion: VERSION,\n\t\t\t\t\tcapabilities: [...capabilities],\n\t\t\t\t\tmode: \"multi\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (command.type === \"list_sessions\")\n\t\t\treturn {\n\t\t\t\tid: command.id,\n\t\t\t\ttype: \"response\",\n\t\t\t\tcommand: \"list_sessions\",\n\t\t\t\tsuccess: true,\n\t\t\t\tdata: { sessions: this.registry.list() },\n\t\t\t};\n\t\tif (command.type === \"open_session\") return this.open(command);\n\t\tif (command.type === \"close_session\") return this.close(command);\n\t\tif (controls.has(command.type)) return undefined;\n\t\tif (!command.sessionId) return error(command.id, command.type, RPC_ERROR_MISSING_SESSION_ID);\n\t\ttry {\n\t\t\tthis.registry.getForCommand(command.sessionId, command.type);\n\t\t\tconst binding = this.bindings.get(command.sessionId);\n\t\t\tif (!binding) return error(command.id, command.type, RPC_ERROR_UNKNOWN_SESSION);\n\t\t\tawait binding.handle(command);\n\t\t\treturn undefined;\n\t\t} catch (cause) {\n\t\t\treturn error(command.id, command.type, this.code(cause));\n\t\t}\n\t}\n\n\tasync dispose(): Promise<void> {\n\t\tawait Promise.all(\n\t\t\t[...this.bindings.entries()].map(async ([sessionId, binding]) => {\n\t\t\t\tlet entry: RpcSessionEntry | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tentry = this.registry.beginClose(sessionId);\n\t\t\t\t} catch {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tawait binding.dispose();\n\t\t\t\t} finally {\n\t\t\t\t\tthis.bindings.delete(sessionId);\n\t\t\t\t\t// Attached sessions outlive this connection: only the last\n\t\t\t\t\t// attachment's close transitions the entry to \"closing\".\n\t\t\t\t\tif (entry.state === \"closing\") await this.registry.closeMarked(sessionId);\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t\tthis.bindings.clear();\n\t}\n\n\tprivate async open(command: Extract<RpcCommand, { type: \"open_session\" }>): Promise<RpcResponse | undefined> {\n\t\tlet opened: OpenRpcSession | undefined;\n\t\ttry {\n\t\t\topened = await this.registry.openSession({\n\t\t\t\tcwd: command.cwd ?? this.defaults.cwd,\n\t\t\t\tsessionPath: command.sessionPath,\n\t\t\t\tpermissionPreset: command.permissionPreset ?? this.defaults.permissionPreset,\n\t\t\t\tcreationModel:\n\t\t\t\t\tcommand.provider && command.modelId\n\t\t\t\t\t\t? { provider: command.provider, modelId: command.modelId }\n\t\t\t\t\t\t: this.defaults.creationModel,\n\t\t\t\tinitialThinkingLevel: command.thinkingLevel ?? this.defaults.initialThinkingLevel,\n\t\t\t});\n\t\t\tconst openedSession = opened;\n\t\t\tconst entry = this.registry.getForCommand(openedSession.sessionId, \"open_session\");\n\t\t\tthis.bindings.set(\n\t\t\t\topenedSession.sessionId,\n\t\t\t\tawait this.createBinding(\n\t\t\t\t\topenedSession.sessionId,\n\t\t\t\t\tentry,\n\t\t\t\t\tthis.writer,\n\t\t\t\t\t() => void this.close({ type: \"close_session\", sessionId: openedSession.sessionId }),\n\t\t\t\t\tthis.connectionOptions,\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst state = entry.runtime!.session;\n\t\t\tthis.writer.enqueue(opened.sessionId, {\n\t\t\t\tid: command.id,\n\t\t\t\ttype: \"response\",\n\t\t\t\tcommand: \"open_session\",\n\t\t\t\tsuccess: true,\n\t\t\t\tdata: {\n\t\t\t\t\tsessionId: opened.sessionId,\n\t\t\t\t\tstate: buildRpcSessionState(state),\n\t\t\t\t\t...(opened.attached ? { attached: true } : {}),\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn undefined;\n\t\t} catch (cause) {\n\t\t\tif (opened) {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.registry.close(opened.sessionId);\n\t\t\t\t} catch {\n\t\t\t\t\t/* The open rollback has already removed the entry. */\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn error(command.id, \"open_session\", this.code(cause));\n\t\t}\n\t}\n\n\tprivate async close(command: Extract<RpcCommand, { type: \"close_session\" }>): Promise<RpcResponse | undefined> {\n\t\ttry {\n\t\t\t// This must be the first operation: binding.dispose() awaits teardown and\n\t\t\t// otherwise leaves a window where commands can enter the old handler.\n\t\t\tconst entry = this.registry.beginClose(command.sessionId);\n\t\t\ttry {\n\t\t\t\tawait this.bindings.get(command.sessionId)?.dispose();\n\t\t\t} finally {\n\t\t\t\tthis.bindings.delete(command.sessionId);\n\t\t\t\t// Other attachments may still own the live session; only the last\n\t\t\t\t// close finalizes the runtime teardown.\n\t\t\t\tif (entry.state === \"closing\") await this.registry.closeMarked(command.sessionId);\n\t\t\t}\n\t\t\tthis.writer.closeSession(command.sessionId, {\n\t\t\t\tid: command.id,\n\t\t\t\ttype: \"response\",\n\t\t\t\tcommand: \"close_session\",\n\t\t\t\tsuccess: true,\n\t\t\t\tdata: {},\n\t\t\t});\n\t\t\treturn undefined;\n\t\t} catch (cause) {\n\t\t\treturn error(command.id, \"close_session\", this.code(cause));\n\t\t}\n\t}\n\n\tprivate code(cause: unknown): string {\n\t\tif (cause instanceof RpcSessionRegistryError) {\n\t\t\treturn cause.code === RPC_ERROR_OPEN_FAILED ? cause.message : cause.code;\n\t\t}\n\t\tif (cause instanceof Error && [RPC_ERROR_UNKNOWN_SESSION, RPC_ERROR_SESSION_CLOSING].includes(cause.message)) {\n\t\t\treturn cause.message;\n\t\t}\n\t\treturn cause instanceof Error && cause.message\n\t\t\t? `${RPC_ERROR_OPEN_FAILED}: ${cause.message}`\n\t\t\t: RPC_ERROR_UNKNOWN_SESSION;\n\t}\n}\n"]}
@@ -13,6 +13,10 @@ export interface RpcSessionEntry {
13
13
  profile: Readonly<RpcSessionLaunchProfile>;
14
14
  durableSessionId?: string;
15
15
  sessionPath?: string;
16
+ /** Canonical reservation key for path-opened sessions; matches the reservations set. */
17
+ reservationKey?: string;
18
+ /** Live attachments (open + later attaches). The runtime is disposed only when the last one closes. */
19
+ attachments: number;
16
20
  lifecycleMutex: Promise<void>;
17
21
  }
18
22
  export declare class RpcSessionRegistryError extends Error {
@@ -27,6 +31,8 @@ export interface OpenRpcSession {
27
31
  sessionId: string;
28
32
  durableSessionId: string;
29
33
  sessionPath?: string;
34
+ /** True when this open attached to an already-open session instead of creating one. */
35
+ attached?: boolean;
30
36
  }
31
37
  /** Process-local lifecycle owner for multi-session RPC runtimes. */
32
38
  export declare class RpcSessionRegistry {
@@ -40,6 +46,9 @@ export declare class RpcSessionRegistry {
40
46
  /**
41
47
  * Starts a close synchronously. Call this before disposing any session-owned
42
48
  * binding so a concurrent command cannot reach a half-disposed handler.
49
+ * Each call releases one attachment; the entry transitions to "closing" only
50
+ * when the last attachment closes, so callers must check the returned state
51
+ * and skip finalization while other attachments remain.
43
52
  */
44
53
  beginClose(handle: string): RpcSessionEntry;
45
54
  close(handle: string): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"session-registry.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/session-registry.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAwB,MAAM,2CAA2C,CAAC;AAChG,OAAO,EACN,KAAK,yBAAyB,EAC9B,KAAK,mBAAmB,EACxB,KAAK,gCAAgC,EAErC,MAAM,qCAAqC,CAAC;AAG7C,qEAAqE;AACrE,MAAM,WAAW,uBAAwB,SAAQ,yBAAyB;IACzE,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,MAAM,cAAc,GAAG,IAAI,CAAC,mBAAmB,EAAE,SAAS,GAAG,SAAS,CAAC,CAAC;AAC9E,MAAM,MAAM,eAAe,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,GAAG,QAAQ,CAAC;AAExE,MAAM,WAAW,eAAe;IAC/B,KAAK,EAAE,eAAe,CAAC;IACvB,OAAO,CAAC,EAAE,cAAc,CAAC;IACzB,KAAK,EAAE,aAAa,CAAC;IACrB,OAAO,EAAE,QAAQ,CAAC,uBAAuB,CAAC,CAAC;IAC3C,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,WAA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) {
34
34
  this.validateProfile(profile);
35
35
  const sessionPath = profile.sessionPath ? canonicalPath(profile.sessionPath) : undefined;
36
- if (sessionPath && this.reservations.has(sessionPath))
37
- throw new RpcSessionRegistryError("session_path_in_use");
36
+ if (sessionPath && this.reservations.has(sessionPath)) {
37
+ // Attach-on-open: a live session outlives individual client attachments, so a
38
+ // resume (or a second surface) for an already-hosted path joins the existing
39
+ // runtime instead of failing. Entries still opening or closing keep the
40
+ // exclusive reservation and reject as before.
41
+ const existing = [...this.entries].find(([, entry]) => entry.reservationKey === sessionPath && entry.state === "open");
42
+ if (!existing)
43
+ throw new RpcSessionRegistryError("session_path_in_use");
44
+ const [handle, entry] = existing;
45
+ entry.attachments += 1;
46
+ if (!entry.durableSessionId)
47
+ throw new RpcSessionRegistryError("session_path_in_use");
48
+ return {
49
+ sessionId: handle,
50
+ durableSessionId: entry.durableSessionId,
51
+ sessionPath: entry.sessionPath,
52
+ attached: true,
53
+ };
54
+ }
38
55
  if (sessionPath)
39
56
  this.reservations.add(sessionPath);
40
57
  // Resume vs create parity (D1 + omo SenpiSessionRuntime.ts:198-200):
@@ -52,6 +69,8 @@ export class RpcSessionRegistry {
52
69
  scope: new ProviderScope(),
53
70
  profile: storedProfile,
54
71
  sessionPath,
72
+ reservationKey: sessionPath,
73
+ attachments: 1,
55
74
  lifecycleMutex: Promise.resolve(),
56
75
  };
57
76
  this.entries.set(handle, entry);
@@ -110,16 +129,25 @@ export class RpcSessionRegistry {
110
129
  /**
111
130
  * Starts a close synchronously. Call this before disposing any session-owned
112
131
  * binding so a concurrent command cannot reach a half-disposed handler.
132
+ * Each call releases one attachment; the entry transitions to "closing" only
133
+ * when the last attachment closes, so callers must check the returned state
134
+ * and skip finalization while other attachments remain.
113
135
  */
114
136
  beginClose(handle) {
115
137
  const entry = this.entries.get(handle);
116
138
  if (entry?.state !== "open")
117
139
  throw new RpcSessionRegistryError("unknown_session");
140
+ entry.attachments -= 1;
141
+ if (entry.attachments > 0)
142
+ return entry;
118
143
  entry.state = "closing";
119
144
  return entry;
120
145
  }
121
146
  async close(handle) {
122
- this.beginClose(handle);
147
+ const entry = this.beginClose(handle);
148
+ // Other attachments may still own the live session; only the last close finalizes.
149
+ if (entry.state !== "closing")
150
+ return;
123
151
  return this.closeMarked(handle);
124
152
  }
125
153
  /** Completes a close previously made visible by beginClose(). */
@@ -1 +1 @@
1
- {"version":3,"file":"session-registry.js","sourceRoot":"","sources":["../../../src/modes/rpc/session-registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAChG,OAAO,EAIN,yBAAyB,GACzB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAoB/D,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAGjD,YAAY,IAAqC,EAAE,MAAe;QACjE,KAAK,CAAC,IAAI,KAAK,aAAa,IAAI,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;QACtE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;IACvC,CAAC;CACD;AAaD,SAAS,aAAa,CAAC,IAAY;IAClC,MAAM,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACnC,IAAI,UAAU,CAAC,YAAY,CAAC;QAAE,OAAO,YAAY,CAAC,YAAY,CAAC,CAAC;IAChE,OAAO,GAAG,YAAY,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,IAAI,QAAQ,CAAC,YAAY,CAAC,EAAE,CAAC;AAC3E,CAAC;AAED,SAAS,aAAa,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AAC,MAAM,CAAC,CAAC;gBAC5B,IAAI,KAAK,CAAC,WAAW;oBAAE,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;YACpE,CAAC;QACF,CAAC,CAAC,EAAE,CAAC;QACL,OAAO,KAAK,CAAC,cAAc,CAAC;IAC7B,CAAC;IAED,IAAI;QAQH,OAAO,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;YACrD,SAAS;YACT,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;YACxC,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,GAAG,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG;YACtB,IAAI,EAAE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,cAAc,CAAC,cAAc,EAAE;YAC5D,MAAM,EAAE,KAAK,CAAC,KAAK;SACnB,CAAC,CAAC,CAAC;IACL,CAAC;IAEO,eAAe,CAAC,OAAgC;QACvD,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,KAAK,SAAS,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,EAAE,CAAC;YACzG,MAAM,IAAI,uBAAuB,CAAC,cAAc,CAAC,CAAC;QACnD,CAAC;IACF,CAAC;CACD","sourcesContent":["import { existsSync, realpathSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, resolve } from \"node:path\";\nimport { ProviderScope, runWithProviderScope } from \"@earendil-works/pi-ai/node/provider-scope\";\nimport {\n\ttype AgentSessionLaunchProfile,\n\ttype AgentSessionRuntime,\n\ttype CreateAgentSessionRuntimeFactory,\n\tcreateAgentSessionRuntime,\n} from \"../../core/agent-session-runtime.ts\";\nimport { SessionManager } from \"../../core/session-manager.ts\";\n\n/** The immutable flags selected when a routing session is opened. */\nexport interface RpcSessionLaunchProfile extends AgentSessionLaunchProfile {\n\tsessionPath?: string;\n}\n\nexport type SessionRuntime = Pick<AgentSessionRuntime, \"session\" | \"dispose\">;\nexport type RpcSessionState = \"opening\" | \"open\" | \"closing\" | \"closed\";\n\nexport interface RpcSessionEntry {\n\tstate: RpcSessionState;\n\truntime?: SessionRuntime;\n\tscope: ProviderScope;\n\tprofile: Readonly<RpcSessionLaunchProfile>;\n\tdurableSessionId?: string;\n\tsessionPath?: string;\n\tlifecycleMutex: Promise<void>;\n}\n\nexport class RpcSessionRegistryError extends Error {\n\treadonly code: \"unknown_session\" | \"session_closing\" | \"session_path_in_use\" | \"invalid_path\" | \"open_failed\";\n\n\tconstructor(code: RpcSessionRegistryError[\"code\"], reason?: string) {\n\t\tsuper(code === \"open_failed\" && reason ? `${code}: ${reason}` : code);\n\t\tthis.code = code;\n\t\tthis.name = \"RpcSessionRegistryError\";\n\t}\n}\n\nexport interface RpcSessionRegistryOptions {\n\tagentDir: string;\n\tcreateRuntime: CreateAgentSessionRuntimeFactory;\n}\n\nexport interface OpenRpcSession {\n\tsessionId: string;\n\tdurableSessionId: string;\n\tsessionPath?: string;\n}\n\nfunction canonicalPath(path: string): string {\n\tconst absolutePath = resolve(path);\n\tif (existsSync(absolutePath)) return realpathSync(absolutePath);\n\treturn `${realpathSync(dirname(absolutePath))}/${basename(absolutePath)}`;\n}\n\nfunction frozenProfile(profile: RpcSessionLaunchProfile): Readonly<RpcSessionLaunchProfile> {\n\treturn Object.freeze({\n\t\t...profile,\n\t\t...(profile.creationModel ? { creationModel: Object.freeze({ ...profile.creationModel }) } : {}),\n\t});\n}\n\n/** Process-local lifecycle owner for multi-session RPC runtimes. */\nexport class RpcSessionRegistry {\n\tprivate readonly entries = new Map<string, RpcSessionEntry>();\n\tprivate readonly reservations = new Set<string>();\n\tprivate nextHandle = 0;\n\tprivate readonly options: RpcSessionRegistryOptions;\n\n\tconstructor(options: RpcSessionRegistryOptions) {\n\t\tthis.options = options;\n\t}\n\n\tasync openSession(profile: RpcSessionLaunchProfile): Promise<OpenRpcSession> {\n\t\tthis.validateProfile(profile);\n\t\tconst sessionPath = profile.sessionPath ? canonicalPath(profile.sessionPath) : undefined;\n\t\tif (sessionPath && this.reservations.has(sessionPath)) throw new RpcSessionRegistryError(\"session_path_in_use\");\n\t\tif (sessionPath) this.reservations.add(sessionPath);\n\n\t\t// Resume vs create parity (D1 + omo SenpiSessionRuntime.ts:198-200):\n\t\t// Create-only launch semantics mirror classic startup flags. A resumed\n\t\t// session restores its persisted model and thinking level instead of being\n\t\t// overridden by the new open_session request.\n\t\tconst isResume = sessionPath !== undefined && existsSync(sessionPath);\n\t\tconst storedProfile = frozenProfile({ ...profile, ...(sessionPath ? { sessionPath } : {}) });\n\t\tconst runtimeProfile = isResume\n\t\t\t? frozenProfile({ ...storedProfile, creationModel: undefined, initialThinkingLevel: undefined })\n\t\t\t: storedProfile;\n\n\t\tconst handle = `rpc-${++this.nextHandle}`;\n\t\tconst entry: RpcSessionEntry = {\n\t\t\tstate: \"opening\",\n\t\t\tscope: new ProviderScope(),\n\t\t\tprofile: storedProfile,\n\t\t\tsessionPath,\n\t\t\tlifecycleMutex: Promise.resolve(),\n\t\t};\n\t\tthis.entries.set(handle, entry);\n\t\ttry {\n\t\t\tconst manager = sessionPath\n\t\t\t\t? SessionManager.open(sessionPath, undefined, storedProfile.cwd)\n\t\t\t\t: SessionManager.create(storedProfile.cwd);\n\t\t\tentry.runtime = await runWithProviderScope(entry.scope, () =>\n\t\t\t\tcreateAgentSessionRuntime(this.options.createRuntime, {\n\t\t\t\t\tcwd: manager.getCwd(),\n\t\t\t\t\tagentDir: this.options.agentDir,\n\t\t\t\t\tsessionManager: manager,\n\t\t\t\t\tlaunchProfile: runtimeProfile,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tentry.durableSessionId = manager.getSessionId();\n\t\t\tentry.sessionPath ??= manager.getSessionFile();\n\t\t\tentry.state = \"open\";\n\t\t\treturn { sessionId: handle, durableSessionId: entry.durableSessionId, sessionPath: entry.sessionPath };\n\t\t} catch (error) {\n\t\t\t// Runtime construction may have started extensions, watchers, and provider\n\t\t\t// registrations before it rejects. Keep the reservation and entry private\n\t\t\t// until all of those resources have been torn down, then release them as\n\t\t\t// one rollback so the path can immediately be opened again.\n\t\t\ttry {\n\t\t\t\tawait entry.runtime?.dispose();\n\t\t\t} catch {\n\t\t\t\t// The original construction error remains the externally visible cause.\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\tawait entry.scope.close?.();\n\t\t\t\t} finally {\n\t\t\t\t\tthis.entries.delete(handle);\n\t\t\t\t\tif (sessionPath) this.reservations.delete(sessionPath);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (error instanceof RpcSessionRegistryError) throw error;\n\t\t\tthrow new RpcSessionRegistryError(\"open_failed\", error instanceof Error ? error.message : undefined);\n\t\t}\n\t}\n\n\tgetForCommand(handle: string, command: string): RpcSessionEntry {\n\t\tconst entry = this.entries.get(handle);\n\t\tif (!entry) throw new RpcSessionRegistryError(\"unknown_session\");\n\t\tif (entry.state === \"closing\" && ![\"abort\", \"abort_bash\", \"extension_ui_response\"].includes(command)) {\n\t\t\tthrow new RpcSessionRegistryError(\"session_closing\");\n\t\t}\n\t\tif (entry.state !== \"open\" && entry.state !== \"closing\") throw new RpcSessionRegistryError(\"unknown_session\");\n\t\treturn entry;\n\t}\n\n\t/**\n\t * Starts a close synchronously. Call this before disposing any session-owned\n\t * binding so a concurrent command cannot reach a half-disposed handler.\n\t */\n\tbeginClose(handle: string): RpcSessionEntry {\n\t\tconst entry = this.entries.get(handle);\n\t\tif (entry?.state !== \"open\") throw new RpcSessionRegistryError(\"unknown_session\");\n\t\tentry.state = \"closing\";\n\t\treturn entry;\n\t}\n\n\tasync close(handle: string): Promise<void> {\n\t\tthis.beginClose(handle);\n\t\treturn this.closeMarked(handle);\n\t}\n\n\t/** Completes a close previously made visible by beginClose(). */\n\tasync closeMarked(handle: string): Promise<void> {\n\t\tconst entry = this.entries.get(handle);\n\t\tif (entry?.state !== \"closing\") throw new RpcSessionRegistryError(\"unknown_session\");\n\t\tentry.lifecycleMutex = (async () => {\n\t\t\ttry {\n\t\t\t\tawait entry.runtime?.session.abort();\n\t\t\t\tawait entry.runtime?.session.waitForIdle();\n\t\t\t\tawait entry.runtime?.dispose();\n\t\t\t\tawait entry.scope.close?.();\n\t\t\t} finally {\n\t\t\t\tentry.state = \"closed\";\n\t\t\t\tthis.entries.delete(handle);\n\t\t\t\tif (entry.sessionPath) this.reservations.delete(entry.sessionPath);\n\t\t\t}\n\t\t})();\n\t\treturn entry.lifecycleMutex;\n\t}\n\n\tlist(): Array<{\n\t\tsessionId: string;\n\t\tdurableSessionId?: string;\n\t\tsessionPath?: string;\n\t\tcwd: string;\n\t\tname?: string;\n\t\tstatus: RpcSessionState;\n\t}> {\n\t\treturn [...this.entries].map(([sessionId, entry]) => ({\n\t\t\tsessionId,\n\t\t\tdurableSessionId: entry.durableSessionId,\n\t\t\tsessionPath: entry.sessionPath,\n\t\t\tcwd: entry.profile.cwd,\n\t\t\tname: entry.runtime?.session.sessionManager.getSessionName(),\n\t\t\tstatus: entry.state,\n\t\t}));\n\t}\n\n\tprivate validateProfile(profile: RpcSessionLaunchProfile): void {\n\t\tif (!isAbsolute(profile.cwd) || (profile.sessionPath !== undefined && !isAbsolute(profile.sessionPath))) {\n\t\t\tthrow new RpcSessionRegistryError(\"invalid_path\");\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"session-registry.js","sourceRoot":"","sources":["../../../src/modes/rpc/session-registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAChG,OAAO,EAIN,yBAAyB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c,CAAC,CAAC;QACnD,CAAC;IACF,CAAC;CACD","sourcesContent":["import { existsSync, realpathSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, resolve } from \"node:path\";\nimport { ProviderScope, runWithProviderScope } from \"@earendil-works/pi-ai/node/provider-scope\";\nimport {\n\ttype AgentSessionLaunchProfile,\n\ttype AgentSessionRuntime,\n\ttype CreateAgentSessionRuntimeFactory,\n\tcreateAgentSessionRuntime,\n} from \"../../core/agent-session-runtime.ts\";\nimport { SessionManager } from \"../../core/session-manager.ts\";\n\n/** The immutable flags selected when a routing session is opened. */\nexport interface RpcSessionLaunchProfile extends AgentSessionLaunchProfile {\n\tsessionPath?: string;\n}\n\nexport type SessionRuntime = Pick<AgentSessionRuntime, \"session\" | \"dispose\">;\nexport type RpcSessionState = \"opening\" | \"open\" | \"closing\" | \"closed\";\n\nexport interface RpcSessionEntry {\n\tstate: RpcSessionState;\n\truntime?: SessionRuntime;\n\tscope: ProviderScope;\n\tprofile: Readonly<RpcSessionLaunchProfile>;\n\tdurableSessionId?: string;\n\tsessionPath?: string;\n\t/** Canonical reservation key for path-opened sessions; matches the reservations set. */\n\treservationKey?: string;\n\t/** Live attachments (open + later attaches). The runtime is disposed only when the last one closes. */\n\tattachments: number;\n\tlifecycleMutex: Promise<void>;\n}\n\nexport class RpcSessionRegistryError extends Error {\n\treadonly code: \"unknown_session\" | \"session_closing\" | \"session_path_in_use\" | \"invalid_path\" | \"open_failed\";\n\n\tconstructor(code: RpcSessionRegistryError[\"code\"], reason?: string) {\n\t\tsuper(code === \"open_failed\" && reason ? `${code}: ${reason}` : code);\n\t\tthis.code = code;\n\t\tthis.name = \"RpcSessionRegistryError\";\n\t}\n}\n\nexport interface RpcSessionRegistryOptions {\n\tagentDir: string;\n\tcreateRuntime: CreateAgentSessionRuntimeFactory;\n}\n\nexport interface OpenRpcSession {\n\tsessionId: string;\n\tdurableSessionId: string;\n\tsessionPath?: string;\n\t/** True when this open attached to an already-open session instead of creating one. */\n\tattached?: boolean;\n}\n\nfunction canonicalPath(path: string): string {\n\tconst absolutePath = resolve(path);\n\tif (existsSync(absolutePath)) return realpathSync(absolutePath);\n\treturn `${realpathSync(dirname(absolutePath))}/${basename(absolutePath)}`;\n}\n\nfunction frozenProfile(profile: RpcSessionLaunchProfile): Readonly<RpcSessionLaunchProfile> {\n\treturn Object.freeze({\n\t\t...profile,\n\t\t...(profile.creationModel ? { creationModel: Object.freeze({ ...profile.creationModel }) } : {}),\n\t});\n}\n\n/** Process-local lifecycle owner for multi-session RPC runtimes. */\nexport class RpcSessionRegistry {\n\tprivate readonly entries = new Map<string, RpcSessionEntry>();\n\tprivate readonly reservations = new Set<string>();\n\tprivate nextHandle = 0;\n\tprivate readonly options: RpcSessionRegistryOptions;\n\n\tconstructor(options: RpcSessionRegistryOptions) {\n\t\tthis.options = options;\n\t}\n\n\tasync openSession(profile: RpcSessionLaunchProfile): Promise<OpenRpcSession> {\n\t\tthis.validateProfile(profile);\n\t\tconst sessionPath = profile.sessionPath ? canonicalPath(profile.sessionPath) : undefined;\n\t\tif (sessionPath && this.reservations.has(sessionPath)) {\n\t\t\t// Attach-on-open: a live session outlives individual client attachments, so a\n\t\t\t// resume (or a second surface) for an already-hosted path joins the existing\n\t\t\t// runtime instead of failing. Entries still opening or closing keep the\n\t\t\t// exclusive reservation and reject as before.\n\t\t\tconst existing = [...this.entries].find(\n\t\t\t\t([, entry]) => entry.reservationKey === sessionPath && entry.state === \"open\",\n\t\t\t);\n\t\t\tif (!existing) throw new RpcSessionRegistryError(\"session_path_in_use\");\n\t\t\tconst [handle, entry] = existing;\n\t\t\tentry.attachments += 1;\n\t\t\tif (!entry.durableSessionId) throw new RpcSessionRegistryError(\"session_path_in_use\");\n\t\t\treturn {\n\t\t\t\tsessionId: handle,\n\t\t\t\tdurableSessionId: entry.durableSessionId,\n\t\t\t\tsessionPath: entry.sessionPath,\n\t\t\t\tattached: true,\n\t\t\t};\n\t\t}\n\t\tif (sessionPath) this.reservations.add(sessionPath);\n\n\t\t// Resume vs create parity (D1 + omo SenpiSessionRuntime.ts:198-200):\n\t\t// Create-only launch semantics mirror classic startup flags. A resumed\n\t\t// session restores its persisted model and thinking level instead of being\n\t\t// overridden by the new open_session request.\n\t\tconst isResume = sessionPath !== undefined && existsSync(sessionPath);\n\t\tconst storedProfile = frozenProfile({ ...profile, ...(sessionPath ? { sessionPath } : {}) });\n\t\tconst runtimeProfile = isResume\n\t\t\t? frozenProfile({ ...storedProfile, creationModel: undefined, initialThinkingLevel: undefined })\n\t\t\t: storedProfile;\n\n\t\tconst handle = `rpc-${++this.nextHandle}`;\n\t\tconst entry: RpcSessionEntry = {\n\t\t\tstate: \"opening\",\n\t\t\tscope: new ProviderScope(),\n\t\t\tprofile: storedProfile,\n\t\t\tsessionPath,\n\t\t\treservationKey: sessionPath,\n\t\t\tattachments: 1,\n\t\t\tlifecycleMutex: Promise.resolve(),\n\t\t};\n\t\tthis.entries.set(handle, entry);\n\t\ttry {\n\t\t\tconst manager = sessionPath\n\t\t\t\t? SessionManager.open(sessionPath, undefined, storedProfile.cwd)\n\t\t\t\t: SessionManager.create(storedProfile.cwd);\n\t\t\tentry.runtime = await runWithProviderScope(entry.scope, () =>\n\t\t\t\tcreateAgentSessionRuntime(this.options.createRuntime, {\n\t\t\t\t\tcwd: manager.getCwd(),\n\t\t\t\t\tagentDir: this.options.agentDir,\n\t\t\t\t\tsessionManager: manager,\n\t\t\t\t\tlaunchProfile: runtimeProfile,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tentry.durableSessionId = manager.getSessionId();\n\t\t\tentry.sessionPath ??= manager.getSessionFile();\n\t\t\tentry.state = \"open\";\n\t\t\treturn { sessionId: handle, durableSessionId: entry.durableSessionId, sessionPath: entry.sessionPath };\n\t\t} catch (error) {\n\t\t\t// Runtime construction may have started extensions, watchers, and provider\n\t\t\t// registrations before it rejects. Keep the reservation and entry private\n\t\t\t// until all of those resources have been torn down, then release them as\n\t\t\t// one rollback so the path can immediately be opened again.\n\t\t\ttry {\n\t\t\t\tawait entry.runtime?.dispose();\n\t\t\t} catch {\n\t\t\t\t// The original construction error remains the externally visible cause.\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\tawait entry.scope.close?.();\n\t\t\t\t} finally {\n\t\t\t\t\tthis.entries.delete(handle);\n\t\t\t\t\tif (sessionPath) this.reservations.delete(sessionPath);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (error instanceof RpcSessionRegistryError) throw error;\n\t\t\tthrow new RpcSessionRegistryError(\"open_failed\", error instanceof Error ? error.message : undefined);\n\t\t}\n\t}\n\n\tgetForCommand(handle: string, command: string): RpcSessionEntry {\n\t\tconst entry = this.entries.get(handle);\n\t\tif (!entry) throw new RpcSessionRegistryError(\"unknown_session\");\n\t\tif (entry.state === \"closing\" && ![\"abort\", \"abort_bash\", \"extension_ui_response\"].includes(command)) {\n\t\t\tthrow new RpcSessionRegistryError(\"session_closing\");\n\t\t}\n\t\tif (entry.state !== \"open\" && entry.state !== \"closing\") throw new RpcSessionRegistryError(\"unknown_session\");\n\t\treturn entry;\n\t}\n\n\t/**\n\t * Starts a close synchronously. Call this before disposing any session-owned\n\t * binding so a concurrent command cannot reach a half-disposed handler.\n\t * Each call releases one attachment; the entry transitions to \"closing\" only\n\t * when the last attachment closes, so callers must check the returned state\n\t * and skip finalization while other attachments remain.\n\t */\n\tbeginClose(handle: string): RpcSessionEntry {\n\t\tconst entry = this.entries.get(handle);\n\t\tif (entry?.state !== \"open\") throw new RpcSessionRegistryError(\"unknown_session\");\n\t\tentry.attachments -= 1;\n\t\tif (entry.attachments > 0) return entry;\n\t\tentry.state = \"closing\";\n\t\treturn entry;\n\t}\n\n\tasync close(handle: string): Promise<void> {\n\t\tconst entry = this.beginClose(handle);\n\t\t// Other attachments may still own the live session; only the last close finalizes.\n\t\tif (entry.state !== \"closing\") return;\n\t\treturn this.closeMarked(handle);\n\t}\n\n\t/** Completes a close previously made visible by beginClose(). */\n\tasync closeMarked(handle: string): Promise<void> {\n\t\tconst entry = this.entries.get(handle);\n\t\tif (entry?.state !== \"closing\") throw new RpcSessionRegistryError(\"unknown_session\");\n\t\tentry.lifecycleMutex = (async () => {\n\t\t\ttry {\n\t\t\t\tawait entry.runtime?.session.abort();\n\t\t\t\tawait entry.runtime?.session.waitForIdle();\n\t\t\t\tawait entry.runtime?.dispose();\n\t\t\t\tawait entry.scope.close?.();\n\t\t\t} finally {\n\t\t\t\tentry.state = \"closed\";\n\t\t\t\tthis.entries.delete(handle);\n\t\t\t\tif (entry.sessionPath) this.reservations.delete(entry.sessionPath);\n\t\t\t}\n\t\t})();\n\t\treturn entry.lifecycleMutex;\n\t}\n\n\tlist(): Array<{\n\t\tsessionId: string;\n\t\tdurableSessionId?: string;\n\t\tsessionPath?: string;\n\t\tcwd: string;\n\t\tname?: string;\n\t\tstatus: RpcSessionState;\n\t}> {\n\t\treturn [...this.entries].map(([sessionId, entry]) => ({\n\t\t\tsessionId,\n\t\t\tdurableSessionId: entry.durableSessionId,\n\t\t\tsessionPath: entry.sessionPath,\n\t\t\tcwd: entry.profile.cwd,\n\t\t\tname: entry.runtime?.session.sessionManager.getSessionName(),\n\t\t\tstatus: entry.state,\n\t\t}));\n\t}\n\n\tprivate validateProfile(profile: RpcSessionLaunchProfile): void {\n\t\tif (!isAbsolute(profile.cwd) || (profile.sessionPath !== undefined && !isAbsolute(profile.sessionPath))) {\n\t\t\tthrow new RpcSessionRegistryError(\"invalid_path\");\n\t\t}\n\t}\n}\n"]}
package/docs/providers.md CHANGED
@@ -302,6 +302,54 @@ credential under the provider you select; an environment variable is shared by b
302
302
 
303
303
  The file is created with `0600` permissions (user read/write only). Auth file credentials take priority over environment variables.
304
304
 
305
+ #### Multiple accounts per provider
306
+
307
+ Any provider can hold more than one credential. The quickest way is numbered environment variables
308
+ over the provider's primary key variable - a gap in the numbering is fine:
309
+
310
+ ```bash
311
+ export OPENAI_API_KEY="sk-first"
312
+ export OPENAI_API_KEY_2="sk-second" # any provider: ANTHROPIC_API_KEY_2, GEMINI_API_KEY_2, ...
313
+ ```
314
+
315
+ Stored credentials pool through an `accounts` array. The flat top-level fields always stay a valid
316
+ credential (older binaries keep authenticating with them), and each slot's `name` is its stable
317
+ identity:
318
+
319
+ ```json
320
+ {
321
+ "openai": {
322
+ "type": "api_key",
323
+ "key": "sk-first",
324
+ "accounts": [
325
+ { "name": "default", "key": "sk-first", "source": "login" },
326
+ { "name": "work", "key": "sk-second", "source": "login" }
327
+ ],
328
+ "pinned": "work"
329
+ }
330
+ }
331
+ ```
332
+
333
+ With more than one account, requests rotate automatically: a session sticks to one account
334
+ (session-affine selection), and a rate-limited or auth-failed account fails over to a healthy
335
+ sibling **within the same provider and model** before the model fallback chain is consulted -
336
+ credential rotation changes which account serves the request, never which model answers it.
337
+ Rotation never happens after a response has started streaming. Cooldowns persist in
338
+ `~/.senpi/agent/credential-pool-state.json` (health only - never key material).
339
+
340
+ Manage accounts with `/account <provider> [list | pin <name> | unpin | remove <name>]`, and tune
341
+ behavior per provider in `models.json`:
342
+
343
+ ```json
344
+ {
345
+ "providers": {
346
+ "openai": {
347
+ "credentials": { "rotation": true, "affinity": true, "cooldownBaseMs": 60000 }
348
+ }
349
+ }
350
+ }
351
+ ```
352
+
305
353
  API key credentials can also include provider-scoped environment values. These values are used before process environment variables when resolving the credential key, provider/model headers, and provider configuration such as Cloudflare account IDs, Azure OpenAI settings, Vertex project/location, Bedrock settings, `PI_CACHE_RETENTION`, and `HTTP_PROXY`/`HTTPS_PROXY`.
306
354
 
307
355
  ```json
package/docs/rpc.md CHANGED
@@ -100,7 +100,7 @@ hosts) sees neither variable and is unaffected. A host whose supervisor is alive
100
100
  | Command | Params | Success data | Notes |
101
101
  | --- | --- | --- | --- |
102
102
  | `get_protocol_info` | - | `{ protocolVersion: 1, serverVersion: string, capabilities: string[], mode: "classic"\|"multi" }` | Answered in BOTH modes; side-effect-free; the capability probe. Multi-session hosts include `multi_session` plus the negotiated launch capabilities. |
103
- | `open_session` | `sessionPath?`, `cwd?`, `provider?`, `modelId?`, `thinkingLevel?`, `permissionPreset?` (all optional; paths MUST be absolute) | `{ sessionId, state: RpcSessionState }` | `sessionPath` = today's `--session` semantics (open-if-exists else create persisting there, `session-manager.ts:926-940`); `provider`/`modelId` applied only on create (resume restores the session's model — mirrors `SenpiSessionRuntime.ts:198-200`); params form the immutable launch profile (D8). |
103
+ | `open_session` | `sessionPath?`, `cwd?`, `provider?`, `modelId?`, `thinkingLevel?`, `permissionPreset?` (all optional; paths MUST be absolute) | `{ sessionId, state: RpcSessionState, attached?: true }` | `sessionPath` = today's `--session` semantics (open-if-exists else create persisting there, `session-manager.ts:926-940`); `provider`/`modelId` applied only on create (resume restores the session's model — mirrors `SenpiSessionRuntime.ts:198-200`); params form the immutable launch profile (D8). When the path is already held by a fully-open session, the open ATTACHES to it: same routing handle, `attached: true`, one more attachment counted; the runtime is torn down only when the last attachment closes. |
104
104
  | `close_session` | `sessionId` | `{}` | Aborts active work, awaits agent idle + settled persistence, flushes queued events, detaches subscriptions; its response is the LAST record tagged with that handle — no events after (test-pinned). |
105
105
  | `list_sessions` | - | `{ sessions: [{ sessionId, durableSessionId, sessionPath, cwd, name, status }] }` | Includes `opening`/`closing` entries with their status. |
106
106
  | every existing command | + `sessionId` (REQUIRED in multi mode) | unchanged | Routed to that session. |
@@ -115,7 +115,7 @@ In the response `error` field, machine-matchable:
115
115
 
116
116
  - `unknown_session`
117
117
  - `session_closing`
118
- - `session_path_in_use`
118
+ - `session_path_in_use` (path held by a session still `opening` or already `closing`; a fully-open session is attached instead)
119
119
  - `missing_session_id` (session-scoped command without `sessionId` in multi mode)
120
120
  - `multi_session_disabled` (`open_session` in classic mode)
121
121
  - `invalid_path` (relative `sessionPath`/`cwd`)
@@ -131,7 +131,7 @@ Strict FIFO per session; one total stdout order; cross-session order unspecified
131
131
 
132
132
  ### Duplicate/idempotency
133
133
 
134
- Duplicate `open_session` while a path reservation is held → `session_path_in_use`. `close_session` on unknown/already-closed → `unknown_session` error. Request `id`s are client-owned; the server echoes them without dedup.
134
+ Duplicate `open_session` while a path reservation is held by a fully-open session ATTACH (`attached: true`, same handle); while held by an `opening`/`closing` entry → `session_path_in_use`. `close_session` releases one attachment; the runtime is disposed only when the last attachment closes. `close_session` on unknown/already-closed → `unknown_session` error. Request `id`s are client-owned; the server echoes them without dedup.
135
135
 
136
136
  ## Protocol Overview
137
137
 
@@ -197,9 +197,11 @@ sending/queueing. Bare inline dollar text remains literal.
197
197
 
198
198
  Response:
199
199
  ```json
200
- {"id": "req-1", "type": "response", "command": "prompt", "success": true}
200
+ {"id": "req-1", "type": "response", "command": "prompt", "success": true, "data": { "disposition": "started" }}
201
201
  ```
202
202
 
203
+ The prompt success response carries `data.disposition` (`"started"` | `"queued"` | `"handled"`), captured from the host session's own disposition callback so proxied clients can resolve optimistic-echo contracts exactly like the local path. Older hosts omit `data`; clients must then degrade to canonical-only rendering (treat the echo as rejected). The response is emitted before the user `message_start` event on the same connection, and disposition callbacks registered through the client run synchronously inside response-frame dispatch — never through the resolved promise's microtask.
204
+
203
205
  `success: true` means the prompt was accepted, queued, or handled immediately. `success: false` means the prompt was rejected before acceptance. Failures after acceptance are reported through the normal event and message stream, not as a second `response` for the same request id.
204
206
 
205
207
  The `images` field is optional. Each image uses `ImageContent` format: `{"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}`.
@@ -12,6 +12,20 @@
12
12
 
13
13
  ### Removed
14
14
 
15
+ ## [2026.8.28] - 2026-08-28
16
+
17
+ ### Breaking Changes
18
+
19
+ ### Added
20
+
21
+ ### Changed
22
+
23
+ ### Fixed
24
+
25
+ - JavaScript and Python eval kernels resolve worker and prelude assets from the executable sidecar in Bun-compiled distributions instead of passing unusable `$bunfs` paths to `Worker` and `python3`.
26
+
27
+ ### Removed
28
+
15
29
  ## [2026.8.27] - 2026-08-27
16
30
 
17
31
  ### Breaking Changes
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@code-yeongyu/senpi-codemode",
3
- "version": "2026.8.27",
3
+ "version": "2026.8.28",
4
4
  "private": true,
5
5
  "description": "Source-only senpi extension package for codemode evaluation tools",
6
6
  "type": "module",
@@ -31,14 +31,14 @@
31
31
  },
32
32
  "dependencies": {
33
33
  "@babel/parser": "8.0.4",
34
- "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.8.27",
34
+ "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.8.28",
35
35
  "typebox": "1.3.18"
36
36
  },
37
37
  "peerDependencies": {
38
- "@code-yeongyu/senpi": "2026.8.27"
38
+ "@code-yeongyu/senpi": "2026.8.28"
39
39
  },
40
40
  "devDependencies": {
41
- "@code-yeongyu/senpi": "2026.8.27"
41
+ "@code-yeongyu/senpi": "2026.8.28"
42
42
  },
43
43
  "keywords": [
44
44
  "senpi",
@@ -1,5 +1,8 @@
1
+ import { dirname, join } from "node:path";
2
+ import { fileURLToPath, pathToFileURL } from "node:url";
1
3
  import type { HostToKernelMessage, KernelToHostMessage } from "../../bridge/protocol.ts";
2
4
  import type { KernelInterruptHandle } from "../../tool/types.ts";
5
+ import { type CodemodeRuntimeAssetEnvironment, resolveCodemodeRuntimeAsset } from "../shared/runtime-asset.ts";
3
6
  import { createInlineWorker, type WorkerLike } from "./inline-worker.ts";
4
7
  import {
5
8
  assertJavaScriptKernelOpen,
@@ -16,6 +19,15 @@ import { bridgeError, spawnNodeWorker, WorkerStartupCancelledError, waitForReady
16
19
  export { JavaScriptKernelClosedError, type JavaScriptKernelMode, type JavaScriptRunInput } from "./kernel-contract.ts";
17
20
  export type { JavaScriptKernelOptions } from "./local-module-loader.ts";
18
21
 
22
+ export interface JavaScriptWorkerEntryUrlOptions extends CodemodeRuntimeAssetEnvironment {
23
+ readonly localPath?: string;
24
+ }
25
+
26
+ export function resolveJsWorkerEntryUrl(options: JavaScriptWorkerEntryUrlOptions = {}): URL {
27
+ const localPath = options.localPath ?? join(dirname(fileURLToPath(import.meta.url)), "worker-entry.js");
28
+ return pathToFileURL(resolveCodemodeRuntimeAsset(localPath, join("kernels", "js", "worker-entry.js"), options));
29
+ }
30
+
19
31
  export class JavaScriptKernel {
20
32
  readonly #options: JavaScriptKernelOptions;
21
33
  readonly #moduleLoader: LocalModuleLoader;
@@ -161,7 +173,7 @@ export class JavaScriptKernel {
161
173
 
162
174
  #spawnWorker(): WorkerLike {
163
175
  try {
164
- const url = this.#options.workerEntryUrl ?? new URL("./worker-entry.js", import.meta.url);
176
+ const url = this.#options.workerEntryUrl ?? resolveJsWorkerEntryUrl();
165
177
  return spawnNodeWorker(url, this.#options.cwd, this.#options.parallelPoolWidth);
166
178
  } catch (error) {
167
179
  if (!(error instanceof Error)) throw error;
@@ -1,7 +1,21 @@
1
+ import { dirname, join } from "node:path";
2
+ import { fileURLToPath, pathToFileURL } from "node:url";
1
3
  import type { HostToKernelMessage, KernelToHostMessage } from "../../bridge/protocol.ts";
4
+ import { type CodemodeRuntimeAssetEnvironment, resolveCodemodeRuntimeAsset } from "../shared/runtime-asset.ts";
2
5
  import type { JavaScriptKernelMode } from "./kernel-contract.ts";
3
6
  import { spawnNodeWorker } from "./worker-host.ts";
4
7
 
8
+ export interface JavaScriptInlineWorkerEntryUrlOptions extends CodemodeRuntimeAssetEnvironment {
9
+ readonly localPath?: string;
10
+ }
11
+
12
+ export function resolveInlineWorkerEntryUrl(options: JavaScriptInlineWorkerEntryUrlOptions = {}): URL {
13
+ const localPath = options.localPath ?? join(dirname(fileURLToPath(import.meta.url)), "inline-worker-entry.js");
14
+ return pathToFileURL(
15
+ resolveCodemodeRuntimeAsset(localPath, join("kernels", "js", "inline-worker-entry.js"), options),
16
+ );
17
+ }
18
+
5
19
  export interface WorkerLike {
6
20
  readonly mode: JavaScriptKernelMode;
7
21
  postMessage(message: HostToKernelMessage): void;
@@ -11,5 +25,5 @@ export interface WorkerLike {
11
25
  }
12
26
 
13
27
  export function createInlineWorker(cwd: string, parallelPoolWidth: number): WorkerLike {
14
- return spawnNodeWorker(new URL("./inline-worker-entry.js", import.meta.url), cwd, parallelPoolWidth, "inline");
28
+ return spawnNodeWorker(resolveInlineWorkerEntryUrl(), cwd, parallelPoolWidth, "inline");
15
29
  }
@@ -8,6 +8,7 @@ import {
8
8
  isKernelToHostMessage,
9
9
  type KernelToHostMessage,
10
10
  } from "../../bridge/protocol.ts";
11
+ import { type CodemodeRuntimeAssetEnvironment, resolveCodemodeRuntimeAsset } from "../shared/runtime-asset.ts";
11
12
  import {
12
13
  defaultSpawn,
13
14
  hardKill,
@@ -47,6 +48,18 @@ export interface PythonTransportOptions {
47
48
 
48
49
  const hardKillWaitMs = 500;
49
50
 
51
+ export interface PythonPreludePathOptions extends CodemodeRuntimeAssetEnvironment {
52
+ readonly localPath?: string;
53
+ }
54
+
55
+ export function resolvePythonPreludePath(options: PythonPreludePathOptions = {}): string {
56
+ return resolveCodemodeRuntimeAsset(
57
+ options.localPath ?? join(dirname(fileURLToPath(import.meta.url)), "prelude.py"),
58
+ join("kernels", "py", "prelude.py"),
59
+ options,
60
+ );
61
+ }
62
+
50
63
  export class PythonKernelTransport {
51
64
  readonly #options: PythonTransportOptions;
52
65
  readonly #child: KernelChild;
@@ -64,7 +77,7 @@ export class PythonKernelTransport {
64
77
  }
65
78
 
66
79
  static async start(options: PythonTransportOptions): Promise<PythonKernelTransport> {
67
- const scriptPath = join(dirname(fileURLToPath(import.meta.url)), "prelude.py");
80
+ const scriptPath = resolvePythonPreludePath();
68
81
  const invocation = splitCommand(options.interpreterPath);
69
82
  const spawnOptions: KernelSpawnOptions = {
70
83
  command: invocation.command,
@@ -1 +1 @@
1
- {"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/edit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAE,gBAAgB,EAAa,MAAM,aAAa,CAAC;AAa/D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAa9D,QAAA,MAAM,UAAU;;;;;;EASf,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAUtD,MAAM,WAAW,eAAe;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC1B;AAqCD,wBAAgB,cAAc,CAAC,QAAQ,SAAS,oBAAoB,GAAG,oBAAoB,KAAK,gBAAgB,CAC/G,QAAQ,EACR,OAAO,UAAU,EACjB,eAAe,GAAG,SAAS,CAC3B,CA8CA"}
1
+ {"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/edit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAE,gBAAgB,EAAa,MAAM,aAAa,CAAC;AAc/D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAa9D,QAAA,MAAM,UAAU;;;;;;EASf,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAUtD,MAAM,WAAW,eAAe;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC1B;AAqCD,wBAAgB,cAAc,CAAC,QAAQ,SAAS,oBAAoB,GAAG,oBAAoB,KAAK,gBAAgB,CAC/G,QAAQ,EACR,OAAO,UAAU,EACjB,eAAe,GAAG,SAAS,CAC3B,CAiEA"}
@@ -2,6 +2,7 @@ import { Type } from "typebox";
2
2
  import { applyEditsToNormalizedContent, detectLineEnding, generateDiffString, generateUnifiedPatch, normalizeToLF, restoreLineEndings, stripBom, } from "./edit-diff.js";
3
3
  import { withFileMutationQueue } from "./file-mutation-queue.js";
4
4
  import { resolveToolPath } from "./path-utils.js";
5
+ import { appendPostMutateNote, runPostMutate } from "./post-mutate.js";
5
6
  const replaceEditSchema = Type.Object({
6
7
  oldText: Type.String({
7
8
  description: "Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.",
@@ -63,7 +64,7 @@ export function createEditTool() {
63
64
  description: "Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.",
64
65
  parameters: editSchema,
65
66
  prepareArguments: prepareEditArguments,
66
- async execute(_toolCallId, input, signal, _onUpdate, { env }) {
67
+ async execute(_toolCallId, input, signal, _onUpdate, { env, postMutate }) {
67
68
  const { path, edits } = validateEditInput(input);
68
69
  const absolutePath = await resolveToolPath(env, path, signal);
69
70
  return withFileMutationQueue(env, absolutePath, async () => {
@@ -92,12 +93,27 @@ export function createEditTool() {
92
93
  throw editAccessError(path, writeResult.error);
93
94
  if (signal?.aborted)
94
95
  throw new Error("Operation aborted");
95
- const diffResult = generateDiffString(baseContent, newContent);
96
+ const outcome = await runPostMutate(postMutate, { tool: "edit", path: absolutePath, signal });
97
+ if (signal?.aborted)
98
+ throw new Error("Operation aborted");
99
+ let committedContent = newContent;
100
+ let rereadNote;
101
+ if (outcome.fileMayHaveChanged) {
102
+ const postMutateRead = await env.readTextFile(absolutePath, signal);
103
+ // The edit itself already landed, so an unreadable file is the hook's doing, not a
104
+ // failed edit. Report it as a note rather than an error that misattributes the failure.
105
+ if (postMutateRead.ok)
106
+ committedContent = normalizeToLF(stripBom(postMutateRead.value).text);
107
+ else
108
+ rereadNote = `postMutate left the file unreadable: ${postMutateRead.error.code}. Reported diff describes the edit before the hook ran.`;
109
+ }
110
+ const diffResult = generateDiffString(baseContent, committedContent);
111
+ const text = appendPostMutateNote(`Successfully replaced ${edits.length} block(s) in ${path}.`, outcome.note, rereadNote);
96
112
  return {
97
- content: [{ type: "text", text: `Successfully replaced ${edits.length} block(s) in ${path}.` }],
113
+ content: [{ type: "text", text }],
98
114
  details: {
99
115
  diff: diffResult.diff,
100
- patch: generateUnifiedPatch(path, baseContent, newContent),
116
+ patch: generateUnifiedPatch(path, baseContent, committedContent),
101
117
  firstChangedLine: diffResult.firstChangedLine,
102
118
  },
103
119
  };