@0xmaxma/claude-gateway 2.1.0 → 2.1.2

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 (191) hide show
  1. package/README.md +1 -0
  2. package/config.template.json +1 -1
  3. package/dist/agent/dreaming/index.d.ts +6 -0
  4. package/dist/agent/dreaming/index.d.ts.map +1 -1
  5. package/dist/agent/dreaming/index.js +3 -3
  6. package/dist/agent/dreaming/index.js.map +1 -1
  7. package/dist/agent/runner.d.ts +10 -1
  8. package/dist/agent/runner.d.ts.map +1 -1
  9. package/dist/agent/runner.js +23 -12
  10. package/dist/agent/runner.js.map +1 -1
  11. package/dist/agent/workspace-loader.d.ts +40 -1
  12. package/dist/agent/workspace-loader.d.ts.map +1 -1
  13. package/dist/agent/workspace-loader.js +100 -6
  14. package/dist/agent/workspace-loader.js.map +1 -1
  15. package/dist/api/cron-router.d.ts.map +1 -1
  16. package/dist/api/cron-router.js +3 -2
  17. package/dist/api/cron-router.js.map +1 -1
  18. package/dist/api/gateway-router.d.ts.map +1 -1
  19. package/dist/api/gateway-router.js +11 -2
  20. package/dist/api/gateway-router.js.map +1 -1
  21. package/dist/api/router.d.ts.map +1 -1
  22. package/dist/api/router.js +40 -5
  23. package/dist/api/router.js.map +1 -1
  24. package/dist/api/share-router.d.ts +1 -1
  25. package/dist/api/share-router.d.ts.map +1 -1
  26. package/dist/api/share-router.js +14 -5
  27. package/dist/api/share-router.js.map +1 -1
  28. package/dist/api/voice-call-router.d.ts.map +1 -1
  29. package/dist/api/voice-call-router.js +8 -5
  30. package/dist/api/voice-call-router.js.map +1 -1
  31. package/dist/api/voice-router.js +1 -1
  32. package/dist/api/voice-router.js.map +1 -1
  33. package/dist/api/voice-settings-router.d.ts.map +1 -1
  34. package/dist/api/voice-settings-router.js +15 -0
  35. package/dist/api/voice-settings-router.js.map +1 -1
  36. package/dist/apps/agent-manager.d.ts +9 -0
  37. package/dist/apps/agent-manager.d.ts.map +1 -1
  38. package/dist/apps/agent-manager.js +38 -0
  39. package/dist/apps/agent-manager.js.map +1 -1
  40. package/dist/apps/compose-generator.d.ts +8 -0
  41. package/dist/apps/compose-generator.d.ts.map +1 -1
  42. package/dist/apps/compose-generator.js +9 -3
  43. package/dist/apps/compose-generator.js.map +1 -1
  44. package/dist/apps/conversation-sandbox.d.ts +78 -0
  45. package/dist/apps/conversation-sandbox.d.ts.map +1 -0
  46. package/dist/apps/conversation-sandbox.js +357 -0
  47. package/dist/apps/conversation-sandbox.js.map +1 -0
  48. package/dist/apps/installer.d.ts +2 -0
  49. package/dist/apps/installer.d.ts.map +1 -1
  50. package/dist/apps/installer.js +5 -0
  51. package/dist/apps/installer.js.map +1 -1
  52. package/dist/apps/registry.d.ts +2 -0
  53. package/dist/apps/registry.d.ts.map +1 -1
  54. package/dist/build-provenance.json +4 -4
  55. package/dist/config/agent-lifecycle.d.ts +4 -2
  56. package/dist/config/agent-lifecycle.d.ts.map +1 -1
  57. package/dist/config/agent-lifecycle.js +11 -3
  58. package/dist/config/agent-lifecycle.js.map +1 -1
  59. package/dist/config/loader.d.ts.map +1 -1
  60. package/dist/config/loader.js +13 -0
  61. package/dist/config/loader.js.map +1 -1
  62. package/dist/config/migrator.d.ts +2 -0
  63. package/dist/config/migrator.d.ts.map +1 -1
  64. package/dist/config/migrator.js +37 -1
  65. package/dist/config/migrator.js.map +1 -1
  66. package/dist/config/reload-policy.d.ts.map +1 -1
  67. package/dist/config/reload-policy.js +5 -0
  68. package/dist/config/reload-policy.js.map +1 -1
  69. package/dist/cron/manager.d.ts +15 -0
  70. package/dist/cron/manager.d.ts.map +1 -1
  71. package/dist/cron/manager.js +53 -1
  72. package/dist/cron/manager.js.map +1 -1
  73. package/dist/index.js +49 -9
  74. package/dist/index.js.map +1 -1
  75. package/dist/orchestration/bridge.d.ts +6 -0
  76. package/dist/orchestration/bridge.d.ts.map +1 -1
  77. package/dist/orchestration/bridge.js +32 -10
  78. package/dist/orchestration/bridge.js.map +1 -1
  79. package/dist/orchestration/capabilities.d.ts.map +1 -1
  80. package/dist/orchestration/capabilities.js +2 -0
  81. package/dist/orchestration/capabilities.js.map +1 -1
  82. package/dist/orchestration/config.js +1 -1
  83. package/dist/orchestration/config.js.map +1 -1
  84. package/dist/orchestration/container.d.ts.map +1 -1
  85. package/dist/orchestration/container.js +51 -2
  86. package/dist/orchestration/container.js.map +1 -1
  87. package/dist/orchestration/context-footprint.d.ts +8 -1
  88. package/dist/orchestration/context-footprint.d.ts.map +1 -1
  89. package/dist/orchestration/context-footprint.js +27 -9
  90. package/dist/orchestration/context-footprint.js.map +1 -1
  91. package/dist/orchestration/dashboard-reader-worker.js +1 -1
  92. package/dist/orchestration/dashboard-reader-worker.js.map +1 -1
  93. package/dist/orchestration/recovery.d.ts.map +1 -1
  94. package/dist/orchestration/recovery.js +30 -0
  95. package/dist/orchestration/recovery.js.map +1 -1
  96. package/dist/orchestration/report-promise.d.ts +9 -0
  97. package/dist/orchestration/report-promise.d.ts.map +1 -0
  98. package/dist/orchestration/report-promise.js +39 -0
  99. package/dist/orchestration/report-promise.js.map +1 -0
  100. package/dist/orchestration/restart-resume.d.ts +19 -0
  101. package/dist/orchestration/restart-resume.d.ts.map +1 -0
  102. package/dist/orchestration/restart-resume.js +53 -0
  103. package/dist/orchestration/restart-resume.js.map +1 -0
  104. package/dist/orchestration/runtime.d.ts +3 -0
  105. package/dist/orchestration/runtime.d.ts.map +1 -1
  106. package/dist/orchestration/runtime.js +35 -8
  107. package/dist/orchestration/runtime.js.map +1 -1
  108. package/dist/orchestration/source-policy.d.ts +2 -0
  109. package/dist/orchestration/source-policy.d.ts.map +1 -1
  110. package/dist/orchestration/source-policy.js +3 -1
  111. package/dist/orchestration/source-policy.js.map +1 -1
  112. package/dist/orchestration/task-files.d.ts +2 -0
  113. package/dist/orchestration/task-files.d.ts.map +1 -1
  114. package/dist/orchestration/task-files.js +17 -6
  115. package/dist/orchestration/task-files.js.map +1 -1
  116. package/dist/orchestration/tasks/driver.d.ts +1 -0
  117. package/dist/orchestration/tasks/driver.d.ts.map +1 -1
  118. package/dist/orchestration/tasks/driver.js +34 -4
  119. package/dist/orchestration/tasks/driver.js.map +1 -1
  120. package/dist/orchestration/tasks/failure.js +1 -1
  121. package/dist/orchestration/tasks/failure.js.map +1 -1
  122. package/dist/orchestration/tasks/scheduler.d.ts +2 -0
  123. package/dist/orchestration/tasks/scheduler.d.ts.map +1 -1
  124. package/dist/orchestration/tasks/scheduler.js +38 -27
  125. package/dist/orchestration/tasks/scheduler.js.map +1 -1
  126. package/dist/orchestration/tasks/service.d.ts +4 -0
  127. package/dist/orchestration/tasks/service.d.ts.map +1 -1
  128. package/dist/orchestration/tasks/service.js +53 -1
  129. package/dist/orchestration/tasks/service.js.map +1 -1
  130. package/dist/orchestration/types.d.ts +13 -0
  131. package/dist/orchestration/types.d.ts.map +1 -1
  132. package/dist/orchestration/types.js.map +1 -1
  133. package/dist/session/process.d.ts +37 -2
  134. package/dist/session/process.d.ts.map +1 -1
  135. package/dist/session/process.js +171 -31
  136. package/dist/session/process.js.map +1 -1
  137. package/dist/share/share-store.d.ts +10 -1
  138. package/dist/share/share-store.d.ts.map +1 -1
  139. package/dist/share/share-store.js +42 -1
  140. package/dist/share/share-store.js.map +1 -1
  141. package/dist/types.d.ts +15 -0
  142. package/dist/types.d.ts.map +1 -1
  143. package/dist/ui/voice-call-client.d.ts +27 -14
  144. package/dist/ui/voice-call-client.d.ts.map +1 -1
  145. package/dist/ui/voice-call-client.js +80 -24
  146. package/dist/ui/voice-call-client.js.map +1 -1
  147. package/dist/ui/voice-call-ui.d.ts +4 -1
  148. package/dist/ui/voice-call-ui.d.ts.map +1 -1
  149. package/dist/ui/voice-call-ui.js +65 -21
  150. package/dist/ui/voice-call-ui.js.map +1 -1
  151. package/dist/voice/errors.js +1 -1
  152. package/dist/voice/errors.js.map +1 -1
  153. package/dist/voice/notes.d.ts +4 -3
  154. package/dist/voice/notes.d.ts.map +1 -1
  155. package/dist/voice/notes.js +14 -11
  156. package/dist/voice/notes.js.map +1 -1
  157. package/dist/voice/telegram-avatar.d.ts +6 -2
  158. package/dist/voice/telegram-avatar.d.ts.map +1 -1
  159. package/dist/voice/telegram-avatar.js +23 -10
  160. package/dist/voice/telegram-avatar.js.map +1 -1
  161. package/dist/voice/turn-manager.d.ts.map +1 -1
  162. package/dist/voice/turn-manager.js +1 -1
  163. package/dist/voice/turn-manager.js.map +1 -1
  164. package/dist/voice/types.d.ts +3 -0
  165. package/dist/voice/types.d.ts.map +1 -1
  166. package/dist/voice/types.js +4 -0
  167. package/dist/voice/types.js.map +1 -1
  168. package/mcp/modules.ts +13 -1
  169. package/mcp/tools/agent/module.ts +3 -1
  170. package/mcp/tools/api/module.ts +9 -1
  171. package/mcp/tools/apps/module.ts +4 -2
  172. package/mcp/tools/apps/skills/create-app-yaml/SKILL.md +1 -1
  173. package/mcp/tools/apps/skills/install-app/SKILL.md +2 -1
  174. package/mcp/tools/cron/module.ts +3 -0
  175. package/mcp/tools/discord/module.ts +44 -11
  176. package/mcp/tools/line/module.ts +11 -0
  177. package/mcp/tools/memory/disable-archive.test.ts +47 -0
  178. package/mcp/tools/memory/isolate-memory.test.ts +95 -0
  179. package/mcp/tools/memory/module.ts +4 -1
  180. package/mcp/tools/shared/isolate.ts +77 -0
  181. package/mcp/tools/shared/share-client.ts +15 -1
  182. package/mcp/tools/skills/module.ts +4 -2
  183. package/mcp/tools/slack/module.ts +12 -5
  184. package/mcp/tools/tasks/module.ts +1 -1
  185. package/mcp/tools/telegram/attachment-log.ts +39 -0
  186. package/mcp/tools/telegram/module.ts +27 -11
  187. package/mcp/tools/telegram/receiver-server.ts +8 -0
  188. package/mcp/tools/wechat/module.ts +2 -0
  189. package/mcp/tools/whatsapp/module.ts +8 -1
  190. package/mcp/tools/whatsapp-cloud/module.ts +14 -7
  191. package/package.json +1 -1
@@ -18,8 +18,12 @@ export declare const INTERRUPTED_NO_REPLY_TEXT = "Session was interrupted before
18
18
  export declare function resolveMaxHistoryMessages(agentMax?: number, globalMax?: number): number;
19
19
  export declare class SessionProcess extends EventEmitter {
20
20
  readonly runtimeProfile?: RuntimeProfile | undefined;
21
+ /** API chat keying the isolated memory (#601): an API session's own chatId is its sessionId, but a chat holds many sessions. */
22
+ private readonly memoryChatId?;
21
23
  private managedProcessGroup?;
22
24
  private containerAttempt?;
25
+ /** The container the current spawn executes in (an app agent's, or its sandbox). */
26
+ private execContainer?;
23
27
  /** Bumped by stop(): a spawnProcess() that awaited across it abandons its spawn. */
24
28
  private spawnEpoch;
25
29
  private starts;
@@ -87,7 +91,9 @@ export declare class SessionProcess extends EventEmitter {
87
91
  private pendingInitialPrompt?;
88
92
  private spawnedConnectors;
89
93
  constructor(sessionId: string, source: ChatChannelOrApi, agentConfig: AgentConfig, gatewayConfig: GatewayConfig, sessionStore: SessionStore, chatId?: string, // for telegram/discord: actual chatId; for api: same as sessionId
90
- runtimeProfile?: RuntimeProfile | undefined);
94
+ runtimeProfile?: RuntimeProfile | undefined,
95
+ /** API chat keying the isolated memory (#601): an API session's own chatId is its sessionId, but a chat holds many sessions. */
96
+ memoryChatId?: string | undefined);
91
97
  /**
92
98
  * Resolve the model for this session.
93
99
  * Priority: per-session override > config.json on disk > cached agentConfig.
@@ -188,6 +194,10 @@ export declare class SessionProcess extends EventEmitter {
188
194
  /** Only trust connector namespaces actually written into this subprocess config. */
189
195
  isSpawnedConnectorTool(name: string): boolean;
190
196
  private managedMcpConfigPath?;
197
+ /** Host file holding this conversation's memory (see writeChatMemoryFile). */
198
+ private chatMemoryPath?;
199
+ /** The context the caller composed (a task driver for workers); the container Agent's is filled in per spawn. */
200
+ private readonly composedContext?;
191
201
  /** Host file holding the appended system prompt (see writeSystemPromptFile). */
192
202
  private systemPromptPath?;
193
203
  private managedConnectorPaths;
@@ -202,8 +212,32 @@ export declare class SessionProcess extends EventEmitter {
202
212
  * A container CLI reads one that prepareContainerProfile writes in its attempt
203
213
  * directory, in the same docker exec as the attempt's mcp.json and ticket. */
204
214
  private writeSystemPromptFile;
215
+ private chatMemory;
216
+ /** Claude runs in the app container, which mounts the workspace at /workspace. */
217
+ private isContainerAgent;
218
+ /** Isolate mode for an app agent (#609): this session executes in its conversation's
219
+ * own sandbox container, never in the shared app container. */
220
+ private sandboxed;
221
+ /** The container this spawn executes in. A worker's driver already resolved its
222
+ * conversation's sandbox; anything else resolves its own conversation's here. */
223
+ private executionContainer;
224
+ /** Outside orchestration a sandbox has no `.sessions/` to read, so its conversation's
225
+ * memory is written into the sandbox's own /tmp, which no other conversation shares. */
226
+ private writeSandboxChatMemory;
227
+ /** A host path under the workspace as the app container sees it. */
228
+ private toContainerPath;
229
+ /** Outside orchestration the conversation's memory cannot join an appended prompt, so
230
+ * it is written fresh each spawn to `.sessions/<id>/` (0700) and passed with
231
+ * --append-system-prompt-file. Undefined when isolate mode is off. */
232
+ private writeChatMemoryFile;
233
+ /** `.sessions/<id>` (0700) for this session's generated spawn files. Recording
234
+ * it as this spawn's directory keeps a stop() of an earlier spawn from removing
235
+ * it at that spawn's exit. */
236
+ private ensureSessionDir;
205
237
  private writeMcpConfig;
206
- /** Find the first API key that has access to this agent (agents: '*' or includes agentId). */
238
+ /** Find the first API key that has access to this agent (agents: '*' or includes agentId).
239
+ * An isolated agent (#609) only gets a non-admin key naming it: a wildcard or admin
240
+ * key reaches every conversation of every agent. */
207
241
  private findApiKeyForAgent;
208
242
  /** Resolved shared-KB vault dir for this agent, or '' when shared KB is disabled. */
209
243
  private resolveSharedKbDir;
@@ -218,6 +252,7 @@ export declare class SessionProcess extends EventEmitter {
218
252
  /** Resolves false when a stop() during its awaits abandoned the spawn: nothing was
219
253
  * started, and a container attempt it prepared is already cleaned up. */
220
254
  private spawnProcess;
255
+ private spawnProcessOnce;
221
256
  private scheduleRestart;
222
257
  /**
223
258
  * Detect the Anthropic API 400 raised when a previously-emitted thinking block
@@ -1 +1 @@
1
- {"version":3,"file":"process.d.ts","sourceRoot":"","sources":["../../src/session/process.ts"],"names":[],"mapp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;IACH,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAkBhC,KAAK,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,SAAS,GAAG,OAAO,CAAC,MAAM,CAAC;IAqB1D,IAAI,YAAY,IAAI,OAAO,CAA6B;IAExD,OAAO,CAAC,wBAAwB;IAYhC,OAAO,CAAC,iCAAiC;IAczC,OAAO,CAAC,4BAA4B;IAOpC;;;;;;;;OAQG;IACH,4BAA4B,IAAI,OAAO;IA8BvC,aAAa,CAAC,MAAM,EAAE,OAAO,GAAG,IAAI;IAwCpC,SAAS,IAAI,OAAO;IAYpB;;;;;;OAMG;IACH,oBAAoB,IAAI,OAAO;IAM/B,kBAAkB,IAAI,IAAI;IAQ1B;;;;;;OAMG;IACH,iBAAiB,IAAI,OAAO;IAI5B;;;;;;;;;OASG;IACH,kBAAkB,IAAI,OAAO;IAI7B,KAAK,IAAI,IAAI;IAIb,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO;IAI/B;;;;;;;;OAQG;IACH,kCAAkC,IAAI,OAAO;IAK7C,SAAS,IAAI,OAAO;IAOpB,OAAO,CAAC,WAAW,CAAC,CAAqB;IACnC,gBAAgB,CAAC,WAAW,CAAC,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,kBAAkB,EAAE,CAAC;IAEvE,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAkF5B"}
@@ -44,6 +44,7 @@ const process_diagnostics_1 = require("./process-diagnostics");
44
44
  const managed_connectors_1 = require("./managed-connectors");
45
45
  const request_tool_capture_1 = require("./request-tool-capture");
46
46
  const container_1 = require("../orchestration/container");
47
+ const conversation_sandbox_1 = require("../apps/conversation-sandbox");
47
48
  const child_process_1 = require("child_process");
48
49
  const crypto_1 = require("crypto");
49
50
  const events_1 = require("events");
@@ -58,6 +59,7 @@ const capacity_1 = require("../orchestration/capacity");
58
59
  const types_1 = require("../orchestration/types");
59
60
  const chokidar_1 = __importDefault(require("chokidar"));
60
61
  const knowledge_1 = require("../agent/knowledge");
62
+ const workspace_loader_1 = require("../agent/workspace-loader");
61
63
  const config_1 = require("../agent/dreaming/config");
62
64
  const types_2 = require("../history/types");
63
65
  const logger_1 = require("../logger");
@@ -252,9 +254,12 @@ class SessionProcess extends events_1.EventEmitter {
252
254
  * caller can tell a rejected `--resume` apart from an ordinary process exit. */
253
255
  get lastStderr() { return this.lastStderrLine; }
254
256
  constructor(sessionId, source, agentConfig, gatewayConfig, sessionStore, chatId, // for telegram/discord: actual chatId; for api: same as sessionId
255
- runtimeProfile) {
257
+ runtimeProfile,
258
+ /** API chat keying the isolated memory (#601): an API session's own chatId is its sessionId, but a chat holds many sessions. */
259
+ memoryChatId) {
256
260
  super();
257
261
  this.runtimeProfile = runtimeProfile;
262
+ this.memoryChatId = memoryChatId;
258
263
  /** Bumped by stop(): a spawnProcess() that awaited across it abandons its spawn. */
259
264
  this.spawnEpoch = 0;
260
265
  // Bumped by every start(): a stop() still awaiting after one ran no longer owns the session's live state.
@@ -376,6 +381,7 @@ class SessionProcess extends events_1.EventEmitter {
376
381
  this.sessionId = sessionId;
377
382
  this.source = source;
378
383
  this.chatId = chatId ?? sessionId;
384
+ this.composedContext = runtimeProfile?.context;
379
385
  this.sessionChannel = (0, types_2.toChatChannel)(source);
380
386
  this.agentConfig = agentConfig;
381
387
  this.gatewayConfig = gatewayConfig;
@@ -723,12 +729,77 @@ class SessionProcess extends events_1.EventEmitter {
723
729
  this.systemPromptPath = file;
724
730
  return moved.args;
725
731
  }
732
+ chatMemory() {
733
+ return (0, workspace_loader_1.composeChatMemory)(this.agentConfig.workspace, this.source, this.memoryChatId ?? this.chatId, (0, workspace_loader_1.agentMemoryBudget)(this.gatewayConfig, this.agentConfig), this.isContainerAgent() ? '/workspace' : undefined);
734
+ }
735
+ /** Claude runs in the app container, which mounts the workspace at /workspace. */
736
+ isContainerAgent() {
737
+ return this.agentConfig.type === 'app-agent' && !!this.agentConfig.container;
738
+ }
739
+ /** Isolate mode for an app agent (#609): this session executes in its conversation's
740
+ * own sandbox container, never in the shared app container. */
741
+ sandboxed() {
742
+ return (0, conversation_sandbox_1.usesConversationSandbox)(this.agentConfig);
743
+ }
744
+ /** The container this spawn executes in. A worker's driver already resolved its
745
+ * conversation's sandbox; anything else resolves its own conversation's here. */
746
+ async executionContainer(held) {
747
+ if (!this.sandboxed())
748
+ return this.agentConfig.container;
749
+ if (this.runtimeProfile?.role === 'worker') {
750
+ if (!(0, conversation_sandbox_1.isSandboxContainerName)(this.agentConfig.container))
751
+ throw Object.assign(new Error('Isolated worker has no conversation sandbox'), { code: 'CONTAINER_ISOLATION_REQUIRED' });
752
+ return this.agentConfig.container;
753
+ }
754
+ // Held until this spawn's process exits, so the sandbox is never reaped or replaced
755
+ // under it; a spawn that starts no process lets go of it (see spawnProcess).
756
+ held.lease = await conversation_sandbox_1.sandboxPool.acquire(this.agentConfig, { source: this.source, chatId: this.memoryChatId ?? this.chatId, sessionId: this.sessionId });
757
+ return held.lease.container;
758
+ }
759
+ /** Outside orchestration a sandbox has no `.sessions/` to read, so its conversation's
760
+ * memory is written into the sandbox's own /tmp, which no other conversation shares. */
761
+ async writeSandboxChatMemory(container) {
762
+ const file = `/tmp/gateway-session-${this.sessionId.replace(/[^\w.-]/g, '_')}/chat-memory.md`;
763
+ await (0, container_1.containerNode)(container, "const fs=require('fs'),path=require('path');let s='';process.stdin.on('data',b=>s+=b);process.stdin.on('end',()=>{fs.mkdirSync(path.dirname(process.argv[1]),{recursive:true,mode:448});fs.writeFileSync(process.argv[1],s,{mode:384});});", [file], this.chatMemory());
764
+ return file;
765
+ }
766
+ /** A host path under the workspace as the app container sees it. */
767
+ toContainerPath(hostPath) {
768
+ return `/workspace/${path.relative(this.agentConfig.workspace, hostPath)}`;
769
+ }
770
+ /** Outside orchestration the conversation's memory cannot join an appended prompt, so
771
+ * it is written fresh each spawn to `.sessions/<id>/` (0700) and passed with
772
+ * --append-system-prompt-file. Undefined when isolate mode is off. */
773
+ writeChatMemoryFile() {
774
+ if (this.runtimeProfile || !this.agentConfig.isolateMemory)
775
+ return undefined;
776
+ const file = path.join(this.ensureSessionDir(), 'chat-memory.md');
777
+ fs.writeFileSync(file, this.chatMemory(), { mode: 0o600 });
778
+ return file;
779
+ }
780
+ /** `.sessions/<id>` (0700) for this session's generated spawn files. Recording
781
+ * it as this spawn's directory keeps a stop() of an earlier spawn from removing
782
+ * it at that spawn's exit. */
783
+ ensureSessionDir() {
784
+ const sessionsRoot = path.join(this.agentConfig.workspace, '.sessions');
785
+ const sessionDir = path.join(sessionsRoot, this.sessionId);
786
+ // Defense-in-depth: a sessionId containing '../' would escape the .sessions
787
+ // directory. Reject anything that resolves outside it.
788
+ const sessionDirRel = path.relative(sessionsRoot, sessionDir);
789
+ if (sessionDirRel.startsWith('..') || path.isAbsolute(sessionDirRel)) {
790
+ throw new Error('invalid session id');
791
+ }
792
+ fs.mkdirSync(sessionDir, { recursive: true, mode: 0o700 });
793
+ this.sessionDirPath = sessionDir;
794
+ return sessionDir;
795
+ }
726
796
  writeMcpConfig() {
727
797
  if (this.runtimeProfile) {
728
798
  // Orchestrators dispatch execution; only eligible workers receive connectors.
729
799
  // App and isolated workers must never receive host connector credentials
730
800
  // or start host-configured stdio servers inside their execution boundary.
731
- if (this.runtimeProfile.role === 'agent' || this.agentConfig.allow_tools === false || this.runtimeProfile.connectorsAllowed === false || this.agentConfig.type === 'app-agent' || (this.runtimeProfile.role === 'worker' && !this.runtimeProfile.hostExecution))
801
+ // Isolate mode (#609) is default-deny: connectors are agent-wide accounts.
802
+ if (this.runtimeProfile.role === 'agent' || this.agentConfig.allow_tools === false || this.runtimeProfile.connectorsAllowed === false || this.agentConfig.type === 'app-agent' || this.agentConfig.isolateMemory || (this.runtimeProfile.role === 'worker' && !this.runtimeProfile.hostExecution))
732
803
  return this.runtimeProfile.mcpConfigPath;
733
804
  const ticket = JSON.parse(fs.readFileSync(this.runtimeProfile.mcpConfigPath, 'utf8'));
734
805
  const { servers, connectors } = (0, managed_connectors_1.prepareManagedConnectors)(this.agentConfig, this.gatewayConfig, this.runtimeProfile, this.managedConnectorPaths);
@@ -745,23 +816,21 @@ class SessionProcess extends events_1.EventEmitter {
745
816
  }
746
817
  if (this.source === 'api' && !this.agentConfig.allow_tools)
747
818
  return null;
819
+ // A conversation sandbox (#609) gets no gateway MCP config at all: the config carries
820
+ // channel tokens and an API key, and the gateway server cannot run in the container.
821
+ if (this.sandboxed())
822
+ return null;
748
823
  const stateDir = path.join(this.agentConfig.workspace, '.telegram-state');
749
- const sessionsRoot = path.join(this.agentConfig.workspace, '.sessions');
750
- const sessionDir = path.join(sessionsRoot, this.sessionId);
751
- // Defense-in-depth: a sessionId containing '../' would escape the .sessions
752
- // directory. Reject anything that resolves outside it.
753
- const sessionDirRel = path.relative(sessionsRoot, sessionDir);
754
- if (sessionDirRel.startsWith('..') || path.isAbsolute(sessionDirRel)) {
755
- throw new Error('invalid session id');
756
- }
757
- fs.mkdirSync(sessionDir, { recursive: true, mode: 0o700 });
758
- this.sessionDirPath = sessionDir;
824
+ const sessionDir = this.ensureSessionDir();
759
825
  const mcpServerPath = path.resolve(__dirname, '..', '..', 'mcp', 'server.ts');
760
826
  // Merge stdio servers from Claude Code user + project configs (project overrides user).
761
827
  // Skip the gateway's own server names from both — gateway always generates its own
762
828
  // config below (RESERVED_CONNECTOR_IDS; connector ids can no longer land here at all).
763
- const userServers = this.readUserScopedMcp();
764
- const projectServers = this.readProjectScopedMcp();
829
+ // Isolate mode (#609) is default-deny: the operator's own MCP servers and the
830
+ // agent's connectors act for every conversation, so none are injected.
831
+ const isolated = this.agentConfig.isolateMemory === true;
832
+ const userServers = isolated ? {} : this.readUserScopedMcp();
833
+ const projectServers = isolated ? {} : this.readProjectScopedMcp();
765
834
  const extraServers = {};
766
835
  for (const [name, server] of Object.entries({ ...userServers, ...projectServers })) {
767
836
  if (!(0, custom_1.isReservedConnectorId)(name))
@@ -770,7 +839,7 @@ class SessionProcess extends events_1.EventEmitter {
770
839
  // Connectors enabled for THIS agent AND connected (every secret present in
771
840
  // mcp-token.env). Resolved fresh each spawn so a web "connect" is picked up
772
841
  // without a daemon restart. Secrets land only in this 0600 mcp-config.json.
773
- const connectorServers = (0, resolve_1.resolveEnabledConnectors)(this.agentConfig, this.gatewayConfig.gateway.customConnectors, this.gatewayConfig.gateway.connectorsDefaultEnabled ?? true);
842
+ const connectorServers = isolated ? {} : (0, resolve_1.resolveEnabledConnectors)(this.agentConfig, this.gatewayConfig.gateway.customConnectors, this.gatewayConfig.gateway.connectorsDefaultEnabled ?? true);
774
843
  const spawnedConnectors = new Map();
775
844
  for (const [name, server] of Object.entries(connectorServers)) {
776
845
  // Defence in depth: slugify() and /oauth/receive both refuse these ids now,
@@ -851,7 +920,13 @@ class SessionProcess extends events_1.EventEmitter {
851
920
  GATEWAY_API_URL: process.env.GATEWAY_API_URL ?? `http://127.0.0.1:${process.env.PORT ?? '10850'}`,
852
921
  GATEWAY_API_KEY: this.findApiKeyForAgent(this.agentConfig.id),
853
922
  GATEWAY_ORIGIN_CHANNEL: this.source,
923
+ // Isolate mode (#609): channel tools refuse every chat but this one.
924
+ GATEWAY_ORIGIN_CHAT_ID: this.source === 'api' ? '' : this.chatId,
854
925
  GATEWAY_WORKSPACE_DIR: this.agentConfig.workspace,
926
+ // Isolate mode (#601): the archive is one index for every conversation, so
927
+ // the memory module turns its tools off instead of filtering them.
928
+ GATEWAY_ISOLATE_MEMORY: this.agentConfig.isolateMemory ? '1' : '',
929
+ GATEWAY_DISABLE_ARCHIVE: this.agentConfig.disableArchive ? '1' : '',
855
930
  GATEWAY_SHARED_SKILLS_DIR: path.join(os.homedir(), '.claude-gateway', 'shared-skills'),
856
931
  // Shared KB vault dir (planning-64 K3), so memory_search corpus:"shared"
857
932
  // can reach the cross-agent vault. Empty when shared KB is disabled.
@@ -869,9 +944,11 @@ class SessionProcess extends events_1.EventEmitter {
869
944
  GATEWAY_RECORD_RETRIEVALS: this.resolveRecordRetrievals(),
870
945
  GATEWAY_SESSION_ID: this.sessionId,
871
946
  // For API sessions: absolute path to session media dir so browser screenshots land there
947
+ // Isolate mode (#609) confines a channel session's files to its own chat's
948
+ // media directory too (named like MediaStore.copyToMedia's).
872
949
  GATEWAY_SESSION_MEDIA_DIR: this.source === 'api'
873
950
  ? path.resolve(this.agentConfig.workspace, '..', 'media', `api-${this.sessionId}`)
874
- : '',
951
+ : isolated ? path.resolve(this.agentConfig.workspace, '..', 'media', `${this.source}-${this.chatId}`) : '',
875
952
  // Image-generation tool (generate_image) — targets an image provider that
876
953
  // may differ from the LLM: IMAGE_BASE_URL/IMAGE_API_KEY override, falling
877
954
  // back to ANTHROPIC_BASE_URL/ANTHROPIC_AUTH_TOKEN when they share a provider.
@@ -909,11 +986,19 @@ class SessionProcess extends events_1.EventEmitter {
909
986
  this.logger.debug('MCP config written', { sessionId: this.sessionId, servers: serverNames });
910
987
  return configPath;
911
988
  }
912
- /** Find the first API key that has access to this agent (agents: '*' or includes agentId). */
989
+ /** Find the first API key that has access to this agent (agents: '*' or includes agentId).
990
+ * An isolated agent (#609) only gets a non-admin key naming it: a wildcard or admin
991
+ * key reaches every conversation of every agent. */
913
992
  findApiKeyForAgent(agentId) {
914
993
  const keys = this.gatewayConfig.gateway.api?.keys;
915
994
  if (!keys?.length)
916
995
  return '';
996
+ if (this.agentConfig.isolateMemory) {
997
+ const scoped = keys.find(k => Array.isArray(k.agents) && k.agents.includes(agentId) && !k.admin)?.key;
998
+ if (!scoped)
999
+ this.logger.warn('Isolated agent has no non-admin API key naming it: gateway-API tools (api_reply, share_file, image/video, WhatsApp and WeChat replies) are unavailable', { agentId });
1000
+ return scoped ?? '';
1001
+ }
917
1002
  // Prefer a key scoped to this agent; fall back to wildcard or admin key.
918
1003
  const match = keys.find(k => (Array.isArray(k.agents) && k.agents.includes(agentId)) ||
919
1004
  k.agents === '*' ||
@@ -960,6 +1045,8 @@ class SessionProcess extends events_1.EventEmitter {
960
1045
  }
961
1046
  throw error;
962
1047
  }
1048
+ if (this.agentConfig.isolateMemory)
1049
+ context += '\n\n' + this.chatMemory();
963
1050
  }
964
1051
  const profileArgs = (0, runtime_profile_1.runtimeProfileArgs)({ ...this.runtimeProfile, context, checkpointCommand: containerAttempt && this.runtimeProfile.checkpointCommand ? `node ${containerAttempt.directory}/checkpoint.cjs ${containerAttempt.directory}/ticket.json` : this.runtimeProfile.checkpointCommand, containerExecution: this.agentConfig.type === 'app-agent', mcpConfigPath: containerAttempt?.config ?? mcpConfigPath ?? this.runtimeProfile.mcpConfigPath, skillPluginDir: containerAttempt && this.runtimeProfile.skillPluginDir ? containerAttempt.directory + '/skill-plugin' : this.runtimeProfile.skillPluginDir }, this.agentConfig.claude.extraFlags ?? []);
965
1052
  args.push(...profileArgs);
@@ -979,6 +1066,11 @@ class SessionProcess extends events_1.EventEmitter {
979
1066
  // Built-in: gateway sessions always run with permissions skipped.
980
1067
  // (The old claude.dangerouslySkipPermissions config is gone.)
981
1068
  args.push('--dangerously-skip-permissions');
1069
+ // Isolated memory mode (#601): Claude Code loads the conversation-neutral
1070
+ // workspace CLAUDE.md itself; this conversation's own USER.md/MEMORY.md
1071
+ // ride alongside it (see writeChatMemoryFile).
1072
+ if (this.chatMemoryPath)
1073
+ args.push('--append-system-prompt-file', this.isContainerAgent() && !this.sandboxed() ? this.toContainerPath(this.chatMemoryPath) : this.chatMemoryPath);
982
1074
  // Enforce allow_tools:false as a real boundary. Gated on the SAME condition as
983
1075
  // writeMcpConfig() (source==='api' && !allow_tools): those sessions get no MCP
984
1076
  // server, but built-in tools would still run and could exfil owner secrets.
@@ -1006,6 +1098,20 @@ class SessionProcess extends events_1.EventEmitter {
1006
1098
  /** Resolves false when a stop() during its awaits abandoned the spawn: nothing was
1007
1099
  * started, and a container attempt it prepared is already cleaned up. */
1008
1100
  async spawnProcess() {
1101
+ // A sandbox lease this spawn took and has not handed to a process.
1102
+ const held = {};
1103
+ try {
1104
+ const started = await this.spawnProcessOnce(held);
1105
+ if (!started)
1106
+ held.lease?.release();
1107
+ return started;
1108
+ }
1109
+ catch (error) {
1110
+ held.lease?.release();
1111
+ throw error;
1112
+ }
1113
+ }
1114
+ async spawnProcessOnce(held) {
1009
1115
  const epoch = this.spawnEpoch;
1010
1116
  const { historyPrompt, loadedAtSpawn, archivedCount, messageCountAtSpawn } = await this.buildInitialPrompt();
1011
1117
  if (epoch !== this.spawnEpoch)
@@ -1013,13 +1119,32 @@ class SessionProcess extends events_1.EventEmitter {
1013
1119
  this.spawnContext = { loadedAtSpawn, archivedCount, messageCountAtSpawn };
1014
1120
  // Determine if this is a docker-exec app-agent before computing paths
1015
1121
  (0, container_1.assertContainerBinding)(this.agentConfig, this.runtimeProfile);
1016
- const isAppAgent = this.agentConfig.type === 'app-agent' && !!this.agentConfig.container;
1122
+ const isAppAgent = this.isContainerAgent();
1123
+ let execContainer;
1124
+ try {
1125
+ execContainer = isAppAgent ? await this.executionContainer(held) : undefined;
1126
+ }
1127
+ catch (error) {
1128
+ if (epoch !== this.spawnEpoch)
1129
+ return false;
1130
+ throw error;
1131
+ }
1132
+ if (epoch !== this.spawnEpoch)
1133
+ return false;
1134
+ this.execContainer = execContainer;
1017
1135
  const freshModel = this.readFreshModel();
1018
1136
  let containerArgs;
1019
1137
  if (isAppAgent && this.runtimeProfile) {
1020
- const profile = this.runtimeProfile, container = this.agentConfig.container;
1021
- const attempt = await (0, container_1.prepareContainerProfile)(this.agentConfig, profile, async (directory) => {
1022
- profile.context = await (0, container_1.containerNode)(container, "process.stdout.write(require('fs').readFileSync('/workspace/CLAUDE.md','utf8'))");
1138
+ const profile = this.runtimeProfile, container = execContainer;
1139
+ const attempt = await (0, container_1.prepareContainerProfile)({ ...this.agentConfig, container }, profile, async (directory) => {
1140
+ // A worker's context arrives composed by its task driver, with the task's
1141
+ // own conversation's memory; only the Agent's is read from the container.
1142
+ if (this.composedContext === undefined) {
1143
+ profile.context = await (0, container_1.containerNode)(container, "process.stdout.write(require('fs').readFileSync('/workspace/CLAUDE.md','utf8'))");
1144
+ // A context set here skips the chat memory append in buildArgs, so it goes in now.
1145
+ if (this.agentConfig.isolateMemory)
1146
+ profile.context += '\n\n' + this.chatMemory();
1147
+ }
1023
1148
  const moved = (0, runtime_profile_1.appendSystemPromptViaFile)(this.buildArgs(null, freshModel, { directory, config: directory + '/mcp.json' }), directory + '/system-prompt.md');
1024
1149
  containerArgs = moved.args;
1025
1150
  return moved.prompt;
@@ -1032,11 +1157,11 @@ class SessionProcess extends events_1.EventEmitter {
1032
1157
  this.containerAttempt = attempt;
1033
1158
  }
1034
1159
  const mcpConfigPath = this.writeMcpConfig();
1035
- // For app-agents, Claude runs inside the container where /workspace is mounted.
1036
- // Convert host paths (agentConfig.workspace-relative) to container paths (/workspace/...).
1037
- const toContainerPath = (hostPath) => `/workspace/${path.relative(this.agentConfig.workspace, hostPath)}`;
1038
- const effectiveMcpPath = (isAppAgent && mcpConfigPath) ? toContainerPath(mcpConfigPath) : mcpConfigPath;
1039
- const containerRestartPath = isAppAgent ? toContainerPath(this.restartSignalPath) : this.restartSignalPath;
1160
+ this.chatMemoryPath = this.sandboxed() && !this.runtimeProfile ? await this.writeSandboxChatMemory(execContainer) : this.writeChatMemoryFile();
1161
+ if (epoch !== this.spawnEpoch)
1162
+ return false;
1163
+ const effectiveMcpPath = (isAppAgent && mcpConfigPath) ? this.toContainerPath(mcpConfigPath) : mcpConfigPath;
1164
+ const containerRestartPath = isAppAgent ? this.toContainerPath(this.restartSignalPath) : this.restartSignalPath;
1040
1165
  const args = containerArgs ?? this.writeSystemPromptFile(this.buildArgs(effectiveMcpPath, freshModel), mcpConfigPath);
1041
1166
  // Resolve the claude binary. An explicit CLAUDE_BIN (which may carry args) is
1042
1167
  // parsed by parseClaudeBin; otherwise probe PATH and the native-installer / legacy
@@ -1131,13 +1256,21 @@ class SessionProcess extends events_1.EventEmitter {
1131
1256
  const configuredWorkerEnvironment = (0, child_env_1.sanitizeJevChildEnv)(this.runtimeProfile?.role === 'worker' ? (0, worker_environment_1.workerEnvironment)(this.agentConfig, this.gatewayConfig) : {}, this.gatewayConfig.gateway.jev);
1132
1257
  const turnEnvironment = this.runtimeProfile?.claudeEffort
1133
1258
  ? { CLAUDE_CODE_EFFORT_LEVEL: this.runtimeProfile.claudeEffort } : {};
1259
+ // Isolate mode (#601): Claude Code's auto memory is one directory per cwd,
1260
+ // loaded into every session there, so it would carry notes across conversations.
1261
+ const isolateEnvironment = this.agentConfig.isolateMemory
1262
+ ? { CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' } : {};
1134
1263
  const containerEnv = {
1135
1264
  HOME: os.homedir(),
1136
1265
  CLAUDE_WORKSPACE: '/workspace',
1137
1266
  ...turnEnvironment,
1267
+ ...isolateEnvironment,
1138
1268
  GATEWAY_RESTART_SIGNAL_PATH: containerRestartPath,
1139
1269
  };
1140
- if (!this.runtimeProfile && process.env.GATEWAY_API_URL)
1270
+ // A conversation sandbox (#609) gets no gateway address or channel token: either
1271
+ // reaches past this conversation.
1272
+ const sandboxed = this.sandboxed();
1273
+ if (!this.runtimeProfile && !sandboxed && process.env.GATEWAY_API_URL)
1141
1274
  containerEnv.GATEWAY_API_URL = process.env.GATEWAY_API_URL;
1142
1275
  // Secrets are forwarded by NAME only (`-e KEY`, no `=value`), which makes
1143
1276
  // Docker read the value from this process's own environment (set on the spawn
@@ -1149,7 +1282,7 @@ class SessionProcess extends events_1.EventEmitter {
1149
1282
  // Claude credentials — it is a bearer token for the agent's whole bot
1150
1283
  // account. It is already placed in the spawn env below, unconditionally.
1151
1284
  const containerAuthEnv = isAppAgent || (this.runtimeProfile?.checkpointCommand && !this.runtimeProfile.hostExecution) ? this.resolveContainerAuthEnv() : {};
1152
- const byNameKeys = [...(this.runtimeProfile ? [] : ['TELEGRAM_BOT_TOKEN']), ...Object.keys(containerAuthEnv), ...Object.keys(configuredWorkerEnvironment)];
1285
+ const byNameKeys = [...(this.runtimeProfile || sandboxed ? [] : ['TELEGRAM_BOT_TOKEN']), ...Object.keys(containerAuthEnv), ...Object.keys(configuredWorkerEnvironment)];
1153
1286
  const dockerEnvFlags = [
1154
1287
  ...Object.entries(containerEnv).flatMap(([k, v]) => ['-e', `${k}=${v}`]),
1155
1288
  ...byNameKeys.flatMap((k) => ['-e', k]),
@@ -1160,7 +1293,7 @@ class SessionProcess extends events_1.EventEmitter {
1160
1293
  ? [
1161
1294
  'exec', '--workdir', '/workspace', '--user', String(containerUid), '-i',
1162
1295
  ...dockerEnvFlags,
1163
- this.agentConfig.container,
1296
+ execContainer,
1164
1297
  ...(this.containerAttempt ? ['node', '-e', container_1.CONTAINER_SUPERVISOR, this.containerAttempt.directory, this.agentConfig.claudeBin ?? claudeBin] : [this.agentConfig.claudeBin ?? claudeBin]),
1165
1298
  ...allArgs,
1166
1299
  ]
@@ -1200,6 +1333,7 @@ class SessionProcess extends events_1.EventEmitter {
1200
1333
  ...(hardenedPath ? { PATH: hardenedPath } : {}),
1201
1334
  ...configuredWorkerEnvironment,
1202
1335
  ...turnEnvironment,
1336
+ ...isolateEnvironment,
1203
1337
  GATEWAY_ORIGIN_SESSION_ID: this.runtimeProfile?.originSessionId ?? this.sessionId,
1204
1338
  GATEWAY_TASK_ID: this.runtimeProfile?.taskId ?? '',
1205
1339
  GATEWAY_TASK_ATTEMPT_ID: this.runtimeProfile?.attemptId ?? '',
@@ -1232,6 +1366,12 @@ class SessionProcess extends events_1.EventEmitter {
1232
1366
  this.process = proc;
1233
1367
  const startsAtSpawn = this.starts;
1234
1368
  proc.once('exit', releaseCapacity);
1369
+ const lease = held.lease;
1370
+ held.lease = undefined;
1371
+ if (lease) {
1372
+ proc.once('exit', () => lease.release());
1373
+ proc.once('error', () => lease.release());
1374
+ }
1235
1375
  proc.once('exit', () => { setTimeout(() => toolCapture?.close(), 200).unref(); });
1236
1376
  proc.once('error', () => toolCapture?.close());
1237
1377
  proc.once('error', releaseCapacity);
@@ -2106,8 +2246,8 @@ class SessionProcess extends events_1.EventEmitter {
2106
2246
  let exited = false;
2107
2247
  const exit = proc ? new Promise(resolve => proc.once('exit', () => { exited = true; resolve(); })) : undefined;
2108
2248
  this.resetBackgroundDispatchState();
2109
- if (attempt && this.agentConfig.container) {
2110
- this.managedGroupStopped = await (0, container_1.stopContainerProfile)(this.agentConfig.container, attempt.directory);
2249
+ if (attempt && this.execContainer) {
2250
+ this.managedGroupStopped = await (0, container_1.stopContainerProfile)(this.execContainer, attempt.directory);
2111
2251
  if (this.containerAttempt === attempt)
2112
2252
  this.containerAttempt = undefined;
2113
2253
  }