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,195 @@
1
+ import { IdempotencyConflictError, WorkflowTransitionError } from "../../orchestration/persistence/errors.js";
2
+ import { WorkflowCoordinatorError } from "../../orchestration/workflow/errors.js";
3
+ import { WorkflowRequestError } from "../../orchestration/workflow/http.js";
4
+ import { WorkflowGuardError } from "../../orchestration/workflow/machine.js";
5
+ import { scrubWorkflowSecrets, withoutWindowEvidence } from "../../shared.js";
6
+ export function createWorkflowStateServices(services) {
7
+ const { orchestration, readBody } = services;
8
+ /** Keep process identity and raw recovery evidence private; the phone only needs the hold and its cause. */
9
+ function wireUiQuarantine() {
10
+ if (!orchestration.writable)
11
+ return undefined;
12
+ const quarantine = orchestration.getUiQuarantine();
13
+ if (!quarantine.active)
14
+ return undefined;
15
+ const bounded = (value, maximum) => withoutWindowEvidence(scrubWorkflowSecrets(value)).slice(0, maximum);
16
+ return {
17
+ active: true,
18
+ reason: bounded(quarantine.reason ??
19
+ 'A previous automated Conductor UI action may have completed without a confirmed receipt. Inspect Conductor before continuing.', 500),
20
+ createdAt: quarantine.createdAt ?? 0,
21
+ ...(quarantine.actionId ? { actionId: bounded(quarantine.actionId, 256) } : {}),
22
+ ...(quarantine.effectId ? { effectId: bounded(quarantine.effectId, 256) } : {})
23
+ };
24
+ }
25
+ function workflowJobStatus(state) {
26
+ if (state === 'owned')
27
+ return 'opening';
28
+ if (state === 'dormant')
29
+ return 'queued';
30
+ if (state === 'cancelled')
31
+ return 'failed';
32
+ return state;
33
+ }
34
+ function projectWorkflowDelegation(workflow, job) {
35
+ if (!workflow.workspaceId || job.state === 'cancelled')
36
+ return null;
37
+ return {
38
+ id: job.id,
39
+ workflowId: workflow.id,
40
+ logicalKey: job.logicalKey,
41
+ bootstrap: job.logicalKey === 'explore:0',
42
+ workspaceId: workflow.workspaceId,
43
+ parentSessionId: workflow.rootSessionId ?? '',
44
+ ...(job.childSessionId ? { childSessionId: job.childSessionId } : {}),
45
+ role: job.role,
46
+ // The immutable preamble remains coordinator-private. Only the public picker
47
+ // settings are useful for role chips and list_delegations.
48
+ resolvedRole: {
49
+ agentType: job.resolvedRole.agentType,
50
+ model: job.resolvedRole.model,
51
+ ...(job.resolvedRole.effort ? { effort: job.resolvedRole.effort } : {}),
52
+ ...(job.resolvedRole.fast === undefined ? {} : { fast: job.resolvedRole.fast })
53
+ },
54
+ prompt: scrubWorkflowSecrets(job.prompt).slice(0, 500),
55
+ returnMode: 'queue',
56
+ status: workflowJobStatus(job.state),
57
+ attempts: job.attemptCount,
58
+ createdAt: job.createdAt,
59
+ updatedAt: job.updatedAt,
60
+ ...(job.state === 'failed'
61
+ ? {
62
+ failure: {
63
+ code: 'workflow_blocked',
64
+ message: workflow.error?.message ?? 'Workflow job failed.',
65
+ retryable: workflow.actions.canRetry
66
+ }
67
+ }
68
+ : {})
69
+ };
70
+ }
71
+ function attachWorkflowState(workspaces) {
72
+ if (!orchestration.writable)
73
+ return [];
74
+ const projections = orchestration.listWorkflowProjections();
75
+ const byWorkspace = new Map(workspaces.map(workspace => [workspace.id, workspace]));
76
+ for (const workflow of projections) {
77
+ if (!workflow.workspaceId)
78
+ continue;
79
+ const workspace = byWorkspace.get(workflow.workspaceId);
80
+ if (!workspace)
81
+ continue;
82
+ const run = orchestration.getWorkflowRun(workflow.id);
83
+ if (!run)
84
+ continue;
85
+ const jobs = orchestration
86
+ .listWorkflowJobs(workflow.id)
87
+ .flatMap(job => projectWorkflowDelegation(workflow, job) ?? []);
88
+ workspace.delegations = [...(workspace.delegations ?? []), ...jobs];
89
+ workspace.session_roles = { ...(workspace.session_roles ?? {}) };
90
+ if (workflow.rootSessionId) {
91
+ workspace.session_roles[workflow.rootSessionId] = {
92
+ role: 'planning',
93
+ workflowId: workflow.id,
94
+ assignedAt: workflow.createdAt
95
+ };
96
+ }
97
+ for (const job of orchestration.listWorkflowJobs(workflow.id)) {
98
+ if (!job.childSessionId)
99
+ continue;
100
+ workspace.session_roles[job.childSessionId] = {
101
+ role: job.role,
102
+ delegationId: job.id,
103
+ workflowId: workflow.id,
104
+ assignedAt: job.createdAt
105
+ };
106
+ }
107
+ // Compatibility for cached clients that only understand one workspace-level run.
108
+ if (!workspace.workflow || workflow.rootSessionId === workspace.active_session_id)
109
+ workspace.workflow = workflow;
110
+ }
111
+ // A terminal run leaves the active Workflow list but not the workspace's identity.
112
+ // Attach only the newest historical projection when no live run already won above;
113
+ // its frozen public roles let the sidebar remain truthful after role settings change.
114
+ const historicalWorkspaceIds = [...byWorkspace.values()]
115
+ .filter(workspace => !workspace.workflow)
116
+ .map(workspace => workspace.id);
117
+ for (const workflow of orchestration.listLatestWorkflowProjectionsForWorkspaces(historicalWorkspaceIds)) {
118
+ if (!workflow.workspaceId)
119
+ continue;
120
+ const workspace = byWorkspace.get(workflow.workspaceId);
121
+ if (workspace && !workspace.workflow) {
122
+ workspace.workflow_identity = {
123
+ id: workflow.id,
124
+ phase: workflow.phase,
125
+ roles: workflow.roles
126
+ };
127
+ }
128
+ }
129
+ return projections;
130
+ }
131
+ function workflowOwningSession(sessionId) {
132
+ if (!orchestration.writable)
133
+ return null;
134
+ for (const projection of orchestration.listWorkflowProjections()) {
135
+ if (projection.rootSessionId === sessionId)
136
+ return projection;
137
+ if (orchestration.listWorkflowJobs(projection.id).some(job => job.childSessionId === sessionId))
138
+ return projection;
139
+ }
140
+ return null;
141
+ }
142
+ function workflowFrozenError(sessionId) {
143
+ const workflow = workflowOwningSession(sessionId);
144
+ if (!workflow)
145
+ return null;
146
+ return {
147
+ error: {
148
+ code: 'workflow_role_frozen',
149
+ message: `Workflow ${workflow.id} froze this chat's model, effort, and Fast setting at Start.`,
150
+ retryable: false
151
+ }
152
+ };
153
+ }
154
+ function workflowHttpError(error) {
155
+ if (error instanceof WorkflowRequestError || error instanceof WorkflowGuardError) {
156
+ return { status: error.status, error: { code: error.code, message: error.message, retryable: false } };
157
+ }
158
+ if (error instanceof WorkflowCoordinatorError) {
159
+ return {
160
+ status: error.status,
161
+ error: { code: error.code, message: error.message, retryable: error.retryable }
162
+ };
163
+ }
164
+ if (error instanceof IdempotencyConflictError) {
165
+ return {
166
+ status: 409,
167
+ error: { code: 'idempotency_conflict', message: error.message, retryable: false }
168
+ };
169
+ }
170
+ if (error instanceof WorkflowTransitionError) {
171
+ return {
172
+ status: 409,
173
+ error: { code: 'workflow_phase_invalid', message: error.message, retryable: false }
174
+ };
175
+ }
176
+ return null;
177
+ }
178
+ async function workflowRequestBody(req) {
179
+ try {
180
+ return JSON.parse((await readBody(req)) || '{}');
181
+ }
182
+ catch {
183
+ throw new WorkflowRequestError('Workflow request body must be valid JSON.');
184
+ }
185
+ }
186
+ return {
187
+ attachWorkflowState,
188
+ wireUiQuarantine,
189
+ workflowRequestBody,
190
+ projectWorkflowDelegation,
191
+ workflowFrozenError,
192
+ workflowOwningSession,
193
+ workflowHttpError
194
+ };
195
+ }
@@ -0,0 +1,366 @@
1
+ import { materializeStagedAttachments } from "../../files/staged-attachments.js";
2
+ import { WorkflowCoordinator } from "../../orchestration/workflow/coordinator.js";
3
+ import { WorkflowCoordinatorError } from "../../orchestration/workflow/errors.js";
4
+ import { WorkflowRequestError, workflowClientIsMcp } from "../../orchestration/workflow/http.js";
5
+ import { renderTranscript } from "../../transcript/parser.js";
6
+ import { retryWontHelp, screenLocked } from "../../writes/guards.js";
7
+ export function createWorkflowServices(services) {
8
+ const { orchestration, relayIdentity, reads, stagedAttachmentIdsInObjective, STAGED_ATTACHMENTS_DIR, createWorkspaceAndRead, workflowCompatibilityError, actuator, sessionPoller, workflowRootInspection, withWorkflowEffectGate, sessionMatchesWorkflowRole, workflowDeliveryCursor, stableWorkflowAttachment, sendWorkflowPrompt, workflowSessionId, assertWorkflowRootStillPristine, workspaceBaseline, workflowWorkspaceCandidate, sessionBaseline, workflowSessionCandidate, workflowEffectPrompt, readsDeliveryCursor, workflowEffectMarker, applyAgentPatch, openChat, batonText } = services;
9
+ const workflowCoordinator = orchestration.writable
10
+ ? new WorkflowCoordinator(orchestration, relayIdentity, {
11
+ captureWorkspaceBaseline: async (repoName) => {
12
+ const repo = reads.listRepos().find(candidate => candidate.name === repoName);
13
+ if (!repo) {
14
+ throw new WorkflowCoordinatorError('workflow_not_found', `Unknown repo ${repoName}.`, { status: 404 });
15
+ }
16
+ if (!repo.root_path) {
17
+ throw new WorkflowCoordinatorError('invalid_request', `${repo.name} has no checkout path.`);
18
+ }
19
+ return {
20
+ kind: 'workspace_ids',
21
+ repo: repo.name,
22
+ workspaceIds: reads
23
+ .listWorkspaces()
24
+ .filter(workspace => workspace.repo_name === repo.name)
25
+ .map(workspace => workspace.id)
26
+ .sort()
27
+ };
28
+ },
29
+ inspectExistingRoot: async (target) => {
30
+ const ws = reads.getWorkspace(target.workspaceId);
31
+ if (!ws || reads.sessionWorkspaceId(target.sessionId) !== ws.id)
32
+ return null;
33
+ const session = reads.getSession(target.sessionId);
34
+ return session ? workflowRootInspection(ws, session) : null;
35
+ },
36
+ bindCreatedRoot: async ({ run, workspaceId }) => {
37
+ const ws = reads.getWorkspace(workspaceId);
38
+ if (!ws)
39
+ return null;
40
+ if (run.target.kind !== 'new_workspace')
41
+ return null;
42
+ if (!run.target.sendImmediately && ws.state !== 'ready')
43
+ return null;
44
+ const sessions = reads.listSessions(workspaceId);
45
+ if (!sessions.length)
46
+ return null;
47
+ const session = sessions.find(candidate => candidate.id === ws.active_session_id) ?? sessions[0];
48
+ if (sessions.length !== 1) {
49
+ const inspection = workflowRootInspection(ws, session);
50
+ return { ...inspection, pristine: false, reason: 'The created workspace has more than one root candidate.' };
51
+ }
52
+ const stageIds = stagedAttachmentIdsInObjective(run.objective);
53
+ if (stageIds.length) {
54
+ if (!ws.worktree)
55
+ return null;
56
+ try {
57
+ materializeStagedAttachments(STAGED_ATTACHMENTS_DIR, ws.worktree, stageIds);
58
+ }
59
+ catch (error) {
60
+ const inspection = workflowRootInspection(ws, session);
61
+ return {
62
+ ...inspection,
63
+ pristine: false,
64
+ reason: error instanceof Error ? error.message : 'The Workflow attachments could not be materialized.'
65
+ };
66
+ }
67
+ }
68
+ return workflowRootInspection(ws, session);
69
+ },
70
+ createWorkspace: call => withWorkflowEffectGate(call, async () => {
71
+ const { target } = call;
72
+ const repo = reads.listRepos().find(candidate => candidate.name === target.repo);
73
+ if (!repo) {
74
+ throw new WorkflowCoordinatorError('workflow_not_found', `Unknown repo ${target.repo}.`, { status: 404 });
75
+ }
76
+ if (!repo.root_path)
77
+ throw new WorkflowCoordinatorError('invalid_request', `${repo.name} has no checkout path.`);
78
+ const { result, created } = await createWorkspaceAndRead('', repo.root_path, repo.name, true);
79
+ if (!result.ok) {
80
+ throw new WorkflowCoordinatorError('workflow_effect_failed', result.error ?? 'Workspace creation failed.', {
81
+ retryable: !retryWontHelp(result.error)
82
+ });
83
+ }
84
+ if (!created) {
85
+ throw new WorkflowCoordinatorError('workflow_effect_failed', 'Conductor accepted the workspace link but no exact workspace row appeared.', { retryable: true });
86
+ }
87
+ return { workspaceId: created.id };
88
+ }),
89
+ configureSession: call => withWorkflowEffectGate(call, async () => {
90
+ const { run, sessionId, role } = call;
91
+ const ws = run.workspaceId ? reads.getWorkspace(run.workspaceId) : null;
92
+ if (!ws || reads.sessionWorkspaceId(sessionId) !== ws.id) {
93
+ throw new WorkflowCoordinatorError('workflow_not_found', 'The Workflow chat is unavailable.', {
94
+ status: 404
95
+ });
96
+ }
97
+ const applied = await applyAgentPatch(ws, sessionId, {
98
+ model: role.model,
99
+ ...(role.effort === undefined ? {} : { effort: role.effort }),
100
+ ...(role.fast === undefined ? {} : { fast: role.fast })
101
+ });
102
+ if (!applied.ok) {
103
+ throw new WorkflowCoordinatorError('workflow_effect_failed', applied.error ?? 'Conductor rejected the frozen role settings.');
104
+ }
105
+ const session = reads.getSession(sessionId);
106
+ if (!session || !sessionMatchesWorkflowRole(session, role)) {
107
+ throw new WorkflowCoordinatorError('workflow_effect_failed', 'Conductor no longer matches every frozen role setting; no fallback was selected.');
108
+ }
109
+ return {
110
+ sessionId,
111
+ agentType: session.agent_type,
112
+ model: role.model,
113
+ effort: session.claude_effort_level,
114
+ fast: Boolean(session.fast_mode)
115
+ };
116
+ }),
117
+ openChild: async (call) => {
118
+ const { run } = call;
119
+ const ws = run.workspaceId ? reads.getWorkspace(run.workspaceId) : null;
120
+ if (!ws)
121
+ throw new WorkflowCoordinatorError('workflow_not_found', 'The Workflow workspace is unavailable.', {
122
+ status: 404
123
+ });
124
+ // A lock probe is read-only and happens before the durable dispatch boundary.
125
+ // Otherwise a locked Mac would quarantine an effect whose child tab was never attempted.
126
+ if ((await screenLocked()) === true) {
127
+ throw new WorkflowCoordinatorError('workflow_effect_failed', 'The Mac is locked — unlock it and retry Workflow.');
128
+ }
129
+ return withWorkflowEffectGate(call, async () => {
130
+ const opened = await openChat(ws);
131
+ if ('error' in opened) {
132
+ throw new WorkflowCoordinatorError('workflow_effect_failed', opened.result.error ?? 'Conductor did not open a tracked child chat.', { retryable: opened.retryable !== false });
133
+ }
134
+ if (!opened.sessionId) {
135
+ throw new WorkflowCoordinatorError('workflow_effect_failed', 'Conductor opened a child tab but did not record its exact session ID.');
136
+ }
137
+ return { sessionId: opened.sessionId };
138
+ });
139
+ },
140
+ captureSessionBaseline: async (workspaceId) => {
141
+ const ws = reads.getWorkspace(workspaceId);
142
+ if (!ws) {
143
+ throw new WorkflowCoordinatorError('workflow_not_found', 'The Workflow workspace is unavailable.', {
144
+ status: 404
145
+ });
146
+ }
147
+ return {
148
+ kind: 'session_ids',
149
+ workspaceId,
150
+ sessionIds: reads
151
+ .listSessions(workspaceId)
152
+ .map(session => session.id)
153
+ .sort()
154
+ };
155
+ },
156
+ captureDeliveryCursor: async (sessionId) => workflowDeliveryCursor(sessionId),
157
+ captureTranscriptCursor: async (sessionId) => ({ rowid: reads.getMessages(sessionId).cursor }),
158
+ materializeHandoff: async ({ run, job }) => {
159
+ const ws = run.workspaceId ? reads.getWorkspace(run.workspaceId) : null;
160
+ if (!ws?.worktree || !run.rootSessionId)
161
+ return undefined;
162
+ const cursor = job.transcriptCursor && typeof job.transcriptCursor === 'object'
163
+ ? job.transcriptCursor.rowid
164
+ : undefined;
165
+ const entries = reads
166
+ .getMessages(run.rootSessionId)
167
+ .entries.filter(entry => typeof cursor !== 'number' || entry.rowid <= cursor);
168
+ const rendered = renderTranscript(entries, { thinking: true, tools: false });
169
+ if (!rendered.kept)
170
+ return undefined;
171
+ const body = [
172
+ `# Workflow handoff for ${job.logicalKey}`,
173
+ '',
174
+ `Workflow: ${run.id}`,
175
+ `Workflow job: ${job.id}`,
176
+ `Root chat: ${run.rootSessionId}`,
177
+ '',
178
+ rendered.text
179
+ ].join('\n');
180
+ return stableWorkflowAttachment(ws.worktree, job.id, `Workflow ${job.role} handoff.md`, body);
181
+ },
182
+ sendPrompt: call => sendWorkflowPrompt(call, false),
183
+ returnBaton: call => sendWorkflowPrompt(call, true),
184
+ resolveDeliveryReceipt: async ({ sessionId, receipt }) => {
185
+ const current = reads.deliveryReceiptForId(sessionId, receipt.id);
186
+ if (current?.kind === 'message')
187
+ return { status: 'delivered', receipt: current };
188
+ if (current?.kind === 'outbox')
189
+ return { status: 'pending' };
190
+ return { status: 'lost', evidence: { receiptId: receipt.id, priorKind: receipt.kind } };
191
+ },
192
+ readChildOutcome: async ({ job }) => {
193
+ if (!job.childSessionId || !job.taskReceipt || typeof job.taskReceipt !== 'object')
194
+ return null;
195
+ const receipt = job.taskReceipt;
196
+ if (receipt.kind !== 'message' || !Number.isSafeInteger(receipt.rowid))
197
+ return null;
198
+ const child = reads.getSession(job.childSessionId);
199
+ if (!child) {
200
+ return {
201
+ kind: 'failure',
202
+ code: 'session_not_found',
203
+ message: 'The tracked child chat disappeared.',
204
+ retryClass: 'deterministic'
205
+ };
206
+ }
207
+ const messages = typeof receipt.turnId === 'string'
208
+ ? reads.getMessagesForTurn(job.childSessionId, receipt.turnId, receipt.rowid)
209
+ : reads.getMessages(job.childSessionId, receipt.rowid);
210
+ const assistants = messages.entries.filter(entry => entry.role === 'assistant' && entry.text.trim());
211
+ const last = assistants.at(-1);
212
+ if (child.status === 'error') {
213
+ return {
214
+ kind: 'failure',
215
+ code: 'completion_failed',
216
+ message: last?.text.trim() || 'The tracked child agent stopped with an error.',
217
+ retryClass: 'deterministic',
218
+ evidence: { assistantRowid: last?.rowid }
219
+ };
220
+ }
221
+ if (child.status !== 'idle' || child.background_tasks.length || !last)
222
+ return null;
223
+ return {
224
+ kind: 'success',
225
+ baton: batonText(last.text),
226
+ evidence: { assistantRowid: last.rowid }
227
+ };
228
+ },
229
+ validateBeforeDispatch: async ({ run, effect }) => {
230
+ if (effect.kind !== 'configure_root' && effect.kind !== 'send_root')
231
+ return;
232
+ const sessionId = workflowSessionId(effect);
233
+ if (!sessionId) {
234
+ throw new WorkflowCoordinatorError('workflow_root_not_pristine', 'The Workflow root effect lost its exact session binding before dispatch.');
235
+ }
236
+ assertWorkflowRootStillPristine(run, sessionId);
237
+ },
238
+ reconcileEffect: async ({ run, effect }) => {
239
+ const sessionId = workflowSessionId(effect);
240
+ if (effect.receipt && sessionId && typeof effect.receipt === 'object') {
241
+ const receipt = effect.receipt;
242
+ if (typeof receipt.id === 'string') {
243
+ const current = reads.deliveryReceiptForId(sessionId, receipt.id);
244
+ if (current)
245
+ return { status: 'committed', receipt: current };
246
+ return { status: 'ambiguous', evidence: { receiptId: receipt.id, state: 'missing' } };
247
+ }
248
+ }
249
+ if (effect.kind === 'configure_root' || effect.kind === 'configure_child') {
250
+ const role = effect.inputs && typeof effect.inputs === 'object'
251
+ ? effect.inputs.role
252
+ : undefined;
253
+ const session = sessionId ? reads.getSession(sessionId) : null;
254
+ if (effect.kind === 'configure_root') {
255
+ const ws = run.workspaceId ? reads.getWorkspace(run.workspaceId) : null;
256
+ if (!ws ||
257
+ !session ||
258
+ run.rootSessionId !== sessionId ||
259
+ reads.sessionWorkspaceId(session.id) !== ws.id ||
260
+ !workflowRootInspection(ws, session).pristine) {
261
+ return { status: 'pending' };
262
+ }
263
+ }
264
+ if (role && session && sessionMatchesWorkflowRole(session, role)) {
265
+ return { status: 'committed', receipt: { sessionId, matched: true } };
266
+ }
267
+ }
268
+ if (effect.kind === 'create_workspace') {
269
+ const baseline = workspaceBaseline(effect.baseline);
270
+ if (!baseline)
271
+ return { status: 'ambiguous', evidence: { baseline: 'invalid' } };
272
+ const prior = new Set(baseline.workspaceIds);
273
+ const candidates = reads
274
+ .listWorkspaces()
275
+ .filter(workspace => workspace.repo_name === baseline.repo && !prior.has(workspace.id))
276
+ .map(workflowWorkspaceCandidate);
277
+ return { status: 'ambiguous', candidates, evidence: { candidateCount: candidates.length } };
278
+ }
279
+ if (effect.kind === 'open_child') {
280
+ const baseline = sessionBaseline(effect.baseline);
281
+ const ws = baseline ? reads.getWorkspace(baseline.workspaceId) : null;
282
+ if (!baseline || !ws)
283
+ return { status: 'ambiguous', evidence: { baseline: 'invalid' } };
284
+ const prior = new Set(baseline.sessionIds);
285
+ const candidates = reads
286
+ .listSessions(ws.id)
287
+ .filter(session => !prior.has(session.id) && workflowRootInspection(ws, session).pristine)
288
+ .map(session => workflowSessionCandidate(ws, session));
289
+ return { status: 'ambiguous', candidates, evidence: { candidateCount: candidates.length } };
290
+ }
291
+ const prompt = workflowEffectPrompt(effect);
292
+ const cursor = readsDeliveryCursor(effect.cursor);
293
+ if (sessionId && cursor) {
294
+ const marker = workflowEffectMarker(effect);
295
+ const receipt = marker
296
+ ? reads.deliveryReceiptContainingSince(sessionId, marker, cursor)
297
+ : prompt
298
+ ? reads.deliveryReceiptSince(sessionId, prompt, cursor)
299
+ : null;
300
+ if (receipt)
301
+ return { status: 'committed', receipt };
302
+ }
303
+ return { status: 'pending' };
304
+ },
305
+ validateAdoption: async ({ effect, candidate }) => {
306
+ if (candidate.kind === 'workspace' && effect.kind === 'create_workspace') {
307
+ const baseline = workspaceBaseline(effect.baseline);
308
+ const ws = reads.getWorkspace(candidate.id);
309
+ if (!baseline || !ws || baseline.workspaceIds.includes(ws.id) || ws.repo_name !== baseline.repo)
310
+ return null;
311
+ return { workspaceId: ws.id };
312
+ }
313
+ if (candidate.kind === 'session' && effect.kind === 'open_child') {
314
+ const baseline = sessionBaseline(effect.baseline);
315
+ const ws = baseline ? reads.getWorkspace(baseline.workspaceId) : null;
316
+ const session = reads.getSession(candidate.id);
317
+ if (!baseline ||
318
+ !ws ||
319
+ !session ||
320
+ baseline.sessionIds.includes(session.id) ||
321
+ reads.sessionWorkspaceId(session.id) !== ws.id ||
322
+ !workflowRootInspection(ws, session).pristine) {
323
+ return null;
324
+ }
325
+ return { sessionId: session.id };
326
+ }
327
+ return null;
328
+ },
329
+ assertCompatibleRelays: async () => {
330
+ const error = await workflowCompatibilityError();
331
+ if (error) {
332
+ throw new WorkflowCoordinatorError('workflow_incompatible_relay', error, {
333
+ status: 409,
334
+ retryable: true
335
+ });
336
+ }
337
+ },
338
+ dispatchMode: effect => actuator.name === 'sidecar' &&
339
+ (effect.kind === 'send_root' ||
340
+ effect.kind === 'send_task' ||
341
+ effect.kind === 'return_baton' ||
342
+ effect.kind === 'authorize_phase')
343
+ ? 'in_process'
344
+ : 'gated_child'
345
+ })
346
+ : null;
347
+ const WORKFLOW_RECOVERY_PHONE_ONLY = 'Workflow recovery is available only from the phone UI.';
348
+ function requirePhoneWorkflowCoordinator(req, forbiddenMessage) {
349
+ if (workflowClientIsMcp(req.headers))
350
+ throw new WorkflowRequestError(forbiddenMessage, 403);
351
+ if (!workflowCoordinator)
352
+ throw new WorkflowCoordinatorError('workflow_incompatible_relay', 'Workflow is unavailable.');
353
+ return workflowCoordinator;
354
+ }
355
+ function wakeWorkflows() {
356
+ if (!workflowCoordinator)
357
+ return;
358
+ for (const workflowId of workflowCoordinator.runIdsNeedingWake()) {
359
+ void workflowCoordinator.wake(workflowId).catch(error => {
360
+ console.error(`[workflow ${workflowId}] wake failed:`, error);
361
+ });
362
+ }
363
+ }
364
+ sessionPoller.subscribe(wakeWorkflows);
365
+ return { workflowCoordinator, requirePhoneWorkflowCoordinator, WORKFLOW_RECOVERY_PHONE_ONLY, wakeWorkflows };
366
+ }
@@ -0,0 +1,35 @@
1
+ import { createBaseServices } from "./services/base.js";
2
+ import { createDelegationsServices } from "./services/delegations.js";
3
+ import { createDeliveryServices } from "./services/delivery.js";
4
+ import { createFilesServices } from "./services/files.js";
5
+ import { createMcpServices } from "./services/mcp.js";
6
+ import { createResponsesServices } from "./services/responses.js";
7
+ import { createVoiceServices } from "./services/voice.js";
8
+ import { createWorkflowServices } from "./services/workflow.js";
9
+ import { createWorkflowProbesServices } from "./services/workflow-probes.js";
10
+ import { createWorkflowStateServices } from "./services/workflow-state.js";
11
+ /** One construction owns every relay connection, queue, and background service. */
12
+ export function createRelayServices() {
13
+ const base = createBaseServices();
14
+ const responses = createResponsesServices({ ...base });
15
+ const mcp = createMcpServices({ ...base, ...responses });
16
+ const voice = createVoiceServices({ ...base });
17
+ const delivery = createDeliveryServices({ ...base });
18
+ const delegations = createDelegationsServices({ ...base, ...delivery });
19
+ const workflowState = createWorkflowStateServices({ ...base, ...responses });
20
+ const workflowProbes = createWorkflowProbesServices({ ...base, ...delivery });
21
+ const workflow = createWorkflowServices({ ...base, ...workflowProbes, ...delivery, ...delegations });
22
+ const files = createFilesServices({ ...responses, ...base });
23
+ return {
24
+ ...base,
25
+ ...responses,
26
+ ...mcp,
27
+ ...voice,
28
+ ...delivery,
29
+ ...delegations,
30
+ ...workflowState,
31
+ ...workflowProbes,
32
+ ...workflow,
33
+ ...files
34
+ };
35
+ }
@@ -0,0 +1,14 @@
1
+ export const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : undefined);
2
+ export const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);
3
+ export function need(args, key) {
4
+ const v = str(args[key]);
5
+ if (!v)
6
+ throw new Error(`${key} is required`);
7
+ return v;
8
+ }
9
+ export function rejectUnknown(args, allowed) {
10
+ const accepted = new Set(allowed);
11
+ const unknown = Object.keys(args).filter(key => !accepted.has(key));
12
+ if (unknown.length)
13
+ throw new Error(`unknown ${unknown.length === 1 ? 'field' : 'fields'}: ${unknown.join(', ')}`);
14
+ }
@@ -0,0 +1,56 @@
1
+ import { str } from "./arguments.js";
2
+ import { INSTRUCTIONS, PROTOCOL_VERSIONS, SERVER_INFO } from "./protocol.js";
3
+ const ok = (id, result) => ({ jsonrpc: '2.0', id: id ?? null, result });
4
+ const err = (id, code, message) => ({
5
+ jsonrpc: '2.0',
6
+ id: id ?? null,
7
+ error: { code, message }
8
+ });
9
+ /**
10
+ * Handle one JSON-RPC message. Returns null for a notification, which by spec takes
11
+ * no reply at all — stdio writes nothing and HTTP answers 202.
12
+ */
13
+ export async function handleRpc(tools, req) {
14
+ const notification = req.id === undefined || req.id === null;
15
+ switch (req.method) {
16
+ case 'initialize': {
17
+ const asked = str(req.params?.protocolVersion);
18
+ return ok(req.id, {
19
+ // Echo the client's version when we know it, else name our newest. A client
20
+ // that can't live with the answer disconnects, which is the spec's own path.
21
+ protocolVersion: asked && PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],
22
+ capabilities: { tools: {} },
23
+ serverInfo: SERVER_INFO,
24
+ instructions: INSTRUCTIONS
25
+ });
26
+ }
27
+ case 'notifications/initialized':
28
+ case 'notifications/cancelled':
29
+ return null;
30
+ case 'ping':
31
+ return notification ? null : ok(req.id, {});
32
+ case 'tools/list':
33
+ return ok(req.id, {
34
+ tools: tools.map(t => ({ name: t.name, description: t.description, inputSchema: t.inputSchema }))
35
+ });
36
+ case 'tools/call': {
37
+ const name = str(req.params?.name);
38
+ const tool = tools.find(t => t.name === name);
39
+ if (!tool)
40
+ return err(req.id, -32602, `unknown tool: ${name}`);
41
+ const args = req.params?.arguments ?? {};
42
+ try {
43
+ const text = await tool.run(args);
44
+ return ok(req.id, { content: [{ type: 'text', text: text || '(no output)' }] });
45
+ }
46
+ catch (e) {
47
+ // A tool failure is a result the model should see and can act on, not a
48
+ // protocol error that would hide the reason behind a transport code.
49
+ const message = e instanceof Error ? e.message : String(e);
50
+ return ok(req.id, { content: [{ type: 'text', text: message }], isError: true });
51
+ }
52
+ }
53
+ default:
54
+ return notification ? null : err(req.id, -32601, `method not found: ${req.method}`);
55
+ }
56
+ }