arco-workbench 0.1.8 → 0.1.9

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 (145) hide show
  1. package/CONTRIBUTING.md +11 -0
  2. package/README.md +7 -5
  3. package/client/dist/assets/{PhosphorBackdrop-D7jdAV_G.js → PhosphorBackdrop-DRu16-Is.js} +1 -1
  4. package/client/dist/assets/{ThemedBackgroundShaderImpl-DrDm60h8.js → ThemedBackgroundShaderImpl-BLdwwQ4D.js} +1 -1
  5. package/client/dist/assets/{XtermView-BGFujb1e.js → XtermView-Xk7_9JaH.js} +1 -1
  6. package/client/dist/assets/{galleryEditor-D951A2sE.js → galleryEditor-CI8ClzBa.js} +1 -1
  7. package/client/dist/assets/{index-DD9kFGsF.css → index-BEFgrUJJ.css} +1 -1
  8. package/client/dist/assets/{index-CsVy3eZm.js → index-C7WzZfsr.js} +246 -244
  9. package/client/dist/index.html +2 -2
  10. package/client/src/App.tsx +2 -0
  11. package/client/src/components/ChatMessage.tsx +33 -8
  12. package/client/src/components/ChatModeView.tsx +2 -0
  13. package/client/src/components/ClusterRightPanel/SkillsControl.tsx +25 -8
  14. package/client/src/components/CodexLateCommand.tsx +34 -0
  15. package/client/src/components/DialogShell.tsx +2 -0
  16. package/client/src/components/MemberCard.tsx +4 -1
  17. package/client/src/components/MemberPane.tsx +3 -1
  18. package/client/src/components/PhoneUpload.tsx +288 -0
  19. package/client/src/components/PrimaryStatus.tsx +14 -6
  20. package/client/src/components/RuntimeStateBanner.tsx +5 -0
  21. package/client/src/components/SkillEditorDialog.tsx +2 -2
  22. package/client/src/components/SkillsSettings.tsx +17 -5
  23. package/client/src/components/TerminalInput.tsx +3 -1
  24. package/client/src/components/WorkflowView.tsx +2 -0
  25. package/client/src/explorer/ArtifactsLens.tsx +37 -28
  26. package/client/src/explorer/ExplorerApp.tsx +5 -4
  27. package/client/src/explorer/types.ts +8 -3
  28. package/client/src/help/content/cluster.tsx +11 -1
  29. package/client/src/help/content/composer.tsx +18 -1
  30. package/client/src/help/content/header.tsx +2 -1
  31. package/client/src/help/content/misc.tsx +1 -1
  32. package/client/src/help/content/settings.tsx +1 -1
  33. package/client/src/help/manualSections/clusters.tsx +3 -0
  34. package/client/src/help/manualSections/configuration.tsx +3 -1
  35. package/client/src/help/manualSections/gettingStarted.tsx +4 -4
  36. package/client/src/help/manualSections/maintenance.tsx +7 -6
  37. package/client/src/help/manualSections/powerFeatures.tsx +3 -2
  38. package/client/src/help/manualSections/workspace.tsx +30 -0
  39. package/client/src/stores/appStore.ts +7 -0
  40. package/client/src/stores/appStore.types.ts +4 -0
  41. package/client/src/styles/global.css +109 -0
  42. package/client/src/utils/phoneTheme.ts +38 -0
  43. package/client/src/utils/phoneUploadApi.ts +10 -0
  44. package/client/src/ws/handleServerMessage.ts +23 -6
  45. package/docs/CLIENT.md +7 -1
  46. package/docs/FEATURES.md +6 -3
  47. package/docs/GETTING_STARTED.md +8 -3
  48. package/docs/INDEX.md +1 -1
  49. package/docs/OPERATIONS.md +199 -48
  50. package/docs/PROTOCOL_CLUSTER.md +9 -1
  51. package/docs/PROVIDERS.md +34 -0
  52. package/docs/SETTINGS.md +5 -3
  53. package/native/darwin-arm64/manifest.json +1 -1
  54. package/native/linux-x64/manifest.json +1 -1
  55. package/native/win32-x64/manifest.json +1 -1
  56. package/node_modules/@arco/shared/dist/protocol/chat.d.ts +1 -0
  57. package/node_modules/@arco/shared/dist/protocol/clusters.d.ts +2 -0
  58. package/node_modules/@arco/shared/dist/protocol/serverMessages.d.ts +11 -0
  59. package/node_modules/@arco/shared/dist/protocol/workflows.d.ts +1 -0
  60. package/node_modules/@arco/shared/package.json +1 -1
  61. package/package.json +2 -2
  62. package/server/dist/clusterDirector.js +1 -0
  63. package/server/dist/clusterPeerOps.js +4 -1
  64. package/server/dist/clusterRehydrate.js +2 -0
  65. package/server/dist/explorerDocs.d.ts +10 -6
  66. package/server/dist/explorerDocs.js +75 -34
  67. package/server/dist/http/attachmentUpload.d.ts +13 -0
  68. package/server/dist/http/attachmentUpload.js +38 -0
  69. package/server/dist/http/browserWorktrees.d.ts +23 -0
  70. package/server/dist/http/browserWorktrees.js +120 -0
  71. package/server/dist/http/phoneUploadDrafts.d.ts +13 -0
  72. package/server/dist/http/phoneUploadDrafts.js +125 -0
  73. package/server/dist/http/phoneUploadListener.d.ts +17 -0
  74. package/server/dist/http/phoneUploadListener.js +81 -0
  75. package/server/dist/http/phoneUploadNetwork.d.ts +9 -0
  76. package/server/dist/http/phoneUploadNetwork.js +106 -0
  77. package/server/dist/http/phoneUploadPage.d.ts +2 -0
  78. package/server/dist/http/phoneUploadPage.js +136 -0
  79. package/server/dist/http/phoneUploadRouteHistory.d.ts +4 -0
  80. package/server/dist/http/phoneUploadRouteHistory.js +72 -0
  81. package/server/dist/http/phoneUploadRoutes.d.ts +4 -0
  82. package/server/dist/http/phoneUploadRoutes.js +419 -0
  83. package/server/dist/http/phoneUploadTheme.d.ts +17 -0
  84. package/server/dist/http/phoneUploadTheme.js +96 -0
  85. package/server/dist/http/projectBinding.d.ts +1 -0
  86. package/server/dist/http/projectBinding.js +3 -2
  87. package/server/dist/http/readConfinement.js +5 -1
  88. package/server/dist/http/router.js +13 -24
  89. package/server/dist/http/writeConfinement.js +19 -2
  90. package/server/dist/primitives/seedWorker.d.ts +1 -0
  91. package/server/dist/primitives/seedWorker.js +2 -1
  92. package/server/dist/providers/codex-appserver/heldCommands.d.ts +14 -0
  93. package/server/dist/providers/codex-appserver/heldCommands.js +54 -0
  94. package/server/dist/providers/codex-appserver/index.d.ts +52 -2
  95. package/server/dist/providers/codex-appserver/index.js +239 -21
  96. package/server/dist/providers/codex-appserver/lateCommands.d.ts +62 -0
  97. package/server/dist/providers/codex-appserver/lateCommands.js +195 -0
  98. package/server/dist/providers/codex-appserver/worker.d.ts +23 -1
  99. package/server/dist/providers/codex-appserver/worker.js +89 -20
  100. package/server/dist/providers/codex.js +2 -2
  101. package/server/dist/providers/codexCodeMode.d.ts +2 -1
  102. package/server/dist/providers/codexCodeMode.js +7 -3
  103. package/server/dist/workers/WorkerManager.d.ts +1 -0
  104. package/server/dist/workers/WorkerManager.js +1 -0
  105. package/server/dist/workers/processKill.d.ts +9 -1
  106. package/server/dist/workers/processKill.js +26 -10
  107. package/server/dist/ws/handoffHandlers.js +2 -0
  108. package/server/dist/ws/turnEngine.js +17 -0
  109. package/server/package.json +1 -1
  110. package/server/src/clusterDirector.ts +1 -0
  111. package/server/src/clusterPeerOps.ts +4 -1
  112. package/server/src/clusterRehydrate.ts +2 -0
  113. package/server/src/explorerDocs.ts +75 -34
  114. package/server/src/http/attachmentUpload.ts +49 -0
  115. package/server/src/http/browserWorktrees.ts +124 -0
  116. package/server/src/http/phoneUploadDrafts.ts +118 -0
  117. package/server/src/http/phoneUploadListener.ts +96 -0
  118. package/server/src/http/phoneUploadNetwork.ts +117 -0
  119. package/server/src/http/phoneUploadPage.ts +137 -0
  120. package/server/src/http/phoneUploadRouteHistory.ts +73 -0
  121. package/server/src/http/phoneUploadRoutes.ts +398 -0
  122. package/server/src/http/phoneUploadTheme.ts +97 -0
  123. package/server/src/http/projectBinding.ts +3 -2
  124. package/server/src/http/readConfinement.ts +5 -1
  125. package/server/src/http/router.ts +11 -25
  126. package/server/src/http/writeConfinement.ts +13 -2
  127. package/server/src/primitives/seedWorker.ts +3 -1
  128. package/server/src/providers/codex-appserver/heldCommands.ts +58 -0
  129. package/server/src/providers/codex-appserver/index.ts +222 -20
  130. package/server/src/providers/codex-appserver/lateCommands.ts +225 -0
  131. package/server/src/providers/codex-appserver/worker.ts +85 -21
  132. package/server/src/providers/codex.ts +2 -2
  133. package/server/src/providers/codexCodeMode.ts +8 -3
  134. package/server/src/workers/WorkerManager.ts +2 -0
  135. package/server/src/workers/processKill.ts +35 -7
  136. package/server/src/ws/handoffHandlers.ts +2 -0
  137. package/server/src/ws/turnEngine.ts +15 -0
  138. package/shared/dist/protocol/chat.d.ts +1 -0
  139. package/shared/dist/protocol/clusters.d.ts +2 -0
  140. package/shared/dist/protocol/serverMessages.d.ts +11 -0
  141. package/shared/dist/protocol/workflows.d.ts +1 -0
  142. package/shared/src/protocol/chat.ts +1 -0
  143. package/shared/src/protocol/clusters.ts +4 -5
  144. package/shared/src/protocol/serverMessages.ts +11 -0
  145. package/shared/src/protocol/workflows.ts +4 -0
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arco/server",
3
- "version": "0.1.8",
3
+ "version": "0.1.9",
4
4
  "private": true,
5
5
  "type": "module"
6
6
  }
@@ -14,6 +14,7 @@ export function buildClusterDirectorDoctrine(role: string | undefined): string |
14
14
  'You are the operator-assigned Director of THIS Arco cluster: you coordinate, read the diff, and land. Peers implement, build, and test.',
15
15
  'At the start of each turn, inspect pending peer mail. If the injected shared plan is marked OUTLINE, call cluster_plan_read before deciding what to do.',
16
16
  'Reconcile relevant tasks, new peer evidence, repository state and applicable project instructions before reporting status. Read the broader plan or history when relevant or stale. Check an operator problem against the affected priorities and open items before asking them anything.',
17
+ 'Answer the operator first. If an issue remains open, recommend the next step, name who owns the work, and say what the operator needs to decide or do and when, if anything. You own coordination with workers. When a worker already owns the follow-up and the operator has nothing to do, say so. Promise later follow-up only when an available trigger can wake you; otherwise explain who must act and when. Ask the operator to nudge the Director only when progress depends on it. New work waits for the operator\'s approval; continue already approved work as usual.',
17
18
  'When this cluster has an Advisor, consult it before a design decision or when the evidence is thin; the decision remains yours.',
18
19
  'Delegate implementation, builds, and test runs only through peer_send and track them on the board. Do not write or edit product code or tests yourself.',
19
20
  'Stay available to the operator. Hand long-running work to peers: the project\'s checks to the tester (or a builder when there is no tester), CI watching to the change\'s author. Use their reports of what was done, run and not covered; do not run builds, test suites or CI waits yourself.',
@@ -363,6 +363,7 @@ export async function peerSend(
363
363
  artifacts.push({ name: basename(abs), contentBase64: data.toString('base64'), byteLength: data.byteLength });
364
364
  }
365
365
  }
366
+ const createdAt = new Date().toISOString();
366
367
  try {
367
368
  await clusterMailbox.enqueue(resolved, {
368
369
  msgId,
@@ -370,7 +371,7 @@ export async function peerSend(
370
371
  fromDisplayName,
371
372
  toWorkflowId: resolved,
372
373
  content: args.content,
373
- createdAt: new Date().toISOString(),
374
+ createdAt,
374
375
  delivered: false,
375
376
  ...(artifacts?.length ? { artifacts } : {}),
376
377
  }, opts?.maxContentBytes !== undefined ? { maxContentBytes: opts.maxContentBytes } : undefined);
@@ -398,6 +399,8 @@ export async function peerSend(
398
399
  from: ctx.workflowId,
399
400
  to: resolved,
400
401
  contentPreview: args.content.length > 200 ? `${args.content.slice(0, 200)}…` : args.content,
402
+ content: args.content,
403
+ ts: Date.parse(createdAt),
401
404
  });
402
405
  const warning = guard && clusterBudget.takeWarning(ctx.workflowId, guard, guardDecision!.count)
403
406
  ? `Warn-only threshold exceeded: ${guardDecision!.count}/${guard.threshold} peer messages this primary turn. Mail accepted. Consolidate related same-recipient information; required work and review still apply.`
@@ -53,6 +53,8 @@ export async function rehydrateClusterOnce(
53
53
  from: m.fromWorkflowId,
54
54
  to: m.toWorkflowId,
55
55
  contentPreview: m.content.length > 200 ? `${m.content.slice(0, 200)}…` : m.content,
56
+ content: m.content,
57
+ ...(Number.isFinite(Date.parse(m.createdAt)) ? { ts: Date.parse(m.createdAt) } : {}),
56
58
  };
57
59
  // broadcastWorkflow stamps the event into the SENDER's events.jsonl
58
60
  // and fans out to that workflow's live observers. The cluster
@@ -1,6 +1,8 @@
1
1
  import { scanBeforeDeadline } from './scanDeadline.js';
2
2
  import { projectFiles, scanBudget, exhausted, type ScanBudget } from './projectScan.js';
3
- import { confinedPath } from './fileAccessPolicy.js';
3
+ import { confinedPath, createReadAccessContext } from './fileAccessPolicy.js';
4
+ import { resolveBoundCwd } from './http/writeConfinement.js';
5
+ import { browserWorktreeFile, browserWorktreeRegistry, confirmBrowserWorktree } from './http/browserWorktrees.js';
4
6
  // ARCHIVE (docs/CLIENT.md) - project-DOCUMENT scan. The ARTIFACTS
5
7
  // lens is a project-artifact tool, and the documents an operator most wants to
6
8
  // find live in the PROJECT TREE (e.g. `Codex/Reports/2026-07-10_*.md`, top-level
@@ -9,16 +11,14 @@ import { confinedPath } from './fileAccessPolicy.js';
9
11
  // scan is the other half: readable documents in the real tree, so drilling into
10
12
  // a project shows the docs written FOR it, not just agent workflow spill.
11
13
  //
12
- // Portable pruned walk (no `fd`), $HOME-jailed, depth/count-capped. `.arco` is
14
+ // Portable pruned walk (no `fd`), depth/count-capped. The global scan stays
15
+ // inside HOME; a scoped project can include Git-confirmed siblings. `.arco` is
13
16
  // pruned wholesale here (the artifacts join owns it — merging both client-side
14
17
  // gives the full picture without double-counting).
15
18
 
16
- import { readdir, stat } from 'fs/promises';
17
- import { basename, join, relative } from 'path';
18
- import { readFile } from 'fs/promises';
19
- import { homedir } from 'os';
20
- import { realpathWithinHome } from './explorerArtifacts.js';
21
- import { arcoHome } from './arcoHome.js';
19
+ import { stat } from 'node:fs/promises';
20
+ import { basename, relative } from 'node:path';
21
+ import { readKnownCwds, realpathWithinHome } from './explorerArtifacts.js';
22
22
 
23
23
  export interface DocEntry {
24
24
  path: string;
@@ -27,7 +27,14 @@ export interface DocEntry {
27
27
  mtime: number;
28
28
  project: string;
29
29
  cwd: string; // the owning project root (drill scoping + reveal-in-tree)
30
- rel: string; // path relative to the project root (shows the subdir)
30
+ rel: string; // path relative to its checkout (shows the subdir)
31
+ branch?: string;
32
+ }
33
+
34
+ interface DocsPage {
35
+ entries: DocEntry[];
36
+ partial: boolean;
37
+ projects?: Array<{ cwd: string; project: string }>;
31
38
  }
32
39
 
33
40
  const PRUNE_DIRS = new Set([
@@ -44,8 +51,28 @@ function isDoc(name: string): boolean {
44
51
  return DOC_EXT.has(ext);
45
52
  }
46
53
 
54
+ async function scanDocuments(root: string, owner: string, budget: ScanBudget, out: DocEntry[],
55
+ authorize: (file: string) => string | Promise<string>, branch?: string): Promise<void> {
56
+ for await (const file of projectFiles(root, { budget, skip: PRUNE_DIRS, hidden: true, maxDepth: MAX_DEPTH })) {
57
+ if (!isDoc(file.name)) continue;
58
+ try {
59
+ const authorized = await scanBeforeDeadline(Promise.resolve(authorize(file.path)), budget);
60
+ if (!authorized) break;
61
+ const st = await scanBeforeDeadline(stat(authorized), budget);
62
+ if (!st) break;
63
+ out.push({ path: file.path, name: file.name, size: st.size, mtime: st.mtimeMs, project: basename(owner), cwd: owner,
64
+ rel: relative(root, file.path), ...(branch ? { branch } : {}) });
65
+ } catch { /* unreadable or outside the project */ }
66
+ }
67
+ }
68
+
69
+ function finishPage(out: DocEntry[], limit: number, budget: ScanBudget): DocsPage {
70
+ out.sort((a, b) => b.mtime - a.mtime);
71
+ return { entries: out.slice(0, limit), partial: budget.partial || out.length > limit };
72
+ }
73
+
47
74
  // Walk one project tree for document files, newest-first, capped.
48
- export async function collectProjectDocsPage(project: string, limit = 1000, global?: ScanBudget): Promise<{ entries: DocEntry[]; partial: boolean }> {
75
+ export async function collectProjectDocsPage(project: string, limit = 1000, global?: ScanBudget): Promise<DocsPage> {
49
76
  const budget = scanBudget();
50
77
  if (global) budget.deadline = Math.min(budget.deadline, global.deadline);
51
78
  const root = await scanBeforeDeadline(realpathWithinHome(project), budget);
@@ -53,54 +80,68 @@ export async function collectProjectDocsPage(project: string, limit = 1000, glob
53
80
  if (global) budget.entries = Math.min(budget.entries, global.entries);
54
81
  const starting = budget.entries;
55
82
  const out: DocEntry[] = [];
56
- for await (const file of projectFiles(root, { budget, skip: PRUNE_DIRS, hidden: true, maxDepth: MAX_DEPTH })) {
57
- if (!isDoc(file.name)) continue;
58
- try {
59
- confinedPath(file.path, [root], 'file');
60
- const st = await scanBeforeDeadline(stat(file.path), budget);
61
- if (!st) break;
62
- out.push({ path: file.path, name: file.name, size: st.size, mtime: st.mtimeMs, project: basename(root), cwd: root, rel: relative(root, file.path) });
63
- } catch { /* unreadable or outside the project */ }
64
- }
83
+ await scanDocuments(root, root, budget, out, file => confinedPath(file, [root], 'file'));
65
84
  if (global) global.entries -= starting - budget.entries;
66
- out.sort((a, b) => b.mtime - a.mtime);
67
- return { entries: out.slice(0, limit), partial: budget.partial || out.length > limit };
85
+ return finishPage(out, limit, budget);
68
86
  }
87
+
69
88
  export async function collectProjectDocs(project: string, limit = 1000): Promise<DocEntry[]> {
70
89
  return (await collectProjectDocsPage(project, limit)).entries;
71
90
  }
72
91
 
73
- const KNOWN_CWDS = join(arcoHome(), 'known-cwds.json');
92
+ async function collectScopedDocs(project: string): Promise<DocsPage> {
93
+ const budget = scanBudget();
94
+ const out: DocEntry[] = [];
95
+ const root = await scanBeforeDeadline(realpathWithinHome(project), budget);
96
+ if (root) await scanDocuments(root, root, budget, out, file => confinedPath(file, [root], 'file'));
97
+ if (exhausted(budget)) return finishPage(out, 1000, budget);
74
98
 
75
- async function readKnownCwds(): Promise<string[]> {
76
- try {
77
- const raw = await readFile(KNOWN_CWDS, 'utf8');
78
- const parsed = JSON.parse(raw);
79
- if (!Array.isArray(parsed)) return [];
80
- return parsed.filter((x): x is string => typeof x === 'string' && x.length > 0);
81
- } catch {
82
- return [];
99
+ const bound = await scanBeforeDeadline(resolveBoundCwd(project, undefined), budget);
100
+ if (!bound?.ok) return finishPage(out, 1000, budget);
101
+ const access = await scanBeforeDeadline(createReadAccessContext(), budget);
102
+ if (!access) return finishPage(out, 1000, budget);
103
+ const owner = root ?? await scanBeforeDeadline(access.safeDirectory(bound.cwd), budget);
104
+ if (!owner) return finishPage(out, 1000, budget);
105
+ const signal = AbortSignal.timeout(Math.max(1, Math.ceil(budget.deadline - performance.now())));
106
+ const registry = await scanBeforeDeadline(browserWorktreeRegistry(owner, signal), budget);
107
+ if (!registry) {
108
+ if (signal.aborted) budget.partial = true;
109
+ return finishPage(out, 1000, budget);
110
+ }
111
+ for (const entry of registry.entries) {
112
+ if (exhausted(budget)) break;
113
+ const tree = await scanBeforeDeadline(confirmBrowserWorktree(registry, entry, access, signal), budget);
114
+ if (!tree) continue;
115
+ await scanDocuments(tree.canonical, owner, budget, out, file => browserWorktreeFile(file, tree, access), tree.branch);
83
116
  }
117
+ if (signal.aborted) budget.partial = true;
118
+ return finishPage(out, 1000, budget);
84
119
  }
85
120
 
86
121
  // Global doc scan across known projects, bounded per-project so a home load over
87
122
  // dozens of projects stays responsive. `project` scopes to one (full limit).
88
- export async function collectDocsPage(opts: { project?: string } = {}): Promise<{ entries: DocEntry[]; partial: boolean }> {
89
- if (opts.project) return collectProjectDocsPage(opts.project);
123
+ export async function collectDocsPage(opts: { project?: string } = {}): Promise<DocsPage> {
124
+ if (opts.project) return collectScopedDocs(opts.project);
90
125
  const global = scanBudget(50_000, 650);
91
126
  const known = await scanBeforeDeadline(readKnownCwds(), global);
92
127
  if (!known) return { entries: [], partial: true };
93
128
  const cwds = [...new Set(known)];
94
129
  const all: DocEntry[] = [];
130
+ const projects = new Map<string, { cwd: string; project: string }>();
131
+ const access = await scanBeforeDeadline(createReadAccessContext(), global);
132
+ if (!access) return { entries: [], partial: true };
95
133
  let partial = false;
96
134
  for (const cwd of cwds) {
97
135
  if (exhausted(global)) { partial = true; break; }
98
- const page = await collectProjectDocsPage(cwd, 150, global).catch(() => ({ entries: [], partial: true }));
136
+ const root = await scanBeforeDeadline(access.safeDirectory(cwd).catch(() => null), global);
137
+ if (!root) continue;
138
+ projects.set(root, { cwd: root, project: basename(root) });
139
+ const page = await collectProjectDocsPage(root, 150, global).catch(() => ({ entries: [], partial: true }));
99
140
  all.push(...page.entries);
100
141
  partial ||= page.partial;
101
142
  }
102
143
  all.sort((a, b) => b.mtime - a.mtime);
103
- return { entries: all.slice(0, 600), partial: partial || all.length > 600 };
144
+ return { entries: all.slice(0, 600), partial: partial || global.partial || all.length > 600, projects: [...projects.values()] };
104
145
  }
105
146
  export async function collectDocs(opts: { project?: string } = {}): Promise<DocEntry[]> {
106
147
  return (await collectDocsPage(opts)).entries;
@@ -0,0 +1,49 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import { writeFile } from 'node:fs/promises';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { basename, extname, join } from 'node:path';
5
+ import { shrinkUploadedImage } from '../uploadImages.js';
6
+ import { queueModelImage } from '../providers/attachments.js';
7
+ import { UPLOADS_DIR, UPLOAD_IMAGE_EXT } from '../server/constants.js';
8
+ import { ensureStorageRoot } from '../storageRoot.js';
9
+
10
+ export interface StoredAttachment {
11
+ fileId: string;
12
+ filename: string;
13
+ path: string;
14
+ }
15
+
16
+ export class UploadTooLarge extends Error {}
17
+
18
+ export async function readAttachmentBody(req: IncomingMessage, limit?: number): Promise<Buffer> {
19
+ const chunks: Buffer[] = [];
20
+ let size = 0;
21
+ for await (const chunk of req.iterator({ destroyOnReturn: false })) {
22
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
23
+ size += bytes.length;
24
+ if (limit !== undefined && size > limit) throw new UploadTooLarge();
25
+ chunks.push(bytes);
26
+ }
27
+ return Buffer.concat(chunks, size);
28
+ }
29
+
30
+ export async function storeAttachment(
31
+ body: Buffer,
32
+ rawFilename: string,
33
+ contentType: string,
34
+ reservation?: { fileId: string; beforeWrite: (file: StoredAttachment) => Promise<void> },
35
+ ): Promise<StoredAttachment> {
36
+ const inferredExt = !extname(rawFilename) ? UPLOAD_IMAGE_EXT[contentType] : undefined;
37
+ const filename = basename(rawFilename) + (inferredExt ?? '');
38
+ const fileId = reservation?.fileId ?? randomUUID().slice(0, 8);
39
+ const root = await ensureStorageRoot(UPLOADS_DIR);
40
+ const path = join(root, `${fileId}-${filename}`);
41
+ const stored = { fileId, filename, path };
42
+ await reservation?.beforeWrite(stored);
43
+ await writeFile(path, body, { flag: 'wx', mode: 0o600 });
44
+ if (!reservation) console.log(`[arco] File uploaded: ${filename} -> ${path}`);
45
+ // Finish any replacement before publishing the stable path.
46
+ await shrinkUploadedImage(path);
47
+ queueModelImage(path);
48
+ return stored;
49
+ }
@@ -0,0 +1,124 @@
1
+ // A read grant for a single Git-confirmed checkout. This does not register the
2
+ // checkout with the global project roots or use the managed-task write grant.
3
+ import { realpath } from 'node:fs';
4
+ import { lstat } from 'node:fs/promises';
5
+ import { homedir } from 'node:os';
6
+ import path from 'node:path';
7
+ import { promisify } from 'node:util';
8
+ import { FileAccessError, isPathWithin, type ReadAccessContext } from '../fileAccessPolicy.js';
9
+ import { gitOutput } from './projectBinding.js';
10
+
11
+ const nativePath = promisify(realpath.native);
12
+ const samePath = (a: string, b: string) => path.relative(a, b) === '';
13
+
14
+ interface RegisteredWorktree {
15
+ directory: string;
16
+ branch: string;
17
+ }
18
+
19
+ interface WorktreeRegistry {
20
+ checkout: string;
21
+ common: string;
22
+ entries: RegisteredWorktree[];
23
+ }
24
+
25
+ interface BrowserWorktree {
26
+ directory: string;
27
+ canonical: string;
28
+ native: string;
29
+ branch: string;
30
+ device: number;
31
+ inode: number;
32
+ }
33
+
34
+ function refuseArcoState(target: string): void {
35
+ if (path.resolve(target).split(path.sep).some(part => part.toLowerCase() === '.arco')) throw new FileAccessError();
36
+ }
37
+
38
+ async function gitDirectory(cwd: string, arg: string, signal?: AbortSignal): Promise<string> {
39
+ const stdout = await gitOutput(cwd, ['rev-parse', '--path-format=absolute', arg], signal);
40
+ return nativePath(stdout.replace(process.platform === 'win32' ? /\r?\n$/ : /\n$/, ''));
41
+ }
42
+
43
+ export async function browserWorktreeRegistry(boundCwd: string, signal?: AbortSignal): Promise<WorktreeRegistry | null> {
44
+ try {
45
+ const output = await gitOutput(boundCwd, ['worktree', 'list', '--porcelain', '-z'], signal);
46
+ const entries = output.split('\0\0').flatMap(record => {
47
+ const [worktree, ...fields] = record.split('\0');
48
+ if (!worktree.startsWith('worktree ') || fields.some(field => /^(bare|prunable)( |$)/.test(field))) return [];
49
+ const directory = path.normalize(worktree.slice('worktree '.length));
50
+ const branch = fields.find(field => field.startsWith('branch refs/heads/'))?.slice('branch refs/heads/'.length);
51
+ const head = fields.find(field => /^HEAD [0-9a-f]{7,64}$/.test(field))?.slice(5, 12);
52
+ return path.isAbsolute(directory) && (branch || head)
53
+ ? [{ directory, branch: branch || ('Detached HEAD ' + head) }] : [];
54
+ });
55
+ if (entries.length < 2) return null;
56
+ const [checkout, common] = await Promise.all([
57
+ gitDirectory(boundCwd, '--show-toplevel', signal),
58
+ gitDirectory(boundCwd, '--git-common-dir', signal),
59
+ ]);
60
+ return { checkout, common, entries: entries.filter(entry => !samePath(entry.directory, checkout)) };
61
+ } catch { return null; }
62
+ }
63
+
64
+ export async function confirmBrowserWorktree(registry: WorktreeRegistry, entry: RegisteredWorktree, access: ReadAccessContext, signal?: AbortSignal): Promise<BrowserWorktree | null> {
65
+ try {
66
+ refuseArcoState(entry.directory);
67
+ const root = await lstat(entry.directory);
68
+ if (!root.isDirectory()) return null;
69
+ const canonical = await access.safeDirectory(entry.directory);
70
+ refuseArcoState(canonical);
71
+ const real = await nativePath(canonical);
72
+ access.assertSafePath(real);
73
+ const home = await nativePath(homedir()).catch(() => homedir());
74
+ if (samePath(real, registry.checkout) || samePath(real, path.parse(real).root) || isPathWithin(real, home)) return null;
75
+ const [top, common] = await Promise.all([
76
+ gitDirectory(real, '--show-toplevel', signal),
77
+ gitDirectory(real, '--git-common-dir', signal),
78
+ ]);
79
+ if (!samePath(real, top) || !samePath(common, registry.common)) return null;
80
+ return { ...entry, canonical, native: real, device: root.dev, inode: root.ino };
81
+ } catch { return null; }
82
+ }
83
+
84
+ export async function browserWorktreeFile(target: string, tree: BrowserWorktree, access: ReadAccessContext): Promise<string> {
85
+ refuseArcoState(target);
86
+ if (!isPathWithin(tree.directory, target) && !isPathWithin(tree.canonical, target)) throw new FileAccessError();
87
+ const { real } = await access.inspect(target, undefined, 'file');
88
+ // Git for Windows and Node may spell the same directory differently when
89
+ // a parent has an 8.3 name. Compare both resolved paths in native spelling.
90
+ const expanded = await nativePath(real);
91
+ access.assertSafePath(expanded);
92
+ refuseArcoState(real);
93
+ refuseArcoState(expanded);
94
+ if (!isPathWithin(tree.native, expanded)) throw new FileAccessError();
95
+ const root = await lstat(tree.directory);
96
+ if (!root.isDirectory() || root.dev !== tree.device || root.ino !== tree.inode) throw new FileAccessError();
97
+ return real;
98
+ }
99
+
100
+ export async function resolveWorktreeFile(target: string, boundCwd: string, access: ReadAccessContext): Promise<string> {
101
+ const registry = await browserWorktreeRegistry(boundCwd);
102
+ if (!registry) throw new FileAccessError();
103
+ let alias: string | undefined;
104
+ let entry = registry.entries.filter(candidate => isPathWithin(candidate.directory, target))
105
+ .sort((a, b) => b.directory.length - a.directory.length)[0];
106
+ if (!entry) {
107
+ // Parent aliases occur on macOS and Windows. Match the root's expanded
108
+ // spelling but keep the request's spelling for read confinement below.
109
+ const spellings = await Promise.all(registry.entries.map(async candidate => ({
110
+ candidate,
111
+ real: await nativePath(candidate.directory).catch(() => null),
112
+ })));
113
+ for (let dir = path.dirname(target); dir !== path.dirname(dir); dir = path.dirname(dir)) {
114
+ const stat = await lstat(dir).catch(() => null);
115
+ if (!stat?.isDirectory()) continue;
116
+ const real = await nativePath(dir);
117
+ const registered = spellings.find(candidate => candidate.real && samePath(candidate.real, real))?.candidate;
118
+ if (registered) { entry = registered; alias = dir; break; }
119
+ }
120
+ }
121
+ const verified = entry && await confirmBrowserWorktree(registry, entry, access);
122
+ if (!verified) throw new FileAccessError();
123
+ return browserWorktreeFile(target, alias ? { ...verified, directory: alias } : verified, access);
124
+ }
@@ -0,0 +1,118 @@
1
+ import { lstatSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
2
+ import { basename, join } from 'node:path';
3
+ import { arcoHome } from '../arcoHome.js';
4
+ import { UPLOADS_DIR, UUID_PATTERN } from '../server/constants.js';
5
+ import { ensureStorageRoot } from '../storageRoot.js';
6
+ import type { StoredAttachment } from './attachmentUpload.js';
7
+
8
+ export const PHONE_DRAFT_TTL_MS = 30 * 60_000;
9
+ const ROOT_NAME = '.phone-upload-drafts';
10
+
11
+ export interface PhoneDraft extends StoredAttachment {
12
+ workflowId: string;
13
+ owner: string;
14
+ expiresAt: number;
15
+ }
16
+
17
+ function recordsDirectory(): string {
18
+ return join(arcoHome(), ROOT_NAME);
19
+ }
20
+
21
+ function recordPath(fileId: string): string {
22
+ if (!UUID_PATTERN.test(fileId)) throw new Error('Invalid phone upload ID');
23
+ return join(recordsDirectory(), fileId + '.json');
24
+ }
25
+
26
+ function safeName(filename: unknown): filename is string {
27
+ return typeof filename === 'string' && /^[\p{L}\p{N}_()-][\p{L}\p{N} ._()-]{0,119}$/u.test(filename);
28
+ }
29
+
30
+ export function phoneFilename(name: string): string {
31
+ const cleaned = name.normalize('NFC').replace(/[^\p{L}\p{N} ._()-]/gu, '_').replace(/^[. ]+|[. ]+$/g, '');
32
+ // A Windows file system also observes the extension after Unicode sanitizing.
33
+ return safeName(cleaned) ? cleaned : '';
34
+ }
35
+
36
+ function readRecord(id: string): PhoneDraft | null {
37
+ try {
38
+ const directory = lstatSync(recordsDirectory());
39
+ if (!directory.isDirectory() || directory.isSymbolicLink()) return null;
40
+ const target = recordPath(id);
41
+ const stat = lstatSync(target);
42
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 4096) return null;
43
+ const entry = JSON.parse(readFileSync(target, 'utf8')) as Partial<PhoneDraft>;
44
+ if (entry.fileId !== id || !safeName(entry.filename) || typeof entry.path !== 'string'
45
+ || basename(entry.path) !== `${id}-${entry.filename}` || typeof entry.owner !== 'string'
46
+ || typeof entry.workflowId !== 'string' || typeof entry.expiresAt !== 'number'
47
+ || !Number.isSafeInteger(entry.expiresAt)) return null;
48
+ return entry as PhoneDraft;
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+
54
+ export async function rememberPhoneDraft(entry: PhoneDraft): Promise<void> {
55
+ const directory = await ensureStorageRoot(recordsDirectory());
56
+ writeFileSync(join(directory, entry.fileId + '.json'), JSON.stringify(entry), { flag: 'wx', mode: 0o600 });
57
+ }
58
+
59
+ export function phoneDraftForOwner(id: string, owner: string): PhoneDraft | null {
60
+ const entry = readRecord(id);
61
+ return entry && entry.owner === owner && entry.expiresAt > Date.now() ? entry : null;
62
+ }
63
+
64
+ export async function discardPhoneDraft(entry: PhoneDraft): Promise<void> {
65
+ const directory = await ensureStorageRoot(UPLOADS_DIR, false);
66
+ // Send may take ownership while the directory check is in flight.
67
+ if (readRecord(entry.fileId)?.path !== entry.path) return;
68
+ const path = join(directory, `${entry.fileId}-${entry.filename}`);
69
+ // Delete only a filename generated for this phone receipt, never a path
70
+ // supplied by the phone or stored in the receipt.
71
+ for (const name of [path, path + '.model.png', path + '.model.jpg']) {
72
+ try { unlinkSync(name); }
73
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
74
+ }
75
+ forgetRecord(entry.fileId);
76
+ }
77
+
78
+ function forgetRecord(fileId: string): void {
79
+ try { unlinkSync(recordPath(fileId)); }
80
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
81
+ }
82
+
83
+ // Called only at the send acceptance points. Removing the cleanup receipt
84
+ // before queuing or starting the turn keeps sent attachments in history.
85
+ export function adoptPhoneDrafts(workflowId: string, attachments: readonly string[] | undefined): boolean {
86
+ const entries: PhoneDraft[] = [];
87
+ for (const path of attachments ?? []) {
88
+ const id = basename(path).slice(0, 36);
89
+ if (!UUID_PATTERN.test(id)) continue;
90
+ const entry = readRecord(id);
91
+ if (!entry) continue;
92
+ if (entry.workflowId !== workflowId || entry.path !== path || entry.expiresAt <= Date.now()) return false;
93
+ entries.push(entry);
94
+ }
95
+ for (const entry of entries) forgetRecord(entry.fileId);
96
+ return true;
97
+ }
98
+
99
+ let sweeping = false;
100
+ export async function sweepPhoneDrafts(): Promise<void> {
101
+ if (sweeping) return;
102
+ sweeping = true;
103
+ try {
104
+ const directory = lstatSync(recordsDirectory());
105
+ if (!directory.isDirectory() || directory.isSymbolicLink()) return;
106
+ for (const file of readdirSync(recordsDirectory())) {
107
+ if (!file.endsWith('.json')) continue;
108
+ const entry = readRecord(file.slice(0, -5));
109
+ if (entry && entry.expiresAt <= Date.now()) await discardPhoneDraft(entry).catch(() => {});
110
+ }
111
+ } catch {
112
+ // No phone uploads yet, or managed storage is unavailable.
113
+ } finally {
114
+ sweeping = false;
115
+ }
116
+ }
117
+
118
+ setInterval(() => { void sweepPhoneDrafts(); }, 30_000).unref();
@@ -0,0 +1,96 @@
1
+ import http, { type IncomingMessage, type Server, type ServerResponse } from 'node:http';
2
+
3
+ // A temporary listener for phone upload when the main server cannot be
4
+ // reached from the private network (the default loopback bind). It binds
5
+ // each private network or tailnet address separately, never a wildcard, and
6
+ // answers one path: the phone upload page and its upload endpoint. Upgrade
7
+ // requests (WebSocket) are refused, and nothing reaches the workbench router.
8
+ // The main server's bind is never changed.
9
+
10
+ export interface PhoneListener {
11
+ origins: string[];
12
+ close(): void;
13
+ }
14
+
15
+ type Handler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;
16
+
17
+ const PHONE_PATH = '/phone-upload';
18
+
19
+ function notFound(res: ServerResponse): void {
20
+ res.writeHead(404, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', Connection: 'close' });
21
+ res.end(JSON.stringify({ error: 'Not found.' }));
22
+ }
23
+
24
+ /** An HTTP server that answers only the phone upload path and refuses everything else. */
25
+ export function createPhoneServer(handler: Handler): Server {
26
+ const server = http.createServer((req, res) => {
27
+ if (req.url !== PHONE_PATH || req.headers.upgrade) return notFound(res);
28
+ handler(req, res).catch(() => {
29
+ if (!res.headersSent) res.writeHead(500, { 'Content-Type': 'application/json' });
30
+ res.end();
31
+ });
32
+ });
33
+ server.on('upgrade', (_req, socket) => { socket.destroy(); });
34
+ server.headersTimeout = 15_000;
35
+ server.requestTimeout = 5 * 60_000;
36
+ server.keepAliveTimeout = 5_000;
37
+ server.maxConnections = 32;
38
+ return server;
39
+ }
40
+
41
+ // Tests bind the listener to loopback while it reports a fixture private
42
+ // address, so the operator route can be exercised without that interface.
43
+ let bindAddressForTest: ((address: string) => string) | null = null;
44
+ export function _bindPhoneListenerForTest(map: ((address: string) => string) | null): void {
45
+ bindAddressForTest = map;
46
+ }
47
+
48
+ function listen(server: Server, address: string, port: number): Promise<number> {
49
+ return new Promise((resolve, reject) => {
50
+ server.once('error', reject);
51
+ server.listen(port, address, () => {
52
+ server.off('error', reject);
53
+ const bound = server.address();
54
+ resolve(typeof bound === 'object' && bound ? bound.port : port);
55
+ });
56
+ });
57
+ }
58
+
59
+ /**
60
+ * Bind one phone server per address. Arco's own port is tried first, so a
61
+ * firewall rule for that port also covers phones; when it is taken on an
62
+ * address, the system picks a free port there. Addresses that cannot be
63
+ * bound are left out.
64
+ */
65
+ export async function startPhoneListener(addresses: string[], preferredPort: number, handler: Handler): Promise<PhoneListener> {
66
+ const servers: Server[] = [];
67
+ const origins: string[] = [];
68
+ for (const address of addresses) {
69
+ let reason = '';
70
+ for (const port of preferredPort ? [preferredPort, 0] : [0]) {
71
+ const server = createPhoneServer(handler);
72
+ try {
73
+ const bound = await listen(server, bindAddressForTest?.(address) ?? address, port);
74
+ server.on('error', error => console.warn(`[arco] phone upload listener: ${error.message}`));
75
+ servers.push(server);
76
+ origins.push(new URL(`http://${address}:${bound}`).origin);
77
+ reason = '';
78
+ break;
79
+ } catch (e) {
80
+ reason = (e as NodeJS.ErrnoException).code ?? 'unknown error';
81
+ server.close();
82
+ }
83
+ }
84
+ // The error code only: the address itself stays out of the log.
85
+ if (reason) console.warn(`[arco] phone upload listener could not bind a private address: ${reason}`);
86
+ }
87
+ return {
88
+ origins,
89
+ close() {
90
+ for (const server of servers) {
91
+ server.close();
92
+ server.closeIdleConnections();
93
+ }
94
+ },
95
+ };
96
+ }