conductor-remote 1.117.0 → 1.118.1

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 (200) hide show
  1. package/README.md +10 -8
  2. package/dist/assets/{PierrePatch-D3_YBIAr.js → PierrePatch-Dh-08CLI.js} +1 -1
  3. package/dist/assets/index-BRzsSW8g.css +1 -0
  4. package/dist/assets/index-BpY3Jhxk.js +65 -0
  5. package/dist/index.html +2 -2
  6. package/dist/push-sw.js +2 -2
  7. package/dist/sw.js +1 -1
  8. package/dist-node/scripts/nosleep-setup.js +2 -2
  9. package/dist-node/scripts/nosleep.js +3 -3
  10. package/dist-node/scripts/service/commands.js +32 -0
  11. package/dist-node/scripts/service/configuration.js +205 -0
  12. package/dist-node/scripts/service/environment.js +59 -0
  13. package/dist-node/scripts/service/flags.js +45 -0
  14. package/dist-node/scripts/service/installation.js +91 -0
  15. package/dist-node/scripts/service/launch-agent.js +134 -0
  16. package/dist-node/scripts/service/network.js +244 -0
  17. package/dist-node/scripts/service/presentation.js +101 -0
  18. package/dist-node/scripts/service/voice.js +113 -0
  19. package/dist-node/scripts/service.js +5 -980
  20. package/dist-node/src/{agent-config.js → agents/agent-config.js} +1 -1
  21. package/dist-node/src/{model-cache.js → agents/model-cache.js} +1 -1
  22. package/dist-node/src/{roles.js → agents/roles.js} +3 -3
  23. package/dist-node/src/db.js +1 -1
  24. package/dist-node/src/{parked.js → delivery/parked.js} +1 -1
  25. package/dist-node/src/{dev-server.js → dev-server/controller.js} +8 -291
  26. package/dist-node/src/dev-server/ports.js +63 -0
  27. package/dist-node/src/dev-server/processes.js +73 -0
  28. package/dist-node/src/dev-server/proxy.js +158 -0
  29. package/dist-node/src/{run-activity.js → dev-server/run-activity.js} +2 -2
  30. package/dist-node/src/dev-server/types.js +1 -0
  31. package/dist-node/src/{file-preview.js → files/file-preview.js} +1 -1
  32. package/dist-node/src/{change-stats.js → git/change-stats.js} +1 -1
  33. package/dist-node/src/{git.js → git/diff.js} +43 -18
  34. package/dist-node/src/{autoupdate.js → host/autoupdate.js} +1 -1
  35. package/dist-node/src/{funnel-watchdog.js → host/funnel-watchdog.js} +4 -4
  36. package/dist-node/src/{logbuf.js → host/logbuf.js} +1 -1
  37. package/dist-node/src/{nosleep-helper.js → host/nosleep-helper.js} +1 -1
  38. package/dist-node/src/{tailscale.js → host/tailscale.js} +1 -1
  39. package/dist-node/src/http/router-types.js +2 -0
  40. package/dist-node/src/http/router.js +78 -0
  41. package/dist-node/src/http/routes/create-workspace.js +90 -0
  42. package/dist-node/src/http/routes/files.js +53 -0
  43. package/dist-node/src/http/routes/prompts.js +363 -0
  44. package/dist-node/src/http/routes/sessions.js +279 -0
  45. package/dist-node/src/http/routes/state.js +186 -0
  46. package/dist-node/src/http/routes/system.js +220 -0
  47. package/dist-node/src/http/routes/voice.js +117 -0
  48. package/dist-node/src/http/routes/workflows.js +248 -0
  49. package/dist-node/src/http/routes/workspaces.js +267 -0
  50. package/dist-node/src/http/services/base.js +252 -0
  51. package/dist-node/src/http/services/delegations.js +301 -0
  52. package/dist-node/src/http/services/delivery.js +433 -0
  53. package/dist-node/src/http/services/files.js +199 -0
  54. package/dist-node/src/http/services/mcp.js +94 -0
  55. package/dist-node/src/http/services/responses.js +120 -0
  56. package/dist-node/src/http/services/voice.js +147 -0
  57. package/dist-node/src/http/services/workflow-probes.js +215 -0
  58. package/dist-node/src/http/services/workflow-state.js +195 -0
  59. package/dist-node/src/http/services/workflow.js +366 -0
  60. package/dist-node/src/http/services.js +35 -0
  61. package/dist-node/src/mcp/arguments.js +14 -0
  62. package/dist-node/src/mcp/dispatcher.js +56 -0
  63. package/dist-node/src/mcp/formatters.js +110 -0
  64. package/dist-node/src/mcp/protocol.js +7 -0
  65. package/dist-node/src/mcp/registry.js +66 -0
  66. package/dist-node/src/mcp/tools/agent-options.js +122 -0
  67. package/dist-node/src/mcp/tools/chat-actions.js +194 -0
  68. package/dist-node/src/mcp/tools/chats.js +194 -0
  69. package/dist-node/src/mcp/tools/delegation.js +135 -0
  70. package/dist-node/src/mcp/tools/system.js +135 -0
  71. package/dist-node/src/mcp/tools/voice.js +136 -0
  72. package/dist-node/src/mcp/tools/workspaces.js +259 -0
  73. package/dist-node/src/mcp/types.js +1 -0
  74. package/dist-node/src/mcp.js +6 -4
  75. package/dist-node/src/{notify.js → notifications/notify.js} +5 -5
  76. package/dist-node/src/{webpush.js → notifications/webpush.js} +1 -1
  77. package/dist-node/src/orchestration/delegation/codec.js +201 -0
  78. package/dist-node/src/{delegation-intake.js → orchestration/delegation/intake.js} +2 -2
  79. package/dist-node/src/{delegation-prompt.js → orchestration/delegation/prompt.js} +1 -1
  80. package/dist-node/src/orchestration/delegation/queue.js +255 -0
  81. package/dist-node/src/orchestration/delegation/store.js +111 -0
  82. package/dist-node/src/orchestration/delegation/types.js +2 -0
  83. package/dist-node/src/orchestration/persistence/capabilities.js +109 -0
  84. package/dist-node/src/orchestration/persistence/codecs.js +148 -0
  85. package/dist-node/src/orchestration/persistence/connection.js +205 -0
  86. package/dist-node/src/orchestration/persistence/db.js +101 -0
  87. package/dist-node/src/orchestration/persistence/effect-recovery.js +227 -0
  88. package/dist-node/src/orchestration/persistence/effect-transitions.js +157 -0
  89. package/dist-node/src/orchestration/persistence/effects.js +109 -0
  90. package/dist-node/src/orchestration/persistence/errors.js +39 -0
  91. package/dist-node/src/orchestration/persistence/events.js +29 -0
  92. package/dist-node/src/orchestration/persistence/idempotency.js +82 -0
  93. package/dist-node/src/orchestration/persistence/job-attempts.js +114 -0
  94. package/dist-node/src/orchestration/persistence/jobs.js +159 -0
  95. package/dist-node/src/orchestration/persistence/projections.js +190 -0
  96. package/dist-node/src/orchestration/persistence/quarantine.js +46 -0
  97. package/dist-node/src/orchestration/persistence/records.js +115 -0
  98. package/dist-node/src/orchestration/persistence/relays.js +78 -0
  99. package/dist-node/src/orchestration/persistence/runs.js +156 -0
  100. package/dist-node/src/{orchestration-schema.js → orchestration/persistence/schema.js} +1 -1
  101. package/dist-node/src/orchestration/persistence/types.js +1 -0
  102. package/dist-node/src/orchestration/persistence/ui-lease.js +197 -0
  103. package/dist-node/src/orchestration/persistence/values.js +114 -0
  104. package/dist-node/src/orchestration/workflow/commands.js +309 -0
  105. package/dist-node/src/orchestration/workflow/coordinator.js +28 -0
  106. package/dist-node/src/orchestration/workflow/effect-recovery.js +125 -0
  107. package/dist-node/src/orchestration/workflow/effects.js +307 -0
  108. package/dist-node/src/orchestration/workflow/errors.js +13 -0
  109. package/dist-node/src/orchestration/workflow/helpers.js +154 -0
  110. package/dist-node/src/orchestration/workflow/job-dispatch.js +312 -0
  111. package/dist-node/src/orchestration/workflow/job-results.js +280 -0
  112. package/dist-node/src/{workflow.js → orchestration/workflow/prompts.js} +2 -2
  113. package/dist-node/src/orchestration/workflow/root.js +293 -0
  114. package/dist-node/src/orchestration/workflow/start.js +99 -0
  115. package/dist-node/src/orchestration/workflow/state.js +105 -0
  116. package/dist-node/src/orchestration/workflow/types.js +1 -0
  117. package/dist-node/src/orchestration/workflow/wake.js +164 -0
  118. package/dist-node/src/prefs.js +1 -1
  119. package/dist-node/src/{background-tasks.js → reads/background-tasks.js} +1 -1
  120. package/dist-node/src/reads/messages.js +362 -0
  121. package/dist-node/src/reads/repository.js +87 -0
  122. package/dist-node/src/reads/sessions.js +165 -0
  123. package/dist-node/src/reads/types.js +1 -0
  124. package/dist-node/src/reads/workspaces.js +230 -0
  125. package/dist-node/src/reads/worktrees.js +45 -0
  126. package/dist-node/src/routes.js +5 -5
  127. package/dist-node/src/{search.js → search/coordinator.js} +4 -4
  128. package/dist-node/src/{search-worker.js → search/worker.js} +3 -3
  129. package/dist-node/src/server.js +14 -3930
  130. package/dist-node/src/settings.js +1 -1
  131. package/dist-node/src/shared.js +10 -10
  132. package/dist-node/src/{transcript.js → transcript/parser.js} +4 -4
  133. package/dist-node/src/{tool-usage-worker.js → usage/tool-usage-worker.js} +1 -1
  134. package/dist-node/src/{tool-usage.js → usage/tool-usage.js} +1 -1
  135. package/dist-node/src/voice/brief.js +22 -50
  136. package/dist-node/src/voice/context.js +1 -1
  137. package/dist-node/src/voice/dates.js +38 -0
  138. package/dist-node/src/voice/history.js +14 -5
  139. package/dist-node/src/voice/prompt.js +10 -9
  140. package/dist-node/src/voice/recall.js +115 -0
  141. package/dist-node/src/{speech.js → voice/speech.js} +1 -1
  142. package/dist-node/src/voice/tools.js +92 -3
  143. package/dist-node/src/voice/webrtc.js +1 -1
  144. package/dist-node/src/wire.js +2 -2
  145. package/dist-node/src/writes/actuator.js +124 -0
  146. package/dist-node/src/writes/agent-options.js +151 -0
  147. package/dist-node/src/writes/applescript/agent-options.applescript +334 -0
  148. package/dist-node/src/writes/applescript/chat-targeting.applescript +149 -0
  149. package/dist-node/src/writes/applescript/composer.applescript +195 -0
  150. package/dist-node/src/writes/applescript/hotspot.applescript +155 -0
  151. package/dist-node/src/writes/applescript/lifecycle.applescript +266 -0
  152. package/dist-node/src/writes/applescript/run-tasks.applescript +208 -0
  153. package/dist-node/src/writes/applescript/source.js +52 -0
  154. package/dist-node/src/writes/applescript/window.applescript +436 -0
  155. package/dist-node/src/writes/applescript/workspace-status.applescript +177 -0
  156. package/dist-node/src/writes/applescript/workspace-targeting.applescript +359 -0
  157. package/dist-node/src/writes/chats.js +160 -0
  158. package/dist-node/src/writes/guards.js +77 -0
  159. package/dist-node/src/writes/runner.js +67 -0
  160. package/dist-node/src/{sidecar.js → writes/sidecar.js} +1 -1
  161. package/dist-node/src/writes/system.js +81 -0
  162. package/dist-node/src/writes/targeting.js +121 -0
  163. package/dist-node/src/writes/types.js +1 -0
  164. package/dist-node/src/writes/ui-lock.js +229 -0
  165. package/dist-node/src/writes/workspaces.js +233 -0
  166. package/docs/voice-setup.md +34 -12
  167. package/package.json +2 -2
  168. package/dist/assets/index-ByTwVInL.css +0 -1
  169. package/dist/assets/index-LAm9X7wv.js +0 -65
  170. package/dist-node/src/conductor.applescript +0 -2279
  171. package/dist-node/src/delegations.js +0 -557
  172. package/dist-node/src/mcp-tools.js +0 -1319
  173. package/dist-node/src/orchestration-db.js +0 -2186
  174. package/dist-node/src/reads.js +0 -787
  175. package/dist-node/src/workflow-coordinator.js +0 -2119
  176. package/dist-node/src/writes.js +0 -1223
  177. /package/dist-node/src/{conductor-settings.js → agents/conductor-settings.js} +0 -0
  178. /package/dist-node/src/{firstprompt.js → delivery/firstprompt.js} +0 -0
  179. /package/dist-node/src/{sendonce.js → delivery/sendonce.js} +0 -0
  180. /package/dist-node/src/{preview-urls.js → dev-server/preview-urls.js} +0 -0
  181. /package/dist-node/src/{run-configs.js → dev-server/run-configs.js} +0 -0
  182. /package/dist-node/src/{attachments.js → files/attachments.js} +0 -0
  183. /package/dist-node/src/{icons.js → files/icons.js} +0 -0
  184. /package/dist-node/src/{staged-attachments.js → files/staged-attachments.js} +0 -0
  185. /package/dist-node/src/{fork-workspace.js → git/fork-workspace.js} +0 -0
  186. /package/dist-node/src/{merge.js → git/merge.js} +0 -0
  187. /package/dist-node/src/{pr.js → git/pr.js} +0 -0
  188. /package/dist-node/src/{nosleep.js → host/nosleep.js} +0 -0
  189. /package/dist-node/src/{relay-processes.js → host/relay-processes.js} +0 -0
  190. /package/dist-node/src/{ui-lease-watchdog.js → host/ui-lease-watchdog.js} +0 -0
  191. /package/dist-node/src/{wifi.js → host/wifi.js} +0 -0
  192. /package/dist-node/src/{orchestration-schema.generated.js → orchestration/persistence/schema.generated.js} +0 -0
  193. /package/dist-node/src/{workflow-effect-runner.js → orchestration/workflow/effect-runner.js} +0 -0
  194. /package/dist-node/src/{workflow-http.js → orchestration/workflow/http.js} +0 -0
  195. /package/dist-node/src/{workflow-machine.js → orchestration/workflow/machine.js} +0 -0
  196. /package/dist-node/src/{session-poller.js → reads/session-poller.js} +0 -0
  197. /package/dist-node/src/{context-breakdown.js → transcript/context-breakdown.js} +0 -0
  198. /package/dist-node/src/{chat-cursor.js → transcript/cursor.js} +0 -0
  199. /package/dist-node/src/{plan-usage.js → usage/plan-usage.js} +0 -0
  200. /package/dist-node/src/{tool-usage-service.js → usage/tool-usage-service.js} +0 -0
@@ -0,0 +1,433 @@
1
+ import path from 'node:path';
2
+ import { applyAgentConfig } from "../../agents/agent-config.js";
3
+ import { stateDir } from "../../config.js";
4
+ import { FirstPromptQueue } from "../../delivery/firstprompt.js";
5
+ import { ParkedPromptQueue } from "../../delivery/parked.js";
6
+ import { SendOnce } from "../../delivery/sendonce.js";
7
+ import { discardStagedAttachment, materializeStagedAttachments, pruneStagedAttachments } from "../../files/staged-attachments.js";
8
+ import { chatRoute, notifyAll } from "../../notifications/notify.js";
9
+ import { readPrefs } from "../../prefs.js";
10
+ import { setAgentOptions } from "../../writes/agent-options.js";
11
+ import { newChat } from "../../writes/chats.js";
12
+ import { lockBlocked, retryWontHelp, screenLocked, sendNeverStarted } from "../../writes/guards.js";
13
+ import { withUiPriority } from "../../writes/ui-lock.js";
14
+ export function createDeliveryServices(services) {
15
+ const { reads, sleep, actuator, STAGED_ATTACHMENTS_DIR, assignWorkflowRoot, orchestration, stagedAttachmentIdsInObjective, modelCache } = services;
16
+ /**
17
+ * Has Conductor taken ownership of the prompt yet? The receipt everything below is
18
+ * built on. The AppleScript actuator reports `ok` on `osascript` exit 0 — which only
19
+ * means the script *ran*, not that Conductor accepted the keystrokes — so without
20
+ * this a dropped send (asleep/unfocused Mac) looks delivered. A prompt accepted into
21
+ * Conductor's durable outbox also counts, before it becomes a transcript row.
22
+ */
23
+ function deliveredSince(sessionId, text, since) {
24
+ return reads.promptDeliveredSince(sessionId, text, since);
25
+ }
26
+ function deliveredRowSince(sessionId, text, sinceRowid) {
27
+ const target = text.trim();
28
+ const { entries } = reads.getMessages(sessionId, sinceRowid);
29
+ return entries.find(e => e.role === 'user' && e.text.trim() === target)?.rowid ?? null;
30
+ }
31
+ /**
32
+ * Watch for that row, ending on a check rather than a sleep, and never past
33
+ * `budgetDeadline`. Conductor records the row or outbox item right after the send
34
+ * presses Enter, so a real send is confirmed in a tick and only the failure path
35
+ * waits the window out.
36
+ *
37
+ * The window is *also* what makes a retry safe — it is deliberately longer than the
38
+ * row takes to appear, because everything past it is allowed to type into the
39
+ * composer again — so note which end of the budget gets clipped when the two
40
+ * compete: a retry only happens with `MIN_ATTEMPT_MS + CONFIRM_WINDOW_MS` left, so
41
+ * a confirm *followed by another attempt* always gets its full window. Only the
42
+ * last confirm of all can be cut short, and nothing follows it to duplicate a row.
43
+ */
44
+ async function confirmDeliveryRow(sessionId, text, sinceRowid, budgetDeadline) {
45
+ const stopAt = Math.min(Date.now() + CONFIRM_WINDOW_MS, budgetDeadline);
46
+ for (;;) {
47
+ const rowid = deliveredRowSince(sessionId, text, sinceRowid);
48
+ if (rowid !== null)
49
+ return rowid;
50
+ if (Date.now() >= stopAt)
51
+ return null;
52
+ await sleep(300);
53
+ }
54
+ }
55
+ async function confirmDelivery(sessionId, text, since, budgetDeadline) {
56
+ const stopAt = Math.min(Date.now() + CONFIRM_WINDOW_MS, budgetDeadline);
57
+ for (;;) {
58
+ if (deliveredSince(sessionId, text, since))
59
+ return true;
60
+ if (Date.now() >= stopAt)
61
+ return false;
62
+ await sleep(300);
63
+ }
64
+ }
65
+ /** How long we watch the transcript after a run before deciding it didn't land. */
66
+ const CONFIRM_WINDOW_MS = 6_000;
67
+ /** Ceiling on a whole send, retries included — no phone should hold a request open longer. */
68
+ const SEND_BUDGET_MS = 55_000;
69
+ /** Below this there isn't room for a run that could plausibly succeed, so don't start one. */
70
+ const MIN_ATTEMPT_MS = 12_000;
71
+ /**
72
+ * The least a confirm is worth doing at all. Held back from every run so a send that
73
+ * lands can be *seen* to have landed — an unconfirmed send is indistinguishable from
74
+ * a lost one, which is the failure this whole path exists to avoid.
75
+ */
76
+ const MIN_CONFIRM_MS = 2_000;
77
+ /** Leaves the response itself time to get home before the caller's own timer fires. */
78
+ const RESPONSE_MARGIN_MS = 5_000;
79
+ /**
80
+ * Budget for a caller that didn't say how long it would wait — a PWA build from
81
+ * before `x-client-timeout-ms`, which aborted a send at a flat 25s. Sized so that
82
+ * such a phone is no worse off than it was: one run with a ceiling like the old one,
83
+ * and no retry (there was never room for a retry inside 25s).
84
+ */
85
+ const LEGACY_SEND_BUDGET_MS = 20_000;
86
+ /**
87
+ * Never outlast the caller. The relay giving up *after* the phone has is the worst
88
+ * available outcome: the phone shows a failure while the send goes on to land, and
89
+ * the user can't tell that from a send that really didn't. Pairing our budget to
90
+ * the PWA's by hand wouldn't hold — the relay updates itself (src/host/autoupdate.ts) while
91
+ * the app sits in a service-worker cache — so the caller states its own deadline
92
+ * and we retry inside it.
93
+ */
94
+ function sendBudget(req) {
95
+ const asked = Number(req.headers['x-client-timeout-ms']);
96
+ if (!Number.isFinite(asked) || asked <= 0)
97
+ return LEGACY_SEND_BUDGET_MS;
98
+ // Floor at one confirmable attempt: a caller in a hurry still gets a real try.
99
+ return Math.max(MIN_ATTEMPT_MS + CONFIRM_WINDOW_MS, Math.min(SEND_BUDGET_MS, asked - RESPONSE_MARGIN_MS));
100
+ }
101
+ /**
102
+ * Where a chat sits in Conductor's tab strip. Both write paths need it: the
103
+ * actuator selects that tab before touching anything, otherwise it acts on
104
+ * whichever tab happens to be active.
105
+ */
106
+ function locateChat(ws, sessionId) {
107
+ const sessions = reads.listSessions(ws.id);
108
+ const index = sessions.findIndex(s => s.id === sessionId);
109
+ if (index < 0 && sessions.length > 1)
110
+ return { error: 'chat is no longer one of the workspace’s tabs' };
111
+ if (index < 0)
112
+ return { tab: undefined, session: undefined };
113
+ return {
114
+ tab: { index: index + 1, count: sessions.length, title: sessions[index].title ?? '' },
115
+ session: sessions[index]
116
+ };
117
+ }
118
+ /**
119
+ * Open a chat tab in a workspace and come back with its id.
120
+ *
121
+ * ⌘T is fire-and-forget like every other keystroke here, so the id is not something
122
+ * the write can return — the DB is the receipt. Which row is the new one is decided by
123
+ * diffing the tab list against the one taken *before* the keystroke, not by taking the
124
+ * newest: a sibling tab or another agent may have opened one in between, and picking by
125
+ * `created_at` would hand back theirs.
126
+ */
127
+ async function openChat(ws) {
128
+ const before = new Set(reads.listSessions(ws.id).map(s => s.id));
129
+ const result = await newChat(ws);
130
+ if (!result.ok)
131
+ return { error: true, result };
132
+ // The new session lands in the DB a beat after Cmd+T — poll for the fresh id.
133
+ for (let i = 0; i < 12; i++) {
134
+ await sleep(500);
135
+ const fresh = reads.listSessions(ws.id).filter(s => !before.has(s.id));
136
+ if (fresh.length > 1) {
137
+ return {
138
+ error: true,
139
+ retryable: false,
140
+ result: {
141
+ ok: false,
142
+ strategy: actuator.name,
143
+ error: 'more than one new chat appeared; refusing to guess which one this request opened'
144
+ }
145
+ };
146
+ }
147
+ if (fresh[0])
148
+ return { sessionId: fresh[0].id };
149
+ }
150
+ // The tab is almost certainly on screen; only its id is missing. Say so rather than
151
+ // failing the call, so a caller can still tell the user where the work went.
152
+ return { sessionId: null };
153
+ }
154
+ /**
155
+ * Deliver a prompt to one chat and confirm it landed, retrying until the caller's
156
+ * budget runs out. The single write path: the phone's own sends go through it, and so
157
+ * does the first-prompt queue, so both get the same targeting, the same read-back,
158
+ * the same retries and the same errors.
159
+ *
160
+ * Retrying here rather than handing the phone a Retry button is the point: the
161
+ * failures this path hits are overwhelmingly warm-up costs — a cold or busy Conductor
162
+ * makes the first AppleScript run slow enough to be killed, and the second finds an
163
+ * activated app and lands — which is exactly why tapping Retry always worked. Two
164
+ * things make doing it automatically safe rather than a way to send a prompt twice:
165
+ * - **The transcript is the receipt.** Every run is followed by a full
166
+ * `CONFIRM_WINDOW_MS` of watching for the matching user row, *including* runs that
167
+ * reported an error, and the last of those checks is the moment before we type
168
+ * again. A run that actually landed — even one killed just after pressing Enter,
169
+ * or one whose row appeared after we'd stopped looking — is reported as delivered.
170
+ * - **The composer is written, not appended to** (`fillComposer` sets AXValue), so a
171
+ * retry replaces a half-finished attempt's text instead of doubling it.
172
+ *
173
+ * Bounded by a wall clock rather than an attempt count, because someone is holding
174
+ * this request open: runs are bounded by the caller's deadline, and we stop rather
175
+ * than start one the budget could not also confirm. The queue's own 3-sends-over-15-
176
+ * minutes schedule sits *outside* this and is unaffected — it retries a delivery that
177
+ * never got off the ground (worktree still setting up), not one Conductor fumbled.
178
+ */
179
+ async function deliverPrompt(ws, sessionId, text, budgetMs = SEND_BUDGET_MS, queue = false) {
180
+ const located = locateChat(ws, sessionId);
181
+ if ('error' in located)
182
+ return { ok: false, strategy: actuator.name, attempts: 0, error: located.error };
183
+ // Snapshot the transcript cursor and outbox ids once: every check below asks "did
184
+ // *this* prompt arrive since we started", so a retry can't be fooled by an older
185
+ // identical prompt moving from the outbox into a new transcript row.
186
+ const before = reads.deliveryCursor(sessionId);
187
+ const label = ws.branch ?? ws.id;
188
+ const deadline = Date.now() + budgetMs;
189
+ let attempts = 0;
190
+ let last = { ok: false, strategy: actuator.name };
191
+ for (;;) {
192
+ attempts++;
193
+ // The run gets the deadline, not a duration: `uiTurn` may hold it behind another
194
+ // write, and only the run knows what was left of the budget when it started. Minus
195
+ // the confirm, so a caller on a tight budget spends it on the run rather than on
196
+ // watching — a 25s-era phone gets one full-length attempt, not two too short to finish.
197
+ last = await actuator.send({ workspace: ws, sessionId, tab: located.tab }, text, {
198
+ deadline: deadline - MIN_CONFIRM_MS,
199
+ queue
200
+ });
201
+ // A run that left the prompt in the composer proved it wrote no row, so the
202
+ // window would be six seconds of watching for nothing. One check still happens:
203
+ // an *earlier* attempt's row can be arriving, and typing again over that is the
204
+ // duplicate this whole path exists to avoid.
205
+ const landed = sendNeverStarted(last.error)
206
+ ? deliveredSince(sessionId, text, before)
207
+ : await confirmDelivery(sessionId, text, before, deadline);
208
+ if (landed) {
209
+ if (attempts > 1)
210
+ console.info(`[relay] send to ${label} landed on attempt ${attempts}`);
211
+ return { ok: true, strategy: last.strategy, attempts };
212
+ }
213
+ if (retryWontHelp(last.error))
214
+ break;
215
+ // A locked screen isn't worth the rest of the budget either — but for the
216
+ // opposite reason: the parked-prompt queue (src/delivery/parked.ts) waits it out far
217
+ // past any deadline a phone could hold open, so hand it over at once.
218
+ if (lockBlocked(last.error))
219
+ break;
220
+ if (deadline - Date.now() < MIN_ATTEMPT_MS + CONFIRM_WINDOW_MS)
221
+ break;
222
+ // The phone only ever sees the outcome; why a send goes missing lives on this
223
+ // side, so leave the trail in relay.log rather than nothing at all.
224
+ console.warn(`[relay] send to ${label} attempt ${attempts} didn’t land (${last.error ?? 'no user row appeared'}) — retrying`);
225
+ }
226
+ const tried = attempts > 1 ? ` (tried ${attempts}×)` : '';
227
+ const error = last.ok
228
+ ? `Send didn’t land in the chat — Conductor may have been asleep or unfocused${tried}. Try again.`
229
+ : `${last.error}${tried}`;
230
+ console.warn(`[relay] send to ${label} failed after ${attempts} attempt(s): ${error}`);
231
+ return { ok: false, strategy: last.strategy, attempts, error };
232
+ }
233
+ /**
234
+ * Undelivered first prompts, owned by this process rather than by the phone (see
235
+ * src/delivery/firstprompt.ts for why). Everything Conductor-side it needs is a plain DB read.
236
+ */
237
+ const firstPrompts = new FirstPromptQueue(path.join(stateDir(), 'first-prompts.json'), {
238
+ inspect: workspaceId => {
239
+ const ws = reads.getWorkspace(workspaceId);
240
+ if (!ws)
241
+ return null;
242
+ // 'setting_up' is the worktree (and the setup script), not the window: Conductor
243
+ // draws the workspace and its chat the moment the row exists, so the queue tries
244
+ // the send then and treats only a post-'ready' failure as one worth counting.
245
+ // `getWorkspace` already limits itself to 'ready'/'setting_up', so an archived
246
+ // workspace reads as no row at all and ages out rather than being typed into.
247
+ const sessions = reads.listSessions(workspaceId);
248
+ const session = sessions.find(s => s.id === ws.active_session_id) ?? sessions[0];
249
+ return {
250
+ phase: ws.state === 'ready' ? 'ready' : 'setting_up',
251
+ sessionId: session?.id ?? null,
252
+ alreadySent: !!session?.last_user_message_at,
253
+ worktree: ws.worktree
254
+ };
255
+ },
256
+ // The queue fires on its own schedule, so it must never make a human tap wait.
257
+ send: (workspaceId, sessionId, text) => withUiPriority('background', async () => {
258
+ const ws = reads.getWorkspace(workspaceId);
259
+ if (!ws)
260
+ return { ok: false, error: 'the workspace is gone' };
261
+ const result = await deliverPrompt(ws, sessionId, text);
262
+ return { ok: result.ok, error: result.error, blocked: lockBlocked(result.error) };
263
+ }),
264
+ setAgent: (workspaceId, sessionId, agent) => withUiPriority('background', async () => {
265
+ const ws = reads.getWorkspace(workspaceId);
266
+ if (!ws)
267
+ return { ok: false, error: 'the workspace is gone' };
268
+ const result = await applyAgentPatch(ws, sessionId, agent);
269
+ return { ok: result.ok, error: result.error, blocked: lockBlocked(result.error) };
270
+ }),
271
+ materialize: async (_workspaceId, worktree, attachmentIds) => {
272
+ try {
273
+ materializeStagedAttachments(STAGED_ATTACHMENTS_DIR, worktree, attachmentIds);
274
+ return { ok: true };
275
+ }
276
+ catch (err) {
277
+ return { ok: false, error: err instanceof Error ? err.message : 'the attached files could not be copied' };
278
+ }
279
+ },
280
+ assignRole: async (workspaceId, sessionId, role, assignedAt) => {
281
+ try {
282
+ const ws = reads.getWorkspace(workspaceId);
283
+ return ws ? assignWorkflowRoot(ws, sessionId, role, assignedAt) : { ok: false, error: 'the workspace is gone' };
284
+ }
285
+ catch (err) {
286
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
287
+ }
288
+ },
289
+ discard: attachmentIds => {
290
+ for (const id of attachmentIds)
291
+ discardStagedAttachment(STAGED_ATTACHMENTS_DIR, id);
292
+ },
293
+ // A locked Mac holds first prompts whole — no attempts spent, no aging — instead
294
+ // of burning all three sends into a lock screen nobody is there to see.
295
+ gate: async () => (await screenLocked()) !== true
296
+ });
297
+ /** Unreferenced pre-workspace uploads get one week for an offline device to reconnect. */
298
+ const STAGED_ATTACHMENT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
299
+ const STAGED_ATTACHMENT_SWEEP_MS = 6 * 60 * 60 * 1000;
300
+ function referencedStagedAttachments() {
301
+ const referenced = new Set();
302
+ for (const draft of Object.values(readPrefs().drafts)) {
303
+ if (draft.deleted)
304
+ continue;
305
+ for (const attachment of draft.attachments) {
306
+ if (attachment.stageId)
307
+ referenced.add(attachment.stageId);
308
+ }
309
+ }
310
+ for (const prompt of firstPrompts.list()) {
311
+ for (const stageId of prompt.attachmentIds ?? [])
312
+ referenced.add(stageId);
313
+ }
314
+ if (orchestration.writable) {
315
+ for (const projection of orchestration.listWorkflowProjections()) {
316
+ const run = orchestration.getWorkflowRun(projection.id);
317
+ if (run?.target.kind !== 'new_workspace')
318
+ continue;
319
+ for (const stageId of stagedAttachmentIdsInObjective(run.objective))
320
+ referenced.add(stageId);
321
+ }
322
+ }
323
+ return referenced;
324
+ }
325
+ function sweepStagedAttachments() {
326
+ const removed = pruneStagedAttachments(STAGED_ATTACHMENTS_DIR, referencedStagedAttachments(), STAGED_ATTACHMENT_MAX_AGE_MS);
327
+ if (removed)
328
+ console.info(`[relay] removed ${removed} abandoned staged attachment(s)`);
329
+ }
330
+ /**
331
+ * Apply staged agent settings to a chat — the shared half of `POST …/agent` and
332
+ * of a send that carries a patch. The `fast` translation lives here because the
333
+ * UI button only *toggles*: the DB says whether the press is needed at all.
334
+ */
335
+ async function applyAgentPatch(ws, sessionId, patch) {
336
+ const located = locateChat(ws, sessionId);
337
+ if ('error' in located)
338
+ return { ok: false, error: located.error };
339
+ const target = { workspace: ws, sessionId, tab: located.tab };
340
+ const result = await applyAgentConfig(patch, {
341
+ read: () => {
342
+ const session = reads.listSessions(ws.id).find(row => row.id === sessionId);
343
+ if (!session)
344
+ return undefined;
345
+ return {
346
+ agentType: session.agent_type,
347
+ model: session.model,
348
+ effort: session.claude_effort_level,
349
+ plan: session.permission_mode === 'plan',
350
+ fast: Boolean(session.fast_mode)
351
+ };
352
+ },
353
+ write: options => setAgentOptions(target, options),
354
+ wait: () => sleep(300)
355
+ });
356
+ if (!result.ok)
357
+ return result;
358
+ if (patch.model) {
359
+ const session = reads.listSessions(ws.id).find(row => row.id === sessionId);
360
+ modelCache.rememberModel(session?.agent_type, patch.model);
361
+ }
362
+ return { ok: true };
363
+ }
364
+ /**
365
+ * One prompt per tap, however many requests carry it (src/delivery/sendonce.ts). Keyed on the
366
+ * phone's own `PendingMessage.id`, which Retry reuses and a fresh send re-rolls, so a
367
+ * repeat someone meant still goes twice. Only an answer the phone would treat as final
368
+ * is remembered: a real failure has to stay retryable, or Retry does nothing for ten
369
+ * minutes and the prompt is lost for good rather than merely doubled.
370
+ */
371
+ const sendOnce = new SendOnce({
372
+ keep: answer => answer.status === 200 || answer.status === 202
373
+ });
374
+ /** What the phone is told when its prompt is parked instead of failed. */
375
+ const PARKED_ERROR = 'The Mac is locked — the relay parked the prompt and will send it when the Mac is unlocked.';
376
+ /**
377
+ * Prompts that hit the lock screen, owned by this process until the Mac unlocks
378
+ * (see src/delivery/parked.ts for why the phone can't wait this out itself).
379
+ */
380
+ const parkedPrompts = new ParkedPromptQueue(path.join(stateDir(), 'parked-prompts.json'), {
381
+ locked: screenLocked,
382
+ // Delivers on unlock, on its own schedule — background, like the first-prompt queue.
383
+ deliver: entry => withUiPriority('background', async () => {
384
+ const ws = reads.getWorkspace(entry.workspaceId);
385
+ if (!ws)
386
+ return { ok: false, error: 'the workspace is gone' };
387
+ // Settings first, prompt only if they stuck — the same order and the same
388
+ // fail-closed rule as the phone's own send (running the prompt on the model
389
+ // the user moved away from is the mistake this exists to prevent). A re-run
390
+ // after a failed prompt re-applies harmlessly: every control is read before
391
+ // it is pressed, so an already-correct value presses nothing.
392
+ if (entry.agent) {
393
+ const applied = await applyAgentPatch(ws, entry.sessionId, entry.agent);
394
+ if (!applied.ok)
395
+ return { ok: false, error: applied.error, blocked: lockBlocked(applied.error) };
396
+ }
397
+ const result = await deliverPrompt(ws, entry.sessionId, entry.text, SEND_BUDGET_MS, entry.queue);
398
+ return { ok: result.ok, error: result.error, blocked: lockBlocked(result.error) };
399
+ }),
400
+ notify: (entry, error) => {
401
+ const ws = reads.getWorkspace(entry.workspaceId);
402
+ const title = ws?.workspace_name ?? ws?.pr_title ?? ws?.branch ?? 'Conductor';
403
+ const preview = entry.text.length > 140 ? `${entry.text.slice(0, 140).trimEnd()}…` : entry.text;
404
+ void notifyAll({
405
+ title,
406
+ body: error ? `Parked prompt failed: ${error}` : `Sent after unlock: ${preview}`,
407
+ // Per chat, so a second parked prompt replaces the first's notification.
408
+ tag: `parked-${entry.sessionId}`,
409
+ url: chatRoute(entry.workspaceId, entry.sessionId),
410
+ kind: error ? 'error' : 'done',
411
+ ts: Date.now()
412
+ });
413
+ }
414
+ });
415
+ return {
416
+ openChat,
417
+ applyAgentPatch,
418
+ deliverPrompt,
419
+ deliveredRowSince,
420
+ SEND_BUDGET_MS,
421
+ locateChat,
422
+ confirmDeliveryRow,
423
+ CONFIRM_WINDOW_MS,
424
+ firstPrompts,
425
+ parkedPrompts,
426
+ confirmDelivery,
427
+ sendBudget,
428
+ sendOnce,
429
+ PARKED_ERROR,
430
+ sweepStagedAttachments,
431
+ STAGED_ATTACHMENT_SWEEP_MS
432
+ };
433
+ }
@@ -0,0 +1,199 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { isAllowedPreviewPath, parseFileReference, parseImageReference } from "../../files/file-preview.js";
5
+ import { readExposeMode } from "../../host/tailscale.js";
6
+ export function createFilesServices(services) {
7
+ const { json, cfg } = services;
8
+ const MIME = {
9
+ '.html': 'text/html; charset=utf-8',
10
+ '.js': 'text/javascript; charset=utf-8',
11
+ '.css': 'text/css; charset=utf-8',
12
+ '.json': 'application/json; charset=utf-8',
13
+ '.webmanifest': 'application/manifest+json; charset=utf-8',
14
+ '.svg': 'image/svg+xml',
15
+ '.png': 'image/png'
16
+ };
17
+ const LOCAL_IMAGE_TYPES = {
18
+ '.avif': 'image/avif',
19
+ '.gif': 'image/gif',
20
+ '.jpeg': 'image/jpeg',
21
+ '.jpg': 'image/jpeg',
22
+ '.png': 'image/png',
23
+ '.webp': 'image/webp'
24
+ };
25
+ const LOCAL_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
26
+ // `/tmp` is a symlink to `/private/tmp` on macOS. os.tmpdir() also covers tools that use the user's
27
+ // per-login temporary directory instead. Resolve both before checking a requested file's real path.
28
+ const LOCAL_IMAGE_ROOTS = [...new Set([os.tmpdir(), '/tmp'].map(root => fs.realpathSync(root)))];
29
+ function insideRoot(filePath, root) {
30
+ const rel = path.relative(root, filePath);
31
+ return rel !== '' && rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
32
+ }
33
+ async function serveLocalImage(req, res, requestedPath) {
34
+ const target = parseImageReference(requestedPath);
35
+ const contentType = target ? LOCAL_IMAGE_TYPES[path.extname(target).toLowerCase()] : null;
36
+ if (!target || !contentType)
37
+ return json(req, res, 404, { error: 'image not found' });
38
+ let filePath;
39
+ let size;
40
+ try {
41
+ filePath = await fs.promises.realpath(target);
42
+ if (!LOCAL_IMAGE_ROOTS.some(root => insideRoot(filePath, root))) {
43
+ const [workspaceRoot, homeRoot, bundledSkillsRoot] = await Promise.all([
44
+ fs.promises.realpath(cfg.workspacesRoot),
45
+ fs.promises.realpath(os.homedir()),
46
+ fs.promises.realpath(BUNDLED_SKILLS_ROOT).catch(() => null)
47
+ ]);
48
+ if (!isAllowedPreviewPath(filePath, workspaceRoot, homeRoot, readExposeMode(), bundledSkillsRoot)) {
49
+ return json(req, res, 404, { error: 'image not found' });
50
+ }
51
+ }
52
+ const info = await fs.promises.stat(filePath);
53
+ if (!info.isFile())
54
+ return json(req, res, 404, { error: 'image not found' });
55
+ size = info.size;
56
+ }
57
+ catch {
58
+ return json(req, res, 404, { error: 'image not found' });
59
+ }
60
+ if (size > LOCAL_IMAGE_MAX_BYTES)
61
+ return json(req, res, 413, { error: 'image is too large' });
62
+ res.writeHead(200, { 'content-type': contentType, 'cache-control': 'no-store' });
63
+ fs.createReadStream(filePath)
64
+ .once('error', () => res.destroy())
65
+ .pipe(res);
66
+ }
67
+ /** A preview stays small enough to render smoothly in the phone's source sheet. */
68
+ const FILE_PREVIEW_MAX_BYTES = 512 * 1024;
69
+ const FILE_PREVIEW_CONTEXT_LINES = 100;
70
+ const FILE_PREVIEW_FIRST_LINES = 500;
71
+ const BUNDLED_SKILLS_ROOT = '/Applications/Conductor.app/Contents/Resources/conductor-skill/skills';
72
+ /**
73
+ * Serve source that an agent linked in its Markdown. The link format comes from
74
+ * coding-agent file references, but its path still arrives from a remote client.
75
+ * Public Funnel clients stay within Conductor workspaces. Tailnet-only relays may
76
+ * also read supporting source files from the signed-in user's home directory.
77
+ */
78
+ async function serveFilePreview(req, res, reference) {
79
+ const target = parseFileReference(reference);
80
+ if (!target)
81
+ return json(req, res, 404, { error: 'source file not found' });
82
+ const refused = (filePath) => {
83
+ const answer = previewRefusal(filePath);
84
+ return json(req, res, answer.status, { error: answer.error });
85
+ };
86
+ let filePath;
87
+ let workspaceRoot;
88
+ let homeRoot;
89
+ let bundledSkillsRoot;
90
+ let size;
91
+ try {
92
+ ;
93
+ [filePath, workspaceRoot, homeRoot, bundledSkillsRoot] = await Promise.all([
94
+ fs.promises.realpath(target.path),
95
+ fs.promises.realpath(cfg.workspacesRoot),
96
+ fs.promises.realpath(os.homedir()),
97
+ fs.promises.realpath(BUNDLED_SKILLS_ROOT).catch(() => null)
98
+ ]);
99
+ if (!isAllowedPreviewPath(filePath, workspaceRoot, homeRoot, readExposeMode(), bundledSkillsRoot)) {
100
+ return refused(filePath);
101
+ }
102
+ const info = await fs.promises.stat(filePath);
103
+ if (!info.isFile())
104
+ return json(req, res, 404, { error: 'source file not found' });
105
+ size = info.size;
106
+ }
107
+ catch {
108
+ // A path this relay would refuse must answer the same whether or not it is there, or
109
+ // a public client learns which home files exist by watching 404 turn into 403.
110
+ return refused(target.path);
111
+ }
112
+ if (size > FILE_PREVIEW_MAX_BYTES)
113
+ return json(req, res, 413, { error: 'source file is too large to preview' });
114
+ let content;
115
+ try {
116
+ const raw = await fs.promises.readFile(filePath);
117
+ if (raw.includes(0))
118
+ return json(req, res, 415, { error: 'source file is not text' });
119
+ content = new TextDecoder('utf-8', { fatal: true }).decode(raw);
120
+ }
121
+ catch {
122
+ return json(req, res, 415, { error: 'source file is not text' });
123
+ }
124
+ const lines = content.split('\n');
125
+ const focus = target.line === null ? null : Math.min(target.line, lines.length);
126
+ const start = focus === null ? 0 : Math.max(0, focus - FILE_PREVIEW_CONTEXT_LINES - 1);
127
+ const end = focus === null
128
+ ? Math.min(lines.length, FILE_PREVIEW_FIRST_LINES)
129
+ : Math.min(lines.length, focus + FILE_PREVIEW_CONTEXT_LINES);
130
+ return json(req, res, 200, {
131
+ path: target.path,
132
+ line: focus,
133
+ lineStart: start + 1,
134
+ lineEnd: end,
135
+ totalLines: lines.length,
136
+ content: lines.slice(start, end).join('\n'),
137
+ truncated: start > 0 || end < lines.length
138
+ });
139
+ }
140
+ /**
141
+ * How to answer for a file the preview will not serve, from the path alone.
142
+ *
143
+ * Chat mentions made the home-directory case ordinary — agents write "plan written to
144
+ * `~/.gstack/plan.md`" constantly — and on a public funnel every one of those is refused
145
+ * by policy. Answering "source file not found" then sends someone hunting for a file that
146
+ * is sitting right there, so a refusal says it is a refusal. It discloses nothing: the
147
+ * verdict comes from the path and the funnel's posture, never from the disk, and it is
148
+ * the answer for an out-of-bounds path whether or not that path exists.
149
+ */
150
+ function previewRefusal(filePath) {
151
+ const mode = readExposeMode();
152
+ if (isAllowedPreviewPath(path.resolve(filePath), cfg.workspacesRoot, os.homedir(), mode, BUNDLED_SKILLS_ROOT)) {
153
+ return { status: 404, error: 'source file not found' };
154
+ }
155
+ return {
156
+ status: 403,
157
+ error: mode === 'public'
158
+ ? 'this relay is reachable from the internet, so it previews files inside Conductor workspaces only'
159
+ : 'outside the files this relay may read'
160
+ };
161
+ }
162
+ /** Hashed Vite assets are immutable and cache-forever; the shell/SW must never go stale. */
163
+ function cacheControl(rel) {
164
+ if (rel.startsWith('assets/'))
165
+ return 'public, max-age=31536000, immutable';
166
+ return 'no-cache';
167
+ }
168
+ function serveStatic(_req, res, pathname) {
169
+ const rel = pathname === '/' ? 'index.html' : pathname.replace(/^\/+/, '');
170
+ const filePath = path.resolve(cfg.publicDir, rel);
171
+ // Contain to publicDir. The URL parser already collapses `..`/`%2e%2e` dot-segments, but don't lean on
172
+ // that: reject anything that resolves outside the dir (a bare `startsWith` would also admit a sibling
173
+ // like `dist-node/`). An empty relative (filePath === publicDir) falls through to the SPA shell below.
174
+ const within = path.relative(cfg.publicDir, filePath);
175
+ if (within.startsWith('..') || path.isAbsolute(within)) {
176
+ res.writeHead(403).end();
177
+ return;
178
+ }
179
+ fs.readFile(filePath, (err, data) => {
180
+ if (err) {
181
+ // SPA fallback to shell.
182
+ fs.readFile(path.join(cfg.publicDir, 'index.html'), (e2, shell) => {
183
+ if (e2)
184
+ return void res.writeHead(404).end('not found');
185
+ res.writeHead(200, { 'content-type': MIME['.html'], 'cache-control': 'no-cache' });
186
+ res.end(shell);
187
+ });
188
+ return;
189
+ }
190
+ const ext = path.extname(filePath);
191
+ res.writeHead(200, {
192
+ 'content-type': MIME[ext] ?? 'application/octet-stream',
193
+ 'cache-control': cacheControl(rel)
194
+ });
195
+ res.end(data);
196
+ });
197
+ }
198
+ return { serveStatic, serveLocalImage, serveFilePreview };
199
+ }