@0xmaxma/claude-gateway 2.1.9 → 2.1.11

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 (271) hide show
  1. package/config.template.json +4 -0
  2. package/dist/agent/runner.d.ts +93 -6
  3. package/dist/agent/runner.d.ts.map +1 -1
  4. package/dist/agent/runner.js +342 -108
  5. package/dist/agent/runner.js.map +1 -1
  6. package/dist/api/async-guard.d.ts +13 -0
  7. package/dist/api/async-guard.d.ts.map +1 -0
  8. package/dist/api/async-guard.js +38 -0
  9. package/dist/api/async-guard.js.map +1 -0
  10. package/dist/api/auth.d.ts +5 -0
  11. package/dist/api/auth.d.ts.map +1 -1
  12. package/dist/api/auth.js +3 -0
  13. package/dist/api/auth.js.map +1 -1
  14. package/dist/api/browser-bindings-router.d.ts.map +1 -1
  15. package/dist/api/browser-bindings-router.js +2 -0
  16. package/dist/api/browser-bindings-router.js.map +1 -1
  17. package/dist/api/capabilities.d.ts +47 -2
  18. package/dist/api/capabilities.d.ts.map +1 -1
  19. package/dist/api/capabilities.js +51 -8
  20. package/dist/api/capabilities.js.map +1 -1
  21. package/dist/api/files-router.d.ts +23 -0
  22. package/dist/api/files-router.d.ts.map +1 -0
  23. package/dist/api/files-router.js +102 -0
  24. package/dist/api/files-router.js.map +1 -0
  25. package/dist/api/gateway-router.d.ts +4 -2
  26. package/dist/api/gateway-router.d.ts.map +1 -1
  27. package/dist/api/gateway-router.js +20 -2
  28. package/dist/api/gateway-router.js.map +1 -1
  29. package/dist/api/git-router.d.ts +4 -0
  30. package/dist/api/git-router.d.ts.map +1 -0
  31. package/dist/api/git-router.js +51 -0
  32. package/dist/api/git-router.js.map +1 -0
  33. package/dist/api/manifest-sources.d.ts.map +1 -1
  34. package/dist/api/manifest-sources.js +6 -0
  35. package/dist/api/manifest-sources.js.map +1 -1
  36. package/dist/api/processes-router.d.ts +28 -0
  37. package/dist/api/processes-router.d.ts.map +1 -0
  38. package/dist/api/processes-router.js +179 -0
  39. package/dist/api/processes-router.js.map +1 -0
  40. package/dist/api/router.d.ts +41 -1
  41. package/dist/api/router.d.ts.map +1 -1
  42. package/dist/api/router.js +112 -25
  43. package/dist/api/router.js.map +1 -1
  44. package/dist/api/voice-router.d.ts.map +1 -1
  45. package/dist/api/voice-router.js +2 -0
  46. package/dist/api/voice-router.js.map +1 -1
  47. package/dist/automation/browser-outcome.d.ts +3 -1
  48. package/dist/automation/browser-outcome.d.ts.map +1 -1
  49. package/dist/automation/browser-outcome.js +2 -2
  50. package/dist/automation/browser-outcome.js.map +1 -1
  51. package/dist/automation/command-speech.d.ts +9 -1
  52. package/dist/automation/command-speech.d.ts.map +1 -1
  53. package/dist/automation/command-speech.js +18 -0
  54. package/dist/automation/command-speech.js.map +1 -1
  55. package/dist/automation/command-steps.d.ts +2 -0
  56. package/dist/automation/command-steps.d.ts.map +1 -1
  57. package/dist/automation/command-steps.js +34 -2
  58. package/dist/automation/command-steps.js.map +1 -1
  59. package/dist/automation/computer-command.d.ts +1 -0
  60. package/dist/automation/computer-command.d.ts.map +1 -1
  61. package/dist/automation/computer-command.js +31 -5
  62. package/dist/automation/computer-command.js.map +1 -1
  63. package/dist/automation/computer-outcome.d.ts +26 -3
  64. package/dist/automation/computer-outcome.d.ts.map +1 -1
  65. package/dist/automation/computer-outcome.js +183 -13
  66. package/dist/automation/computer-outcome.js.map +1 -1
  67. package/dist/automation/computer-policy.d.ts +10 -1
  68. package/dist/automation/computer-policy.d.ts.map +1 -1
  69. package/dist/automation/computer-policy.js +20 -6
  70. package/dist/automation/computer-policy.js.map +1 -1
  71. package/dist/automation/computer-use.d.ts +34 -0
  72. package/dist/automation/computer-use.d.ts.map +1 -1
  73. package/dist/automation/computer-use.js +211 -17
  74. package/dist/automation/computer-use.js.map +1 -1
  75. package/dist/automation/direct-command.d.ts +8 -0
  76. package/dist/automation/direct-command.d.ts.map +1 -1
  77. package/dist/automation/direct-command.js +12 -0
  78. package/dist/automation/direct-command.js.map +1 -1
  79. package/dist/automation/model-choice-evaluator.d.ts +3 -0
  80. package/dist/automation/model-choice-evaluator.d.ts.map +1 -1
  81. package/dist/automation/model-choice-evaluator.js +3 -1
  82. package/dist/automation/model-choice-evaluator.js.map +1 -1
  83. package/dist/automation/vision-decider.d.ts +4 -2
  84. package/dist/automation/vision-decider.d.ts.map +1 -1
  85. package/dist/automation/vision-decider.js +69 -15
  86. package/dist/automation/vision-decider.js.map +1 -1
  87. package/dist/build-provenance.json +4 -4
  88. package/dist/cli/redact.d.ts +1 -0
  89. package/dist/cli/redact.d.ts.map +1 -1
  90. package/dist/cli/redact.js +12 -0
  91. package/dist/cli/redact.js.map +1 -1
  92. package/dist/config/loader.d.ts +5 -0
  93. package/dist/config/loader.d.ts.map +1 -1
  94. package/dist/config/loader.js +121 -0
  95. package/dist/config/loader.js.map +1 -1
  96. package/dist/config/reload-policy.d.ts.map +1 -1
  97. package/dist/config/reload-policy.js +1 -0
  98. package/dist/config/reload-policy.js.map +1 -1
  99. package/dist/config/watcher.d.ts.map +1 -1
  100. package/dist/config/watcher.js +1 -0
  101. package/dist/config/watcher.js.map +1 -1
  102. package/dist/files/config.d.ts +6 -0
  103. package/dist/files/config.d.ts.map +1 -0
  104. package/dist/files/config.js +15 -0
  105. package/dist/files/config.js.map +1 -0
  106. package/dist/files/delete.d.ts +27 -0
  107. package/dist/files/delete.d.ts.map +1 -0
  108. package/dist/files/delete.js +143 -0
  109. package/dist/files/delete.js.map +1 -0
  110. package/dist/files/fs.d.ts +70 -0
  111. package/dist/files/fs.d.ts.map +1 -0
  112. package/dist/files/fs.js +319 -0
  113. package/dist/files/fs.js.map +1 -0
  114. package/dist/files/holds.d.ts +11 -0
  115. package/dist/files/holds.d.ts.map +1 -0
  116. package/dist/files/holds.js +20 -0
  117. package/dist/files/holds.js.map +1 -0
  118. package/dist/files/paths.d.ts +26 -0
  119. package/dist/files/paths.d.ts.map +1 -0
  120. package/dist/files/paths.js +112 -0
  121. package/dist/files/paths.js.map +1 -0
  122. package/dist/files/session-cwd.d.ts +8 -0
  123. package/dist/files/session-cwd.d.ts.map +1 -0
  124. package/dist/files/session-cwd.js +139 -0
  125. package/dist/files/session-cwd.js.map +1 -0
  126. package/dist/git/read.d.ts +25 -0
  127. package/dist/git/read.d.ts.map +1 -0
  128. package/dist/git/read.js +166 -0
  129. package/dist/git/read.js.map +1 -0
  130. package/dist/git/runner.d.ts +46 -0
  131. package/dist/git/runner.d.ts.map +1 -0
  132. package/dist/git/runner.js +176 -0
  133. package/dist/git/runner.js.map +1 -0
  134. package/dist/git/status.d.ts +119 -0
  135. package/dist/git/status.d.ts.map +1 -0
  136. package/dist/git/status.js +273 -0
  137. package/dist/git/status.js.map +1 -0
  138. package/dist/index.js +7 -2
  139. package/dist/index.js.map +1 -1
  140. package/dist/jev/browser-contract.d.ts +3 -0
  141. package/dist/jev/browser-contract.d.ts.map +1 -1
  142. package/dist/jev/browser-contract.js +6 -0
  143. package/dist/jev/browser-contract.js.map +1 -1
  144. package/dist/orchestration/agent-tool-schemas.d.ts +18 -0
  145. package/dist/orchestration/agent-tool-schemas.d.ts.map +1 -1
  146. package/dist/orchestration/agent-tool-schemas.js +11 -3
  147. package/dist/orchestration/agent-tool-schemas.js.map +1 -1
  148. package/dist/orchestration/bridge.d.ts.map +1 -1
  149. package/dist/orchestration/bridge.js +26 -5
  150. package/dist/orchestration/bridge.js.map +1 -1
  151. package/dist/orchestration/browser-routing.d.ts.map +1 -1
  152. package/dist/orchestration/browser-routing.js +2 -1
  153. package/dist/orchestration/browser-routing.js.map +1 -1
  154. package/dist/orchestration/computer-decisions.d.ts +1 -1
  155. package/dist/orchestration/computer-decisions.d.ts.map +1 -1
  156. package/dist/orchestration/computer-decisions.js +21 -7
  157. package/dist/orchestration/computer-decisions.js.map +1 -1
  158. package/dist/orchestration/computer-live.d.ts +62 -0
  159. package/dist/orchestration/computer-live.d.ts.map +1 -0
  160. package/dist/orchestration/computer-live.js +126 -0
  161. package/dist/orchestration/computer-live.js.map +1 -0
  162. package/dist/orchestration/container-tool-schemas.d.ts.map +1 -1
  163. package/dist/orchestration/container-tool-schemas.js +3 -0
  164. package/dist/orchestration/container-tool-schemas.js.map +1 -1
  165. package/dist/orchestration/decisions.d.ts +3 -1
  166. package/dist/orchestration/decisions.d.ts.map +1 -1
  167. package/dist/orchestration/decisions.js +4 -2
  168. package/dist/orchestration/decisions.js.map +1 -1
  169. package/dist/orchestration/gateway-tasks/browser.d.ts +1 -1
  170. package/dist/orchestration/gateway-tasks/browser.d.ts.map +1 -1
  171. package/dist/orchestration/gateway-tasks/browser.js +4 -3
  172. package/dist/orchestration/gateway-tasks/browser.js.map +1 -1
  173. package/dist/orchestration/gateway-tasks/computer-context.d.ts +4 -1
  174. package/dist/orchestration/gateway-tasks/computer-context.d.ts.map +1 -1
  175. package/dist/orchestration/gateway-tasks/computer-context.js +3 -1
  176. package/dist/orchestration/gateway-tasks/computer-context.js.map +1 -1
  177. package/dist/orchestration/gateway-tasks/computer.d.ts +78 -15
  178. package/dist/orchestration/gateway-tasks/computer.d.ts.map +1 -1
  179. package/dist/orchestration/gateway-tasks/computer.js +298 -31
  180. package/dist/orchestration/gateway-tasks/computer.js.map +1 -1
  181. package/dist/orchestration/gateway-tasks/controller.d.ts +14 -2
  182. package/dist/orchestration/gateway-tasks/controller.d.ts.map +1 -1
  183. package/dist/orchestration/gateway-tasks/controller.js +63 -2
  184. package/dist/orchestration/gateway-tasks/controller.js.map +1 -1
  185. package/dist/orchestration/notification-mailbox.js +3 -3
  186. package/dist/orchestration/notification-mailbox.js.map +1 -1
  187. package/dist/orchestration/process-turn.d.ts.map +1 -1
  188. package/dist/orchestration/process-turn.js +4 -1
  189. package/dist/orchestration/process-turn.js.map +1 -1
  190. package/dist/orchestration/response-errors.d.ts.map +1 -1
  191. package/dist/orchestration/response-errors.js +2 -0
  192. package/dist/orchestration/response-errors.js.map +1 -1
  193. package/dist/orchestration/runtime.d.ts +32 -2
  194. package/dist/orchestration/runtime.d.ts.map +1 -1
  195. package/dist/orchestration/runtime.js +106 -10
  196. package/dist/orchestration/runtime.js.map +1 -1
  197. package/dist/orchestration/task-controls.d.ts +8 -0
  198. package/dist/orchestration/task-controls.d.ts.map +1 -1
  199. package/dist/orchestration/task-controls.js +3 -2
  200. package/dist/orchestration/task-controls.js.map +1 -1
  201. package/dist/orchestration/tasks/automation-session.d.ts +42 -11
  202. package/dist/orchestration/tasks/automation-session.d.ts.map +1 -1
  203. package/dist/orchestration/tasks/automation-session.js +101 -21
  204. package/dist/orchestration/tasks/automation-session.js.map +1 -1
  205. package/dist/orchestration/tasks/driver.d.ts.map +1 -1
  206. package/dist/orchestration/tasks/driver.js +19 -1
  207. package/dist/orchestration/tasks/driver.js.map +1 -1
  208. package/dist/orchestration/tasks/service.d.ts +48 -2
  209. package/dist/orchestration/tasks/service.d.ts.map +1 -1
  210. package/dist/orchestration/tasks/service.js +165 -16
  211. package/dist/orchestration/tasks/service.js.map +1 -1
  212. package/dist/orchestration/telegram-tool-status.d.ts.map +1 -1
  213. package/dist/orchestration/telegram-tool-status.js +2 -0
  214. package/dist/orchestration/telegram-tool-status.js.map +1 -1
  215. package/dist/orchestration/types.d.ts +21 -0
  216. package/dist/orchestration/types.d.ts.map +1 -1
  217. package/dist/orchestration/types.js.map +1 -1
  218. package/dist/processes/listeners.d.ts +41 -0
  219. package/dist/processes/listeners.d.ts.map +1 -0
  220. package/dist/processes/listeners.js +140 -0
  221. package/dist/processes/listeners.js.map +1 -0
  222. package/dist/processes/start.d.ts +39 -0
  223. package/dist/processes/start.d.ts.map +1 -0
  224. package/dist/processes/start.js +208 -0
  225. package/dist/processes/start.js.map +1 -0
  226. package/dist/processes/stop.d.ts +37 -0
  227. package/dist/processes/stop.d.ts.map +1 -0
  228. package/dist/processes/stop.js +94 -0
  229. package/dist/processes/stop.js.map +1 -0
  230. package/dist/session/cwd.d.ts +65 -0
  231. package/dist/session/cwd.d.ts.map +1 -0
  232. package/dist/session/cwd.js +24 -0
  233. package/dist/session/cwd.js.map +1 -0
  234. package/dist/session/process.d.ts +17 -0
  235. package/dist/session/process.d.ts.map +1 -1
  236. package/dist/session/process.js +58 -3
  237. package/dist/session/process.js.map +1 -1
  238. package/dist/session/runtime-profile.d.ts +4 -0
  239. package/dist/session/runtime-profile.d.ts.map +1 -1
  240. package/dist/session/runtime-profile.js +1 -0
  241. package/dist/session/runtime-profile.js.map +1 -1
  242. package/dist/session/store.d.ts +13 -1
  243. package/dist/session/store.d.ts.map +1 -1
  244. package/dist/session/store.js +50 -4
  245. package/dist/session/store.js.map +1 -1
  246. package/dist/types.d.ts +19 -0
  247. package/dist/types.d.ts.map +1 -1
  248. package/dist/ui/voice-call-client.d.ts +3 -0
  249. package/dist/ui/voice-call-client.d.ts.map +1 -1
  250. package/dist/ui/voice-call-client.js +10 -1
  251. package/dist/ui/voice-call-client.js.map +1 -1
  252. package/dist/utils/paths.d.ts +5 -0
  253. package/dist/utils/paths.d.ts.map +1 -1
  254. package/dist/utils/paths.js +15 -0
  255. package/dist/utils/paths.js.map +1 -1
  256. package/dist/utils/result.d.ts +16 -0
  257. package/dist/utils/result.d.ts.map +1 -0
  258. package/dist/utils/result.js +8 -0
  259. package/dist/utils/result.js.map +1 -0
  260. package/dist/voice/errors.js +1 -1
  261. package/dist/voice/errors.js.map +1 -1
  262. package/dist/voice/providers/elevenlabs-tts.d.ts.map +1 -1
  263. package/dist/voice/providers/elevenlabs-tts.js +17 -1
  264. package/dist/voice/providers/elevenlabs-tts.js.map +1 -1
  265. package/dist/voice/providers/socket.js +25 -6
  266. package/dist/voice/providers/socket.js.map +1 -1
  267. package/dist/voice/session.js +3 -2
  268. package/dist/voice/session.js.map +1 -1
  269. package/mcp/server.ts +1 -1
  270. package/mcp/tools/tasks/module.ts +2 -1
  271. package/package.json +1 -1
@@ -100,6 +100,10 @@ const types_1 = require("../history/types");
100
100
  const skill_learning_1 = require("./skill-learning");
101
101
  const knowledge_1 = require("./knowledge");
102
102
  const resolve_1 = require("../connectors/resolve");
103
+ const cwd_1 = require("../session/cwd");
104
+ const config_4 = require("../orchestration/config");
105
+ const worker_harness_1 = require("../orchestration/worker-harness");
106
+ const result_1 = require("../utils/result");
103
107
  const DEFAULT_IDLE_TIMEOUT_MINUTES = 30;
104
108
  const DEFAULT_MAX_CONCURRENT = 20;
105
109
  const ANTHROPIC_SOCKET_ERROR = 'socket connection was closed unexpectedly';
@@ -119,10 +123,19 @@ var model_registry_1 = require("./model-registry");
119
123
  Object.defineProperty(exports, "DEFAULT_MODELS", { enumerable: true, get: function () { return model_registry_1.DEFAULT_MODELS; } });
120
124
  const model_registry_2 = require("./model-registry");
121
125
  const plugin_info_1 = require("../pstack/plugin-info");
122
- const config_4 = require("../pstack/config");
126
+ const config_5 = require("../pstack/config");
123
127
  const sheet_1 = require("../pstack/sheet");
124
128
  const setup_1 = require("../pstack/setup");
125
129
  const menu_1 = require("../pstack/menu");
130
+ const paths_1 = require("../utils/paths");
131
+ function realpathOrNull(p) {
132
+ try {
133
+ return fs.realpathSync(p);
134
+ }
135
+ catch {
136
+ return null;
137
+ }
138
+ }
126
139
  const PSTACK_WRITE_REQUIRED = 'Changing the pstack setup needs an API key with write access to this agent. /pstack-setup without arguments shows it.';
127
140
  const PSTACK_SETUP_USAGE = 'Usage: /pstack-setup on | off | <role>: <model-id>[ @<level>] (one per line; "<role>: default" drops an override; "<role> += <model-id>[ @<level>]" / "<role> -= <model-id>" edit a panel list; "default effort: <level|session>").';
128
141
  const PROTECTED_WORKSPACE_FILES = [
@@ -236,8 +249,117 @@ class AgentRunner extends events_1.EventEmitter {
236
249
  this.orchestration?.ownsChannelIngress(source));
237
250
  }
238
251
  orchestrationForApi(sessionId) {
239
- return Boolean((this.orchestration?.ownsSession(sessionId) && !this.orchestration.canReturnToLegacy()) ||
240
- (this.agentConfig.orchestration?.enabled && (this.agentConfig.orchestration.channels ?? ['api']).includes('api')));
252
+ return Boolean((this.orchestration?.ownsSession(sessionId) && !this.orchestration.canReturnToLegacy()) || this.apiChannelOrchestrated());
253
+ }
254
+ apiChannelOrchestrated() {
255
+ return Boolean(this.agentConfig.orchestration?.enabled && (this.agentConfig.orchestration.channels ?? ['api']).includes('api'));
256
+ }
257
+ sessionOwners() {
258
+ if (this.apiSessionOwners)
259
+ return Promise.resolve(this.apiSessionOwners);
260
+ this.apiSessionOwnersLoading ?? (this.apiSessionOwnersLoading = (async () => {
261
+ const owners = new Map();
262
+ for (const [id, record] of await this.sessionStore.listApiSessionRecords(this.agentConfig.id)) {
263
+ owners.set(id, { chatId: record.chatId, cwd: await this.recordCwd(id, record) });
264
+ }
265
+ this.apiSessionOwners = owners;
266
+ return owners;
267
+ })().finally(() => { this.apiSessionOwnersLoading = undefined; }));
268
+ return this.apiSessionOwnersLoading;
269
+ }
270
+ /** The cwd recorded in the session index. */
271
+ async recordCwd(_sessionId, record) {
272
+ return (0, cwd_1.storedCwd)(record);
273
+ }
274
+ /**
275
+ * Registers `sessionId` under `chatId`, or throws SESSION_ID_IN_USE when another chat holds it. Called before the
276
+ * id is added to a chat index, so a turn never runs a session through a chat it does not belong to.
277
+ */
278
+ async claimApiSession(sessionId, chatId) {
279
+ const owners = await this.sessionOwners();
280
+ if (!owners.has(sessionId)) {
281
+ const cwd = await this.recordCwd(sessionId, {});
282
+ // A parallel claim from another chat may have landed during the await; the owner check below sees it.
283
+ if (!owners.has(sessionId))
284
+ owners.set(sessionId, { chatId, cwd });
285
+ }
286
+ if (owners.get(sessionId)?.chatId !== chatId) {
287
+ throw Object.assign(new Error(`Session ${sessionId} belongs to another chat`), { code: 'SESSION_ID_IN_USE' });
288
+ }
289
+ }
290
+ async registerApiSession(chatId, sessionId, onStoreError) {
291
+ await this.claimApiSession(sessionId, chatId);
292
+ const write = this.sessionStore.ensureApiSession(this.agentConfig.id, chatId, sessionId);
293
+ await (onStoreError ? write.catch(onStoreError) : write);
294
+ }
295
+ async sessionCwdOf(sessionId) {
296
+ return (await this.sessionOwners()).get(sessionId)?.cwd ?? { kind: 'none' };
297
+ }
298
+ isApiSessionLive(sessionId, orchestratedLive = this.orchestration?.liveSessionIds() ?? new Set()) {
299
+ return orchestratedLive.has(sessionId) || this.pendingApiSessions.has(sessionId) || this.sessionSpawnLocks.has(sessionId);
300
+ }
301
+ /** Finishes the delete of every retired session whose work has ended: purge what it wrote, then free its id. */
302
+ reapRetiredSessions() {
303
+ for (const [id, { chatId, bound }] of [...this.retiredSessions]) {
304
+ if (this.isApiSessionLive(id))
305
+ continue;
306
+ this.retiredSessions.delete(id);
307
+ this.purgeApiSessionHistory(chatId, id);
308
+ if (bound)
309
+ this.removeApiSessionMedia(id);
310
+ this.apiSessionOwners?.delete(id);
311
+ }
312
+ }
313
+ purgeApiSessionHistory(chatId, sessionId) {
314
+ const mediaPaths = this.historyDb.clearSession(`api-${chatId}`, sessionId);
315
+ media_store_1.MediaStore.deleteMediaFiles(this.agentsBaseDir, this.agentConfig.id, mediaPaths);
316
+ }
317
+ /** Everything under media/api-<id>/ of a deleted folder-bound chat, not only the files its history named. */
318
+ removeApiSessionMedia(sessionId) {
319
+ try {
320
+ fs.rmSync(media_store_1.MediaStore.mediaDir(this.agentsBaseDir, this.agentConfig.id, `api-${sessionId}`), { recursive: true, force: true });
321
+ }
322
+ catch (err) {
323
+ this.logger.warn('Failed to remove the media folder of a deleted folder-bound session', { sessionId, error: err.message });
324
+ }
325
+ }
326
+ /** Throws CWD_UNAVAILABLE when the session's folder no longer resolves; a no-op for unbound sessions. */
327
+ async assertApiCwdAvailable(sessionId) {
328
+ const cwd = await this.apiSessionCwd(sessionId);
329
+ if (cwd && !cwd.ok)
330
+ throw (0, cwd_1.cwdError)(cwd.error);
331
+ }
332
+ async apiSessionCwd(sessionId) {
333
+ const stored = await this.sessionCwdOf(sessionId);
334
+ if (stored.kind === 'none')
335
+ return undefined;
336
+ const reason = this.cwdUnsupportedReason();
337
+ if (reason)
338
+ return (0, result_1.err)({ code: 'unsupported_agent', reason });
339
+ const resolved = await this.cwdResolver.resolve(stored.path);
340
+ return resolved.ok ? resolved : (0, result_1.err)({ code: 'unavailable', reason: resolved.error });
341
+ }
342
+ /** A client-supplied cwd for a new session: `invalid` before anything else is looked at. */
343
+ async parseApiCwd(raw) {
344
+ const parsed = await this.cwdResolver.parse(raw);
345
+ if (!parsed.ok && parsed.error === 'invalid')
346
+ return (0, result_1.err)('invalid');
347
+ const reason = this.cwdUnsupportedReason();
348
+ if (reason)
349
+ return (0, result_1.err)({ code: 'unsupported_agent', reason });
350
+ return parsed.ok ? parsed : (0, result_1.err)({ code: 'unavailable', reason: parsed.error });
351
+ }
352
+ /** Orchestrated chats run their work in tasks, so the agent's default worker setup must be able to run in the folder. */
353
+ cwdUnsupportedReason() {
354
+ if (this.agentConfig.type === 'app-agent')
355
+ return 'container';
356
+ if (!this.apiChannelOrchestrated())
357
+ return undefined;
358
+ if ((0, config_4.resolveOrchestrationConfig)(this.agentConfig.orchestration).tasks.workspaceMode !== 'host')
359
+ return 'workspace_mode';
360
+ if ((0, worker_harness_1.resolveWorkerHarness)(this.agentConfig, this.gatewayConfig, this.agentConfig.claude.model).harness === 'codex')
361
+ return 'codex';
362
+ return undefined;
241
363
  }
242
364
  async sendLinkedOrchestrationChannel(...[binding, text, _id, file]) {
243
365
  const channel = String(binding.channel), chat = String(binding.chat_id);
@@ -321,6 +443,8 @@ class AgentRunner extends events_1.EventEmitter {
321
443
  this.sessions.set(key, agentSession);
322
444
  return agentSession;
323
445
  },
446
+ sessionCwd: ({ source, agentSessionId }) => source === 'api' ? this.apiSessionCwd(agentSessionId) : Promise.resolve(undefined),
447
+ cwdResolver: this.cwdResolver,
324
448
  releaseAgentSession: async (sessionId, agentSession) => {
325
449
  await agentSession.stop();
326
450
  for (const [key, value] of this.sessions)
@@ -331,6 +455,10 @@ class AgentRunner extends events_1.EventEmitter {
331
455
  }
332
456
  return this.orchestrationStarting;
333
457
  }
458
+ /** The live Computer Use run on a device's relay grant; never starts orchestration just to answer. */
459
+ computerActivity(grantId, principalId) {
460
+ return this.orchestration?.computerActivity(grantId, principalId);
461
+ }
334
462
  async orchestrationActivity(sessionId, principalId, after) {
335
463
  return (await this.getOrchestration()).activity(sessionId, principalId, after);
336
464
  }
@@ -508,6 +636,9 @@ class AgentRunner extends events_1.EventEmitter {
508
636
  if (prior)
509
637
  return { text: '', attachments: [], inputId: prior.inputId };
510
638
  }
639
+ await this.claimApiSession(sessionId, chatId);
640
+ // Fail the turn here, with the code the web shows, instead of leaving a task_spawn error for the model to relay.
641
+ await this.assertApiCwdAvailable(sessionId);
511
642
  await this.sessionStore.ensureApiSession(this.agentConfig.id, chatId, sessionId);
512
643
  this.apiChatIds.set(sessionId, chatId);
513
644
  const media = opts.mediaFiles?.length ? await promoteUiUploads(this.agentsBaseDir, this.agentConfig.id, sessionId, opts.mediaFiles, this.logger, preparationDir) : [];
@@ -580,7 +711,8 @@ class AgentRunner extends events_1.EventEmitter {
580
711
  this.pendingApiSessions.delete(sessionId);
581
712
  }
582
713
  }
583
- constructor(agentConfig, gatewayConfig, logger) {
714
+ /** `cwdResolver` comes from the files module through the composition root; without it no session binds a folder. */
715
+ constructor(agentConfig, gatewayConfig, logger, cwdResolver = cwd_1.NO_CWD_RESOLVER) {
584
716
  super();
585
717
  this.stopping = false;
586
718
  this.callbackServer = null;
@@ -710,6 +842,12 @@ class AgentRunner extends events_1.EventEmitter {
710
842
  // (e.g. the app/agent identifier) is not captured at spawn. Record it here
711
843
  // keyed by sessionId so the dashboard can show the actual chat id.
712
844
  this.apiChatIds = new Map();
845
+ /**
846
+ * Sessions deleted while a turn or orchestrated work was live, with the chat they belonged to. Their owner entry
847
+ * stays until that work ends, so the folder still counts as busy while the turn writes; `reapRetiredSessions` then
848
+ * purges what it wrote and frees the id.
849
+ */
850
+ this.retiredSessions = new Map();
713
851
  // Skill registry for detecting /skill-name commands in user messages
714
852
  this.skillRegistry = { skills: new Map() };
715
853
  this.skillNotificationOrigins = new Map();
@@ -762,6 +900,7 @@ class AgentRunner extends events_1.EventEmitter {
762
900
  this.shutdownHandlers = [];
763
901
  this.receiverReload = Promise.resolve();
764
902
  this.channelReloadSnapshot = new Map();
903
+ this.cwdResolver = cwdResolver;
765
904
  this.agentConfig = (0, gateway_config_1.applyGatewayOrchestration)(agentConfig, gatewayConfig);
766
905
  this.gatewayConfig = gatewayConfig;
767
906
  this.logger = logger ?? (0, logger_1.createLogger)(agentConfig.id, gatewayConfig.gateway.logDir);
@@ -2364,9 +2503,10 @@ class AgentRunner extends events_1.EventEmitter {
2364
2503
  }
2365
2504
  }
2366
2505
  }
2367
- // Restart if model changed (including switching back to the agent default)
2368
- if (existing.modelOverride !== effectiveOverride) {
2369
- this.logger.info('Model changed, restarting session', { mapKey, oldModel: existing.modelOverride, newModel: effectiveOverride ?? agentDefaultModel });
2506
+ // Restart if model changed (including switching back to the agent default),
2507
+ // or if the bound folder moved: the respawn re-resolves it or fails.
2508
+ if (existing.modelOverride !== effectiveOverride || await existing.cwdMoved()) {
2509
+ this.logger.info('Model or working folder changed, restarting session', { mapKey, oldModel: existing.modelOverride, newModel: effectiveOverride ?? agentDefaultModel });
2370
2510
  const respawn = (async () => {
2371
2511
  await existing.stop();
2372
2512
  this.sessions.delete(mapKey);
@@ -2415,6 +2555,12 @@ class AgentRunner extends events_1.EventEmitter {
2415
2555
  // Apply per-session model override (caller already normalized to undefined when == agent default)
2416
2556
  if (modelOverride)
2417
2557
  proc.modelOverride = modelOverride;
2558
+ if (source === 'api' && (await this.sessionCwdOf(actualSessionId)).kind !== 'none') {
2559
+ proc.cwdSource = {
2560
+ resolve: async () => (await this.apiSessionCwd(actualSessionId)) ?? (0, result_1.err)({ code: 'unavailable', reason: 'internal' }),
2561
+ note: (cwd) => this.cwdResolver.note(cwd),
2562
+ };
2563
+ }
2418
2564
  // Keep the searchable memory archive (planning-64) fresh for the memory_search
2419
2565
  // tool. Fire-and-forget, detached, OFF the event loop — never blocks the spawn.
2420
2566
  // Isolate mode (#601) and disableArchive (#609) offer no archive tool, so nothing would read the index.
@@ -3156,7 +3302,7 @@ class AgentRunner extends events_1.EventEmitter {
3156
3302
  const plugin = (0, plugin_info_1.pstackPluginInfo)();
3157
3303
  const roles = plugin.installPath ? (0, plugin_info_1.pstackModels)(plugin.installPath) : undefined;
3158
3304
  try {
3159
- const { saved } = await this.updatePstack(previous => arg === 'off' ? undefined : arg === 'on' ? previous ?? {} : (0, config_4.applySheetLines)(previous ?? {}, arg, roles && (role => (0, sheet_1.pstackPanelDefault)(roles, role))));
3305
+ const { saved } = await this.updatePstack(previous => arg === 'off' ? undefined : arg === 'on' ? previous ?? {} : (0, config_5.applySheetLines)(previous ?? {}, arg, roles && (role => (0, sheet_1.pstackPanelDefault)(roles, role))));
3160
3306
  if (!saved)
3161
3307
  return 'pstack is removed from this agent. Its next worker does not load it.';
3162
3308
  // `on` for an agent already set up saves nothing, so a plugin that cannot be read is only noticed here.
@@ -3165,7 +3311,7 @@ class AgentRunner extends events_1.EventEmitter {
3165
3311
  return `pstack is set up for this agent. The next worker loads it with this sheet:\n\n${(0, sheet_1.renderPstackSheet)(saved, roles)}`;
3166
3312
  }
3167
3313
  catch (error) {
3168
- if (!(error instanceof config_4.PstackConfigError))
3314
+ if (!(error instanceof config_5.PstackConfigError))
3169
3315
  throw error;
3170
3316
  return `${error.code}: ${error.message}`;
3171
3317
  }
@@ -3178,7 +3324,7 @@ class AgentRunner extends events_1.EventEmitter {
3178
3324
  step = (0, menu_1.pstackMenuStep)(data, state);
3179
3325
  }
3180
3326
  catch (error) {
3181
- if (!(error instanceof config_4.PstackConfigError))
3327
+ if (!(error instanceof config_5.PstackConfigError))
3182
3328
  throw error;
3183
3329
  return { ...(0, menu_1.pstackMenuScreen)({ kind: 'home' }, state, `⚠️ ${error.message}`), toast: error.message };
3184
3330
  }
@@ -3195,7 +3341,7 @@ class AgentRunner extends events_1.EventEmitter {
3195
3341
  });
3196
3342
  }
3197
3343
  catch (error) {
3198
- if (!(error instanceof config_4.PstackConfigError))
3344
+ if (!(error instanceof config_5.PstackConfigError))
3199
3345
  throw error;
3200
3346
  return { ...(0, menu_1.pstackMenuScreen)(step.view, state, `⚠️ ${error.code}: ${error.message}`), toast: error.message };
3201
3347
  }
@@ -3971,6 +4117,7 @@ class AgentRunner extends events_1.EventEmitter {
3971
4117
  await this.getOrchestration();
3972
4118
  this.stopping = false;
3973
4119
  await this.sweepStaleSessionDirs();
4120
+ await this.sessionOwners();
3974
4121
  await this.startCallbackServer();
3975
4122
  if (this.agentConfig.telegram?.botToken) {
3976
4123
  this.receiver = new receiver_1.TelegramReceiver(this.agentConfig, this.callbackPort, this.gatewayConfig.gateway.logDir, this.gatewayConfig.gateway.headless !== false);
@@ -4689,54 +4836,57 @@ class AgentRunner extends events_1.EventEmitter {
4689
4836
  const err = Object.assign(new Error(`Session ${sessionId} already has a pending request`), { code: 'CONFLICT' });
4690
4837
  throw err;
4691
4838
  }
4692
- // Register session in api-{chatId} index.json on first use (store adds channel prefix internally)
4693
- await this.sessionStore.ensureApiSession(this.agentConfig.id, chatId, sessionId).catch((err) => {
4694
- this.logger.warn('Failed to register API session in index', { agentId: this.agentConfig.id, chatId, sessionId, error: err.message });
4695
- });
4696
- // Use model from request body if provided, otherwise use agent default.
4697
- // A spawn keys its isolated memory by the chat (#601).
4698
- const session = await this.getOrSpawnSession(sessionId, 'api', undefined, opts.model, chatId);
4699
- this.apiChatIds.set(sessionId, chatId);
4700
- // Promote UI-uploaded files from staging to permanent per-session storage
4701
- const finalMediaFiles = opts.mediaFiles?.length
4702
- ? await promoteUiUploads(this.agentsBaseDir, this.agentConfig.id, sessionId, opts.mediaFiles, this.logger)
4703
- : undefined;
4704
- // Refs built from staging paths must follow the files to their promoted
4705
- // location — see remapImageParamsRefs (#74).
4706
- const imageParams = AgentRunner.remapImageParamsRefs(opts.imageParams, opts.mediaFiles, finalMediaFiles);
4707
- // The image-to-video source frame follows the same staging→promoted move.
4708
- const videoParams = AgentRunner.remapVideoParamsRefs(opts.videoParams, opts.mediaFiles, finalMediaFiles);
4709
- // Resolve media files to absolute paths for file-path based image passing
4710
- // (same pattern as Telegram — Claude Code reads files via Read tool instead of base64 inline)
4711
- const imagePaths = finalMediaFiles?.length ? this.resolveMediaPaths(finalMediaFiles) : [];
4712
- // skipUserMessage omits the trigger from both session context and history so only the
4713
- // assistant response is visible — intentional for system-initiated messages (e.g. cron welcome).
4714
- // Claude still receives the prompt via channelXml for this turn; session restarts will not
4715
- // replay it, which is the desired behaviour for one-shot proactive messages.
4716
- if (!opts.skipUserMessage) {
4717
- const apiUserTs = Date.now();
4718
- await this.sessionStore
4719
- .appendMessage(this.agentConfig.id, sessionId, {
4720
- role: 'user',
4721
- content: message,
4722
- ts: apiUserTs,
4723
- })
4724
- .catch(() => { });
4725
- this.historyDb.insertMessage({
4726
- chatId: `api-${chatId}`,
4727
- sessionId,
4728
- source: 'api',
4729
- role: 'user',
4730
- content: message,
4731
- mediaFiles: finalMediaFiles?.length ? finalMediaFiles : undefined,
4732
- // Display-only (#74): lets the UI show which earlier images this turn
4733
- // referenced after a reload. The generation path reads the refs from the
4734
- // image-params note, never from here.
4735
- imageRefs: imageParams?.image_refs?.length ? imageParams.image_refs : undefined,
4736
- ts: apiUserTs,
4839
+ this.pendingApiSessions.add(sessionId); // reserved before the first await so a folder delete sees the turn while it is still preparing
4840
+ const { session, imageParams, videoParams, imagePaths } = await (async () => {
4841
+ // Register session in api-{chatId} index.json on first use (store adds channel prefix internally)
4842
+ await this.registerApiSession(chatId, sessionId, (err) => {
4843
+ this.logger.warn('Failed to register API session in index', { agentId: this.agentConfig.id, chatId, sessionId, error: err.message });
4737
4844
  });
4738
- }
4739
- this.pendingApiSessions.add(sessionId);
4845
+ // Use model from request body if provided, otherwise use agent default.
4846
+ // A spawn keys its isolated memory by the chat (#601).
4847
+ this.apiChatIds.set(sessionId, chatId);
4848
+ const session = await this.getOrSpawnSession(sessionId, 'api', undefined, opts.model, chatId);
4849
+ // Promote UI-uploaded files from staging to permanent per-session storage
4850
+ const finalMediaFiles = opts.mediaFiles?.length
4851
+ ? await promoteUiUploads(this.agentsBaseDir, this.agentConfig.id, sessionId, opts.mediaFiles, this.logger)
4852
+ : undefined;
4853
+ // Refs built from staging paths must follow the files to their promoted
4854
+ // location — see remapImageParamsRefs (#74).
4855
+ const imageParams = AgentRunner.remapImageParamsRefs(opts.imageParams, opts.mediaFiles, finalMediaFiles);
4856
+ // The image-to-video source frame follows the same staging→promoted move.
4857
+ const videoParams = AgentRunner.remapVideoParamsRefs(opts.videoParams, opts.mediaFiles, finalMediaFiles);
4858
+ // Resolve media files to absolute paths for file-path based image passing
4859
+ // (same pattern as Telegram — Claude Code reads files via Read tool instead of base64 inline)
4860
+ const imagePaths = finalMediaFiles?.length ? this.resolveMediaPaths(finalMediaFiles) : [];
4861
+ // skipUserMessage omits the trigger from both session context and history so only the
4862
+ // assistant response is visible — intentional for system-initiated messages (e.g. cron welcome).
4863
+ // Claude still receives the prompt via channelXml for this turn; session restarts will not
4864
+ // replay it, which is the desired behaviour for one-shot proactive messages.
4865
+ if (!opts.skipUserMessage) {
4866
+ const apiUserTs = Date.now();
4867
+ await this.sessionStore
4868
+ .appendMessage(this.agentConfig.id, sessionId, {
4869
+ role: 'user',
4870
+ content: message,
4871
+ ts: apiUserTs,
4872
+ })
4873
+ .catch(() => { });
4874
+ this.historyDb.insertMessage({
4875
+ chatId: `api-${chatId}`,
4876
+ sessionId,
4877
+ source: 'api',
4878
+ role: 'user',
4879
+ content: message,
4880
+ mediaFiles: finalMediaFiles?.length ? finalMediaFiles : undefined,
4881
+ // Display-only (#74): lets the UI show which earlier images this turn
4882
+ // referenced after a reload. The generation path reads the refs from the
4883
+ // image-params note, never from here.
4884
+ imageRefs: imageParams?.image_refs?.length ? imageParams.image_refs : undefined,
4885
+ ts: apiUserTs,
4886
+ });
4887
+ }
4888
+ return { session, imageParams, videoParams, imagePaths };
4889
+ })().catch((error) => { this.pendingApiSessions.delete(sessionId); throw error; });
4740
4890
  // A previous turn that died (hard timeout, crash) may have left attachments
4741
4891
  // buffered under this session — they belong to THAT turn; never let them
4742
4892
  // ride along on this one (#75).
@@ -4870,6 +5020,7 @@ class AgentRunner extends events_1.EventEmitter {
4870
5020
  // exactly as the hard cap below does.
4871
5021
  fail(Object.assign(new Error('Session process exited unexpectedly before responding.'), { code: 'PROCESS_EXITED' }), buffer.join(''));
4872
5022
  };
5023
+ const onStartupError = (error) => fail(error, buffer.join(''));
4873
5024
  const cleanup = () => {
4874
5025
  clearTimeout(globalTimer);
4875
5026
  if (hardCapTimer)
@@ -4878,6 +5029,7 @@ class AgentRunner extends events_1.EventEmitter {
4878
5029
  clearTimeout(quietTimer);
4879
5030
  session.off('output', onOutput);
4880
5031
  session.off('exit', onExit);
5032
+ session.off('startup-error', onStartupError);
4881
5033
  this.pendingApiSessions.delete(sessionId);
4882
5034
  };
4883
5035
  const resetQuiet = () => {
@@ -4952,6 +5104,7 @@ class AgentRunner extends events_1.EventEmitter {
4952
5104
  }, opts.timeoutMs);
4953
5105
  session.on('output', onOutput);
4954
5106
  session.on('exit', onExit);
5107
+ session.on('startup-error', onStartupError);
4955
5108
  session.setProcessing(true);
4956
5109
  session.sendMessage(channelXml);
4957
5110
  // Do NOT call resetQuiet() here — the quiet timer should only start
@@ -4998,49 +5151,52 @@ class AgentRunner extends events_1.EventEmitter {
4998
5151
  const err = Object.assign(new Error(`Session ${sessionId} already has a pending request`), { code: 'CONFLICT' });
4999
5152
  throw err;
5000
5153
  }
5001
- // Register session in api-{chatId} index.json on first use (store adds channel prefix internally)
5002
- await this.sessionStore.ensureApiSession(this.agentConfig.id, chatId, sessionId).catch((err) => {
5003
- this.logger.warn('Failed to register API session in index', { agentId: this.agentConfig.id, chatId, sessionId, error: err.message });
5004
- });
5005
- // Use model from request body if provided, otherwise use agent default.
5006
- // A spawn keys its isolated memory by the chat (#601).
5007
- const session = await this.getOrSpawnSession(sessionId, 'api', undefined, opts.model, chatId);
5008
- this.apiChatIds.set(sessionId, chatId);
5009
- // Promote UI-uploaded files from staging to permanent per-session storage
5010
- const finalMediaFilesStream = opts.mediaFiles?.length
5011
- ? await promoteUiUploads(this.agentsBaseDir, this.agentConfig.id, sessionId, opts.mediaFiles, this.logger)
5012
- : undefined;
5013
- // Refs built from staging paths must follow the files to their promoted
5014
- // location — see remapImageParamsRefs (#74).
5015
- const imageParamsStream = AgentRunner.remapImageParamsRefs(opts.imageParams, opts.mediaFiles, finalMediaFilesStream);
5016
- // The image-to-video source frame follows the same staging→promoted move.
5017
- const videoParamsStream = AgentRunner.remapVideoParamsRefs(opts.videoParams, opts.mediaFiles, finalMediaFilesStream);
5018
- // Resolve media files to absolute paths for file-path based image passing
5019
- const imagePathsStream = finalMediaFilesStream?.length ? this.resolveMediaPaths(finalMediaFilesStream) : [];
5020
- if (!opts.skipUserMessage) {
5021
- const streamUserTs = Date.now();
5022
- await this.sessionStore
5023
- .appendMessage(this.agentConfig.id, sessionId, {
5024
- role: 'user',
5025
- content: message,
5026
- ts: streamUserTs,
5027
- })
5028
- .catch(() => { });
5029
- this.historyDb.insertMessage({
5030
- chatId: `api-${chatId}`,
5031
- sessionId,
5032
- source: 'api',
5033
- role: 'user',
5034
- content: message,
5035
- mediaFiles: finalMediaFilesStream?.length ? finalMediaFilesStream : undefined,
5036
- // Display-only (#74): lets the UI show which earlier images this turn
5037
- // referenced after a reload. The generation path reads the refs from the
5038
- // image-params note, never from here.
5039
- imageRefs: imageParamsStream?.image_refs?.length ? imageParamsStream.image_refs : undefined,
5040
- ts: streamUserTs,
5154
+ this.pendingApiSessions.add(sessionId); // reserved before the first await so a folder delete sees the turn while it is still preparing
5155
+ const { session, imageParams: imageParamsStream, videoParams: videoParamsStream, imagePaths: imagePathsStream } = await (async () => {
5156
+ // Register session in api-{chatId} index.json on first use (store adds channel prefix internally)
5157
+ await this.registerApiSession(chatId, sessionId, (err) => {
5158
+ this.logger.warn('Failed to register API session in index', { agentId: this.agentConfig.id, chatId, sessionId, error: err.message });
5041
5159
  });
5042
- }
5043
- this.pendingApiSessions.add(sessionId);
5160
+ // Use model from request body if provided, otherwise use agent default.
5161
+ // A spawn keys its isolated memory by the chat (#601).
5162
+ this.apiChatIds.set(sessionId, chatId);
5163
+ const session = await this.getOrSpawnSession(sessionId, 'api', undefined, opts.model, chatId);
5164
+ // Promote UI-uploaded files from staging to permanent per-session storage
5165
+ const finalMediaFilesStream = opts.mediaFiles?.length
5166
+ ? await promoteUiUploads(this.agentsBaseDir, this.agentConfig.id, sessionId, opts.mediaFiles, this.logger)
5167
+ : undefined;
5168
+ // Refs built from staging paths must follow the files to their promoted
5169
+ // location — see remapImageParamsRefs (#74).
5170
+ const imageParamsStream = AgentRunner.remapImageParamsRefs(opts.imageParams, opts.mediaFiles, finalMediaFilesStream);
5171
+ // The image-to-video source frame follows the same staging→promoted move.
5172
+ const videoParamsStream = AgentRunner.remapVideoParamsRefs(opts.videoParams, opts.mediaFiles, finalMediaFilesStream);
5173
+ // Resolve media files to absolute paths for file-path based image passing
5174
+ const imagePathsStream = finalMediaFilesStream?.length ? this.resolveMediaPaths(finalMediaFilesStream) : [];
5175
+ if (!opts.skipUserMessage) {
5176
+ const streamUserTs = Date.now();
5177
+ await this.sessionStore
5178
+ .appendMessage(this.agentConfig.id, sessionId, {
5179
+ role: 'user',
5180
+ content: message,
5181
+ ts: streamUserTs,
5182
+ })
5183
+ .catch(() => { });
5184
+ this.historyDb.insertMessage({
5185
+ chatId: `api-${chatId}`,
5186
+ sessionId,
5187
+ source: 'api',
5188
+ role: 'user',
5189
+ content: message,
5190
+ mediaFiles: finalMediaFilesStream?.length ? finalMediaFilesStream : undefined,
5191
+ // Display-only (#74): lets the UI show which earlier images this turn
5192
+ // referenced after a reload. The generation path reads the refs from the
5193
+ // image-params note, never from here.
5194
+ imageRefs: imageParamsStream?.image_refs?.length ? imageParamsStream.image_refs : undefined,
5195
+ ts: streamUserTs,
5196
+ });
5197
+ }
5198
+ return { session, imageParams: imageParamsStream, videoParams: videoParamsStream, imagePaths: imagePathsStream };
5199
+ })().catch((error) => { this.pendingApiSessions.delete(sessionId); throw error; });
5044
5200
  // A previous turn that died (hard timeout, crash) may have left attachments
5045
5201
  // buffered under this session — they belong to THAT turn; never let them
5046
5202
  // ride along on this one (#75).
@@ -5137,12 +5293,14 @@ class AgentRunner extends events_1.EventEmitter {
5137
5293
  // added for — the client saw the deltas and no `result` will ever land.
5138
5294
  fail(Object.assign(new Error('Session process exited unexpectedly before responding.'), { code: 'PROCESS_EXITED' }), buffer.join(''));
5139
5295
  };
5296
+ const onStartupError = (error) => fail(error, buffer.join(''));
5140
5297
  const cleanup = () => {
5141
5298
  clearTimeout(globalTimer);
5142
5299
  if (hardCapTimer)
5143
5300
  clearTimeout(hardCapTimer);
5144
5301
  session.off('output', onOutput);
5145
5302
  session.off('exit', onExit);
5303
+ session.off('startup-error', onStartupError);
5146
5304
  this.pendingApiSessions.delete(sessionId);
5147
5305
  };
5148
5306
  // Called when the SSE client disconnects. Detaches that connection's sink —
@@ -5259,6 +5417,7 @@ class AgentRunner extends events_1.EventEmitter {
5259
5417
  }, opts.timeoutMs);
5260
5418
  session.on('output', onOutput);
5261
5419
  session.on('exit', onExit);
5420
+ session.on('startup-error', onStartupError);
5262
5421
  // Image paths only work when allowTools:true — Claude needs the Read tool to access them
5263
5422
  const allowToolsStream = opts.allowTools ?? false;
5264
5423
  if (!allowToolsStream && imagePathsStream.length) {
@@ -5314,6 +5473,48 @@ class AgentRunner extends events_1.EventEmitter {
5314
5473
  hasActiveApiSession(sessionId) {
5315
5474
  return this.pendingApiSessions.has(sessionId);
5316
5475
  }
5476
+ /** Loads what {@link workIn} reads, so the check itself can run with no await, in the same step as what it guards. */
5477
+ async prepareWorkCheck() {
5478
+ await this.sessionOwners();
5479
+ this.reapRetiredSessions();
5480
+ }
5481
+ /**
5482
+ * What works in the real folder `dir`, in a folder inside it, or in one holding it, through any name or symlink
5483
+ * alias: `turn` for a live or queued turn, `spawn` for a process still spawning, `task` for an unfinished task and
5484
+ * `session` for an idle session process still running there. Keyed on live work and on the folder, not on the
5485
+ * session record, so deleting a session mid-turn does not unlock the folder. A live session whose binding cannot be
5486
+ * read counts everywhere. Synchronous; call {@link prepareWorkCheck} first.
5487
+ */
5488
+ workIn(dir) {
5489
+ const reasons = new Set();
5490
+ const owners = this.apiSessionOwners ?? new Map();
5491
+ const touches = (stored) => {
5492
+ if (!stored || stored.kind === 'none')
5493
+ return false;
5494
+ const real = realpathOrNull(stored.path);
5495
+ return real !== null && ((0, paths_1.pathWithin)(real, dir) || (0, paths_1.pathWithin)(dir, real));
5496
+ };
5497
+ const live = this.orchestration?.liveSessionIds() ?? new Set();
5498
+ for (const sessionId of new Set([...this.pendingApiSessions, ...this.sessionSpawnLocks.keys(), ...live])) {
5499
+ if (touches(owners.get(sessionId)?.cwd))
5500
+ reasons.add(this.sessionSpawnLocks.has(sessionId) ? 'spawn' : 'turn');
5501
+ }
5502
+ for (const task of this.orchestration?.activeTaskCwds() ?? []) {
5503
+ if (touches((0, cwd_1.storedCwd)(task)))
5504
+ reasons.add('task');
5505
+ }
5506
+ for (const proc of this.sessions.values()) {
5507
+ const cwd = proc.cwdDir;
5508
+ if (cwd && ((0, paths_1.pathWithin)(cwd, dir) || (0, paths_1.pathWithin)(dir, cwd)))
5509
+ reasons.add('session');
5510
+ }
5511
+ return reasons;
5512
+ }
5513
+ /** A turn, a spawn or a task works in or around the real folder `dir`. An idle session process does not count. */
5514
+ async hasActiveWorkIn(dir) {
5515
+ await this.prepareWorkCheck();
5516
+ return [...this.workIn(dir)].some((reason) => reason !== 'session');
5517
+ }
5317
5518
  /**
5318
5519
  * Attach a sink to a session's current turn stream (#421) — the server half of
5319
5520
  * "resume a turn on a new connection".
@@ -5444,6 +5645,21 @@ class AgentRunner extends events_1.EventEmitter {
5444
5645
  getHistoryDb() {
5445
5646
  return this.historyDb;
5446
5647
  }
5648
+ /**
5649
+ * How every session response reports its folder: `cwd` as stored, whether its own settings load, whether it still
5650
+ * resolves, and whether a turn, a spawn or an orchestrated task is live on it.
5651
+ */
5652
+ async sessionCwdView(sessionId) {
5653
+ this.reapRetiredSessions();
5654
+ const active = this.isApiSessionLive(sessionId);
5655
+ const stored = await this.sessionCwdOf(sessionId);
5656
+ if (stored.kind === 'none')
5657
+ return { cwd: null, trusted: false, cwdState: null, active };
5658
+ const resolved = await this.cwdResolver.resolve(stored.path);
5659
+ if (resolved.ok)
5660
+ return { cwd: stored.path, trusted: resolved.value.trusted, cwdState: 'available', active };
5661
+ return { cwd: stored.path, trusted: false, cwdState: resolved.error === 'not_found' ? 'missing' : 'unavailable', active };
5662
+ }
5447
5663
  getAllSessionMeta() {
5448
5664
  return this.sessionStore.getAllSessionMeta(this.agentConfig.id);
5449
5665
  }
@@ -5474,7 +5690,7 @@ class AgentRunner extends events_1.EventEmitter {
5474
5690
  return { result: { error: 'SESSION_ID_REQUIRED' }, responseText: '⚠️ /rename renames the session given by session_id; send it with the session to rename.', actions: [] };
5475
5691
  }
5476
5692
  // Register session in the api-{chatId} index on first use (same as sendApiMessageStream)
5477
- await this.sessionStore.ensureApiSession(agentId, storeChatId, sessionId).catch((err) => {
5693
+ await this.registerApiSession(storeChatId, sessionId, (err) => {
5478
5694
  this.logger.warn('Failed to register API session in index for command', { agentId, chatId, sessionId, error: err.message });
5479
5695
  });
5480
5696
  // Persist a command message to the permanent history DB ONLY — not the model's session
@@ -5816,6 +6032,7 @@ class AgentRunner extends events_1.EventEmitter {
5816
6032
  }
5817
6033
  }
5818
6034
  async listApiSessions(chatId) {
6035
+ this.reapRetiredSessions();
5819
6036
  return this.sessionStore.listSessions(this.agentConfig.id, chatId, 'api');
5820
6037
  }
5821
6038
  /**
@@ -5826,11 +6043,14 @@ class AgentRunner extends events_1.EventEmitter {
5826
6043
  async apiSessionExists(chatId, sessionId) {
5827
6044
  return this.sessionStore.apiSessionExists(this.agentConfig.id, chatId, sessionId);
5828
6045
  }
5829
- async createApiSession(chatId, prompt, name) {
6046
+ /** `cwd` comes from {@link parseApiCwd}; its path is stored on the session and resolved again at every turn. */
6047
+ async createApiSession(chatId, prompt, name, cwd) {
5830
6048
  const sessionName = name ?? (prompt
5831
6049
  ? (prompt.length > 60 ? `${prompt.slice(0, 60)}...` : prompt)
5832
6050
  : undefined);
5833
- const meta = await this.sessionStore.createTelegramSession(this.agentConfig.id, chatId, sessionName, 'api');
6051
+ const owners = await this.sessionOwners();
6052
+ const meta = await this.sessionStore.createTelegramSession(this.agentConfig.id, chatId, sessionName, 'api', cwd?.path);
6053
+ owners.set(meta.id, { chatId, cwd: cwd ? { kind: 'path', path: cwd.path } : { kind: 'none' } });
5834
6054
  if (!name && prompt) {
5835
6055
  this.generateSessionNameInBackground(chatId, meta.id, prompt);
5836
6056
  }
@@ -5863,6 +6083,7 @@ class AgentRunner extends events_1.EventEmitter {
5863
6083
  return {
5864
6084
  sessionId: meta.id,
5865
6085
  sessionName: meta.name,
6086
+ ...await this.sessionCwdView(meta.id),
5866
6087
  messageCount: meta.messageCount,
5867
6088
  archivedCount: meta.archivedCount ?? 0,
5868
6089
  ...context,
@@ -5872,7 +6093,7 @@ class AgentRunner extends events_1.EventEmitter {
5872
6093
  async updateApiSession(chatId, sessionId, updates) {
5873
6094
  if (updates.sessionName) {
5874
6095
  // Ensure session exists in the file index (may be missing for older sessions stored only in SQLite)
5875
- await this.sessionStore.ensureApiSession(this.agentConfig.id, chatId, sessionId).catch((err) => {
6096
+ await this.registerApiSession(chatId, sessionId, (err) => {
5876
6097
  this.logger.warn('Failed to register API session in index', { agentId: this.agentConfig.id, chatId, sessionId, error: err.message });
5877
6098
  });
5878
6099
  await this.sessionStore.updateSessionMeta(this.agentConfig.id, chatId, sessionId, { name: updates.sessionName }, 'api');
@@ -5880,15 +6101,28 @@ class AgentRunner extends events_1.EventEmitter {
5880
6101
  return { sessionId, ...(updates.sessionName ? { sessionName: updates.sessionName } : {}) };
5881
6102
  }
5882
6103
  async deleteApiSession(chatId, sessionId) {
6104
+ let inChat = true;
6105
+ const wasBound = (await this.sessionCwdOf(sessionId)).kind !== 'none';
5883
6106
  await this.sessionStore.deleteTelegramSession(this.agentConfig.id, chatId, sessionId, 'api').catch((err) => {
5884
6107
  // Legacy sessions (stored only in SQLite, no file index entry) are treated as already deleted
5885
- if (err instanceof store_2.SessionNotInIndexError)
6108
+ if (err instanceof store_2.SessionNotInIndexError) {
6109
+ inChat = false;
5886
6110
  return;
6111
+ }
5887
6112
  throw err;
5888
6113
  });
5889
- // Purge from SQLite so the session no longer appears in listSessions()
5890
- const mediaPaths = this.historyDb.clearSession(`api-${chatId}`, sessionId);
5891
- media_store_1.MediaStore.deleteMediaFiles(this.agentsBaseDir, this.agentConfig.id, mediaPaths);
6114
+ this.purgeApiSessionHistory(chatId, sessionId);
6115
+ // A session this chat does not hold keeps its owner and folder, since its transcript is still where it was.
6116
+ if (!inChat)
6117
+ return;
6118
+ // Live work keeps the owner entry, which the busy check reads, until it ends.
6119
+ if (this.isApiSessionLive(sessionId)) {
6120
+ this.retiredSessions.set(sessionId, { chatId, bound: wasBound });
6121
+ return;
6122
+ }
6123
+ if (wasBound)
6124
+ this.removeApiSessionMedia(sessionId);
6125
+ this.apiSessionOwners?.delete(sessionId);
5892
6126
  }
5893
6127
  /** The route has already authorized this API principal for the Agent. Preserve
5894
6128
  * the original channel binding, but never impersonate its human sender. */