@0xmaxma/claude-gateway 2.1.10 → 2.1.12

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 (162) hide show
  1. package/config.template.json +4 -0
  2. package/dist/agent/runner.d.ts +68 -2
  3. package/dist/agent/runner.d.ts.map +1 -1
  4. package/dist/agent/runner.js +338 -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 +98 -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/build-provenance.json +4 -4
  48. package/dist/cli/redact.d.ts +1 -0
  49. package/dist/cli/redact.d.ts.map +1 -1
  50. package/dist/cli/redact.js +12 -0
  51. package/dist/cli/redact.js.map +1 -1
  52. package/dist/config/loader.d.ts +5 -0
  53. package/dist/config/loader.d.ts.map +1 -1
  54. package/dist/config/loader.js +121 -0
  55. package/dist/config/loader.js.map +1 -1
  56. package/dist/config/reload-policy.d.ts.map +1 -1
  57. package/dist/config/reload-policy.js +1 -0
  58. package/dist/config/reload-policy.js.map +1 -1
  59. package/dist/config/watcher.d.ts.map +1 -1
  60. package/dist/config/watcher.js +1 -0
  61. package/dist/config/watcher.js.map +1 -1
  62. package/dist/files/config.d.ts +6 -0
  63. package/dist/files/config.d.ts.map +1 -0
  64. package/dist/files/config.js +15 -0
  65. package/dist/files/config.js.map +1 -0
  66. package/dist/files/delete.d.ts +27 -0
  67. package/dist/files/delete.d.ts.map +1 -0
  68. package/dist/files/delete.js +143 -0
  69. package/dist/files/delete.js.map +1 -0
  70. package/dist/files/fs.d.ts +70 -0
  71. package/dist/files/fs.d.ts.map +1 -0
  72. package/dist/files/fs.js +319 -0
  73. package/dist/files/fs.js.map +1 -0
  74. package/dist/files/holds.d.ts +11 -0
  75. package/dist/files/holds.d.ts.map +1 -0
  76. package/dist/files/holds.js +20 -0
  77. package/dist/files/holds.js.map +1 -0
  78. package/dist/files/paths.d.ts +26 -0
  79. package/dist/files/paths.d.ts.map +1 -0
  80. package/dist/files/paths.js +112 -0
  81. package/dist/files/paths.js.map +1 -0
  82. package/dist/files/session-cwd.d.ts +8 -0
  83. package/dist/files/session-cwd.d.ts.map +1 -0
  84. package/dist/files/session-cwd.js +139 -0
  85. package/dist/files/session-cwd.js.map +1 -0
  86. package/dist/git/read.d.ts +25 -0
  87. package/dist/git/read.d.ts.map +1 -0
  88. package/dist/git/read.js +166 -0
  89. package/dist/git/read.js.map +1 -0
  90. package/dist/git/runner.d.ts +46 -0
  91. package/dist/git/runner.d.ts.map +1 -0
  92. package/dist/git/runner.js +176 -0
  93. package/dist/git/runner.js.map +1 -0
  94. package/dist/git/status.d.ts +119 -0
  95. package/dist/git/status.d.ts.map +1 -0
  96. package/dist/git/status.js +273 -0
  97. package/dist/git/status.js.map +1 -0
  98. package/dist/index.js +7 -2
  99. package/dist/index.js.map +1 -1
  100. package/dist/orchestration/agent-tool-schemas.js +1 -1
  101. package/dist/orchestration/agent-tool-schemas.js.map +1 -1
  102. package/dist/orchestration/bridge.d.ts.map +1 -1
  103. package/dist/orchestration/bridge.js +2 -1
  104. package/dist/orchestration/bridge.js.map +1 -1
  105. package/dist/orchestration/response-errors.d.ts.map +1 -1
  106. package/dist/orchestration/response-errors.js +2 -0
  107. package/dist/orchestration/response-errors.js.map +1 -1
  108. package/dist/orchestration/runtime.d.ts +10 -1
  109. package/dist/orchestration/runtime.d.ts.map +1 -1
  110. package/dist/orchestration/runtime.js +23 -3
  111. package/dist/orchestration/runtime.js.map +1 -1
  112. package/dist/orchestration/tasks/driver.d.ts.map +1 -1
  113. package/dist/orchestration/tasks/driver.js +19 -1
  114. package/dist/orchestration/tasks/driver.js.map +1 -1
  115. package/dist/orchestration/tasks/service.d.ts +25 -2
  116. package/dist/orchestration/tasks/service.d.ts.map +1 -1
  117. package/dist/orchestration/tasks/service.js +45 -4
  118. package/dist/orchestration/tasks/service.js.map +1 -1
  119. package/dist/orchestration/types.d.ts +2 -0
  120. package/dist/orchestration/types.d.ts.map +1 -1
  121. package/dist/orchestration/types.js.map +1 -1
  122. package/dist/processes/listeners.d.ts +41 -0
  123. package/dist/processes/listeners.d.ts.map +1 -0
  124. package/dist/processes/listeners.js +140 -0
  125. package/dist/processes/listeners.js.map +1 -0
  126. package/dist/processes/start.d.ts +39 -0
  127. package/dist/processes/start.d.ts.map +1 -0
  128. package/dist/processes/start.js +208 -0
  129. package/dist/processes/start.js.map +1 -0
  130. package/dist/processes/stop.d.ts +37 -0
  131. package/dist/processes/stop.d.ts.map +1 -0
  132. package/dist/processes/stop.js +94 -0
  133. package/dist/processes/stop.js.map +1 -0
  134. package/dist/session/cwd.d.ts +65 -0
  135. package/dist/session/cwd.d.ts.map +1 -0
  136. package/dist/session/cwd.js +24 -0
  137. package/dist/session/cwd.js.map +1 -0
  138. package/dist/session/process.d.ts +17 -0
  139. package/dist/session/process.d.ts.map +1 -1
  140. package/dist/session/process.js +58 -3
  141. package/dist/session/process.js.map +1 -1
  142. package/dist/session/runtime-profile.d.ts +2 -0
  143. package/dist/session/runtime-profile.d.ts.map +1 -1
  144. package/dist/session/runtime-profile.js +1 -0
  145. package/dist/session/runtime-profile.js.map +1 -1
  146. package/dist/session/store.d.ts +13 -1
  147. package/dist/session/store.d.ts.map +1 -1
  148. package/dist/session/store.js +50 -4
  149. package/dist/session/store.js.map +1 -1
  150. package/dist/types.d.ts +19 -0
  151. package/dist/types.d.ts.map +1 -1
  152. package/dist/utils/paths.d.ts +5 -0
  153. package/dist/utils/paths.d.ts.map +1 -1
  154. package/dist/utils/paths.js +15 -0
  155. package/dist/utils/paths.js.map +1 -1
  156. package/dist/utils/result.d.ts +16 -0
  157. package/dist/utils/result.d.ts.map +1 -0
  158. package/dist/utils/result.js +8 -0
  159. package/dist/utils/result.js.map +1 -0
  160. package/mcp/tools/telegram/model-menu-request.ts +48 -0
  161. package/mcp/tools/telegram/receiver-server.ts +31 -28
  162. 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)
@@ -512,6 +636,9 @@ class AgentRunner extends events_1.EventEmitter {
512
636
  if (prior)
513
637
  return { text: '', attachments: [], inputId: prior.inputId };
514
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);
515
642
  await this.sessionStore.ensureApiSession(this.agentConfig.id, chatId, sessionId);
516
643
  this.apiChatIds.set(sessionId, chatId);
517
644
  const media = opts.mediaFiles?.length ? await promoteUiUploads(this.agentsBaseDir, this.agentConfig.id, sessionId, opts.mediaFiles, this.logger, preparationDir) : [];
@@ -584,7 +711,8 @@ class AgentRunner extends events_1.EventEmitter {
584
711
  this.pendingApiSessions.delete(sessionId);
585
712
  }
586
713
  }
587
- 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) {
588
716
  super();
589
717
  this.stopping = false;
590
718
  this.callbackServer = null;
@@ -714,6 +842,12 @@ class AgentRunner extends events_1.EventEmitter {
714
842
  // (e.g. the app/agent identifier) is not captured at spawn. Record it here
715
843
  // keyed by sessionId so the dashboard can show the actual chat id.
716
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();
717
851
  // Skill registry for detecting /skill-name commands in user messages
718
852
  this.skillRegistry = { skills: new Map() };
719
853
  this.skillNotificationOrigins = new Map();
@@ -766,6 +900,7 @@ class AgentRunner extends events_1.EventEmitter {
766
900
  this.shutdownHandlers = [];
767
901
  this.receiverReload = Promise.resolve();
768
902
  this.channelReloadSnapshot = new Map();
903
+ this.cwdResolver = cwdResolver;
769
904
  this.agentConfig = (0, gateway_config_1.applyGatewayOrchestration)(agentConfig, gatewayConfig);
770
905
  this.gatewayConfig = gatewayConfig;
771
906
  this.logger = logger ?? (0, logger_1.createLogger)(agentConfig.id, gatewayConfig.gateway.logDir);
@@ -2368,9 +2503,10 @@ class AgentRunner extends events_1.EventEmitter {
2368
2503
  }
2369
2504
  }
2370
2505
  }
2371
- // Restart if model changed (including switching back to the agent default)
2372
- if (existing.modelOverride !== effectiveOverride) {
2373
- 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 });
2374
2510
  const respawn = (async () => {
2375
2511
  await existing.stop();
2376
2512
  this.sessions.delete(mapKey);
@@ -2419,6 +2555,12 @@ class AgentRunner extends events_1.EventEmitter {
2419
2555
  // Apply per-session model override (caller already normalized to undefined when == agent default)
2420
2556
  if (modelOverride)
2421
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
+ }
2422
2564
  // Keep the searchable memory archive (planning-64) fresh for the memory_search
2423
2565
  // tool. Fire-and-forget, detached, OFF the event loop — never blocks the spawn.
2424
2566
  // Isolate mode (#601) and disableArchive (#609) offer no archive tool, so nothing would read the index.
@@ -3160,7 +3302,7 @@ class AgentRunner extends events_1.EventEmitter {
3160
3302
  const plugin = (0, plugin_info_1.pstackPluginInfo)();
3161
3303
  const roles = plugin.installPath ? (0, plugin_info_1.pstackModels)(plugin.installPath) : undefined;
3162
3304
  try {
3163
- 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))));
3164
3306
  if (!saved)
3165
3307
  return 'pstack is removed from this agent. Its next worker does not load it.';
3166
3308
  // `on` for an agent already set up saves nothing, so a plugin that cannot be read is only noticed here.
@@ -3169,7 +3311,7 @@ class AgentRunner extends events_1.EventEmitter {
3169
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)}`;
3170
3312
  }
3171
3313
  catch (error) {
3172
- if (!(error instanceof config_4.PstackConfigError))
3314
+ if (!(error instanceof config_5.PstackConfigError))
3173
3315
  throw error;
3174
3316
  return `${error.code}: ${error.message}`;
3175
3317
  }
@@ -3182,7 +3324,7 @@ class AgentRunner extends events_1.EventEmitter {
3182
3324
  step = (0, menu_1.pstackMenuStep)(data, state);
3183
3325
  }
3184
3326
  catch (error) {
3185
- if (!(error instanceof config_4.PstackConfigError))
3327
+ if (!(error instanceof config_5.PstackConfigError))
3186
3328
  throw error;
3187
3329
  return { ...(0, menu_1.pstackMenuScreen)({ kind: 'home' }, state, `⚠️ ${error.message}`), toast: error.message };
3188
3330
  }
@@ -3199,7 +3341,7 @@ class AgentRunner extends events_1.EventEmitter {
3199
3341
  });
3200
3342
  }
3201
3343
  catch (error) {
3202
- if (!(error instanceof config_4.PstackConfigError))
3344
+ if (!(error instanceof config_5.PstackConfigError))
3203
3345
  throw error;
3204
3346
  return { ...(0, menu_1.pstackMenuScreen)(step.view, state, `⚠️ ${error.code}: ${error.message}`), toast: error.message };
3205
3347
  }
@@ -3975,6 +4117,7 @@ class AgentRunner extends events_1.EventEmitter {
3975
4117
  await this.getOrchestration();
3976
4118
  this.stopping = false;
3977
4119
  await this.sweepStaleSessionDirs();
4120
+ await this.sessionOwners();
3978
4121
  await this.startCallbackServer();
3979
4122
  if (this.agentConfig.telegram?.botToken) {
3980
4123
  this.receiver = new receiver_1.TelegramReceiver(this.agentConfig, this.callbackPort, this.gatewayConfig.gateway.logDir, this.gatewayConfig.gateway.headless !== false);
@@ -4693,54 +4836,57 @@ class AgentRunner extends events_1.EventEmitter {
4693
4836
  const err = Object.assign(new Error(`Session ${sessionId} already has a pending request`), { code: 'CONFLICT' });
4694
4837
  throw err;
4695
4838
  }
4696
- // Register session in api-{chatId} index.json on first use (store adds channel prefix internally)
4697
- await this.sessionStore.ensureApiSession(this.agentConfig.id, chatId, sessionId).catch((err) => {
4698
- this.logger.warn('Failed to register API session in index', { agentId: this.agentConfig.id, chatId, sessionId, error: err.message });
4699
- });
4700
- // Use model from request body if provided, otherwise use agent default.
4701
- // A spawn keys its isolated memory by the chat (#601).
4702
- const session = await this.getOrSpawnSession(sessionId, 'api', undefined, opts.model, chatId);
4703
- this.apiChatIds.set(sessionId, chatId);
4704
- // Promote UI-uploaded files from staging to permanent per-session storage
4705
- const finalMediaFiles = opts.mediaFiles?.length
4706
- ? await promoteUiUploads(this.agentsBaseDir, this.agentConfig.id, sessionId, opts.mediaFiles, this.logger)
4707
- : undefined;
4708
- // Refs built from staging paths must follow the files to their promoted
4709
- // location — see remapImageParamsRefs (#74).
4710
- const imageParams = AgentRunner.remapImageParamsRefs(opts.imageParams, opts.mediaFiles, finalMediaFiles);
4711
- // The image-to-video source frame follows the same staging→promoted move.
4712
- const videoParams = AgentRunner.remapVideoParamsRefs(opts.videoParams, opts.mediaFiles, finalMediaFiles);
4713
- // Resolve media files to absolute paths for file-path based image passing
4714
- // (same pattern as Telegram — Claude Code reads files via Read tool instead of base64 inline)
4715
- const imagePaths = finalMediaFiles?.length ? this.resolveMediaPaths(finalMediaFiles) : [];
4716
- // skipUserMessage omits the trigger from both session context and history so only the
4717
- // assistant response is visible — intentional for system-initiated messages (e.g. cron welcome).
4718
- // Claude still receives the prompt via channelXml for this turn; session restarts will not
4719
- // replay it, which is the desired behaviour for one-shot proactive messages.
4720
- if (!opts.skipUserMessage) {
4721
- const apiUserTs = Date.now();
4722
- await this.sessionStore
4723
- .appendMessage(this.agentConfig.id, sessionId, {
4724
- role: 'user',
4725
- content: message,
4726
- ts: apiUserTs,
4727
- })
4728
- .catch(() => { });
4729
- this.historyDb.insertMessage({
4730
- chatId: `api-${chatId}`,
4731
- sessionId,
4732
- source: 'api',
4733
- role: 'user',
4734
- content: message,
4735
- mediaFiles: finalMediaFiles?.length ? finalMediaFiles : undefined,
4736
- // Display-only (#74): lets the UI show which earlier images this turn
4737
- // referenced after a reload. The generation path reads the refs from the
4738
- // image-params note, never from here.
4739
- imageRefs: imageParams?.image_refs?.length ? imageParams.image_refs : undefined,
4740
- 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 });
4741
4844
  });
4742
- }
4743
- 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; });
4744
4890
  // A previous turn that died (hard timeout, crash) may have left attachments
4745
4891
  // buffered under this session — they belong to THAT turn; never let them
4746
4892
  // ride along on this one (#75).
@@ -4874,6 +5020,7 @@ class AgentRunner extends events_1.EventEmitter {
4874
5020
  // exactly as the hard cap below does.
4875
5021
  fail(Object.assign(new Error('Session process exited unexpectedly before responding.'), { code: 'PROCESS_EXITED' }), buffer.join(''));
4876
5022
  };
5023
+ const onStartupError = (error) => fail(error, buffer.join(''));
4877
5024
  const cleanup = () => {
4878
5025
  clearTimeout(globalTimer);
4879
5026
  if (hardCapTimer)
@@ -4882,6 +5029,7 @@ class AgentRunner extends events_1.EventEmitter {
4882
5029
  clearTimeout(quietTimer);
4883
5030
  session.off('output', onOutput);
4884
5031
  session.off('exit', onExit);
5032
+ session.off('startup-error', onStartupError);
4885
5033
  this.pendingApiSessions.delete(sessionId);
4886
5034
  };
4887
5035
  const resetQuiet = () => {
@@ -4956,6 +5104,7 @@ class AgentRunner extends events_1.EventEmitter {
4956
5104
  }, opts.timeoutMs);
4957
5105
  session.on('output', onOutput);
4958
5106
  session.on('exit', onExit);
5107
+ session.on('startup-error', onStartupError);
4959
5108
  session.setProcessing(true);
4960
5109
  session.sendMessage(channelXml);
4961
5110
  // Do NOT call resetQuiet() here — the quiet timer should only start
@@ -5002,49 +5151,52 @@ class AgentRunner extends events_1.EventEmitter {
5002
5151
  const err = Object.assign(new Error(`Session ${sessionId} already has a pending request`), { code: 'CONFLICT' });
5003
5152
  throw err;
5004
5153
  }
5005
- // Register session in api-{chatId} index.json on first use (store adds channel prefix internally)
5006
- await this.sessionStore.ensureApiSession(this.agentConfig.id, chatId, sessionId).catch((err) => {
5007
- this.logger.warn('Failed to register API session in index', { agentId: this.agentConfig.id, chatId, sessionId, error: err.message });
5008
- });
5009
- // Use model from request body if provided, otherwise use agent default.
5010
- // A spawn keys its isolated memory by the chat (#601).
5011
- const session = await this.getOrSpawnSession(sessionId, 'api', undefined, opts.model, chatId);
5012
- this.apiChatIds.set(sessionId, chatId);
5013
- // Promote UI-uploaded files from staging to permanent per-session storage
5014
- const finalMediaFilesStream = opts.mediaFiles?.length
5015
- ? await promoteUiUploads(this.agentsBaseDir, this.agentConfig.id, sessionId, opts.mediaFiles, this.logger)
5016
- : undefined;
5017
- // Refs built from staging paths must follow the files to their promoted
5018
- // location — see remapImageParamsRefs (#74).
5019
- const imageParamsStream = AgentRunner.remapImageParamsRefs(opts.imageParams, opts.mediaFiles, finalMediaFilesStream);
5020
- // The image-to-video source frame follows the same staging→promoted move.
5021
- const videoParamsStream = AgentRunner.remapVideoParamsRefs(opts.videoParams, opts.mediaFiles, finalMediaFilesStream);
5022
- // Resolve media files to absolute paths for file-path based image passing
5023
- const imagePathsStream = finalMediaFilesStream?.length ? this.resolveMediaPaths(finalMediaFilesStream) : [];
5024
- if (!opts.skipUserMessage) {
5025
- const streamUserTs = Date.now();
5026
- await this.sessionStore
5027
- .appendMessage(this.agentConfig.id, sessionId, {
5028
- role: 'user',
5029
- content: message,
5030
- ts: streamUserTs,
5031
- })
5032
- .catch(() => { });
5033
- this.historyDb.insertMessage({
5034
- chatId: `api-${chatId}`,
5035
- sessionId,
5036
- source: 'api',
5037
- role: 'user',
5038
- content: message,
5039
- mediaFiles: finalMediaFilesStream?.length ? finalMediaFilesStream : undefined,
5040
- // Display-only (#74): lets the UI show which earlier images this turn
5041
- // referenced after a reload. The generation path reads the refs from the
5042
- // image-params note, never from here.
5043
- imageRefs: imageParamsStream?.image_refs?.length ? imageParamsStream.image_refs : undefined,
5044
- 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 });
5045
5159
  });
5046
- }
5047
- 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; });
5048
5200
  // A previous turn that died (hard timeout, crash) may have left attachments
5049
5201
  // buffered under this session — they belong to THAT turn; never let them
5050
5202
  // ride along on this one (#75).
@@ -5141,12 +5293,14 @@ class AgentRunner extends events_1.EventEmitter {
5141
5293
  // added for — the client saw the deltas and no `result` will ever land.
5142
5294
  fail(Object.assign(new Error('Session process exited unexpectedly before responding.'), { code: 'PROCESS_EXITED' }), buffer.join(''));
5143
5295
  };
5296
+ const onStartupError = (error) => fail(error, buffer.join(''));
5144
5297
  const cleanup = () => {
5145
5298
  clearTimeout(globalTimer);
5146
5299
  if (hardCapTimer)
5147
5300
  clearTimeout(hardCapTimer);
5148
5301
  session.off('output', onOutput);
5149
5302
  session.off('exit', onExit);
5303
+ session.off('startup-error', onStartupError);
5150
5304
  this.pendingApiSessions.delete(sessionId);
5151
5305
  };
5152
5306
  // Called when the SSE client disconnects. Detaches that connection's sink —
@@ -5263,6 +5417,7 @@ class AgentRunner extends events_1.EventEmitter {
5263
5417
  }, opts.timeoutMs);
5264
5418
  session.on('output', onOutput);
5265
5419
  session.on('exit', onExit);
5420
+ session.on('startup-error', onStartupError);
5266
5421
  // Image paths only work when allowTools:true — Claude needs the Read tool to access them
5267
5422
  const allowToolsStream = opts.allowTools ?? false;
5268
5423
  if (!allowToolsStream && imagePathsStream.length) {
@@ -5318,6 +5473,48 @@ class AgentRunner extends events_1.EventEmitter {
5318
5473
  hasActiveApiSession(sessionId) {
5319
5474
  return this.pendingApiSessions.has(sessionId);
5320
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
+ }
5321
5518
  /**
5322
5519
  * Attach a sink to a session's current turn stream (#421) — the server half of
5323
5520
  * "resume a turn on a new connection".
@@ -5448,6 +5645,21 @@ class AgentRunner extends events_1.EventEmitter {
5448
5645
  getHistoryDb() {
5449
5646
  return this.historyDb;
5450
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
+ }
5451
5663
  getAllSessionMeta() {
5452
5664
  return this.sessionStore.getAllSessionMeta(this.agentConfig.id);
5453
5665
  }
@@ -5478,7 +5690,7 @@ class AgentRunner extends events_1.EventEmitter {
5478
5690
  return { result: { error: 'SESSION_ID_REQUIRED' }, responseText: '⚠️ /rename renames the session given by session_id; send it with the session to rename.', actions: [] };
5479
5691
  }
5480
5692
  // Register session in the api-{chatId} index on first use (same as sendApiMessageStream)
5481
- await this.sessionStore.ensureApiSession(agentId, storeChatId, sessionId).catch((err) => {
5693
+ await this.registerApiSession(storeChatId, sessionId, (err) => {
5482
5694
  this.logger.warn('Failed to register API session in index for command', { agentId, chatId, sessionId, error: err.message });
5483
5695
  });
5484
5696
  // Persist a command message to the permanent history DB ONLY — not the model's session
@@ -5820,6 +6032,7 @@ class AgentRunner extends events_1.EventEmitter {
5820
6032
  }
5821
6033
  }
5822
6034
  async listApiSessions(chatId) {
6035
+ this.reapRetiredSessions();
5823
6036
  return this.sessionStore.listSessions(this.agentConfig.id, chatId, 'api');
5824
6037
  }
5825
6038
  /**
@@ -5830,11 +6043,14 @@ class AgentRunner extends events_1.EventEmitter {
5830
6043
  async apiSessionExists(chatId, sessionId) {
5831
6044
  return this.sessionStore.apiSessionExists(this.agentConfig.id, chatId, sessionId);
5832
6045
  }
5833
- 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) {
5834
6048
  const sessionName = name ?? (prompt
5835
6049
  ? (prompt.length > 60 ? `${prompt.slice(0, 60)}...` : prompt)
5836
6050
  : undefined);
5837
- 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' } });
5838
6054
  if (!name && prompt) {
5839
6055
  this.generateSessionNameInBackground(chatId, meta.id, prompt);
5840
6056
  }
@@ -5867,6 +6083,7 @@ class AgentRunner extends events_1.EventEmitter {
5867
6083
  return {
5868
6084
  sessionId: meta.id,
5869
6085
  sessionName: meta.name,
6086
+ ...await this.sessionCwdView(meta.id),
5870
6087
  messageCount: meta.messageCount,
5871
6088
  archivedCount: meta.archivedCount ?? 0,
5872
6089
  ...context,
@@ -5876,7 +6093,7 @@ class AgentRunner extends events_1.EventEmitter {
5876
6093
  async updateApiSession(chatId, sessionId, updates) {
5877
6094
  if (updates.sessionName) {
5878
6095
  // Ensure session exists in the file index (may be missing for older sessions stored only in SQLite)
5879
- await this.sessionStore.ensureApiSession(this.agentConfig.id, chatId, sessionId).catch((err) => {
6096
+ await this.registerApiSession(chatId, sessionId, (err) => {
5880
6097
  this.logger.warn('Failed to register API session in index', { agentId: this.agentConfig.id, chatId, sessionId, error: err.message });
5881
6098
  });
5882
6099
  await this.sessionStore.updateSessionMeta(this.agentConfig.id, chatId, sessionId, { name: updates.sessionName }, 'api');
@@ -5884,15 +6101,28 @@ class AgentRunner extends events_1.EventEmitter {
5884
6101
  return { sessionId, ...(updates.sessionName ? { sessionName: updates.sessionName } : {}) };
5885
6102
  }
5886
6103
  async deleteApiSession(chatId, sessionId) {
6104
+ let inChat = true;
6105
+ const wasBound = (await this.sessionCwdOf(sessionId)).kind !== 'none';
5887
6106
  await this.sessionStore.deleteTelegramSession(this.agentConfig.id, chatId, sessionId, 'api').catch((err) => {
5888
6107
  // Legacy sessions (stored only in SQLite, no file index entry) are treated as already deleted
5889
- if (err instanceof store_2.SessionNotInIndexError)
6108
+ if (err instanceof store_2.SessionNotInIndexError) {
6109
+ inChat = false;
5890
6110
  return;
6111
+ }
5891
6112
  throw err;
5892
6113
  });
5893
- // Purge from SQLite so the session no longer appears in listSessions()
5894
- const mediaPaths = this.historyDb.clearSession(`api-${chatId}`, sessionId);
5895
- 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);
5896
6126
  }
5897
6127
  /** The route has already authorized this API principal for the Agent. Preserve
5898
6128
  * the original channel binding, but never impersonate its human sender. */