@0xmaxma/claude-gateway 2.1.1 → 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 (159) hide show
  1. package/README.md +1 -1
  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 +1 -1
  8. package/dist/agent/runner.d.ts.map +1 -1
  9. package/dist/agent/runner.js +9 -4
  10. package/dist/agent/runner.js.map +1 -1
  11. package/dist/agent/workspace-loader.d.ts +12 -0
  12. package/dist/agent/workspace-loader.d.ts.map +1 -1
  13. package/dist/agent/workspace-loader.js +34 -4
  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 +1 -1
  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 +2 -2
  37. package/dist/apps/agent-manager.d.ts.map +1 -1
  38. package/dist/apps/agent-manager.js +12 -3
  39. package/dist/apps/agent-manager.js.map +1 -1
  40. package/dist/apps/compose-generator.d.ts +4 -0
  41. package/dist/apps/compose-generator.d.ts.map +1 -1
  42. package/dist/apps/compose-generator.js +6 -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 +1 -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 +1 -0
  53. package/dist/apps/registry.d.ts.map +1 -1
  54. package/dist/build-provenance.json +4 -4
  55. package/dist/config/loader.d.ts.map +1 -1
  56. package/dist/config/loader.js +3 -0
  57. package/dist/config/loader.js.map +1 -1
  58. package/dist/config/migrator.d.ts +2 -0
  59. package/dist/config/migrator.d.ts.map +1 -1
  60. package/dist/config/migrator.js +37 -1
  61. package/dist/config/migrator.js.map +1 -1
  62. package/dist/config/reload-policy.d.ts.map +1 -1
  63. package/dist/config/reload-policy.js +2 -0
  64. package/dist/config/reload-policy.js.map +1 -1
  65. package/dist/cron/manager.d.ts +15 -0
  66. package/dist/cron/manager.d.ts.map +1 -1
  67. package/dist/cron/manager.js +53 -1
  68. package/dist/cron/manager.js.map +1 -1
  69. package/dist/index.js +21 -9
  70. package/dist/index.js.map +1 -1
  71. package/dist/orchestration/bridge.d.ts +4 -0
  72. package/dist/orchestration/bridge.d.ts.map +1 -1
  73. package/dist/orchestration/bridge.js +25 -6
  74. package/dist/orchestration/bridge.js.map +1 -1
  75. package/dist/orchestration/capabilities.d.ts.map +1 -1
  76. package/dist/orchestration/capabilities.js +1 -0
  77. package/dist/orchestration/capabilities.js.map +1 -1
  78. package/dist/orchestration/config.js +1 -1
  79. package/dist/orchestration/config.js.map +1 -1
  80. package/dist/orchestration/container.d.ts.map +1 -1
  81. package/dist/orchestration/container.js +48 -1
  82. package/dist/orchestration/container.js.map +1 -1
  83. package/dist/orchestration/context-footprint.d.ts.map +1 -1
  84. package/dist/orchestration/context-footprint.js +1 -1
  85. package/dist/orchestration/context-footprint.js.map +1 -1
  86. package/dist/orchestration/recovery.d.ts.map +1 -1
  87. package/dist/orchestration/recovery.js +27 -0
  88. package/dist/orchestration/recovery.js.map +1 -1
  89. package/dist/orchestration/report-promise.d.ts +9 -0
  90. package/dist/orchestration/report-promise.d.ts.map +1 -0
  91. package/dist/orchestration/report-promise.js +39 -0
  92. package/dist/orchestration/report-promise.js.map +1 -0
  93. package/dist/orchestration/restart-resume.d.ts +7 -1
  94. package/dist/orchestration/restart-resume.d.ts.map +1 -1
  95. package/dist/orchestration/restart-resume.js +22 -1
  96. package/dist/orchestration/restart-resume.js.map +1 -1
  97. package/dist/orchestration/runtime.d.ts +3 -0
  98. package/dist/orchestration/runtime.d.ts.map +1 -1
  99. package/dist/orchestration/runtime.js +32 -7
  100. package/dist/orchestration/runtime.js.map +1 -1
  101. package/dist/orchestration/tasks/driver.d.ts +1 -0
  102. package/dist/orchestration/tasks/driver.d.ts.map +1 -1
  103. package/dist/orchestration/tasks/driver.js +23 -3
  104. package/dist/orchestration/tasks/driver.js.map +1 -1
  105. package/dist/orchestration/tasks/service.d.ts +1 -3
  106. package/dist/orchestration/tasks/service.d.ts.map +1 -1
  107. package/dist/orchestration/tasks/service.js +5 -17
  108. package/dist/orchestration/tasks/service.js.map +1 -1
  109. package/dist/session/process.d.ts +15 -1
  110. package/dist/session/process.d.ts.map +1 -1
  111. package/dist/session/process.js +101 -15
  112. package/dist/session/process.js.map +1 -1
  113. package/dist/share/share-store.d.ts +10 -1
  114. package/dist/share/share-store.d.ts.map +1 -1
  115. package/dist/share/share-store.js +42 -1
  116. package/dist/share/share-store.js.map +1 -1
  117. package/dist/types.d.ts +7 -0
  118. package/dist/types.d.ts.map +1 -1
  119. package/dist/ui/voice-call-client.d.ts +27 -14
  120. package/dist/ui/voice-call-client.d.ts.map +1 -1
  121. package/dist/ui/voice-call-client.js +80 -24
  122. package/dist/ui/voice-call-client.js.map +1 -1
  123. package/dist/ui/voice-call-ui.d.ts +4 -1
  124. package/dist/ui/voice-call-ui.d.ts.map +1 -1
  125. package/dist/ui/voice-call-ui.js +65 -21
  126. package/dist/ui/voice-call-ui.js.map +1 -1
  127. package/dist/voice/errors.js +1 -1
  128. package/dist/voice/errors.js.map +1 -1
  129. package/dist/voice/notes.d.ts +4 -3
  130. package/dist/voice/notes.d.ts.map +1 -1
  131. package/dist/voice/notes.js +14 -11
  132. package/dist/voice/notes.js.map +1 -1
  133. package/dist/voice/telegram-avatar.d.ts +6 -2
  134. package/dist/voice/telegram-avatar.d.ts.map +1 -1
  135. package/dist/voice/telegram-avatar.js +23 -10
  136. package/dist/voice/telegram-avatar.js.map +1 -1
  137. package/dist/voice/turn-manager.d.ts.map +1 -1
  138. package/dist/voice/turn-manager.js +1 -1
  139. package/dist/voice/turn-manager.js.map +1 -1
  140. package/dist/voice/types.d.ts +3 -0
  141. package/dist/voice/types.d.ts.map +1 -1
  142. package/dist/voice/types.js +4 -0
  143. package/dist/voice/types.js.map +1 -1
  144. package/mcp/modules.ts +13 -1
  145. package/mcp/tools/api/module.ts +9 -1
  146. package/mcp/tools/discord/module.ts +44 -11
  147. package/mcp/tools/line/module.ts +11 -0
  148. package/mcp/tools/memory/disable-archive.test.ts +47 -0
  149. package/mcp/tools/memory/module.ts +2 -1
  150. package/mcp/tools/shared/isolate.ts +77 -0
  151. package/mcp/tools/shared/share-client.ts +15 -1
  152. package/mcp/tools/slack/module.ts +12 -5
  153. package/mcp/tools/telegram/attachment-log.ts +39 -0
  154. package/mcp/tools/telegram/module.ts +27 -11
  155. package/mcp/tools/telegram/receiver-server.ts +8 -0
  156. package/mcp/tools/wechat/module.ts +2 -0
  157. package/mcp/tools/whatsapp/module.ts +8 -1
  158. package/mcp/tools/whatsapp-cloud/module.ts +14 -7
  159. package/package.json +1 -1
package/mcp/modules.ts CHANGED
@@ -16,12 +16,24 @@ import { NarrateModule } from './tools/narrate/module';
16
16
  import { AppsModule } from './tools/apps/module';
17
17
  import { ApiModule } from './tools/api/module';
18
18
  import { MemoryModule } from './tools/memory/module';
19
+ import { isolateAllowsModule } from './tools/shared/isolate';
19
20
  import type { ChannelModule, ToolModule } from './types';
20
21
 
21
- /** Shared registration for execution and read-only capability discovery. */
22
+ /**
23
+ * Shared registration for execution and read-only capability discovery. In
24
+ * isolate mode the allowlist drops every module it does not name, so a module
25
+ * added here later is off for isolated conversations until allowlisted.
26
+ */
22
27
  export function gatewayModules(
23
28
  role?: string,
24
29
  media = false
30
+ ): Array<ChannelModule | ToolModule> {
31
+ return registeredModules(role, media).filter((m) => isolateAllowsModule(m.id));
32
+ }
33
+
34
+ function registeredModules(
35
+ role: string | undefined,
36
+ media: boolean
25
37
  ): Array<ChannelModule | ToolModule> {
26
38
  return role
27
39
  ? [
@@ -1,4 +1,5 @@
1
1
  import type { ToolModule, McpToolDefinition, McpToolResult, ToolVisibility } from '../../types';
2
+ import { resolveIsolateMediaPath } from '../shared/isolate';
2
3
 
3
4
  export class ApiModule implements ToolModule {
4
5
  id = 'api';
@@ -44,6 +45,13 @@ export class ApiModule implements ToolModule {
44
45
  return { content: [{ type: 'text', text: 'No files provided.' }] };
45
46
  }
46
47
 
48
+ let paths: string[];
49
+ try {
50
+ paths = files.map(resolveIsolateMediaPath);
51
+ } catch (err) {
52
+ return { content: [{ type: 'text', text: `api_reply: ${(err as Error).message}` }], isError: true };
53
+ }
54
+
47
55
  const apiUrl = process.env.GATEWAY_API_URL;
48
56
  const agentId = process.env.GATEWAY_AGENT_ID;
49
57
  const sessionId = process.env.GATEWAY_SESSION_ID;
@@ -65,7 +73,7 @@ export class ApiModule implements ToolModule {
65
73
  'Content-Type': 'application/json',
66
74
  ...(apiKey ? { 'X-Api-Key': apiKey } : {}),
67
75
  },
68
- body: JSON.stringify({ files }),
76
+ body: JSON.stringify({ files: paths }),
69
77
  signal: AbortSignal.timeout(5000),
70
78
  },
71
79
  );
@@ -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
+ });
@@ -34,7 +34,8 @@ export class MemoryModule implements ToolModule {
34
34
  // Available whenever the agent's workspace dir is known (same gate as skills).
35
35
  // Never in isolated memory mode (#601): the archive is one index over
36
36
  // every conversation's notes, so a search could return another conversation's data.
37
- return Boolean(process.env.GATEWAY_WORKSPACE_DIR) && !process.env.GATEWAY_ISOLATE_MEMORY;
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;
38
39
  }
39
40
 
40
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);
@@ -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
  })
@@ -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
  }
@@ -41,6 +41,7 @@ import { join, extname, sep } from 'path'
41
41
  import { execFileSync } from 'child_process'
42
42
  import { createWorkingStateManager, drainOrphanForwards, chunkText, htmlToPlain } from './typing'
43
43
  import { extractRepliedAttachment, safeName } from './reply-attachment'
44
+ import { recordChatAttachments } from './attachment-log'
44
45
  // Import compiled dist/, not raw src/ — src/ is not published (files: ["mcp/"]),
45
46
  // so a src/ import crashes this bun-run receiver on installed packages (the bug
46
47
  // that silenced every bot on systemd installs). Enforced by
@@ -1071,6 +1072,13 @@ async function handleInbound(
1071
1072
  // file_id so the agent can fetch it with download_attachment — without this a
1072
1073
  // quote-reply of e.g. a CSV dropped the file entirely.
1073
1074
  const repliedAttachment = extractRepliedAttachment(replyMsg)
1075
+ // Isolate mode downloads only the file_ids this chat was shown (#609).
1076
+ const repliedPhotoId = orchestrationSpool && replyMsg?.photo ? replyMsg.photo[replyMsg.photo.length - 1]!.file_id : undefined
1077
+ try {
1078
+ recordChatAttachments(STATE_DIR, chat_id, [attachment?.file_id, repliedPhotoId, repliedAttachment?.file_id].filter((id): id is string => Boolean(id)))
1079
+ } catch (err) {
1080
+ process.stderr.write(`telegram channel: failed to record attachment ids: ${err}\n`)
1081
+ }
1074
1082
 
1075
1083
  // image_path goes in meta only — an in-content "[image attached — read: PATH]"
1076
1084
  // annotation is forgeable by any allowlisted sender typing that string.
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import type { ToolModule, McpToolDefinition, McpToolResult, ToolVisibility } from '../../types';
16
16
  import { WeChatClient } from './client';
17
+ import { assertOriginChat } from '../shared/isolate';
17
18
 
18
19
  export class WeChatModule implements ToolModule {
19
20
  id = 'wechat';
@@ -78,6 +79,7 @@ export class WeChatModule implements ToolModule {
78
79
  };
79
80
  }
80
81
  try {
82
+ assertOriginChat(chatId);
81
83
  await this.getClient().send(chatId, text);
82
84
  return { content: [{ type: 'text', text: 'sent' }] };
83
85
  } catch (err) {
@@ -16,6 +16,7 @@
16
16
  * port, not through this MCP subprocess at all.
17
17
  */
18
18
  import type { ToolModule, McpToolDefinition, McpToolResult, ToolVisibility } from '../../types';
19
+ import { assertOriginChat, resolveIsolateMediaPath } from '../shared/isolate';
19
20
 
20
21
  export class WhatsAppModule implements ToolModule {
21
22
  id = 'whatsapp';
@@ -95,7 +96,7 @@ export class WhatsAppModule implements ToolModule {
95
96
  private async handleReply(args: Record<string, unknown>): Promise<McpToolResult> {
96
97
  const chatId = typeof args.chat_id === 'string' ? args.chat_id : '';
97
98
  const text = typeof args.text === 'string' ? args.text : '';
98
- const imagePath = typeof args.image_path === 'string' ? args.image_path : undefined;
99
+ let imagePath = typeof args.image_path === 'string' ? args.image_path : undefined;
99
100
  const accountId = typeof args.account_id === 'string' && args.account_id ? args.account_id : undefined;
100
101
  const replyTo =
101
102
  typeof args.reply_to_message_id === 'string' && args.reply_to_message_id
@@ -110,6 +111,12 @@ export class WhatsAppModule implements ToolModule {
110
111
  if (!chatId) {
111
112
  return { content: [{ type: 'text', text: 'whatsapp_reply: missing chat_id' }], isError: true };
112
113
  }
114
+ try {
115
+ assertOriginChat(chatId);
116
+ if (imagePath) imagePath = resolveIsolateMediaPath(imagePath);
117
+ } catch (err) {
118
+ return { content: [{ type: 'text', text: `whatsapp_reply: ${(err as Error).message}` }], isError: true };
119
+ }
113
120
  if (!text && !imagePath) {
114
121
  return {
115
122
  content: [{ type: 'text', text: 'whatsapp_reply: text or image_path is required' }],