@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
@@ -31,6 +31,7 @@ import { createMessageHandler } from './inbound';
31
31
  import { initDedupDir, isDuplicate, pruneDedup } from '../telegram/dedup';
32
32
  import type { DiscordMessageContext } from './types';
33
33
  import { MAX_ATTACHMENT_BYTES } from '../shared/limits';
34
+ import { assertOriginChat, resolveIsolateMediaPath, isolateMediaDir, isolateMode } from '../shared/isolate';
34
35
 
35
36
  /** AgentRunner callback base (origin of CLAUDE_CHANNEL_CALLBACK, "" when unset).
36
37
  * Used to mint/approve `/cli` pairings via the runner, the same bridge the
@@ -44,6 +45,8 @@ function cliCallbackBase(): string {
44
45
  }
45
46
  }
46
47
 
48
+ const DISCORD_CDN_HOSTS = new Set(['cdn.discordapp.com', 'media.discordapp.net']);
49
+
47
50
  export class DiscordModule implements ChannelModule {
48
51
  id = 'discord' as ChannelId;
49
52
  toolVisibility: ToolVisibility = 'current-channel';
@@ -69,6 +72,8 @@ export class DiscordModule implements ChannelModule {
69
72
  // discord_reply after a transient send hiccup even though the upload
70
73
  // succeeded, which spams duplicate images. We never re-send the same file.
71
74
  private readonly sentFiles = new Set<string>();
75
+ /** Threads discord_create_thread opened from this conversation (#609). */
76
+ private readonly createdThreads = new Set<string>();
72
77
 
73
78
  constructor() {
74
79
  this.stateDir = process.env.DISCORD_STATE_DIR
@@ -712,8 +717,18 @@ export class DiscordModule implements ChannelModule {
712
717
  };
713
718
  }
714
719
 
720
+ /**
721
+ * Fetch a channel the tool may act on: the conversation's own, or (isolate
722
+ * mode) a thread this process created with discord_create_thread. Any other
723
+ * thread, even one under the origin channel, is its own conversation.
724
+ */
725
+ private async fetchOriginChannel(channelId: string): Promise<any> {
726
+ if (!this.createdThreads.has(channelId)) assertOriginChat(channelId);
727
+ return this.client.channels.fetch(channelId);
728
+ }
729
+
715
730
  private async handleReply(args: Record<string, unknown>): Promise<McpToolResult> {
716
- const channel = await this.client.channels.fetch(args.channel_id as string);
731
+ const channel = await this.fetchOriginChannel(args.channel_id as string);
717
732
  const text = args.text as string;
718
733
  const replyTo = args.reply_to as string | undefined;
719
734
  const requested = (args.files as string[] | undefined) ?? [];
@@ -730,14 +745,15 @@ export class DiscordModule implements ChannelModule {
730
745
  return { content: [{ type: 'text', text: 'already sent (duplicate suppressed)' }] };
731
746
  }
732
747
 
733
- for (const f of files) {
734
- const st = fs.statSync(f);
748
+ const paths = files.map(resolveIsolateMediaPath);
749
+ paths.forEach((p, i) => {
750
+ const st = fs.statSync(p);
735
751
  if (st.size > MAX_ATTACHMENT_BYTES) {
736
- throw new Error(`file too large: ${f} (${(st.size / 1024 / 1024).toFixed(1)}MB, max 50MB)`);
752
+ throw new Error(`file too large: ${files[i]} (${(st.size / 1024 / 1024).toFixed(1)}MB, max 50MB)`);
737
753
  }
738
- }
754
+ });
739
755
 
740
- const sent = await sendMessage(channel, text, { replyTo, files, useEmbed });
756
+ const sent = await sendMessage(channel, text, { replyTo, files: paths, useEmbed });
741
757
  // Mark as sent only AFTER the send succeeds — if sendMessage throws, the files
742
758
  // stay un-marked so a genuine retry re-delivers them (never silently dropped).
743
759
  for (const f of files) this.sentFiles.add(f);
@@ -746,14 +762,14 @@ export class DiscordModule implements ChannelModule {
746
762
  }
747
763
 
748
764
  private async handleReact(args: Record<string, unknown>): Promise<McpToolResult> {
749
- const channel = await this.client.channels.fetch(args.channel_id as string);
765
+ const channel = await this.fetchOriginChannel(args.channel_id as string);
750
766
  const message = await channel.messages.fetch(args.message_id as string);
751
767
  await message.react(args.emoji as string);
752
768
  return { content: [{ type: 'text', text: 'reacted' }] };
753
769
  }
754
770
 
755
771
  private async handleEditMessage(args: Record<string, unknown>): Promise<McpToolResult> {
756
- const channel = await this.client.channels.fetch(args.channel_id as string);
772
+ const channel = await this.fetchOriginChannel(args.channel_id as string);
757
773
  const message = await channel.messages.fetch(args.message_id as string);
758
774
  const edited = await message.edit(args.text as string);
759
775
  return { content: [{ type: 'text', text: `edited (id: ${edited.id})` }] };
@@ -761,11 +777,27 @@ export class DiscordModule implements ChannelModule {
761
777
 
762
778
  private async handleDownloadAttachment(args: Record<string, unknown>): Promise<McpToolResult> {
763
779
  const url = args.url as string;
780
+ // Isolate mode: only Discord's own CDN, and into this conversation's media
781
+ // dir rather than the inbox every conversation shares.
782
+ let destDir = this.inboxDir;
783
+ if (isolateMode()) {
784
+ let parsed: URL | null = null;
785
+ try { parsed = new URL(url); } catch {}
786
+ if (!parsed || parsed.protocol !== 'https:' || !DISCORD_CDN_HOSTS.has(parsed.hostname)) {
787
+ throw new Error('isolate mode: only https://cdn.discordapp.com or https://media.discordapp.net attachment URLs can be downloaded');
788
+ }
789
+ // A CDN attachment URL names the channel it was posted in:
790
+ // /attachments/<channel_id>/<attachment_id>/<file>. Only this conversation's.
791
+ const [, kind, channelId] = parsed.pathname.split('/');
792
+ if (kind !== 'attachments' || !channelId) throw new Error('isolate mode: only channel attachment URLs can be downloaded');
793
+ if (!this.createdThreads.has(channelId)) assertOriginChat(channelId);
794
+ destDir = isolateMediaDir();
795
+ }
764
796
  const filename = (args.filename as string | undefined) ?? path.basename(url.split('?')[0]);
765
797
  const ext = path.extname(filename).replace(/[^a-zA-Z0-9.]/g, '') || '.bin';
766
- const dlPath = path.join(this.inboxDir, `${Date.now()}-${filename.replace(/[^a-zA-Z0-9._-]/g, '_')}`);
798
+ const dlPath = path.join(destDir, `${Date.now()}-${filename.replace(/[^a-zA-Z0-9._-]/g, '_')}`);
767
799
 
768
- fs.mkdirSync(this.inboxDir, { recursive: true });
800
+ fs.mkdirSync(destDir, { recursive: true });
769
801
 
770
802
  await new Promise<void>((resolve, reject) => {
771
803
  const proto = url.startsWith('https') ? https : http;
@@ -785,7 +817,7 @@ export class DiscordModule implements ChannelModule {
785
817
  }
786
818
 
787
819
  private async handleCreateThread(args: Record<string, unknown>): Promise<McpToolResult> {
788
- const channel = await this.client.channels.fetch(args.channel_id as string);
820
+ const channel = await this.fetchOriginChannel(args.channel_id as string);
789
821
  const name = (args.name as string).slice(0, 100);
790
822
  let thread: any;
791
823
  if (args.message_id) {
@@ -794,6 +826,7 @@ export class DiscordModule implements ChannelModule {
794
826
  } else {
795
827
  thread = await channel.threads.create({ name, autoArchiveDuration: 60 });
796
828
  }
829
+ this.createdThreads.add(thread.id);
797
830
  return { content: [{ type: 'text', text: `thread created (id: ${thread.id})` }] };
798
831
  }
799
832
  }
@@ -16,6 +16,7 @@ import type { ToolModule, McpToolDefinition, McpToolResult, ToolVisibility } fro
16
16
  import { messagingApi } from '@line/bot-sdk';
17
17
  import { chunkText, planLineSend, LINE_TEXT_LIMIT } from './pure';
18
18
  import { createShares, ShareClientError, shareBridgeEnabled } from '../shared/share-client';
19
+ import { assertOriginChat } from '../shared/isolate';
19
20
 
20
21
  /** Default lifetime of a share URL handed to LINE (1 hour). */
21
22
  const DEFAULT_MEDIA_URL_TTL_MS = 60 * 60 * 1000;
@@ -128,6 +129,11 @@ export class LineModule implements ToolModule {
128
129
  if (!chatId) {
129
130
  return { content: [{ type: 'text', text: 'line_reply: missing chat_id' }], isError: true };
130
131
  }
132
+ try {
133
+ assertOriginChat(chatId);
134
+ } catch (err) {
135
+ return { content: [{ type: 'text', text: `line_reply: ${(err as Error).message}` }], isError: true };
136
+ }
131
137
  if (!text) {
132
138
  return { content: [{ type: 'text', text: 'line_reply: text cannot be empty' }], isError: true };
133
139
  }
@@ -200,6 +206,11 @@ export class LineModule implements ToolModule {
200
206
  if (!chatId) {
201
207
  return { content: [{ type: 'text', text: 'line_image: missing chat_id' }], isError: true };
202
208
  }
209
+ try {
210
+ assertOriginChat(chatId);
211
+ } catch (err) {
212
+ return { content: [{ type: 'text', text: `line_image: ${(err as Error).message}` }], isError: true };
213
+ }
203
214
  if (!image) {
204
215
  return { content: [{ type: 'text', text: 'line_image: image path is required' }], isError: true };
205
216
  }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Bun tests for disable_archive (#609): an agent that turns the archive off
3
+ * is never offered memory_search/memory_get, independent of isolate mode.
4
+ */
5
+
6
+ import { test, expect, beforeEach, afterEach } from 'bun:test';
7
+
8
+ import { MemoryModule } from './module';
9
+ import { SkillsModule } from '../skills/module';
10
+
11
+ const originalEnv = {
12
+ GATEWAY_WORKSPACE_DIR: process.env.GATEWAY_WORKSPACE_DIR,
13
+ GATEWAY_ISOLATE_MEMORY: process.env.GATEWAY_ISOLATE_MEMORY,
14
+ GATEWAY_DISABLE_ARCHIVE: process.env.GATEWAY_DISABLE_ARCHIVE,
15
+ };
16
+
17
+ beforeEach(() => {
18
+ process.env.GATEWAY_WORKSPACE_DIR = '/tmp/disable-archive-workspace';
19
+ delete process.env.GATEWAY_ISOLATE_MEMORY;
20
+ delete process.env.GATEWAY_DISABLE_ARCHIVE;
21
+ });
22
+
23
+ afterEach(() => {
24
+ for (const [k, v] of Object.entries(originalEnv)) {
25
+ if (v === undefined) delete process.env[k];
26
+ else process.env[k] = v;
27
+ }
28
+ });
29
+
30
+ test('the memory module is offered when the archive is not disabled', () => {
31
+ expect(new MemoryModule().isEnabled()).toBe(true);
32
+ });
33
+
34
+ test('GATEWAY_DISABLE_ARCHIVE turns the memory module off, so memory_search/memory_get are never registered', () => {
35
+ process.env.GATEWAY_DISABLE_ARCHIVE = '1';
36
+ expect(new MemoryModule().isEnabled()).toBe(false);
37
+ });
38
+
39
+ test('an empty GATEWAY_DISABLE_ARCHIVE (the forwarded value for an unset flag) keeps the module on', () => {
40
+ process.env.GATEWAY_DISABLE_ARCHIVE = '';
41
+ expect(new MemoryModule().isEnabled()).toBe(true);
42
+ });
43
+
44
+ test('disabling the archive does not imply isolate mode: other workspace modules stay on', () => {
45
+ process.env.GATEWAY_DISABLE_ARCHIVE = '1';
46
+ expect(new SkillsModule().isEnabled()).toBe(true);
47
+ });
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Bun tests for isolated memory mode (#601). The knowledge archive is one
3
+ * index per agent with no conversation column, so any session's memory_search can
4
+ * return a note written for another sender. Isolate mode turns the module off.
5
+ */
6
+
7
+ import { test, expect, beforeEach, afterEach } from 'bun:test';
8
+ import { Database } from 'bun:sqlite';
9
+ import * as fs from 'fs';
10
+ import * as os from 'os';
11
+ import * as path from 'path';
12
+
13
+ import { MemoryModule } from './module';
14
+ import { SkillsModule } from '../skills/module';
15
+ import { CronModule } from '../cron/module';
16
+ import { AgentModule } from '../agent/module';
17
+ import { AppsModule } from '../apps/module';
18
+ import { archiveDbPath } from './archive-reader';
19
+
20
+ let agentDir: string;
21
+ const originalEnv = {
22
+ GATEWAY_WORKSPACE_DIR: process.env.GATEWAY_WORKSPACE_DIR,
23
+ GATEWAY_SHARED_KB_DIR: process.env.GATEWAY_SHARED_KB_DIR,
24
+ GATEWAY_ISOLATE_MEMORY: process.env.GATEWAY_ISOLATE_MEMORY,
25
+ GATEWAY_API_URL: process.env.GATEWAY_API_URL,
26
+ GATEWAY_AGENT_ID: process.env.GATEWAY_AGENT_ID,
27
+ };
28
+
29
+ beforeEach(() => {
30
+ agentDir = fs.mkdtempSync(path.join(os.tmpdir(), 'kb-iso-'));
31
+ const workspaceDir = path.join(agentDir, 'workspace');
32
+ fs.mkdirSync(workspaceDir);
33
+ // Same schema src/ writes; one chunk recorded while serving conversation A.
34
+ const db = new Database(archiveDbPath(workspaceDir));
35
+ db.exec(`
36
+ CREATE TABLE kb_chunks (rowid_id INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT UNIQUE, path TEXT,
37
+ start_line INTEGER, end_line INTEGER, text TEXT, updated_at INTEGER);
38
+ CREATE TABLE kb_chunk_recall (chunk_id TEXT PRIMARY KEY, importance INTEGER, triggers TEXT, project_key TEXT);
39
+ CREATE TABLE kb_chunk_provenance (chunk_id TEXT PRIMARY KEY, origin_class TEXT, session_kind TEXT,
40
+ observed_at INTEGER, supersedes_key TEXT);
41
+ CREATE VIRTUAL TABLE kb_chunks_fts USING fts5(text, content='kb_chunks', content_rowid='rowid_id');
42
+ CREATE TRIGGER kb_chunks_ai AFTER INSERT ON kb_chunks BEGIN
43
+ INSERT INTO kb_chunks_fts(rowid, text) VALUES (new.rowid_id, new.text);
44
+ END;
45
+ `);
46
+ db.prepare('INSERT INTO kb_chunks(id,path,start_line,end_line,text,updated_at) VALUES(?,?,?,?,?,?)')
47
+ .run('c1', 'memory/chat-a.md', 1, 1, 'Chat A bank account ends 4321', 1);
48
+ db.close();
49
+ process.env.GATEWAY_WORKSPACE_DIR = workspaceDir;
50
+ delete process.env.GATEWAY_SHARED_KB_DIR;
51
+ delete process.env.GATEWAY_ISOLATE_MEMORY;
52
+ });
53
+
54
+ afterEach(() => {
55
+ fs.rmSync(agentDir, { recursive: true, force: true });
56
+ for (const [k, v] of Object.entries(originalEnv)) {
57
+ if (v === undefined) delete process.env[k];
58
+ else process.env[k] = v;
59
+ }
60
+ });
61
+
62
+ test('without isolate mode, any session can search a note written for another sender', async () => {
63
+ const mod = new MemoryModule();
64
+ expect(mod.isEnabled()).toBe(true);
65
+ const result = await mod.handleTool('memory_search', { query: 'bank account' });
66
+ expect((result.content[0] as { text: string }).text).toContain('4321');
67
+ });
68
+
69
+ test('isolate mode turns the memory module off, so its tools are never registered', () => {
70
+ process.env.GATEWAY_ISOLATE_MEMORY = '1';
71
+ expect(new MemoryModule().isEnabled()).toBe(false);
72
+ });
73
+
74
+ test('isolate mode turns the skills module off: the skill catalog is shared by every conversation', () => {
75
+ expect(new SkillsModule().isEnabled()).toBe(true);
76
+ process.env.GATEWAY_ISOLATE_MEMORY = '1';
77
+ expect(new SkillsModule().isEnabled()).toBe(false);
78
+ });
79
+
80
+ test('isolate mode turns the cron and agent modules off: jobs and the persona are shared by every conversation', () => {
81
+ process.env.GATEWAY_API_URL = 'http://127.0.0.1:1';
82
+ process.env.GATEWAY_AGENT_ID = 'shared-bot';
83
+ expect(new CronModule().isEnabled()).toBe(true);
84
+ expect(new AgentModule().isEnabled()).toBe(true);
85
+ process.env.GATEWAY_ISOLATE_MEMORY = '1';
86
+ expect(new CronModule().isEnabled()).toBe(false);
87
+ expect(new AgentModule().isEnabled()).toBe(false);
88
+ });
89
+
90
+ test('isolate mode turns the apps module off: restoring or uninstalling an app rewinds every conversation\'s memory', () => {
91
+ process.env.GATEWAY_API_URL = 'http://127.0.0.1:1';
92
+ expect(new AppsModule().isEnabled()).toBe(true);
93
+ process.env.GATEWAY_ISOLATE_MEMORY = '1';
94
+ expect(new AppsModule().isEnabled()).toBe(false);
95
+ });
@@ -32,7 +32,10 @@ export class MemoryModule implements ToolModule {
32
32
 
33
33
  isEnabled(): boolean {
34
34
  // Available whenever the agent's workspace dir is known (same gate as skills).
35
- return Boolean(process.env.GATEWAY_WORKSPACE_DIR);
35
+ // Never in isolated memory mode (#601): the archive is one index over
36
+ // every conversation's notes, so a search could return another conversation's data.
37
+ // Nor when the agent turns the archive off (#609).
38
+ return Boolean(process.env.GATEWAY_WORKSPACE_DIR) && !process.env.GATEWAY_ISOLATE_MEMORY && !process.env.GATEWAY_DISABLE_ARCHIVE;
36
39
  }
37
40
 
38
41
  getTools(): McpToolDefinition[] {
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Isolate-mode policy for the gateway MCP server (#609). In isolate mode
3
+ * (GATEWAY_ISOLATE_MEMORY non-empty) one agent serves many unrelated end users
4
+ * and one conversation is (channel, chatId), so every tool must stay inside the
5
+ * conversation that spawned this server. Outside isolate mode every helper here
6
+ * is a no-op.
7
+ *
8
+ * Self-contained on purpose, like share-client.ts: mcp/** ships as source
9
+ * without src/** (see tests/unit/mcp-no-src-imports.test.ts).
10
+ */
11
+ import * as fs from 'fs';
12
+ import * as path from 'path';
13
+
14
+ /** Non-channel modules that are safe per conversation. Everything else is off.
15
+ * `narrate` only speaks through the task bridge into the task's own conversation. */
16
+ export const ISOLATE_SAFE_MODULES: ReadonlySet<string> = new Set(['image', 'video', 'share-file', 'narrate']);
17
+
18
+ export function isolateMode(): boolean {
19
+ return Boolean(process.env.GATEWAY_ISOLATE_MEMORY);
20
+ }
21
+
22
+ /**
23
+ * Default-deny module allowlist. In isolate mode only the originating channel's
24
+ * module (never every channel when the origin is unknown), plus the
25
+ * per-conversation-safe modules above, may load.
26
+ */
27
+ export function isolateAllowsModule(id: string): boolean {
28
+ if (!isolateMode()) return true;
29
+ const origin = process.env.GATEWAY_ORIGIN_CHANNEL ?? '';
30
+ return (origin !== '' && id === origin) || ISOLATE_SAFE_MODULES.has(id);
31
+ }
32
+
33
+ /**
34
+ * Origin-chat lock: in isolate mode a tool may only act on this conversation's
35
+ * own chat.
36
+ */
37
+ export function assertOriginChat(chatId: string): void {
38
+ if (!isolateMode()) return;
39
+ const origin = process.env.GATEWAY_ORIGIN_CHAT_ID ?? '';
40
+ if (!origin) throw new Error('isolate mode: the originating chat is unknown, so chat tools are disabled');
41
+ if (chatId === origin) return;
42
+ throw new Error('isolate mode: this conversation can only reply to its own chat');
43
+ }
44
+
45
+ /** This session's own media dir; isolate mode fails closed without one. */
46
+ export function isolateMediaDir(): string {
47
+ const dir = process.env.GATEWAY_SESSION_MEDIA_DIR ?? '';
48
+ if (!dir) throw new Error('isolate mode: no session media directory, so file attachments are disabled');
49
+ return dir;
50
+ }
51
+
52
+ /**
53
+ * In isolate mode a local file a tool sends or shares must realpath-resolve
54
+ * inside this session's media dir. A relative path is media-root relative
55
+ * ("media/<chat>/x.png" or "<chat>/x.png"), the form the share route accepts;
56
+ * the agent media root is the session media dir's parent. Returns the path to
57
+ * send: the validated realpath in isolate mode, `file` unchanged otherwise.
58
+ */
59
+ export function resolveIsolateMediaPath(file: string): string {
60
+ if (!isolateMode()) return file;
61
+ const dir = isolateMediaDir();
62
+ const abs = path.isAbsolute(file)
63
+ ? file
64
+ : path.resolve(path.dirname(dir), file.startsWith('media/') ? file.slice('media/'.length) : file);
65
+ let real: string;
66
+ let dirReal: string;
67
+ try {
68
+ real = fs.realpathSync(abs);
69
+ dirReal = fs.realpathSync(dir);
70
+ } catch {
71
+ throw new Error(`isolate mode: file not found in this conversation's media directory: ${file}`);
72
+ }
73
+ if (!real.startsWith(dirReal + path.sep)) {
74
+ throw new Error(`isolate mode: file is outside this conversation's media directory: ${file}`);
75
+ }
76
+ return real;
77
+ }
@@ -9,6 +9,8 @@
9
9
  * module must not import from src/ (see tests/unit/mcp-no-src-imports.test.ts).
10
10
  */
11
11
 
12
+ import { resolveIsolateMediaPath } from './isolate';
13
+
12
14
  const REQUEST_TIMEOUT_MS = 15_000;
13
15
 
14
16
  export type ShareRef = { artifact_id?: string; path?: string };
@@ -131,6 +133,16 @@ export async function createShares(
131
133
  refs: ShareRef[],
132
134
  opts: { purpose?: string; ttlSeconds?: number; allowDocuments?: boolean } = {},
133
135
  ): Promise<ShareItem[]> {
136
+ // Isolate mode: a path ref must sit in this conversation's own media dir. An
137
+ // artifact ref is already resolved per (agent, session) by the gateway.
138
+ refs = refs.map((ref) => {
139
+ if (ref.path === undefined) return ref;
140
+ try {
141
+ return { ...ref, path: resolveIsolateMediaPath(ref.path) };
142
+ } catch (err) {
143
+ throw new ShareClientError('isolate_path_denied', (err as Error).message, 403);
144
+ }
145
+ });
134
146
  const body: Record<string, unknown> = {
135
147
  agent_id: process.env.GATEWAY_AGENT_ID,
136
148
  session_id: process.env.GATEWAY_SESSION_ID,
@@ -195,7 +207,9 @@ function extractError(
195
207
 
196
208
  /** Revoke a share by id. Throws ShareClientError on failure. */
197
209
  export async function revokeShare(shareId: string): Promise<void> {
198
- const { status, json } = await callGateway('DELETE', `/api/v1/shares/${encodeURIComponent(shareId)}`);
210
+ // An isolated agent's share is revoked only by its own session (#609).
211
+ const session = process.env.GATEWAY_ISOLATE_MEMORY && process.env.GATEWAY_SESSION_ID ? `?session_id=${encodeURIComponent(process.env.GATEWAY_SESSION_ID)}` : '';
212
+ const { status, json } = await callGateway('DELETE', `/api/v1/shares/${encodeURIComponent(shareId)}${session}`);
199
213
  if (status !== 200) {
200
214
  const message = typeof json.error === 'string' ? json.error : `revoke failed (HTTP ${status})`;
201
215
  throw new ShareClientError('revoke_failed', message, status);
@@ -26,8 +26,10 @@ export class SkillsModule implements ToolModule {
26
26
  toolVisibility: ToolVisibility = 'all-configured';
27
27
 
28
28
  isEnabled(): boolean {
29
- // Skills tools are available when workspace dir is known
30
- return Boolean(process.env.GATEWAY_WORKSPACE_DIR);
29
+ // Skills tools are available when workspace dir is known. Never in
30
+ // isolated memory mode (#601): the skill catalog is shared by every
31
+ // conversation, so one sender must not be able to add to it.
32
+ return Boolean(process.env.GATEWAY_WORKSPACE_DIR) && !process.env.GATEWAY_ISOLATE_MEMORY;
31
33
  }
32
34
 
33
35
  getTools(): McpToolDefinition[] {
@@ -22,6 +22,7 @@ import type { ToolModule, McpToolDefinition, McpToolResult, ToolVisibility } fro
22
22
  // run at least once for this import to resolve locally.
23
23
  import { SlackClient } from '../../../dist/api/slack-client.js';
24
24
  import { MAX_ATTACHMENT_BYTES } from '../shared/limits';
25
+ import { assertOriginChat, resolveIsolateMediaPath } from '../shared/isolate';
25
26
 
26
27
  export class SlackModule implements ToolModule {
27
28
  id = 'slack';
@@ -103,6 +104,11 @@ export class SlackModule implements ToolModule {
103
104
  if (!chatId) {
104
105
  return { content: [{ type: 'text', text: 'slack_reply: missing chat_id' }], isError: true };
105
106
  }
107
+ try {
108
+ assertOriginChat(chatId);
109
+ } catch (err) {
110
+ return { content: [{ type: 'text', text: `slack_reply: ${(err as Error).message}` }], isError: true };
111
+ }
106
112
 
107
113
  // Drop files already delivered successfully this session (retry-dedup): a
108
114
  // small model sometimes retries slack_reply after a transient hiccup even
@@ -127,19 +133,20 @@ export class SlackModule implements ToolModule {
127
133
  try {
128
134
  // Size-check before any upload starts, so an oversized file fails fast
129
135
  // instead of half-way through a multi-file batch.
130
- for (const f of files) {
131
- const st = fs.statSync(f);
136
+ const paths = files.map(resolveIsolateMediaPath);
137
+ paths.forEach((p, i) => {
138
+ const st = fs.statSync(p);
132
139
  if (st.size > MAX_ATTACHMENT_BYTES) {
133
- throw new Error(`file too large: ${f} (${(st.size / 1024 / 1024).toFixed(1)}MB, max 50MB)`);
140
+ throw new Error(`file too large: ${files[i]} (${(st.size / 1024 / 1024).toFixed(1)}MB, max 50MB)`);
134
141
  }
135
- }
142
+ });
136
143
 
137
144
  // With files, ONE uploadFiles call carries both the attachments and the
138
145
  // text (as Slack's initial_comment) — never also postMessage, which would
139
146
  // split one reply into two Slack messages.
140
147
  const sent =
141
148
  files.length > 0
142
- ? await client.uploadFiles(chatId, files, {
149
+ ? await client.uploadFiles(chatId, paths, {
143
150
  threadTs: threadId || undefined,
144
151
  initialComment: text || undefined,
145
152
  })
@@ -10,7 +10,7 @@ export { AGENT_TASK_TOOLS } from '../../../dist/orchestration/agent-tool-schemas
10
10
  export { SUBAGENT_TOOLS, readonlyDenied } from '../../../dist/orchestration/subagent-tool-schemas.js';
11
11
  export const WORKER_REPORT_TOOLS: McpToolDefinition[] = [
12
12
  JEV_TOOL,
13
- { name: 'task_memory_append', description: 'Append an explicitly requested memory note for a channel task. API tasks cannot write memory. Files are restricted to MEMORY.md, USER.md, or memory/<name>.md. Retains existing content and deduplicates retries.', inputSchema: schema({ note: text, path: text }, ['note']) },
13
+ { name: 'task_memory_append', description: 'Append an explicitly requested memory note for a channel task. API tasks cannot write memory. Files are restricted to MEMORY.md, USER.md, or memory/<name>.md; in isolated memory mode only MEMORY.md or USER.md, written to the conversation directory. Retains existing content and deduplicates retries.', inputSchema: schema({ note: text, path: text }, ['note']) },
14
14
  { name: 'task_stage_file', description: 'Stage a finished image or document for the user. The orchestration attaches it to the next completed agent response after this task succeeds, using the original destination. This tool does not send to a channel. Call once per output file. For an image returned by an MCP tool (such as a remote browser screenshot), omit path to use the latest captured image in this attempt, or pass source_tool_call_id to select its tool call. The gateway saves the actual image bytes; never invent a screenshot filename. For an existing local file supply path.', inputSchema: schema({ path: text, source_tool_call_id: text, caption: text }, []) },
15
15
  { name: 'task_report_progress', description: 'Report factual progress internally. At phase changes include a checkpoint with phase, evidenceVersion, checks, findings and nextAction. This does not send a user message.', inputSchema: schema({ text, checkpoint: WORKFLOW_SCHEMA }, ['text']) },
16
16
  { name: 'task_request_input', description: 'Ask the user for information required by your task, then end this turn immediately.', inputSchema: schema({ question: text }, ['question']) },
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Per-chat record of the attachment file_ids the receiver delivered (#609). A
3
+ * Telegram file_id carries no chat, so isolate mode downloads only a file_id
4
+ * this log shows arrived in the conversation's own chat. The receiver writes,
5
+ * the session MCP server reads; both share TELEGRAM_STATE_DIR.
6
+ */
7
+ import * as fs from 'fs';
8
+ import * as path from 'path';
9
+
10
+ /** Newest file_ids kept per chat. */
11
+ export const MAX_LOGGED_ATTACHMENTS = 200;
12
+
13
+ function logFile(stateDir: string, chatId: string): string {
14
+ return path.join(stateDir, 'attachments', `${chatId.replace(/[^0-9A-Za-z_-]/g, '_')}.json`);
15
+ }
16
+
17
+ function readLog(file: string): string[] {
18
+ try {
19
+ const ids = JSON.parse(fs.readFileSync(file, 'utf8'));
20
+ return Array.isArray(ids) ? ids.filter((id): id is string => typeof id === 'string') : [];
21
+ } catch {
22
+ return [];
23
+ }
24
+ }
25
+
26
+ export function recordChatAttachments(stateDir: string, chatId: string, fileIds: string[]): void {
27
+ if (fileIds.length === 0) return;
28
+ const file = logFile(stateDir, chatId);
29
+ const ids = [...readLog(file).filter((id) => !fileIds.includes(id)), ...fileIds].slice(-MAX_LOGGED_ATTACHMENTS);
30
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
31
+ // Written whole and renamed, so the session never reads half a log.
32
+ const tmp = `${file}.${process.pid}.tmp`;
33
+ fs.writeFileSync(tmp, JSON.stringify(ids), { mode: 0o600 });
34
+ fs.renameSync(tmp, file);
35
+ }
36
+
37
+ export function chatHasAttachment(stateDir: string, chatId: string, fileId: string): boolean {
38
+ return readLog(logFile(stateDir, chatId)).includes(fileId);
39
+ }
@@ -9,6 +9,8 @@ import * as os from 'os';
9
9
  import { migrateAccess, defaultAccess } from './pure';
10
10
  import { chunkText, htmlToPlain, parseRepliedTurnId } from './typing';
11
11
  import { MAX_ATTACHMENT_BYTES } from '../shared/limits';
12
+ import { assertOriginChat, isolateMediaDir, isolateMode, resolveIsolateMediaPath } from '../shared/isolate';
13
+ import { chatHasAttachment } from './attachment-log';
12
14
  import type {
13
15
  ChannelModule,
14
16
  ChannelCapabilities,
@@ -281,22 +283,26 @@ export class TelegramModule implements ChannelModule {
281
283
  }
282
284
 
283
285
  private assertAllowedChat(chat_id: string): void {
286
+ assertOriginChat(chat_id);
284
287
  const access = this.readAccessFile();
285
288
  if (access.allowFrom.includes(chat_id)) return;
286
289
  if (access.groupAllowlist.includes(chat_id)) return;
287
290
  throw new Error(`chat ${chat_id} is not allowlisted`);
288
291
  }
289
292
 
290
- private assertSendable(f: string): void {
293
+ /** The path to send for `f`, refusing channel state (and, isolated, files outside the session media). */
294
+ private sendablePath(f: string): string {
295
+ const file = resolveIsolateMediaPath(f);
291
296
  let real: string, stateReal: string;
292
297
  try {
293
- real = fs.realpathSync(f);
298
+ real = fs.realpathSync(file);
294
299
  stateReal = fs.realpathSync(this.stateDir);
295
- } catch { return; }
300
+ } catch { return file; }
296
301
  const inbox = path.join(stateReal, 'inbox');
297
302
  if (real.startsWith(stateReal + path.sep) && !real.startsWith(inbox + path.sep)) {
298
303
  throw new Error(`refusing to send channel state: ${f}`);
299
304
  }
305
+ return file;
300
306
  }
301
307
 
302
308
  private async handleReply(args: Record<string, unknown>): Promise<McpToolResult> {
@@ -336,13 +342,13 @@ export class TelegramModule implements ChannelModule {
336
342
  }
337
343
  }
338
344
 
339
- for (const f of files) {
340
- this.assertSendable(f);
341
- const st = fs.statSync(f);
345
+ const paths = files.map((f) => this.sendablePath(f));
346
+ paths.forEach((p, i) => {
347
+ const st = fs.statSync(p);
342
348
  if (st.size > MAX_ATTACHMENT_BYTES) {
343
- throw new Error(`file too large: ${f} (${(st.size / 1024 / 1024).toFixed(1)}MB, max 50MB)`);
349
+ throw new Error(`file too large: ${files[i]} (${(st.size / 1024 / 1024).toFixed(1)}MB, max 50MB)`);
344
350
  }
345
- }
351
+ });
346
352
 
347
353
  const access = this.readAccessFile();
348
354
  const limit = Math.max(1, Math.min(access.textChunkLimit ?? MAX_CHUNK_LIMIT, MAX_CHUNK_LIMIT));
@@ -374,7 +380,7 @@ export class TelegramModule implements ChannelModule {
374
380
  throw new Error(`reply failed after ${sentIds.length} of ${chunks.length} chunk(s) sent: ${msg}`);
375
381
  }
376
382
 
377
- for (const f of files) {
383
+ for (const f of paths) {
378
384
  const ext = path.extname(f).toLowerCase();
379
385
  const input = new InputFile(f);
380
386
  const opts = reply_to != null && replyMode !== 'off'
@@ -417,6 +423,16 @@ export class TelegramModule implements ChannelModule {
417
423
 
418
424
  private async handleDownload(args: Record<string, unknown>): Promise<McpToolResult> {
419
425
  const file_id = args.file_id as string;
426
+ // A file_id carries no chat, so isolate mode takes only one the receiver
427
+ // logged for this conversation's chat, and saves it to the session's media.
428
+ let saveDir = this.inboxDir;
429
+ if (isolateMode()) {
430
+ const origin = process.env.GATEWAY_ORIGIN_CHAT_ID ?? '';
431
+ if (!origin || !chatHasAttachment(this.stateDir, origin, file_id)) {
432
+ throw new Error('isolate mode: this file_id was not sent in this conversation');
433
+ }
434
+ saveDir = isolateMediaDir();
435
+ }
420
436
  const token = this.getToken()!;
421
437
  const file = await this.bot.api.getFile(file_id);
422
438
  if (!file.file_path) throw new Error('Telegram returned no file_path — file may have expired');
@@ -428,8 +444,8 @@ export class TelegramModule implements ChannelModule {
428
444
  const rawExt = file.file_path.includes('.') ? file.file_path.split('.').pop()! : 'bin';
429
445
  const ext = rawExt.replace(/[^a-zA-Z0-9]/g, '') || 'bin';
430
446
  const uniqueId = (file.file_unique_id ?? '').replace(/[^a-zA-Z0-9_-]/g, '') || 'dl';
431
- const dlPath = path.join(this.inboxDir, `${Date.now()}-${uniqueId}.${ext}`);
432
- fs.mkdirSync(this.inboxDir, { recursive: true });
447
+ const dlPath = path.join(saveDir, `${Date.now()}-${uniqueId}.${ext}`);
448
+ fs.mkdirSync(saveDir, { recursive: true });
433
449
  fs.writeFileSync(dlPath, buf);
434
450
  return { content: [{ type: 'text', text: dlPath }] };
435
451
  }