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,157 @@
1
+ import { isTerminalWorkflowPhase } from "../workflow/machine.js";
2
+ import { WorkflowTransitionError } from "./errors.js";
3
+ import { appendEvent, findEvent, touchRun } from "./events.js";
4
+ import { requireEffect, requireEffectByAction, requireEffectOwner, requireRun } from "./records.js";
5
+ import { optionalJson, processAuditKey, RUNNABLE_PHASES, TERMINAL_EFFECT_STATES, validateProcessIdentity, validateRelayIdentity } from "./values.js";
6
+ export function markWorkflowEffectDispatched(context, input) {
7
+ validateRelayIdentity(input.owner);
8
+ if (input.externalProcess)
9
+ validateProcessIdentity(input.externalProcess, 'external effect process');
10
+ return context.immediate(() => {
11
+ const run = requireRun(context, input.runId);
12
+ if (!RUNNABLE_PHASES.includes(run.phase)) {
13
+ throw new WorkflowTransitionError(`Workflow ${run.id} cannot dispatch a UI effect while ${run.phase}`);
14
+ }
15
+ return transitionEffect(context, {
16
+ ...input,
17
+ from: ['prepared'],
18
+ to: 'dispatched',
19
+ mayExecute: input.mayExecute ?? false,
20
+ eventKey: input.eventKey ?? `effect_dispatched:${input.actionId}:${input.attemptNumber}`,
21
+ eventType: 'workflow_effect_dispatched'
22
+ });
23
+ });
24
+ }
25
+ export function markWorkflowEffectMayExecute(context, input) {
26
+ validateRelayIdentity(input.owner);
27
+ if (input.externalProcess)
28
+ validateProcessIdentity(input.externalProcess, 'external effect process');
29
+ return context.immediate(() => {
30
+ const run = requireRun(context, input.runId);
31
+ if (!RUNNABLE_PHASES.includes(run.phase)) {
32
+ throw new WorkflowTransitionError(`Workflow ${run.id} cannot release a UI gate while ${run.phase}`);
33
+ }
34
+ const effect = requireEffectByAction(context, input.runId, input.actionId);
35
+ requireEffectOwner(effect, input.owner, input.attemptNumber);
36
+ if (effect.state !== 'dispatched' || effect.launchNonce !== input.launchNonce) {
37
+ throw new WorkflowTransitionError(`effect ${input.actionId} is not the matching dispatched attempt`);
38
+ }
39
+ const identityKey = input.externalProcess ? processAuditKey(input.externalProcess) : 'in-process';
40
+ const eventKey = `effect_may_execute:${input.actionId}:${input.attemptNumber}:${identityKey}`;
41
+ const prior = findEvent(context, input.runId, eventKey);
42
+ if (prior) {
43
+ if (prior.type !== 'workflow_effect_may_execute') {
44
+ throw new WorkflowTransitionError(`effect execution event ${eventKey} conflicts with existing audit`);
45
+ }
46
+ return effect;
47
+ }
48
+ const at = context.now();
49
+ const externalProcess = input.externalProcess ?? effect.externalProcess;
50
+ context.db
51
+ .prepare(`UPDATE workflow_effects SET may_execute = 1, external_pid = ?, external_process_started_at = ?,
52
+ external_process_group = ?, updated_at = ? WHERE id = ?`)
53
+ .run(externalProcess?.pid ?? null, externalProcess?.processStartedAt ?? null, externalProcess?.processGroup ?? null, at, effect.id);
54
+ context.db
55
+ .prepare(`UPDATE workflow_effect_attempts SET may_execute = 1, external_pid = ?,
56
+ external_process_started_at = ?, external_process_group = ?, updated_at = ?
57
+ WHERE effect_id = ? AND attempt_number = ?`)
58
+ .run(externalProcess?.pid ?? null, externalProcess?.processStartedAt ?? null, externalProcess?.processGroup ?? null, at, effect.id, input.attemptNumber);
59
+ touchRun(context, input.runId, at);
60
+ appendEvent(context, input.runId, eventKey, 'workflow_effect_may_execute', {
61
+ effectId: effect.id,
62
+ actionId: input.actionId,
63
+ attemptNumber: input.attemptNumber,
64
+ ...(input.externalProcess ? { externalProcess: input.externalProcess } : {})
65
+ });
66
+ return requireEffect(context, effect.id);
67
+ });
68
+ }
69
+ export function markWorkflowEffectCommitted(context, input) {
70
+ return transitionEffect(context, {
71
+ ...input,
72
+ from: ['dispatched', 'ambiguous'],
73
+ to: 'committed',
74
+ eventKey: input.eventKey ?? `effect_committed:${input.actionId}`,
75
+ eventType: 'workflow_effect_committed'
76
+ });
77
+ }
78
+ export function markWorkflowEffectFailed(context, input) {
79
+ return transitionEffect(context, {
80
+ ...input,
81
+ from: ['prepared'],
82
+ to: 'failed',
83
+ eventKey: input.eventKey ?? `effect_failed:${input.actionId}:${input.attemptNumber}`,
84
+ eventType: 'workflow_effect_failed'
85
+ });
86
+ }
87
+ export function markWorkflowEffectFailedBeforeMayExecute(context, input) {
88
+ return transitionEffect(context, {
89
+ ...input,
90
+ from: ['dispatched'],
91
+ to: 'failed',
92
+ requireMayExecute: false,
93
+ mayExecute: false,
94
+ eventKey: input.eventKey ?? `effect_failed_before_execute:${input.actionId}:${input.attemptNumber}`,
95
+ eventType: 'workflow_effect_failed_before_may_execute'
96
+ });
97
+ }
98
+ export function markWorkflowEffectAmbiguous(context, input) {
99
+ return transitionEffect(context, {
100
+ ...input,
101
+ from: ['dispatched'],
102
+ to: 'ambiguous',
103
+ eventKey: input.eventKey ?? `effect_ambiguous:${input.actionId}`,
104
+ eventType: 'workflow_effect_ambiguous'
105
+ });
106
+ }
107
+ export function markWorkflowEffectCancelled(context, input) {
108
+ return transitionEffect(context, {
109
+ ...input,
110
+ from: ['prepared', 'failed'],
111
+ to: 'cancelled',
112
+ eventKey: input.eventKey ?? `effect_cancelled:${input.actionId}`,
113
+ eventType: 'workflow_effect_cancelled'
114
+ });
115
+ }
116
+ export function transitionEffect(context, input) {
117
+ return context.immediate(() => {
118
+ const effect = requireEffectByAction(context, input.runId, input.actionId);
119
+ const run = requireRun(context, input.runId);
120
+ if (!input.from.includes(effect.state)) {
121
+ throw new WorkflowTransitionError(`effect ${input.actionId} is ${effect.state}, expected ${input.from.join(' or ')}`);
122
+ }
123
+ if (input.requireMayExecute !== undefined && effect.mayExecute !== input.requireMayExecute) {
124
+ throw new WorkflowTransitionError(`effect ${input.actionId} mayExecute evidence changed`);
125
+ }
126
+ const attemptNumber = input.attemptNumber ?? (effect.attemptCount > 0 ? effect.attemptCount : undefined);
127
+ if (input.owner && attemptNumber !== undefined) {
128
+ requireEffectOwner(effect, input.owner, attemptNumber);
129
+ }
130
+ const at = context.now();
131
+ const terminalAt = TERMINAL_EFFECT_STATES.includes(input.to) ? at : null;
132
+ const externalProcess = input.externalProcess ?? effect.externalProcess;
133
+ context.db
134
+ .prepare(`UPDATE workflow_effects SET state = ?, launch_nonce = ?, external_pid = ?,
135
+ external_process_started_at = ?, external_process_group = ?, may_execute = ?, receipt_json = ?,
136
+ error_code = ?, error_message = ?, updated_at = ?, terminal_at = ? WHERE id = ?`)
137
+ .run(input.to, input.launchNonce ?? effect.launchNonce ?? null, externalProcess?.pid ?? null, externalProcess?.processStartedAt ?? null, externalProcess?.processGroup ?? null, input.mayExecute === undefined ? (effect.mayExecute ? 1 : 0) : input.mayExecute ? 1 : 0, input.receipt === undefined ? optionalJson(effect.receipt) : optionalJson(input.receipt), input.errorCode ?? effect.errorCode ?? null, input.errorMessage ?? effect.errorMessage ?? null, at, terminalAt, effect.id);
138
+ if (attemptNumber !== undefined) {
139
+ context.db
140
+ .prepare(`UPDATE workflow_effect_attempts SET state = ?, launch_nonce = ?, external_pid = ?,
141
+ external_process_started_at = ?, external_process_group = ?, may_execute = ?, receipt_json = ?,
142
+ evidence_json = ?, error_code = ?, error_message = ?, updated_at = ?, terminal_at = ?
143
+ WHERE effect_id = ? AND attempt_number = ?`)
144
+ .run(input.to, input.launchNonce ?? effect.launchNonce ?? null, externalProcess?.pid ?? null, externalProcess?.processStartedAt ?? null, externalProcess?.processGroup ?? null, input.mayExecute === undefined ? (effect.mayExecute ? 1 : 0) : input.mayExecute ? 1 : 0, input.receipt === undefined ? optionalJson(effect.receipt) : optionalJson(input.receipt), optionalJson(input.evidence), input.errorCode ?? null, input.errorMessage ?? null, at, terminalAt, effect.id, attemptNumber);
145
+ }
146
+ touchRun(context, input.runId, at);
147
+ const late = input.to === 'committed' && isTerminalWorkflowPhase(run.phase);
148
+ appendEvent(context, input.runId, input.eventKey, late ? 'late_effect' : input.eventType, {
149
+ effectId: effect.id,
150
+ actionId: input.actionId,
151
+ attemptNumber,
152
+ errorCode: input.errorCode,
153
+ ...(late ? { intendedEventType: input.eventType } : {})
154
+ });
155
+ return requireEffect(context, effect.id);
156
+ });
157
+ }
@@ -0,0 +1,109 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { and, eq } from 'drizzle-orm';
3
+ import { decodeEffect } from "./codecs.js";
4
+ import { WorkflowTransitionError } from "./errors.js";
5
+ import { appendEvent, touchRun } from "./events.js";
6
+ import { canonicalOptional } from "./idempotency.js";
7
+ import { checkRunGuard, getWorkflowEffect, requireEffect, requireEffectAttempt, requireEffectByAction, requireRun } from "./records.js";
8
+ import { workflowEffects } from "./schema.js";
9
+ import { ACTIVE_PHASES, json, nonEmpty, optionalJson, RUNNABLE_PHASES, validateRelayIdentity } from "./values.js";
10
+ export function insertEffect(context, input) {
11
+ context.db
12
+ .prepare(`INSERT INTO workflow_effects (
13
+ id, run_id, action_id, job_id, kind, state, target_json, inputs_json, baseline_json,
14
+ cursor_json, created_at, updated_at
15
+ ) VALUES (?, ?, ?, ?, ?, 'prepared', ?, ?, ?, ?, ?, ?)`)
16
+ .run(input.id, input.runId, input.actionId, input.jobId ?? null, nonEmpty(input.kind, 'effect kind'), optionalJson(input.target), optionalJson(input.inputs), optionalJson(input.baseline), optionalJson(input.cursor), input.at, input.at);
17
+ }
18
+ export function prepareWorkflowEffect(context, input) {
19
+ return context.immediate(() => {
20
+ const run = requireRun(context, input.runId);
21
+ checkRunGuard(run, ACTIVE_PHASES, input.expectedCancellationGeneration);
22
+ const existing = context.orm
23
+ .select()
24
+ .from(workflowEffects)
25
+ .where(and(eq(workflowEffects.runId, input.runId), eq(workflowEffects.actionId, input.actionId)))
26
+ .get();
27
+ if (existing) {
28
+ const effect = decodeEffect(existing);
29
+ const same = effect.kind === input.kind &&
30
+ effect.jobId === input.jobId &&
31
+ canonicalOptional(effect.target) === canonicalOptional(input.target) &&
32
+ canonicalOptional(effect.inputs) === canonicalOptional(input.inputs) &&
33
+ canonicalOptional(effect.baseline) === canonicalOptional(input.baseline) &&
34
+ canonicalOptional(effect.cursor) === canonicalOptional(input.cursor);
35
+ if (!same)
36
+ throw new WorkflowTransitionError(`action ${input.actionId} already has different frozen inputs`);
37
+ return { created: false, effect };
38
+ }
39
+ const id = input.id ?? randomUUID();
40
+ const at = context.now();
41
+ insertEffect(context, { ...input, id, at });
42
+ touchRun(context, input.runId, at);
43
+ appendEvent(context, input.runId, input.eventKey, 'workflow_effect_prepared', {
44
+ effectId: id,
45
+ actionId: input.actionId,
46
+ kind: input.kind,
47
+ jobId: input.jobId
48
+ });
49
+ return { created: true, effect: requireEffect(context, id) };
50
+ });
51
+ }
52
+ /** Commit a positively reconciled settings match without entering the UI dispatch boundary. */
53
+ export function markWorkflowEffectSatisfiedWithoutDispatch(context, input) {
54
+ return context.immediate(() => {
55
+ const run = requireRun(context, input.runId);
56
+ checkRunGuard(run, RUNNABLE_PHASES, input.expectedCancellationGeneration);
57
+ const effect = requireEffectByAction(context, input.runId, input.actionId);
58
+ if (effect.kind !== 'configure_root' && effect.kind !== 'configure_child') {
59
+ throw new WorkflowTransitionError(`effect ${input.actionId} is not a configuration effect`);
60
+ }
61
+ if (effect.state !== 'prepared' || effect.owner || effect.mayExecute) {
62
+ throw new WorkflowTransitionError(`effect ${input.actionId} is not an unowned prepared configuration`);
63
+ }
64
+ const at = context.now();
65
+ const result = context.db
66
+ .prepare(`UPDATE workflow_effects SET state = 'committed', receipt_json = ?, updated_at = ?, terminal_at = ?
67
+ WHERE id = ? AND state = 'prepared' AND owner_instance_id IS NULL AND may_execute = 0`)
68
+ .run(json(input.receipt), at, at, effect.id);
69
+ if (Number(result.changes) !== 1) {
70
+ throw new WorkflowTransitionError(`configuration effect ${input.actionId} changed concurrently`);
71
+ }
72
+ touchRun(context, input.runId, at);
73
+ appendEvent(context, input.runId, input.eventKey ?? `effect_satisfied_without_dispatch:${input.actionId}`, 'workflow_effect_satisfied_without_dispatch', { effectId: effect.id, actionId: effect.actionId, receipt: input.receipt });
74
+ return requireEffect(context, effect.id);
75
+ });
76
+ }
77
+ export function claimPreparedWorkflowEffect(context, input) {
78
+ validateRelayIdentity(input.owner);
79
+ return context.immediate(() => {
80
+ const run = requireRun(context, input.runId);
81
+ checkRunGuard(run, RUNNABLE_PHASES, input.expectedCancellationGeneration);
82
+ const effect = getWorkflowEffect(context, input.runId, input.actionId);
83
+ if (effect?.state !== 'prepared' || effect.owner)
84
+ return undefined;
85
+ const attemptNumber = effect.attemptCount + 1;
86
+ const attemptId = `${effect.id}:attempt:${attemptNumber}`;
87
+ const at = context.now();
88
+ const result = context.db
89
+ .prepare(`UPDATE workflow_effects SET owner_instance_id = ?, owner_pid = ?, owner_process_started_at = ?,
90
+ owner_protocol_version = ?, attempt_count = ?, updated_at = ?
91
+ WHERE id = ? AND state = 'prepared' AND owner_instance_id IS NULL`)
92
+ .run(input.owner.instanceId, input.owner.pid, input.owner.processStartedAt, input.owner.protocolVersion, attemptNumber, at, effect.id);
93
+ if (Number(result.changes) !== 1)
94
+ return undefined;
95
+ context.db
96
+ .prepare(`INSERT INTO workflow_effect_attempts (
97
+ id, effect_id, attempt_number, state, owner_instance_id, owner_pid,
98
+ owner_process_started_at, owner_protocol_version, created_at, updated_at
99
+ ) VALUES (?, ?, ?, 'prepared', ?, ?, ?, ?, ?, ?)`)
100
+ .run(attemptId, effect.id, attemptNumber, input.owner.instanceId, input.owner.pid, input.owner.processStartedAt, input.owner.protocolVersion, at, at);
101
+ touchRun(context, input.runId, at);
102
+ appendEvent(context, input.runId, `effect_claimed:${input.actionId}:${attemptNumber}`, 'workflow_effect_claimed', {
103
+ effectId: effect.id,
104
+ actionId: input.actionId,
105
+ attemptNumber
106
+ });
107
+ return { effect: requireEffect(context, effect.id), attempt: requireEffectAttempt(context, attemptId) };
108
+ });
109
+ }
@@ -0,0 +1,39 @@
1
+ import { ORCHESTRATION_SCHEMA_VERSION } from "./schema.js";
2
+ export class OrchestrationError extends Error {
3
+ }
4
+ export class UnsupportedOrchestrationSchemaError extends OrchestrationError {
5
+ foundVersion;
6
+ supportedVersion = ORCHESTRATION_SCHEMA_VERSION;
7
+ constructor(foundVersion) {
8
+ super(`orchestration schema ${foundVersion} is newer than supported schema ${ORCHESTRATION_SCHEMA_VERSION}`);
9
+ this.name = 'UnsupportedOrchestrationSchemaError';
10
+ this.foundVersion = foundVersion;
11
+ }
12
+ }
13
+ export class IdempotencyConflictError extends OrchestrationError {
14
+ operation;
15
+ clientId;
16
+ constructor(operation, clientId) {
17
+ super(`clientId ${clientId} was already used with a different ${operation} request`);
18
+ this.name = 'IdempotencyConflictError';
19
+ this.operation = operation;
20
+ this.clientId = clientId;
21
+ }
22
+ }
23
+ export class WorkflowTransitionError extends OrchestrationError {
24
+ constructor(message) {
25
+ super(message);
26
+ this.name = 'WorkflowTransitionError';
27
+ }
28
+ }
29
+ export class UiLeaseUnavailableError extends OrchestrationError {
30
+ result;
31
+ constructor(result) {
32
+ const message = result.status === 'busy'
33
+ ? `Conductor's UI is busy — held by relay PID ${result.owner.pid} (${result.reason}). Try again shortly.`
34
+ : `Conductor's UI is quarantined — ${result.quarantine.reason ?? 'confirm Conductor is stable on the phone'}.`;
35
+ super(message);
36
+ this.name = 'UiLeaseUnavailableError';
37
+ this.result = result;
38
+ }
39
+ }
@@ -0,0 +1,29 @@
1
+ import { and, asc, eq } from 'drizzle-orm';
2
+ import { decodeEvent } from "./codecs.js";
3
+ import { workflowEvents } from "./schema.js";
4
+ import { nonEmpty, optionalJson } from "./values.js";
5
+ export function listWorkflowEvents(context, runId) {
6
+ return context.orm
7
+ .select()
8
+ .from(workflowEvents)
9
+ .where(eq(workflowEvents.runId, runId))
10
+ .orderBy(asc(workflowEvents.id))
11
+ .all()
12
+ .map(row => decodeEvent(row));
13
+ }
14
+ export function findEvent(context, runId, eventKey) {
15
+ const row = context.orm
16
+ .select()
17
+ .from(workflowEvents)
18
+ .where(and(eq(workflowEvents.runId, runId), eq(workflowEvents.eventKey, eventKey)))
19
+ .get();
20
+ return row ? decodeEvent(row) : undefined;
21
+ }
22
+ export function appendEvent(context, runId, eventKey, type, data) {
23
+ context.db
24
+ .prepare('INSERT INTO workflow_events(run_id, event_key, type, data_json, created_at) VALUES (?, ?, ?, ?, ?)')
25
+ .run(runId, nonEmpty(eventKey, 'event key'), nonEmpty(type, 'event type'), optionalJson(data), context.now());
26
+ }
27
+ export function touchRun(context, runId, at) {
28
+ context.db.prepare('UPDATE workflow_runs SET updated_at = ? WHERE id = ?').run(at, runId);
29
+ }
@@ -0,0 +1,82 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { and, eq } from 'drizzle-orm';
3
+ import { IdempotencyConflictError, OrchestrationError } from "./errors.js";
4
+ import { workflowIdempotency } from "./schema.js";
5
+ import { asObject, isPromiseLike, json, nonEmpty } from "./values.js";
6
+ const canonicalize = (value, inArray = false) => {
7
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
8
+ return value;
9
+ if (typeof value === 'number') {
10
+ if (!Number.isFinite(value))
11
+ throw new OrchestrationError('canonical request contains a non-finite number');
12
+ return Object.is(value, -0) ? 0 : value;
13
+ }
14
+ if (typeof value === 'undefined')
15
+ return inArray ? null : undefined;
16
+ if (Array.isArray(value))
17
+ return value.map(entry => canonicalize(entry, true));
18
+ if (typeof value !== 'object' || Object.getPrototypeOf(value) !== Object.prototype) {
19
+ throw new OrchestrationError('canonical requests must contain only JSON objects and values');
20
+ }
21
+ const result = {};
22
+ for (const key of Object.keys(value).sort()) {
23
+ const normalized = canonicalize(value[key]);
24
+ if (normalized !== undefined)
25
+ result[key] = normalized;
26
+ }
27
+ return result;
28
+ };
29
+ export const canonicalRequestJson = (request) => json(canonicalize(request));
30
+ export const canonicalOptional = (value) => value === undefined ? '__orchestration_undefined__' : canonicalRequestJson(value);
31
+ export const canonicalRequestHash = (request) => createHash('sha256').update(canonicalRequestJson(request)).digest('hex');
32
+ export const hashCapabilityToken = (token) => createHash('sha256').update(nonEmpty(token, 'capability token')).digest('hex');
33
+ export function idempotentMutation(context, operation, clientId, request, mutate, link = {}) {
34
+ nonEmpty(operation, 'operation');
35
+ nonEmpty(clientId, 'clientId');
36
+ const requestHash = canonicalRequestHash(request);
37
+ return context.immediate(() => {
38
+ const existing = context.orm
39
+ .select({ requestHash: workflowIdempotency.requestHash, result: workflowIdempotency.result })
40
+ .from(workflowIdempotency)
41
+ .where(and(eq(workflowIdempotency.operation, operation), eq(workflowIdempotency.clientId, clientId)))
42
+ .get();
43
+ if (existing) {
44
+ if (existing.requestHash !== requestHash)
45
+ throw new IdempotencyConflictError(operation, clientId);
46
+ return { replayed: true, result: existing.result };
47
+ }
48
+ const result = mutate();
49
+ if (isPromiseLike(result))
50
+ throw new OrchestrationError('idempotent mutations must be synchronous');
51
+ const resultRecord = asObject(result);
52
+ const resultRunId = typeof resultRecord.runId === 'string' ? resultRecord.runId : undefined;
53
+ const resultActionId = typeof resultRecord.actionId === 'string' ? resultRecord.actionId : undefined;
54
+ context.db
55
+ .prepare(`INSERT INTO workflow_idempotency
56
+ (operation, client_id, request_hash, result_json, run_id, action_id, created_at)
57
+ VALUES (?, ?, ?, ?, ?, ?, ?)`)
58
+ .run(operation, clientId, requestHash, json(result), link.runId ?? resultRunId ?? null, link.actionId ?? resultActionId ?? null, context.now());
59
+ return { replayed: false, result };
60
+ });
61
+ }
62
+ /**
63
+ * Read the stable result before re-running live preconditions. This matters for
64
+ * Workflow Start: after the first accepted request, its root is intentionally no
65
+ * longer pristine and roles.json may have changed, but an identical client retry
66
+ * must still receive the original accepted run.
67
+ */
68
+ export function getIdempotentMutation(context, operation, clientId, request) {
69
+ nonEmpty(operation, 'operation');
70
+ nonEmpty(clientId, 'clientId');
71
+ const existing = context.orm
72
+ .select({ requestHash: workflowIdempotency.requestHash, result: workflowIdempotency.result })
73
+ .from(workflowIdempotency)
74
+ .where(and(eq(workflowIdempotency.operation, operation), eq(workflowIdempotency.clientId, clientId)))
75
+ .get();
76
+ if (!existing)
77
+ return undefined;
78
+ if (existing.requestHash !== canonicalRequestHash(request)) {
79
+ throw new IdempotencyConflictError(operation, clientId);
80
+ }
81
+ return { result: existing.result };
82
+ }
@@ -0,0 +1,114 @@
1
+ import { isTerminalWorkflowJobState } from "../workflow/machine.js";
2
+ import { WorkflowTransitionError } from "./errors.js";
3
+ import { appendEvent, findEvent, touchRun } from "./events.js";
4
+ import { canonicalOptional } from "./idempotency.js";
5
+ import { requireJob, requireJobAttempt, requireRun } from "./records.js";
6
+ import { json, optionalJson, sameOwner, validateRelayIdentity } from "./values.js";
7
+ export function createWorkflowJobAttempt(context, input) {
8
+ validateRelayIdentity(input.owner);
9
+ return context.immediate(() => {
10
+ const job = requireJob(context, input.jobId);
11
+ const run = requireRun(context, job.runId);
12
+ if (run.phase === 'completed' ||
13
+ run.phase === 'cancelled' ||
14
+ job.cancellationGeneration !== run.cancellationGeneration) {
15
+ throw new WorkflowTransitionError(`cannot create an attempt for inactive job ${job.id}`);
16
+ }
17
+ if (job.state === 'cancelled' || job.state === 'returned') {
18
+ throw new WorkflowTransitionError(`cannot attempt ${job.state} job ${job.id}`);
19
+ }
20
+ if (job.state !== 'owned' || !job.owner || !sameOwner(job.owner, input.owner)) {
21
+ throw new WorkflowTransitionError(`job ${job.id} is not claimed by this relay`);
22
+ }
23
+ const attemptNumber = job.attemptCount + 1;
24
+ const id = `${job.id}:attempt:${attemptNumber}`;
25
+ const at = context.now();
26
+ context.db
27
+ .prepare(`INSERT INTO workflow_job_attempts (
28
+ id, job_id, attempt_number, state, child_session_id, open_effect_id, configure_effect_id,
29
+ task_effect_id, baton_effect_id, owner_instance_id, owner_pid, owner_process_started_at,
30
+ owner_protocol_version, created_at, updated_at
31
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
32
+ .run(id, job.id, attemptNumber, input.state ?? job.state, input.childSessionId ?? null, input.effectIds?.open ?? null, input.effectIds?.configure ?? null, input.effectIds?.task ?? null, input.effectIds?.baton ?? null, input.owner.instanceId, input.owner.pid, input.owner.processStartedAt, input.owner.protocolVersion, at, at);
33
+ context.db
34
+ .prepare('UPDATE workflow_jobs SET attempt_count = ?, updated_at = ? WHERE id = ?')
35
+ .run(attemptNumber, at, job.id);
36
+ touchRun(context, job.runId, at);
37
+ appendEvent(context, job.runId, `job_attempt:${job.id}:${attemptNumber}`, 'workflow_job_attempt_created', {
38
+ jobId: job.id,
39
+ attemptNumber
40
+ });
41
+ return requireJobAttempt(context, id);
42
+ });
43
+ }
44
+ export function updateWorkflowJobAttempt(context, input) {
45
+ return context.immediate(() => {
46
+ const job = requireJob(context, input.jobId);
47
+ const run = requireRun(context, job.runId);
48
+ if (run.phase === 'completed' ||
49
+ run.phase === 'cancelled' ||
50
+ job.state === 'cancelled' ||
51
+ job.cancellationGeneration !== run.cancellationGeneration) {
52
+ throw new WorkflowTransitionError(`cannot advance an attempt for inactive job ${job.id}`);
53
+ }
54
+ const id = `${job.id}:attempt:${input.attemptNumber}`;
55
+ const attempt = requireJobAttempt(context, id);
56
+ if (attempt.state !== input.expectedState) {
57
+ throw new WorkflowTransitionError(`job attempt ${input.attemptNumber} is ${attempt.state}, expected ${input.expectedState}`);
58
+ }
59
+ const at = context.now();
60
+ const terminalAt = isTerminalWorkflowJobState(input.state) ? at : null;
61
+ const result = context.db
62
+ .prepare(`UPDATE workflow_job_attempts SET state = ?, child_session_id = ?, outcome_json = ?,
63
+ failure_evidence_json = ?, updated_at = ?, terminal_at = ?
64
+ WHERE id = ? AND state = ?`)
65
+ .run(input.state, input.childSessionId === undefined ? (attempt.childSessionId ?? null) : input.childSessionId, input.outcome === undefined ? optionalJson(attempt.outcome) : optionalJson(input.outcome), input.failureEvidence === undefined
66
+ ? optionalJson(attempt.failureEvidence)
67
+ : optionalJson(input.failureEvidence), at, terminalAt, id, input.expectedState);
68
+ if (Number(result.changes) !== 1)
69
+ throw new WorkflowTransitionError(`job attempt ${id} changed concurrently`);
70
+ touchRun(context, job.runId, at);
71
+ appendEvent(context, job.runId, input.eventKey, input.eventType, {
72
+ jobId: job.id,
73
+ attemptNumber: input.attemptNumber,
74
+ state: input.state
75
+ });
76
+ return requireJobAttempt(context, id);
77
+ });
78
+ }
79
+ /** Preserve an outcome observed after cancellation without reopening the job. */
80
+ export function recordLateWorkflowChildResult(context, input) {
81
+ return context.immediate(() => {
82
+ const job = requireJob(context, input.jobId);
83
+ const run = requireRun(context, input.runId);
84
+ if (job.runId !== run.id)
85
+ throw new WorkflowTransitionError(`job ${job.id} does not belong to Workflow ${run.id}`);
86
+ if (run.phase !== 'cancelled' || job.state !== 'cancelled') {
87
+ throw new WorkflowTransitionError(`job ${job.id} is not a cancelled late-result target`);
88
+ }
89
+ const attemptNumber = input.attemptNumber ?? job.attemptCount;
90
+ const attempt = attemptNumber > 0 ? requireJobAttempt(context, `${job.id}:attempt:${attemptNumber}`) : undefined;
91
+ const prior = findEvent(context, run.id, input.eventKey);
92
+ if (prior) {
93
+ if (prior.type !== 'late_child_result' || canonicalOptional(job.outcome) !== canonicalOptional(input.outcome)) {
94
+ throw new WorkflowTransitionError(`late child event ${input.eventKey} conflicts with existing evidence`);
95
+ }
96
+ return job;
97
+ }
98
+ const at = context.now();
99
+ context.db
100
+ .prepare('UPDATE workflow_jobs SET outcome_json = ?, updated_at = ? WHERE id = ?')
101
+ .run(json(input.outcome), at, job.id);
102
+ if (attempt) {
103
+ context.db
104
+ .prepare('UPDATE workflow_job_attempts SET outcome_json = ?, updated_at = ? WHERE id = ?')
105
+ .run(json(input.outcome), at, attempt.id);
106
+ }
107
+ appendEvent(context, run.id, input.eventKey, 'late_child_result', {
108
+ jobId: job.id,
109
+ attemptNumber,
110
+ outcome: input.outcome
111
+ });
112
+ return requireJob(context, job.id);
113
+ });
114
+ }