arco-workbench 0.2.4 → 0.2.5

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 (253) hide show
  1. package/CONTRIBUTING.md +1 -1
  2. package/THIRD_PARTY_NOTICES +2 -2
  3. package/client/dist/assets/{PhosphorBackdrop-CHXVFLGT.js → PhosphorBackdrop-CLILIwOQ.js} +1 -1
  4. package/client/dist/assets/{ThemedBackgroundShaderImpl-Bhs4I9jA.js → ThemedBackgroundShaderImpl-B87chcb5.js} +1 -1
  5. package/client/dist/assets/{XtermView-CdfurwFx.js → XtermView-BP_j7WSN.js} +1 -1
  6. package/client/dist/assets/{galleryEditor-DYjZZ4cf.js → galleryEditor-B90phoBI.js} +1 -1
  7. package/client/dist/assets/{index-BjDmFvqG.js → index-BfPp1Oup.js} +269 -269
  8. package/client/dist/index.html +1 -1
  9. package/client/src/App.tsx +2 -2
  10. package/client/src/components/AuthReloginNotice.tsx +7 -6
  11. package/client/src/components/ChatMessage.tsx +41 -29
  12. package/client/src/components/ChatPanel.tsx +17 -4
  13. package/client/src/components/ClaudeNativeAccountPicker.tsx +32 -0
  14. package/client/src/components/ClaudeNativeAuthRow.tsx +71 -19
  15. package/client/src/components/ClusterRightPanel/AddWorkerSection.tsx +11 -281
  16. package/client/src/components/ClusterRightPanel/AutoPickupControl.tsx +1 -1
  17. package/client/src/components/ClusterRightPanel/FreshMemberForm.tsx +315 -0
  18. package/client/src/components/ClusterRightPanel/ReplaceMemberDialog.tsx +17 -7
  19. package/client/src/components/ClusterRightPanel/index.tsx +1 -1
  20. package/client/src/components/ClusterRightPanel/useFreshMemberPicker.ts +6 -4
  21. package/client/src/components/ClusterTab.tsx +2 -2
  22. package/client/src/components/Connections/Connections.tsx +5 -9
  23. package/client/src/components/Connections/model.ts +3 -1
  24. package/client/src/components/FileViewerModal.tsx +54 -17
  25. package/client/src/components/GitHubPanel/index.tsx +9 -5
  26. package/client/src/components/HandoffDialog.tsx +5 -3
  27. package/client/src/components/MobileShell.tsx +1 -33
  28. package/client/src/components/OperatorQuestionNotice.tsx +5 -4
  29. package/client/src/components/ProvidersPopover.tsx +6 -2
  30. package/client/src/components/RightPanel/ActivityTab.tsx +2 -1
  31. package/client/src/components/RightPanel/ConfigTab.tsx +23 -5
  32. package/client/src/components/RightPanel/OutputsPanel.tsx +21 -9
  33. package/client/src/components/RightPanel/outputsReconcile.ts +31 -0
  34. package/client/src/components/SettingsPanel.tsx +7 -10
  35. package/client/src/components/SpawnDialog.tsx +14 -3
  36. package/client/src/components/TabBar.tsx +2 -2
  37. package/client/src/components/TabContextMenu.tsx +73 -133
  38. package/client/src/components/TerminalInput.tsx +4 -3
  39. package/client/src/components/TranscriptWorkerDialog.tsx +14 -4
  40. package/client/src/components/UsageBar.tsx +37 -18
  41. package/client/src/components/WorkflowCreator/ClusterMembersSection.tsx +29 -3
  42. package/client/src/components/WorkflowCreator/index.tsx +29 -15
  43. package/client/src/components/WorkflowView.tsx +1 -1
  44. package/client/src/components/providerIndicator.ts +7 -3
  45. package/client/src/components/settings/GitHubAuthRow.tsx +34 -0
  46. package/client/src/explorer/ArtifactsLens.tsx +17 -8
  47. package/client/src/explorer/ExplorerApp.tsx +3 -3
  48. package/client/src/explorer/types.ts +3 -1
  49. package/client/src/help/content/cluster.tsx +10 -4
  50. package/client/src/help/content/composer.tsx +3 -2
  51. package/client/src/help/content/header.tsx +6 -3
  52. package/client/src/help/content/misc.tsx +7 -5
  53. package/client/src/help/content/rightPanel.tsx +8 -4
  54. package/client/src/help/content/settings.tsx +14 -3
  55. package/client/src/help/content/tabbar.tsx +1 -1
  56. package/client/src/help/manualSections/actions.tsx +5 -1
  57. package/client/src/help/manualSections/clusters.tsx +20 -14
  58. package/client/src/help/manualSections/configuration.tsx +6 -4
  59. package/client/src/help/manualSections/gettingStarted.tsx +4 -2
  60. package/client/src/help/manualSections/maintenance.tsx +24 -0
  61. package/client/src/help/manualSections/powerFeatures.tsx +1 -0
  62. package/client/src/help/manualSections/providers.tsx +11 -4
  63. package/client/src/help/manualSections/workspace.tsx +3 -3
  64. package/client/src/hooks/useClaudeNativeCatalog.ts +26 -0
  65. package/client/src/hooks/useClaudeNativeLogin.ts +16 -11
  66. package/client/src/hooks/useWebSocket.ts +4 -2
  67. package/client/src/layout/layoutRange.ts +4 -5
  68. package/client/src/questions/waitingQuestion.ts +2 -0
  69. package/client/src/stores/appStore.ts +5 -1
  70. package/client/src/stores/appStore.types.ts +2 -0
  71. package/client/src/stores/replayContext.ts +20 -0
  72. package/client/src/utils/chatFileLinks.ts +34 -3
  73. package/client/src/utils/claudeAuth.ts +9 -1
  74. package/client/src/ws/handleServerMessage.ts +11 -3
  75. package/docs/ARCHITECTURE.md +3 -3
  76. package/docs/BACKUP.md +1 -1
  77. package/docs/CLIENT.md +10 -5
  78. package/docs/EXTENDING.md +1 -1
  79. package/docs/FEATURES.md +3 -3
  80. package/docs/GETTING_STARTED.md +5 -4
  81. package/docs/GIT_WORKBENCH.md +8 -0
  82. package/docs/GLOSSARY.md +2 -2
  83. package/docs/GOTCHAS.md +4 -4
  84. package/docs/HTTP_API.md +54 -23
  85. package/docs/OPERATIONS.md +11 -0
  86. package/docs/OPERATOR_ACTIONS.md +2 -2
  87. package/docs/OUTPUTS.md +48 -6
  88. package/docs/PERSISTENCE.md +1 -1
  89. package/docs/PRIMITIVES.md +4 -2
  90. package/docs/PROTOCOL_CLUSTER.md +12 -6
  91. package/docs/PROTOCOL_PRIMITIVES.md +1 -1
  92. package/docs/PROVIDERS.md +46 -9
  93. package/docs/RESEARCH.md +1 -1
  94. package/docs/SETTINGS.md +9 -4
  95. package/node_modules/@arco/shared/dist/protocol/clusters.d.ts +15 -3
  96. package/node_modules/@arco/shared/dist/protocol/clusters.js +1 -1
  97. package/node_modules/@arco/shared/dist/protocol/models.d.ts +6 -1
  98. package/node_modules/@arco/shared/dist/protocol/operatorQuestions.d.ts +2 -1
  99. package/node_modules/@arco/shared/dist/protocol/settings.d.ts +3 -0
  100. package/node_modules/@arco/shared/dist/protocol/settings.js +5 -0
  101. package/node_modules/@arco/shared/dist/protocol/workflows.d.ts +1 -0
  102. package/node_modules/@arco/shared/dist/protocol/workflows.js +0 -2
  103. package/node_modules/@arco/shared/package.json +1 -1
  104. package/package.json +2 -2
  105. package/scripts/packaging/services.mjs +20 -1
  106. package/scripts/packaging/update.mjs +37 -2
  107. package/server/dist/attention.d.ts +6 -0
  108. package/server/dist/attention.js +6 -0
  109. package/server/dist/auth.d.ts +5 -0
  110. package/server/dist/auth.js +31 -20
  111. package/server/dist/clusterAutoTurn.d.ts +5 -1
  112. package/server/dist/clusterAutoTurn.js +31 -9
  113. package/server/dist/clusterPresets.js +3 -3
  114. package/server/dist/effortValidation.d.ts +2 -2
  115. package/server/dist/effortValidation.js +4 -4
  116. package/server/dist/explorerArtifacts.d.ts +1 -0
  117. package/server/dist/explorerArtifacts.js +12 -1
  118. package/server/dist/geminiMembers.d.ts +7 -1
  119. package/server/dist/geminiMembers.js +28 -14
  120. package/server/dist/http/conversationFiles.d.ts +36 -0
  121. package/server/dist/http/conversationFiles.js +222 -0
  122. package/server/dist/http/fileBytes.d.ts +3 -0
  123. package/server/dist/http/fileBytes.js +33 -0
  124. package/server/dist/http/fileContentRoute.d.ts +2 -0
  125. package/server/dist/http/fileContentRoute.js +139 -0
  126. package/server/dist/http/fileRead.d.ts +54 -2
  127. package/server/dist/http/fileRead.js +31 -24
  128. package/server/dist/http/outputRoutes.js +14 -21
  129. package/server/dist/http/readConfinement.d.ts +0 -11
  130. package/server/dist/http/readConfinement.js +4 -30
  131. package/server/dist/http/router.js +40 -66
  132. package/server/dist/index.js +26 -12
  133. package/server/dist/management/initHubLink.js +1 -1
  134. package/server/dist/outputs.js +8 -0
  135. package/server/dist/primitives/exportContext.d.ts +2 -0
  136. package/server/dist/primitives/exportContext.js +13 -2
  137. package/server/dist/primitives/runCompare.d.ts +7 -1
  138. package/server/dist/primitives/runCompare.js +44 -20
  139. package/server/dist/project/taskLedger.js +46 -34
  140. package/server/dist/providerAccounts.d.ts +4 -0
  141. package/server/dist/providerAccounts.js +20 -1
  142. package/server/dist/providers/antigravity/artifacts.d.ts +23 -0
  143. package/server/dist/providers/antigravity/artifacts.js +140 -0
  144. package/server/dist/providers/antigravity/index.js +85 -7
  145. package/server/dist/providers/antigravity/questions.d.ts +2 -0
  146. package/server/dist/providers/antigravity/questions.js +58 -0
  147. package/server/dist/providers/claude-native/auth.d.ts +9 -8
  148. package/server/dist/providers/claude-native/auth.js +50 -58
  149. package/server/dist/providers/claude-native/authStatus.d.ts +2 -2
  150. package/server/dist/providers/claude-native/authStatus.js +9 -7
  151. package/server/dist/providers/claude-native/catalog.d.ts +6 -5
  152. package/server/dist/providers/claude-native/catalog.js +50 -39
  153. package/server/dist/providers/claude-native/oauth.d.ts +10 -9
  154. package/server/dist/providers/claude-native/oauth.js +120 -96
  155. package/server/dist/providers/claude-native/worker.d.ts +1 -0
  156. package/server/dist/providers/claude-native/worker.js +38 -23
  157. package/server/dist/providers/codex-appserver/operatorQuestions.d.ts +5 -3
  158. package/server/dist/providers/codex-appserver/operatorQuestions.js +27 -13
  159. package/server/dist/server/broadcast.js +6 -0
  160. package/server/dist/settings.d.ts +1 -0
  161. package/server/dist/settings.js +39 -7
  162. package/server/dist/skills.js +1 -1
  163. package/server/dist/smartPickupAdapters.d.ts +1 -0
  164. package/server/dist/smartPickupAdapters.js +2 -2
  165. package/server/dist/smartPickupObserver.js +8 -5
  166. package/server/dist/thirdPartySkills.js +11 -5
  167. package/server/dist/usage.d.ts +1 -1
  168. package/server/dist/usage.js +39 -27
  169. package/server/dist/workers/WorkerManager.d.ts +1 -0
  170. package/server/dist/workers/WorkerManager.js +1 -0
  171. package/server/dist/workers/processKill.js +37 -24
  172. package/server/dist/workflowMeta.js +2 -2
  173. package/server/dist/ws/clusterHandlers.d.ts +2 -2
  174. package/server/dist/ws/clusterHandlers.js +127 -113
  175. package/server/dist/ws/clusterMembers.d.ts +1 -1
  176. package/server/dist/ws/clusterMembers.js +34 -4
  177. package/server/dist/ws/compactHandlers.js +30 -14
  178. package/server/dist/ws/compareHandlers.js +53 -21
  179. package/server/dist/ws/gateHandlers.js +2 -0
  180. package/server/dist/ws/genesisHandlers.js +5 -3
  181. package/server/dist/ws/handoffHandlers.d.ts +1 -1
  182. package/server/dist/ws/handoffHandlers.js +115 -39
  183. package/server/dist/ws/transcriptWorkerHandlers.js +7 -2
  184. package/server/dist/ws/turnEngine.js +33 -18
  185. package/server/dist/ws/updatePrimaryConfig.d.ts +3 -2
  186. package/server/dist/ws/updatePrimaryConfig.js +236 -133
  187. package/server/dist/ws/workflowHandlers.js +21 -4
  188. package/server/package.json +1 -1
  189. package/server/src/attention.ts +7 -0
  190. package/server/src/auth.ts +33 -20
  191. package/server/src/clusterAutoTurn.ts +31 -11
  192. package/server/src/clusterPresets.ts +2 -2
  193. package/server/src/effortValidation.ts +4 -4
  194. package/server/src/explorerArtifacts.ts +12 -1
  195. package/server/src/geminiMembers.ts +26 -15
  196. package/server/src/http/conversationFiles.ts +231 -0
  197. package/server/src/http/fileBytes.ts +34 -0
  198. package/server/src/http/fileContentRoute.ts +123 -0
  199. package/server/src/http/fileRead.ts +30 -25
  200. package/server/src/http/outputRoutes.ts +13 -13
  201. package/server/src/http/readConfinement.ts +3 -30
  202. package/server/src/http/router.ts +38 -62
  203. package/server/src/index.ts +27 -18
  204. package/server/src/management/initHubLink.ts +1 -1
  205. package/server/src/outputs.ts +8 -0
  206. package/server/src/primitives/exportContext.ts +14 -2
  207. package/server/src/primitives/runCompare.ts +73 -46
  208. package/server/src/project/taskLedger.ts +47 -30
  209. package/server/src/providerAccounts.ts +20 -1
  210. package/server/src/providers/antigravity/artifacts.ts +121 -0
  211. package/server/src/providers/antigravity/index.ts +64 -6
  212. package/server/src/providers/antigravity/questions.ts +52 -0
  213. package/server/src/providers/claude-native/auth.ts +45 -60
  214. package/server/src/providers/claude-native/authStatus.ts +9 -8
  215. package/server/src/providers/claude-native/catalog.ts +52 -35
  216. package/server/src/providers/claude-native/oauth.ts +101 -77
  217. package/server/src/providers/claude-native/worker.ts +38 -22
  218. package/server/src/providers/codex-appserver/operatorQuestions.ts +26 -12
  219. package/server/src/server/broadcast.ts +4 -0
  220. package/server/src/settings.ts +36 -8
  221. package/server/src/skills.ts +1 -1
  222. package/server/src/smartPickupAdapters.ts +3 -2
  223. package/server/src/smartPickupObserver.ts +8 -5
  224. package/server/src/thirdPartySkills.ts +11 -5
  225. package/server/src/usage.ts +30 -22
  226. package/server/src/workers/WorkerManager.ts +2 -0
  227. package/server/src/workers/processKill.ts +37 -23
  228. package/server/src/workflowMeta.ts +2 -2
  229. package/server/src/ws/clusterHandlers.ts +107 -104
  230. package/server/src/ws/clusterMembers.ts +25 -6
  231. package/server/src/ws/compactHandlers.ts +29 -15
  232. package/server/src/ws/compareHandlers.ts +59 -25
  233. package/server/src/ws/gateHandlers.ts +2 -0
  234. package/server/src/ws/genesisHandlers.ts +5 -4
  235. package/server/src/ws/handoffHandlers.ts +105 -37
  236. package/server/src/ws/transcriptWorkerHandlers.ts +6 -2
  237. package/server/src/ws/turnEngine.ts +32 -17
  238. package/server/src/ws/updatePrimaryConfig.ts +230 -132
  239. package/server/src/ws/workflowHandlers.ts +20 -4
  240. package/shared/dist/protocol/clusters.d.ts +15 -3
  241. package/shared/dist/protocol/clusters.js +1 -1
  242. package/shared/dist/protocol/models.d.ts +6 -1
  243. package/shared/dist/protocol/operatorQuestions.d.ts +2 -1
  244. package/shared/dist/protocol/settings.d.ts +3 -0
  245. package/shared/dist/protocol/settings.js +5 -0
  246. package/shared/dist/protocol/workflows.d.ts +1 -0
  247. package/shared/dist/protocol/workflows.js +0 -2
  248. package/shared/src/protocol/clusters.ts +23 -5
  249. package/shared/src/protocol/compare.ts +2 -2
  250. package/shared/src/protocol/models.ts +8 -4
  251. package/shared/src/protocol/operatorQuestions.ts +2 -1
  252. package/shared/src/protocol/settings.ts +8 -1
  253. package/shared/src/protocol/workflows.ts +1 -1
@@ -0,0 +1,231 @@
1
+ import path from 'node:path';
2
+ import { opendir } from 'node:fs/promises';
3
+ import * as clusters from '../clusterStore.js';
4
+ import { createReadAccessContext, FileAccessError, isPathWithin, safeDirectory, type ReadAccessContext } from '../fileAccessPolicy.js';
5
+ import { artifactsDir } from '../workers/limits.js';
6
+ import { resolveBoundCwd } from './writeConfinement.js';
7
+ import { resolveBrowserRead } from './readConfinement.js';
8
+
9
+ const WORKFLOW_ID = /^[a-z0-9_-]{1,64}$/i;
10
+ const MAX_ENTRIES = 8192;
11
+ const MAX_DEPTH = 12;
12
+ const MAX_CHOICES = 32;
13
+ const MAX_PEERS = 256;
14
+
15
+ interface Member {
16
+ workflowId: string;
17
+ name: string;
18
+ cwd: string;
19
+ canonicalCwd: string;
20
+ live: boolean;
21
+ }
22
+ interface SearchRoot {
23
+ dir: string;
24
+ member: Member;
25
+ artifacts: boolean;
26
+ }
27
+
28
+ export interface FileMatch {
29
+ path: string;
30
+ workflowId?: string;
31
+ name?: string;
32
+ artifact?: boolean;
33
+ }
34
+
35
+ const missing = (err: unknown) => ['ENOENT', 'ENOTDIR'].includes((err as NodeJS.ErrnoException).code ?? '');
36
+ const missingFile = () => Object.assign(new Error('File not found.'), { code: 'ENOENT' });
37
+ const artifactOwner = (file: string) => /(?:^|[\\/])\.arco[\\/]workflows[\\/]([^\\/]+)[\\/]artifacts(?:[\\/]|$)/i.exec(file)?.[1];
38
+
39
+ export async function conversationScope(viewerId: string, sourceId: string) {
40
+ if (!WORKFLOW_ID.test(viewerId) || (sourceId && !WORKFLOW_ID.test(sourceId))) throw new FileAccessError();
41
+ const id = clusters.getClusterIdForWorkflow(viewerId);
42
+ const stored = id ? await clusters.readCluster(id) : null;
43
+ const cluster = stored?.members.includes(viewerId) ? stored : null;
44
+ const members = new Map<string, Promise<Member>>();
45
+ const member = (workflowId: string): Promise<Member> => {
46
+ if (workflowId !== viewerId && !cluster?.members.includes(workflowId)) throw new FileAccessError();
47
+ let value = members.get(workflowId);
48
+ if (!value) {
49
+ value = (async () => {
50
+ const bound = await resolveBoundCwd(undefined, workflowId);
51
+ // Saved members may have a recorded working directory before the tab
52
+ // rehydrates. Only the current cluster record provides that binding.
53
+ const cwd = bound.ok ? bound.cwd : cluster ? clusters.memberCwdFor(cluster, workflowId) : null;
54
+ if (!cwd) throw new FileAccessError();
55
+ return { workflowId, cwd, canonicalCwd: safeDirectory(cwd), name: clusters.displayNameFor(workflowId), live: bound.ok };
56
+ })();
57
+ members.set(workflowId, value);
58
+ }
59
+ return value;
60
+ };
61
+ const viewer = await member(viewerId);
62
+ const source = sourceId ? await member(sourceId) : viewer;
63
+ return { source, member, memberIds: cluster?.members ?? [viewerId], clustered: !!cluster };
64
+ }
65
+
66
+ type ConversationScope = Awaited<ReturnType<typeof conversationScope>>;
67
+
68
+ function projectRoot(member: Member): SearchRoot { return { dir: member.canonicalCwd, member, artifacts: false }; }
69
+ function artifactRoot(member: Member): SearchRoot {
70
+ return { dir: artifactsDir(member.canonicalCwd, member.workflowId), member, artifacts: true };
71
+ }
72
+
73
+ function matchIn(root: SearchRoot, file: string): FileMatch {
74
+ return { path: file, workflowId: root.member.workflowId, name: root.artifacts ? root.member.name : 'Project', artifact: root.artifacts };
75
+ }
76
+
77
+ // Artifact paths must stay in their owner's artifact tree, including when an
78
+ // alias in the project resolved to that tree or the owner lives in a worktree.
79
+ async function checkArtifact(file: string, owner: string, scope: ConversationScope, access: ReadAccessContext): Promise<FileMatch> {
80
+ const root = artifactRoot(await scope.member(owner));
81
+ const writtenRoot = artifactsDir(root.member.cwd, owner);
82
+ if (!isPathWithin(root.dir, file) && !isPathWithin(writtenRoot, file)) throw new FileAccessError();
83
+ // A linked artifact root would make another directory the owner's tree.
84
+ if (await access.safeDirectory(root.dir) !== root.dir) throw new FileAccessError();
85
+ return matchIn(root, await access.confinedPath(file, [root.dir, writtenRoot]));
86
+ }
87
+
88
+ async function exactFile(file: string, member: Member, scope: ConversationScope, access: ReadAccessContext): Promise<FileMatch> {
89
+ const owner = artifactOwner(file);
90
+ if (owner) {
91
+ try { return await checkArtifact(file, owner, scope, access); }
92
+ catch (err) {
93
+ if (!missing(err)) throw err;
94
+ // Keep the link to an output moved through Arco's output index.
95
+ const producer = await scope.member(owner);
96
+ const tracked = await import('../outputs.js').then(m => m.resolveTrackedOutput(producer.cwd, owner, file)).catch(() => null);
97
+ if (!tracked) throw err;
98
+ const trackedOwner = artifactOwner(tracked);
99
+ return trackedOwner ? checkArtifact(tracked, trackedOwner, scope, access)
100
+ : { path: tracked, workflowId: owner, name: producer.name, artifact: true };
101
+ }
102
+ }
103
+ const real = member.live
104
+ ? await resolveBrowserRead(file, member.cwd, member.workflowId)
105
+ : await access.confinedPath(file, [member.cwd]);
106
+ const realOwner = artifactOwner(real);
107
+ return realOwner ? checkArtifact(real, realOwner, scope, access) : { path: real, workflowId: member.workflowId };
108
+ }
109
+
110
+ interface SearchResult { matches: FileMatch[]; searched: SearchRoot[]; truncated: boolean }
111
+ interface SearchBudget { entries: number; truncated: boolean }
112
+
113
+ // Directory enumeration is bounded across the whole request. Listings don't
114
+ // follow links or descend into hidden/runtime trees. A matching regular file
115
+ // and every directory are checked under the same root before use.
116
+ async function searchName(root: SearchRoot, name: string, access: ReadAccessContext,
117
+ matches: Map<string, FileMatch>, budget: SearchBudget): Promise<void> {
118
+ async function walk(dir: string, depth: number): Promise<void> {
119
+ if (budget.entries >= MAX_ENTRIES || matches.size >= MAX_CHOICES || depth > MAX_DEPTH) {
120
+ budget.truncated = true;
121
+ return;
122
+ }
123
+ try {
124
+ if (await access.confinedPath(dir, [root.dir], 'directory') !== dir) return;
125
+ for await (const entry of await opendir(dir)) {
126
+ if (budget.entries++ >= MAX_ENTRIES || matches.size >= MAX_CHOICES) {
127
+ budget.truncated = true;
128
+ break;
129
+ }
130
+ if (entry.name.startsWith('.') || ['node_modules', 'raw-tools'].includes(entry.name.toLowerCase())) continue;
131
+ const file = path.join(dir, entry.name);
132
+ if (entry.isDirectory()) await walk(file, depth + 1);
133
+ else if (entry.isFile() && (process.platform === 'win32' ? entry.name.toLowerCase() === name.toLowerCase() : entry.name === name)) {
134
+ const resolved = await access.confinedPath(file, [root.dir]).catch(err => {
135
+ if (missing(err) || err instanceof FileAccessError) return undefined;
136
+ throw err;
137
+ });
138
+ if (resolved === file) matches.set(file, matchIn(root, file));
139
+ }
140
+ }
141
+ } catch (err) {
142
+ if (!missing(err) && (err as NodeJS.ErrnoException).code !== 'EACCES' && (err as NodeJS.ErrnoException).code !== 'EPERM') throw err;
143
+ }
144
+ }
145
+ await walk(root.dir, 0);
146
+ }
147
+
148
+ export async function resolveConversationFile(asked: string, scope: ConversationScope,
149
+ options: { exact: boolean; sourceKnown: boolean; legacyOwner: string }): Promise<SearchResult> {
150
+ const { source } = scope;
151
+ const access = await createReadAccessContext();
152
+ if (!asked || asked.includes('\0')) throw new FileAccessError();
153
+ if (options.exact && !path.isAbsolute(asked)) throw new FileAccessError();
154
+ const absolute = path.resolve(source.cwd, asked);
155
+ access.assertSafePath(absolute);
156
+ const bare = !/[\\/]/.test(asked) && !asked.startsWith('.');
157
+ if (options.legacyOwner && (!bare || !scope.clustered || !scope.memberIds.includes(options.legacyOwner))) throw new FileAccessError();
158
+
159
+ const result: SearchResult = { matches: [], searched: [], truncated: false };
160
+ const matches = new Map<string, FileMatch>();
161
+ const budget: SearchBudget = { entries: 0, truncated: false };
162
+ const project = projectRoot(source);
163
+ const artifacts = artifactRoot(source);
164
+
165
+ const probe = async (read: () => Promise<FileMatch>, bestEffort = false) => {
166
+ try {
167
+ const match = await read();
168
+ matches.set(match.path, match);
169
+ } catch (err) {
170
+ if (!missing(err) && !(bestEffort && err instanceof FileAccessError)) throw err;
171
+ }
172
+ };
173
+ const finish = () => ({ ...result, matches: [...matches.values()], truncated: budget.truncated });
174
+
175
+ const qualified = path.isAbsolute(asked) || /^(?:\.\.?)[\\/]/.test(asked);
176
+ if (!path.isAbsolute(asked) && path.win32.isAbsolute(asked)) return finish();
177
+ if (!options.legacyOwner) {
178
+ result.searched.push(project);
179
+ await probe(() => exactFile(absolute, source, scope, access));
180
+ if (options.exact || qualified || (!bare && matches.size)) {
181
+ if (options.exact && matches.size && !matches.has(asked)) throw missingFile();
182
+ return finish();
183
+ }
184
+ }
185
+
186
+ const peerRoots = async (): Promise<SearchRoot[]> => {
187
+ const ids = options.legacyOwner ? [options.legacyOwner] : scope.memberIds.filter(id => id !== source.workflowId);
188
+ if (ids.length > MAX_PEERS) budget.truncated = true;
189
+ const roots: SearchRoot[] = [];
190
+ for (const id of ids.slice(0, MAX_PEERS)) {
191
+ const member = await scope.member(id).catch(err => {
192
+ if (err instanceof FileAccessError || missing(err)) return null;
193
+ throw err;
194
+ });
195
+ if (member) roots.push(artifactRoot(member));
196
+ }
197
+ return roots;
198
+ };
199
+
200
+ const search = async (roots: SearchRoot[], projectFallback?: SearchRoot) => {
201
+ for (const root of roots) {
202
+ const target = path.resolve(root.dir, asked);
203
+ if (!isPathWithin(root.dir, target)) continue;
204
+ result.searched.push(root);
205
+ await probe(() => checkArtifact(target, root.member.workflowId, scope, access), true);
206
+ if (matches.size >= MAX_CHOICES) {
207
+ budget.truncated = true;
208
+ return;
209
+ }
210
+ }
211
+ if (!bare) return;
212
+ for (const root of projectFallback ? [...roots, projectFallback] : roots) {
213
+ await searchName(root, asked, access, matches, budget);
214
+ if (budget.entries >= MAX_ENTRIES || matches.size >= MAX_CHOICES) {
215
+ budget.truncated = true;
216
+ break;
217
+ }
218
+ }
219
+ };
220
+
221
+ if (options.legacyOwner) {
222
+ await search(await peerRoots());
223
+ if (!matches.size) throw new FileAccessError();
224
+ } else if (options.sourceKnown) {
225
+ await search([artifacts], project);
226
+ if (!matches.size) await search(await peerRoots());
227
+ } else {
228
+ await search([artifacts, ...await peerRoots()], project);
229
+ }
230
+ return finish();
231
+ }
@@ -0,0 +1,34 @@
1
+ import type { FileHandle } from 'node:fs/promises';
2
+ import type { IncomingMessage, ServerResponse } from 'node:http';
3
+ import { pipeline } from 'node:stream/promises';
4
+
5
+ export async function sendFileBytes(req: IncomingMessage, res: ServerResponse, handle: FileHandle,
6
+ size: number, name: string, mime?: string): Promise<void> {
7
+ const range = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range || '');
8
+ // A multipart or malformed range is ignored. Browsers seek with one byte
9
+ // range, including open-ended ranges and suffixes (the tail of a PDF).
10
+ const partial = !!(range && (range[1] || range[2]));
11
+ const start = !partial ? 0 : range[1] ? Number(range[1]) : Math.max(0, size - Number(range[2]));
12
+ const end = partial && range[1] && range[2] ? Math.min(Number(range[2]), size - 1) : size - 1;
13
+ if (partial && (start > end || start >= size)) {
14
+ res.writeHead(416, { 'Content-Range': `bytes */${size}`, 'Accept-Ranges': 'bytes', 'Cache-Control': 'no-store' });
15
+ res.end();
16
+ return;
17
+ }
18
+ const encodedName = encodeURIComponent(Buffer.from(name).toString())
19
+ .replace(/['()*]/g, char => '%' + char.charCodeAt(0).toString(16).toUpperCase());
20
+ res.writeHead(partial ? 206 : 200, {
21
+ 'Content-Type': mime ?? 'application/octet-stream',
22
+ 'Cache-Control': 'no-store',
23
+ 'X-Content-Type-Options': 'nosniff',
24
+ // Native PDF viewers need an unsandboxed same-origin frame. The body
25
+ // still has a fixed PDF content type and cannot be sniffed as HTML.
26
+ 'Content-Security-Policy': mime === 'application/pdf' ? "default-src 'none'; frame-ancestors 'self'" : "sandbox; default-src 'none'",
27
+ 'Content-Disposition': `${mime ? 'inline' : 'attachment'}; filename*=UTF-8''${encodedName}`,
28
+ 'Accept-Ranges': 'bytes',
29
+ 'Content-Length': partial ? end - start + 1 : size,
30
+ ...(partial ? { 'Content-Range': `bytes ${start}-${end}/${size}` } : {}),
31
+ });
32
+ if (req.method === 'HEAD' || !size) res.end();
33
+ else await pipeline(handle.createReadStream({ autoClose: false, emitClose: false, start, end }), res);
34
+ }
@@ -0,0 +1,123 @@
1
+ import path from 'node:path';
2
+ import type { IncomingMessage, ServerResponse } from 'node:http';
3
+ import type { FileHandle } from 'node:fs/promises';
4
+ import { openCheckedFile } from '../checkedFile.js';
5
+ import { FileAccessError } from '../fileAccessPolicy.js';
6
+ import { geminiSessionKey, openGeminiArtifact } from '../providers/antigravity/artifacts.js';
7
+ import { outputContext } from '../outputs.js';
8
+ import { conversationScope, resolveConversationFile, type FileMatch } from './conversationFiles.js';
9
+ import { sendFileBytes } from './fileBytes.js';
10
+ import { readExplorerHandle } from './fileRead.js';
11
+ import { resolveBrowserRead } from './readConfinement.js';
12
+
13
+ const PREVIEW_MIME = new Map([
14
+ ['.mp3', 'audio/mpeg'], ['.wav', 'audio/wav'], ['.ogg', 'audio/ogg'], ['.opus', 'audio/ogg'],
15
+ ['.m4a', 'audio/mp4'], ['.aac', 'audio/aac'], ['.oga', 'audio/ogg'], ['.flac', 'audio/flac'],
16
+ ['.mp4', 'video/mp4'], ['.m4v', 'video/mp4'], ['.webm', 'video/webm'], ['.ogv', 'video/ogg'],
17
+ ['.mov', 'video/quicktime'], ['.pdf', 'application/pdf'],
18
+ ]);
19
+
20
+ const ROUTE = '/api/file-content';
21
+
22
+ function json(res: ServerResponse, status: number, body: unknown): true {
23
+ res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
24
+ res.end(JSON.stringify(body));
25
+ return true;
26
+ }
27
+
28
+ export async function tryHandleFileContent(req: IncomingMessage, res: ServerResponse): Promise<boolean> {
29
+ if (req.url?.split('?')[0] !== ROUTE || (req.method !== 'GET' && req.method !== 'HEAD')) return false;
30
+ const params = new URL(req.url, 'http://localhost').searchParams;
31
+ const asked = params.get('path') || '';
32
+ const cwd = params.get('cwd') || '';
33
+ const viewer = params.get('workflowId') || '';
34
+ const source = params.get('sourceWorkflowId') || '';
35
+ const legacyOwner = params.get('artifactOwner') || '';
36
+ const download = params.get('download') === '1';
37
+ const bytes = download || params.get('bytes') === '1';
38
+ const exact = bytes || params.get('exact') === '1';
39
+ if (req.method === 'HEAD' && !bytes) return false;
40
+
41
+ const selectedUrl = (match: FileMatch, mode?: 'bytes' | 'download') => {
42
+ const query = new URLSearchParams({ path: match.path, exact: '1' });
43
+ if (cwd) query.set('cwd', cwd);
44
+ if (viewer) query.set('workflowId', viewer);
45
+ if (match.workflowId) query.set('sourceWorkflowId', match.workflowId);
46
+ if (mode) query.set(mode, '1');
47
+ return ROUTE + '?' + query;
48
+ };
49
+ const respond = async (match: FileMatch, handle: FileHandle, size: number): Promise<true> => {
50
+ const mime = PREVIEW_MIME.get(path.extname(match.path).toLowerCase());
51
+ if (bytes) {
52
+ if (!download && !mime) throw new FileAccessError();
53
+ await sendFileBytes(req, res, handle, size, path.basename(match.path), download ? undefined : mime);
54
+ return true;
55
+ }
56
+ const payload = mime
57
+ ? { type: mime === 'application/pdf' ? 'pdf' : mime.split('/')[0], size, url: selectedUrl(match, 'bytes') }
58
+ : await readExplorerHandle(match.path, handle, size);
59
+ return json(res, 200, { ...payload, resolvedPath: match.path,
60
+ ...(match.artifact ? { artifactOwner: match.name } : {}),
61
+ ...(mime || payload.type === 'binary' || payload.type === 'too-large' ? { downloadUrl: selectedUrl(match, 'download') } : {}),
62
+ });
63
+ };
64
+
65
+ try {
66
+ if ((source && !viewer) || (legacyOwner && exact) || (exact && !path.isAbsolute(asked))) throw new FileAccessError();
67
+ const key = geminiSessionKey(asked);
68
+ if (key !== undefined) {
69
+ if (!key || !viewer || legacyOwner) throw new FileAccessError();
70
+ // Continue serving saved Gemini outputs through the manifest. When a
71
+ // message has a peer sender, authorize it before using that manifest.
72
+ const member = source && source !== viewer ? (await conversationScope(viewer, source)).source : undefined;
73
+ const ctx = await outputContext(member?.cwd ?? cwd, member?.workflowId ?? viewer).catch(() => { throw new FileAccessError(); });
74
+ const { file, handle, info } = await openGeminiArtifact(ctx.cwd, ctx.workflowId, { key });
75
+ try {
76
+ if (exact && file !== asked) return json(res, 404, { type: 'error', error: `File not found: ${asked}.` });
77
+ return await respond({ path: file, workflowId: ctx.workflowId }, handle, info.size);
78
+ } finally { await handle.close(); }
79
+ }
80
+
81
+ let match: FileMatch;
82
+ const scope = viewer ? await conversationScope(viewer, source).catch(err => {
83
+ // Older call sites can read a tracked output of a saved workflow even
84
+ // when it has no live tab. Keep the narrow tracked-output lookup below.
85
+ if (err instanceof FileAccessError && !source && !legacyOwner) return undefined;
86
+ throw err;
87
+ }) : undefined;
88
+ if (scope) {
89
+ const found = await resolveConversationFile(asked, scope, { exact, sourceKnown: Boolean(source), legacyOwner });
90
+ if (!exact && (found.matches.length > 1 || (found.truncated && found.matches.length > 0))) {
91
+ return json(res, 200, {
92
+ type: 'choices',
93
+ choices: found.matches.map(item => ({
94
+ workflowId: item.workflowId, name: item.name ?? 'Project', resolvedPath: item.path, readUrl: selectedUrl(item),
95
+ })),
96
+ ...(found.truncated ? { truncated: true } : {}),
97
+ });
98
+ }
99
+ const chosen = found.matches[0];
100
+ if (!chosen) {
101
+ const locations = found.searched.map(root => root.artifacts ? `${root.member.name} artifacts (${root.dir})` : root.dir);
102
+ const search = locations.length ? ` Searched: ${[...new Set(locations)].join(', ')}.` : '';
103
+ const limit = found.truncated ? ' Search reached its limit. Use a more specific path.' : '';
104
+ return json(res, 404, { type: 'error', error: `File not found: ${asked}.${search}${limit}` });
105
+ }
106
+ match = chosen;
107
+ } else {
108
+ if (legacyOwner) throw new FileAccessError();
109
+ const resolved = await resolveBrowserRead(asked, cwd, viewer);
110
+ if (exact && resolved !== asked) return json(res, 404, { type: 'error', error: `File not found: ${asked}.` });
111
+ match = { path: resolved };
112
+ }
113
+
114
+ const handle = await openCheckedFile(match.path);
115
+ try { return await respond(match, handle, (await handle.stat()).size); }
116
+ finally { await handle.close(); }
117
+ } catch (err) {
118
+ if (res.headersSent) { res.destroy(); return true; }
119
+ const code = (err as NodeJS.ErrnoException).code;
120
+ const message = code === 'ENOENT' || code === 'ENOTDIR' ? `File not found: ${asked}` : (err instanceof Error ? err.message : String(err));
121
+ return json(res, code === 'EACCES' ? 403 : 404, { type: 'error', error: message });
122
+ }
123
+ }
@@ -1,7 +1,5 @@
1
1
  import { openCheckedFile } from '../checkedFile.js';
2
- import { open } from 'fs/promises';
3
- import { constants } from 'fs';
4
- import { FileAccessError } from '../fileAccessPolicy.js';
2
+ import type { FileHandle } from 'fs/promises';
5
3
  import { extname, resolve } from 'path';
6
4
  import { MAX_TEXT_SIZE, MAX_IMAGE_SIZE } from '../server/constants.js';
7
5
 
@@ -17,29 +15,36 @@ const IMAGE_MIME: Record<string, string> = {
17
15
  };
18
16
 
19
17
  export async function readFileForExplorer(path: string) {
20
- const ext = extname(path).toLowerCase();
21
18
  const handle = await openCheckedFile(path);
22
- try {
23
- const stats = await handle.stat();
24
- if (!stats.isFile()) throw new FileAccessError();
25
- const size = stats.size;
26
- if (IMAGE_MIME[ext]) {
27
- if (size > MAX_IMAGE_SIZE) return { type: 'too-large' as const, size, kind: 'image' as const };
28
- const buf = await handle.readFile();
29
- return {
30
- type: 'image' as const,
31
- dataUrl: `data:${IMAGE_MIME[ext]};base64,${buf.toString('base64')}`,
32
- size,
33
- };
34
- }
35
- if (size > MAX_TEXT_SIZE) return { type: 'too-large' as const, size, kind: 'text' as const };
36
- const buf = await handle.readFile();
37
- const sample = buf.subarray(0, Math.min(8192, buf.length));
38
- if (sample.includes(0)) {
39
- return { type: 'binary' as const, size };
40
- }
41
- return { type: 'text' as const, content: buf.toString('utf-8'), size };
42
- } finally { await handle.close(); }
19
+ try { return await readExplorerHandle(path, handle, (await handle.stat()).size); }
20
+ finally { await handle.close(); }
21
+ }
22
+
23
+ // Use the handle that passed authorization and stop at the inspected length,
24
+ // even if the producer appends bytes while the preview is loading.
25
+ export async function readExplorerHandle(path: string, handle: FileHandle, size: number) {
26
+ const mime = IMAGE_MIME[extname(path).toLowerCase()];
27
+ if (size > (mime ? MAX_IMAGE_SIZE : MAX_TEXT_SIZE)) return { type: 'too-large' as const, size, kind: mime ? 'image' : 'text' };
28
+ const buffer = Buffer.alloc(size);
29
+ let offset = 0;
30
+ while (offset < size) {
31
+ const { bytesRead } = await handle.read(buffer, offset, size - offset, offset);
32
+ if (!bytesRead) break;
33
+ offset += bytesRead;
34
+ }
35
+ const bytes = buffer.subarray(0, offset);
36
+ if (mime) return { type: 'image' as const, dataUrl: `data:${mime};base64,${bytes.toString('base64')}`, size: offset };
37
+ if (bytes.subarray(0, 8192).includes(0)) return { type: 'binary' as const, size: offset };
38
+ return { type: 'text' as const, content: bytes.toString('utf8'), size: offset };
39
+ }
40
+
41
+ // Media playback uses the same exact output id and bounded download handle.
42
+ export function readGeminiPreview(file: string, handle: FileHandle, size: number, ctx: { cwd: string; workflowId: string }, id: string) {
43
+ const ext = extname(file).toLowerCase();
44
+ const type = ['.mp3', '.wav', '.ogg', '.m4a', '.flac', '.opus'].includes(ext) ? 'audio'
45
+ : ['.mp4', '.webm', '.mov'].includes(ext) ? 'video' : null;
46
+ if (type) return { type, size, url: '/api/outputs/file?' + new URLSearchParams({ cwd: ctx.cwd, workflowId: ctx.workflowId, id }) };
47
+ return readExplorerHandle(file, handle, size);
43
48
  }
44
49
 
45
50
  // Claude CLI stores historical transcripts at
@@ -1,7 +1,6 @@
1
1
  import { openCheckedFile } from '../checkedFile.js';
2
2
  import { constants } from 'node:fs';
3
3
  import { open, lstat } from 'node:fs/promises';
4
- import { pipeline } from 'node:stream/promises';
5
4
  import type { IncomingMessage, ServerResponse } from 'node:http';
6
5
  import type { WorkflowOutput } from '@arco/shared';
7
6
  import { getClusterCached, displayNameFor } from '../clusterStore.js';
@@ -9,9 +8,11 @@ import { listOutputs, outputContext, readOutput, saveOutputText, transferOutput
9
8
  import { outputDirectory, readOutputIndex } from '../outputStore.js';
10
9
  import { keepCovering, readKeep } from '../keepStore.js';
11
10
  import path from 'node:path';
12
- import { readFileForExplorer } from '../http/fileRead.js';
11
+ import { openGeminiArtifact } from '../providers/antigravity/artifacts.js';
12
+ import { readExplorerHandle, readGeminiPreview } from './fileRead.js';
13
+ import { sendFileBytes } from './fileBytes.js';
13
14
  import { REFUSED_EXTENSIONS, desktopOpenAvailable, isLoopbackAddress, launchOpener, openerCommand, refusalFor } from './outputOpen.js';
14
- const MIME: Record<string, string> = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', wav: 'audio/wav', mp3: 'audio/mpeg', ogg: 'audio/ogg', flac: 'audio/flac', m4a: 'audio/mp4', mp4: 'video/mp4', webm: 'video/webm', mov: 'video/quicktime' };
15
+ const MIME: Record<string, string> = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', opus: 'audio/ogg', wav: 'audio/wav', mp3: 'audio/mpeg', ogg: 'audio/ogg', flac: 'audio/flac', m4a: 'audio/mp4', mp4: 'video/mp4', webm: 'video/webm', mov: 'video/quicktime' };
15
16
  function json(res: ServerResponse, status: number, body: unknown): true { res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(body)); return true; }
16
17
  async function bodyOf(req: IncomingMessage): Promise<Record<string, unknown>> {
17
18
  let text = '';
@@ -52,20 +53,19 @@ export async function tryHandleOutputRoutes(req: IncomingMessage, res: ServerRes
52
53
  const inline = (await readOutputIndex(ctx.cwd, ctx.workflowId)).entries.find(entry => entry.id === id)?.inline;
53
54
  if (inline) return json(res, 200, { type: 'text', content: inline.content, size: Buffer.byteLength(inline.content) });
54
55
  }
55
- const { entry, file } = await readOutput(ctx, id);
56
- if (url.pathname === '/api/outputs/content') return json(res, 200, await readFileForExplorer(file));
57
- const handle = await openCheckedFile(file);
56
+ const gemini = id.startsWith('gemini-') ? await openGeminiArtifact(ctx.cwd, ctx.workflowId, { id }) : null;
57
+ const file = gemini?.file ?? (await readOutput(ctx, id)).file;
58
+ const name = path.basename(file);
59
+ const handle = gemini?.handle ?? await openCheckedFile(file);
58
60
  try {
59
- const info = await handle.stat();
61
+ const info = gemini?.info ?? await handle.stat();
60
62
  if (!info.isFile()) throw new Error('Output is not a regular file.');
61
- const ext = entry.name.split('.').pop()?.toLowerCase() || '';
63
+ if (url.pathname === '/api/outputs/content') return json(res, 200, gemini
64
+ ? await readGeminiPreview(file, handle, info.size, ctx, id) : await readExplorerHandle(file, handle, info.size));
65
+ const ext = name.split('.').pop()?.toLowerCase() || '';
62
66
  // Active formats and unknown binaries are downloads, never executable previews.
63
67
  const preview = url.searchParams.get('download') !== '1' && !!MIME[ext];
64
- const range = /^bytes=(\d+)-(\d*)$/.exec(req.headers.range || '');
65
- const start = range ? Number(range[1]) : 0, end = range?.[2] ? Math.min(Number(range[2]), info.size - 1) : info.size - 1;
66
- if (range && (start > end || start >= info.size)) { res.writeHead(416, { 'Content-Range': `bytes */${info.size}` }); res.end(); return true; }
67
- res.writeHead(range ? 206 : 200, { 'Content-Type': preview ? MIME[ext] : 'application/octet-stream', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "sandbox; default-src 'none'", 'Content-Disposition': `${preview ? 'inline' : 'attachment'}; filename*=UTF-8''${encodeURIComponent(entry.name)}`, 'Accept-Ranges': 'bytes', 'Content-Length': range ? end - start + 1 : info.size, ...(range ? { 'Content-Range': `bytes ${start}-${end}/${info.size}` } : {}) });
68
- if (info.size) await pipeline(handle.createReadStream({ autoClose: false, emitClose: false, start, end }), res); else res.end();
68
+ await sendFileBytes(req, res, handle, info.size, name, preview ? MIME[ext] : undefined);
69
69
  return true;
70
70
  } finally { await handle.close(); }
71
71
  }
@@ -8,7 +8,7 @@ import { UPLOADS_DIR } from '../server/constants.js';
8
8
  import { SCRATCH_ROOT } from '../media/scratch.js';
9
9
  import { artifactsDir } from '../workers/limits.js';
10
10
  import { resolveWorktreeFile } from './browserWorktrees.js';
11
- import * as clusterStore from '../clusterStore.js';
11
+ import { geminiSessionKey } from '../providers/antigravity/artifacts.js';
12
12
 
13
13
  export async function readRoots(cwd?: string | null, workflowId?: string | null): Promise<string[]> {
14
14
  const bound = await resolveBoundCwd(cwd, workflowId);
@@ -18,6 +18,8 @@ export async function readRoots(cwd?: string | null, workflowId?: string | null)
18
18
 
19
19
  export async function resolveBrowserRead(p: string, cwd?: string | null, workflowId?: string | null, kind: 'file' | 'directory' = 'file'): Promise<string> {
20
20
  if (!p || p.includes('\0')) throw new FileAccessError();
21
+ // Session files are served only by the workflow-bound handle reader.
22
+ if (geminiSessionKey(p) !== undefined) throw new FileAccessError();
21
23
  if (workflowId && cwd && kind === 'file') {
22
24
  assertSafePath(path.resolve(cwd, p));
23
25
  const tracked = await import('../outputs.js').then(m => m.resolveTrackedOutput(cwd, workflowId, p)).catch(() => null);
@@ -44,35 +46,6 @@ export async function resolveBrowserRead(p: string, cwd?: string | null, workflo
44
46
  }
45
47
  }
46
48
 
47
- // Search only a bound conversation's cluster members after ordinary resolution
48
- // has failed. Every candidate goes through the existing workflow-document guard.
49
- export async function clusterArtifactMatches(cwd: string, workflowId: string, name: string): Promise<{
50
- searched: Array<{ workflowId: string; name: string }>;
51
- matches: Array<{ workflowId: string; name: string; path: string }>;
52
- } | null> {
53
- if (!name || path.basename(name) !== name || name.includes('\\') || name.startsWith('.')) return null;
54
- const bound = await resolveBoundCwd(cwd, workflowId);
55
- const clusterId = clusterStore.getClusterIdForWorkflow(workflowId);
56
- const cluster = clusterId ? await clusterStore.readCluster(clusterId) : null;
57
- if (!bound.ok || !cluster || !cluster.members.includes(workflowId)) return null;
58
- const searched = cluster.members.map((id) => ({ workflowId: id, name: clusterStore.displayNameFor(id) }));
59
- const matches: Array<{ workflowId: string; name: string; path: string }> = [];
60
- for (const member of searched) {
61
- try {
62
- const memberBound = await resolveBoundCwd(cluster.cwd, member.workflowId);
63
- const memberCwd = memberBound.ok ? memberBound.cwd : cluster.cwd;
64
- const resolved = await resolveWorkflowDocument(memberCwd, member.workflowId, 'artifacts', name);
65
- const root = artifactsDir(memberCwd, member.workflowId);
66
- // Tracked outputs can resolve outside artifacts; this fallback cannot.
67
- const checked = confinedPath(resolved, [root]);
68
- matches.push({ ...member, path: checked });
69
- } catch (err) {
70
- if ((err as NodeJS.ErrnoException).code !== 'ENOENT' && !(err instanceof FileAccessError)) throw err;
71
- }
72
- }
73
- return { searched, matches };
74
- }
75
-
76
49
  // The project picker grants directory names only, not file content. Ordinary
77
50
  // absolute locations may be navigated without pre-registering every ancestor
78
51
  // (mounts, network shares, Windows drives); protected roots are never listed.