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,255 @@
1
+ /**
2
+ * Advances persisted ordinary-chat delegations through UI delivery and return.
3
+ * One queue owns retries and the two-observation completion barrier for its stores.
4
+ */
5
+ import { decodeDelegation } from "./codec.js";
6
+ // ── guarded transitions and the single queue producer ──────────────────────────
7
+ const NEXT = {
8
+ queued: ['opening', 'failed'],
9
+ opening: ['configuring', 'failed'],
10
+ configuring: ['sending', 'failed'],
11
+ sending: ['running', 'failed'],
12
+ running: ['returning', 'failed'],
13
+ returning: ['returned', 'failed'],
14
+ returned: [],
15
+ failed: []
16
+ };
17
+ /** Pure state edge: only stage data may change; the accepted envelope stays frozen. */
18
+ export function transitionDelegation(job, status, patch, updatedAt = Date.now()) {
19
+ if (!NEXT[job.status].includes(status))
20
+ throw new Error(`illegal delegation transition ${job.status} → ${status}`);
21
+ if (status === 'failed' && !patch.failure)
22
+ throw new Error('failed requires failure');
23
+ return decodeDelegation({
24
+ ...job,
25
+ status,
26
+ updatedAt,
27
+ ...(patch.childSessionId === undefined ? {} : { childSessionId: patch.childSessionId }),
28
+ ...(patch.handoff === undefined ? {} : { handoff: patch.handoff }),
29
+ ...(patch.sentRowid === undefined ? {} : { sentRowid: patch.sentRowid }),
30
+ ...(patch.completionRowid === undefined ? {} : { completionRowid: patch.completionRowid }),
31
+ ...(patch.returnCursor === undefined ? {} : { returnCursor: patch.returnCursor }),
32
+ ...(patch.returnAttachment === undefined ? {} : { returnAttachment: patch.returnAttachment }),
33
+ ...(patch.returnText === undefined ? {} : { returnText: patch.returnText }),
34
+ ...(patch.returnRowid === undefined ? {} : { returnRowid: patch.returnRowid }),
35
+ ...(patch.outcome === undefined ? {} : { outcome: patch.outcome }),
36
+ ...(patch.failure === undefined ? {} : { failure: patch.failure }),
37
+ ...(patch.attempts === undefined ? {} : { attempts: patch.attempts }),
38
+ ...(patch.lastAttemptAt === undefined ? {} : { lastAttemptAt: patch.lastAttemptAt })
39
+ });
40
+ }
41
+ function actionCode(status) {
42
+ if (status === 'opening')
43
+ return 'opening_failed';
44
+ if (status === 'configuring')
45
+ return 'configuration_failed';
46
+ if (status === 'sending')
47
+ return 'send_failed';
48
+ if (status === 'returning')
49
+ return 'return_failed';
50
+ return 'state_invalid';
51
+ }
52
+ /**
53
+ * One producer for every worktree registered with this process. It performs at
54
+ * most one side effect at a time and stops at `running`; the shared session poller
55
+ * calls `wake()` on later ticks. That keeps waiting jobs out of the UI lock.
56
+ */
57
+ export class DelegationQueue {
58
+ deps;
59
+ now;
60
+ retryDelayMs;
61
+ maxAttempts;
62
+ blockedError;
63
+ onError;
64
+ stores = new Set();
65
+ completionCandidates = new Map();
66
+ pumping = null;
67
+ rerun = false;
68
+ constructor(deps, options = {}) {
69
+ this.deps = deps;
70
+ this.now = options.now ?? Date.now;
71
+ this.retryDelayMs = options.retryDelayMs ?? 5_000;
72
+ this.maxAttempts = options.maxAttempts ?? 3;
73
+ this.blockedError = options.blockedError ?? (() => false);
74
+ this.onError = options.onError ?? (message => console.warn(`[relay] ${message}`));
75
+ }
76
+ /** Persist intake before returning, then let the queue finish independently. */
77
+ enqueue(store, raw) {
78
+ const roles = store.sessionRoles();
79
+ if (roles.warning)
80
+ throw new Error(`cannot enqueue beside malformed sessions.json: ${roles.warning}`);
81
+ const job = store.put(raw);
82
+ this.stores.add(store);
83
+ void this.wake();
84
+ return job;
85
+ }
86
+ /** Register persisted work from startup without rewriting it. */
87
+ resume(stores) {
88
+ for (const store of stores)
89
+ this.stores.add(store);
90
+ void this.wake();
91
+ }
92
+ /** One shared-poller tick (or intake); concurrent calls join the same producer. */
93
+ wake() {
94
+ this.rerun = true;
95
+ if (!this.pumping) {
96
+ this.pumping = this.pump()
97
+ .catch(err => this.onError(`delegation queue failed: ${err instanceof Error ? err.message : err}`))
98
+ .finally(() => {
99
+ this.pumping = null;
100
+ if (this.rerun)
101
+ void this.wake();
102
+ });
103
+ }
104
+ return this.pumping;
105
+ }
106
+ async invoke(status, action) {
107
+ try {
108
+ return await action();
109
+ }
110
+ catch (err) {
111
+ return {
112
+ ok: false,
113
+ code: actionCode(status),
114
+ error: err instanceof Error ? err.message : String(err),
115
+ retryable: true,
116
+ blocked: this.blockedError(err)
117
+ };
118
+ }
119
+ }
120
+ async pump() {
121
+ do {
122
+ this.rerun = false;
123
+ while (await this.stepOne()) { }
124
+ } while (this.rerun);
125
+ }
126
+ /** Find one job able to make progress. Waiting/blocked jobs do not hold up others. */
127
+ async stepOne() {
128
+ const entries = [...this.stores]
129
+ .flatMap(store => store.list().jobs.map(job => ({ store, job })))
130
+ .sort((a, b) => a.job.createdAt - b.job.createdAt || a.job.id.localeCompare(b.job.id));
131
+ for (const { store, job } of entries) {
132
+ if (job.status === 'failed')
133
+ continue;
134
+ if (job.status === 'returned') {
135
+ store.remove(job.id);
136
+ return true;
137
+ }
138
+ if (job.status === 'queued') {
139
+ store.put(transitionDelegation(job, 'opening', {}, this.now()));
140
+ return true;
141
+ }
142
+ if (this.retryPending(job))
143
+ continue;
144
+ if (job.status === 'opening') {
145
+ const result = await this.invoke('opening', () => this.deps.open(job));
146
+ if (!result.ok) {
147
+ if (this.recordFailure(store, job, result))
148
+ return true;
149
+ continue;
150
+ }
151
+ store.assign(result.childSessionId, {
152
+ role: job.role,
153
+ delegationId: job.id,
154
+ parentSessionId: job.parentSessionId,
155
+ assignedAt: this.now()
156
+ });
157
+ store.put(transitionDelegation(job, 'configuring', { childSessionId: result.childSessionId, handoff: result.handoff }, this.now()));
158
+ return true;
159
+ }
160
+ if (job.status === 'configuring') {
161
+ const result = await this.invoke('configuring', () => this.deps.configure(job));
162
+ if (!result.ok) {
163
+ if (this.recordFailure(store, job, result))
164
+ return true;
165
+ continue;
166
+ }
167
+ store.put(transitionDelegation(job, 'sending', {}, this.now()));
168
+ return true;
169
+ }
170
+ if (job.status === 'sending') {
171
+ const result = await this.invoke('sending', () => this.deps.send(job));
172
+ if (!result.ok) {
173
+ if (this.recordFailure(store, job, result))
174
+ return true;
175
+ continue;
176
+ }
177
+ store.put(transitionDelegation(job, 'running', { sentRowid: result.sentRowid }, this.now()));
178
+ return true;
179
+ }
180
+ if (job.status === 'running') {
181
+ let completion;
182
+ try {
183
+ completion = await this.deps.completion(job);
184
+ }
185
+ catch (err) {
186
+ console.warn(`[relay] delegation completion read failed: ${err instanceof Error ? err.message : err}`);
187
+ continue;
188
+ }
189
+ const key = `${job.workspaceId}\0${job.id}`;
190
+ if (!completion) {
191
+ this.completionCandidates.delete(key);
192
+ continue;
193
+ }
194
+ const signature = JSON.stringify(completion);
195
+ if (this.completionCandidates.get(key) !== signature) {
196
+ this.completionCandidates.set(key, signature);
197
+ continue;
198
+ }
199
+ this.completionCandidates.delete(key);
200
+ store.put(transitionDelegation(job, 'returning', { outcome: completion.outcome, completionRowid: completion.completionRowid }, this.now()));
201
+ return true;
202
+ }
203
+ if (job.status === 'returning') {
204
+ const result = await this.invoke('returning', () => this.deps.returnResult(job));
205
+ if (!result.ok) {
206
+ if (this.recordFailure(store, job, result))
207
+ return true;
208
+ continue;
209
+ }
210
+ if ('pending' in result) {
211
+ // A queued Baton clears the composer before SQLite exposes any row.
212
+ // Persist the pre-dispatch cursor once, then only poll for the exact
213
+ // eventual row; repeating the UI action here would enqueue a duplicate.
214
+ if (job.returnCursor === result.returnCursor)
215
+ continue;
216
+ store.put(decodeDelegation({
217
+ ...job,
218
+ returnCursor: result.returnCursor,
219
+ returnAttachment: result.returnAttachment,
220
+ returnText: result.returnText,
221
+ updatedAt: this.now()
222
+ }));
223
+ return true;
224
+ }
225
+ store.put(transitionDelegation(job, 'returned', { returnRowid: result.returnRowid }, this.now()));
226
+ return true;
227
+ }
228
+ }
229
+ return false;
230
+ }
231
+ retryPending(job) {
232
+ return job.attempts > 0 && job.lastAttemptAt !== undefined && this.now() - job.lastAttemptAt < this.retryDelayMs;
233
+ }
234
+ /** True when persistence changed; false for a lock-blocked/no-cost attempt. */
235
+ recordFailure(store, job, result) {
236
+ if (result.blocked)
237
+ return false;
238
+ const attempts = job.attempts + 1;
239
+ const now = this.now();
240
+ if (attempts >= this.maxAttempts || result.retryable === false) {
241
+ store.put(transitionDelegation(job, 'failed', {
242
+ attempts,
243
+ lastAttemptAt: now,
244
+ failure: {
245
+ code: result.code ?? actionCode(job.status),
246
+ message: result.error,
247
+ retryable: result.retryable !== false
248
+ }
249
+ }, now));
250
+ return true;
251
+ }
252
+ store.put(decodeDelegation({ ...job, attempts, lastAttemptAt: now, updatedAt: now }));
253
+ return true;
254
+ }
255
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Worktree-scoped delegated-job and session-role persistence.
3
+ *
4
+ * Conductor owns the chat history; these small files hold only active/failed work
5
+ * plus durable role identity. A decoder failure is public state, not permission to
6
+ * delete a file: callers receive warnings and the bytes remain for repair/dismissal.
7
+ */
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { decodeDelegation, decodeSessionRoles, SAFE_ID, text } from "./codec.js";
11
+ const DIRECTORY = path.join('.context', 'delegations');
12
+ const SESSIONS_FILE = 'sessions.json';
13
+ function atomicWrite(file, value) {
14
+ const temporary = `${file}.${process.pid}.tmp`;
15
+ fs.mkdirSync(path.dirname(file), { recursive: true });
16
+ try {
17
+ fs.writeFileSync(temporary, `${JSON.stringify(value, null, '\t')}\n`, { mode: 0o600 });
18
+ fs.chmodSync(temporary, 0o600);
19
+ fs.renameSync(temporary, file);
20
+ }
21
+ catch (err) {
22
+ try {
23
+ fs.unlinkSync(temporary);
24
+ }
25
+ catch { }
26
+ throw err;
27
+ }
28
+ }
29
+ export class DelegationStore {
30
+ directory;
31
+ constructor(worktree) {
32
+ this.directory = path.join(worktree, DIRECTORY);
33
+ }
34
+ list() {
35
+ let files;
36
+ try {
37
+ files = fs
38
+ .readdirSync(this.directory)
39
+ .filter(file => file.endsWith('.json') && file !== SESSIONS_FILE)
40
+ .sort();
41
+ }
42
+ catch (err) {
43
+ if (err.code === 'ENOENT')
44
+ return { jobs: [], warnings: [] };
45
+ return { jobs: [], warnings: [{ file: this.directory, message: String(err) }] };
46
+ }
47
+ const jobs = [];
48
+ const warnings = [];
49
+ for (const file of files) {
50
+ try {
51
+ jobs.push(decodeDelegation(JSON.parse(fs.readFileSync(path.join(this.directory, file), 'utf8'))));
52
+ }
53
+ catch (err) {
54
+ warnings.push({ file, message: err instanceof Error ? err.message : String(err) });
55
+ }
56
+ }
57
+ return { jobs, warnings };
58
+ }
59
+ get(id) {
60
+ if (!SAFE_ID.test(id))
61
+ return null;
62
+ try {
63
+ return decodeDelegation(JSON.parse(fs.readFileSync(path.join(this.directory, `${id}.json`), 'utf8')));
64
+ }
65
+ catch (err) {
66
+ if (err.code === 'ENOENT')
67
+ return null;
68
+ throw err;
69
+ }
70
+ }
71
+ put(raw) {
72
+ const job = decodeDelegation(raw);
73
+ atomicWrite(path.join(this.directory, `${job.id}.json`), job);
74
+ return job;
75
+ }
76
+ remove(id) {
77
+ if (!SAFE_ID.test(id))
78
+ return false;
79
+ try {
80
+ fs.unlinkSync(path.join(this.directory, `${id}.json`));
81
+ return true;
82
+ }
83
+ catch (err) {
84
+ if (err.code === 'ENOENT')
85
+ return false;
86
+ throw err;
87
+ }
88
+ }
89
+ sessionRoles() {
90
+ const file = path.join(this.directory, SESSIONS_FILE);
91
+ try {
92
+ return { sessions: decodeSessionRoles(JSON.parse(fs.readFileSync(file, 'utf8'))) };
93
+ }
94
+ catch (err) {
95
+ if (err.code === 'ENOENT')
96
+ return { sessions: {} };
97
+ return { sessions: {}, warning: err instanceof Error ? err.message : String(err) };
98
+ }
99
+ }
100
+ assign(sessionId, assignment) {
101
+ text(sessionId, 'session id');
102
+ const current = this.sessionRoles();
103
+ if (current.warning)
104
+ throw new Error(`cannot update malformed sessions.json: ${current.warning}`);
105
+ const sessions = decodeSessionRoles({
106
+ version: 1,
107
+ sessions: { ...current.sessions, [sessionId]: assignment }
108
+ });
109
+ atomicWrite(path.join(this.directory, SESSIONS_FILE), { version: 1, sessions });
110
+ }
111
+ }
@@ -0,0 +1,2 @@
1
+ /** Persisted ordinary-chat delegation records and the queue adapter contract. */
2
+ export {};
@@ -0,0 +1,109 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { eq } from 'drizzle-orm';
3
+ import { OrchestrationError, WorkflowTransitionError } from "./errors.js";
4
+ import { appendEvent } from "./events.js";
5
+ import { requireRun } from "./records.js";
6
+ import { workflowCapabilities, workflowCapabilitySelectSchema } from "./schema.js";
7
+ import { json } from "./values.js";
8
+ export function getWorkflowCapability(context, tokenHash) {
9
+ const candidate = context.orm
10
+ .select()
11
+ .from(workflowCapabilities)
12
+ .where(eq(workflowCapabilities.tokenHash, tokenHash.toLowerCase()))
13
+ .get();
14
+ if (!candidate)
15
+ return undefined;
16
+ const row = workflowCapabilitySelectSchema.parse(candidate);
17
+ return {
18
+ id: row.id,
19
+ tokenHash: row.tokenHash,
20
+ runId: row.runId,
21
+ rootSessionId: row.rootSessionId,
22
+ cycle: row.cycle,
23
+ phase: row.phase,
24
+ revision: row.revision,
25
+ allowedRoles: row.allowedRoles,
26
+ ...(row.issuedWithRowid === null
27
+ ? {}
28
+ : {
29
+ issuedWith: {
30
+ rowid: row.issuedWithRowid,
31
+ ...(row.issuedWithTurnId === null ? {} : { turnId: row.issuedWithTurnId })
32
+ }
33
+ }),
34
+ ...(row.consumedAt === null ? {} : { consumedAt: row.consumedAt }),
35
+ ...(row.revokedAt === null ? {} : { revokedAt: row.revokedAt }),
36
+ createdAt: row.createdAt
37
+ };
38
+ }
39
+ export function issueWorkflowCapability(context, input) {
40
+ if (!/^[a-f\d]{64}$/i.test(input.tokenHash))
41
+ throw new OrchestrationError('capability token hash must be SHA-256 hex');
42
+ return context.immediate(() => {
43
+ const run = requireRun(context, input.runId);
44
+ if (run.rootSessionId !== input.rootSessionId)
45
+ throw new WorkflowTransitionError('capability root does not match Workflow');
46
+ if (run.phase !== input.phase || run.cycle !== input.cycle || run.revision !== input.revision) {
47
+ throw new WorkflowTransitionError('capability coordinates do not match Workflow');
48
+ }
49
+ const id = input.id ?? randomUUID();
50
+ const at = context.now();
51
+ context.db
52
+ .prepare(`INSERT INTO workflow_capabilities (
53
+ id, token_hash, run_id, root_session_id, cycle, phase, revision, allowed_roles_json,
54
+ issued_with_rowid, issued_with_turn_id, created_at
55
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
56
+ .run(id, input.tokenHash.toLowerCase(), input.runId, input.rootSessionId, input.cycle, input.phase, input.revision, json([...new Set(input.allowedRoles)].sort()), input.issuedWith?.rowid ?? null, input.issuedWith?.turnId ?? null, at);
57
+ appendEvent(context, input.runId, input.eventKey, 'workflow_capability_issued', {
58
+ capabilityId: id,
59
+ phase: input.phase,
60
+ cycle: input.cycle,
61
+ revision: input.revision,
62
+ allowedRoles: input.allowedRoles,
63
+ issuedWith: input.issuedWith
64
+ });
65
+ return id;
66
+ });
67
+ }
68
+ export function consumeWorkflowCapability(context, input) {
69
+ return context.immediate(() => {
70
+ const capability = getWorkflowCapability(context, input.tokenHash);
71
+ if (!capability ||
72
+ capability.runId !== input.runId ||
73
+ capability.rootSessionId !== input.rootSessionId ||
74
+ capability.phase !== input.expectedPhase ||
75
+ capability.cycle !== input.expectedCycle ||
76
+ capability.revision !== input.expectedRevision ||
77
+ capability.consumedAt !== undefined ||
78
+ capability.revokedAt !== undefined ||
79
+ !capability.allowedRoles.includes(input.role)) {
80
+ throw new WorkflowTransitionError('Workflow capability is invalid, stale, consumed, or wrong-role');
81
+ }
82
+ const run = requireRun(context, input.runId);
83
+ if (run.rootSessionId !== input.rootSessionId ||
84
+ run.phase !== input.expectedPhase ||
85
+ run.cycle !== input.expectedCycle ||
86
+ run.revision !== input.expectedRevision) {
87
+ throw new WorkflowTransitionError('Workflow advanced past this capability');
88
+ }
89
+ const at = context.now();
90
+ context.db.prepare('UPDATE workflow_capabilities SET consumed_at = ? WHERE id = ?').run(at, capability.id);
91
+ appendEvent(context, input.runId, input.eventKey, 'workflow_capability_consumed', {
92
+ capabilityId: capability.id,
93
+ role: input.role
94
+ });
95
+ return capability.id;
96
+ });
97
+ }
98
+ export function revokeWorkflowCapabilities(context, runId, eventKey, phase) {
99
+ return context.immediate(() => {
100
+ const at = context.now();
101
+ const result = context.db
102
+ .prepare(`UPDATE workflow_capabilities SET revoked_at = ?
103
+ WHERE run_id = ? AND consumed_at IS NULL AND revoked_at IS NULL AND (? IS NULL OR phase = ?)`)
104
+ .run(at, runId, phase ?? null, phase ?? null);
105
+ const count = Number(result.changes);
106
+ appendEvent(context, runId, eventKey, 'workflow_capabilities_revoked', { phase, count });
107
+ return count;
108
+ });
109
+ }
@@ -0,0 +1,148 @@
1
+ import { OrchestrationError } from "./errors.js";
2
+ import { workflowEffectAttemptSelectSchema, workflowEffectSelectSchema, workflowEventSelectSchema, workflowJobAttemptSelectSchema, workflowJobSelectSchema, workflowRunSelectSchema } from "./schema.js";
3
+ import { externalFromColumns, jsonProperty, ownerFromColumns } from "./values.js";
4
+ export function decodeRun(candidate) {
5
+ const row = workflowRunSelectSchema.parse(candidate);
6
+ const blocked = row.blockedActionId
7
+ ? {
8
+ actionId: row.blockedActionId,
9
+ errorCode: row.blockedErrorCode ?? 'workflow_blocked',
10
+ message: row.blockedMessage ?? 'Workflow is blocked',
11
+ resumePhase: row.resumePhase ?? 'pending_root',
12
+ retryClass: row.retryClass ?? 'terminal',
13
+ ...(row.blockedCandidates ? { candidates: row.blockedCandidates.value } : {}),
14
+ ...(row.blockedAt === null ? {} : { blockedAt: row.blockedAt })
15
+ }
16
+ : undefined;
17
+ return {
18
+ id: row.id,
19
+ objective: row.objective,
20
+ target: row.target,
21
+ roles: row.roles,
22
+ phase: row.phase,
23
+ cycle: row.cycle,
24
+ revision: row.revision,
25
+ ...(row.workspaceId === null ? {} : { workspaceId: row.workspaceId }),
26
+ ...(row.rootSessionId === null ? {} : { rootSessionId: row.rootSessionId }),
27
+ ...jsonProperty('pristineEvidence', row.pristineEvidence),
28
+ ...jsonProperty('deliveryBaseline', row.deliveryBaseline),
29
+ ...(row.planningInterpretation === null ? {} : { planningInterpretation: row.planningInterpretation }),
30
+ cancellationGeneration: row.cancellationGeneration,
31
+ ...(blocked ? { blocked } : {}),
32
+ implementationBatonsDelivered: row.implementationBatonsDelivered,
33
+ createdAt: row.createdAt,
34
+ updatedAt: row.updatedAt,
35
+ ...(row.terminalAt === null ? {} : { terminalAt: row.terminalAt })
36
+ };
37
+ }
38
+ export function decodeJob(candidate) {
39
+ const row = workflowJobSelectSchema.parse(candidate);
40
+ const owner = ownerFromColumns(row);
41
+ return {
42
+ id: row.id,
43
+ runId: row.runId,
44
+ logicalKey: row.logicalKey,
45
+ role: row.role,
46
+ cycle: row.cycle,
47
+ revision: row.revision,
48
+ resolvedRole: row.resolvedRole,
49
+ prompt: row.prompt,
50
+ state: row.state,
51
+ cancellationGeneration: row.cancellationGeneration,
52
+ ...(owner ? { owner } : {}),
53
+ ...jsonProperty('transcriptCursor', row.transcriptCursor),
54
+ ...(row.childSessionId === null ? {} : { childSessionId: row.childSessionId }),
55
+ ...jsonProperty('outcome', row.outcome),
56
+ ...jsonProperty('taskReceipt', row.taskReceipt),
57
+ ...jsonProperty('batonReceipt', row.batonReceipt),
58
+ attemptCount: row.attemptCount,
59
+ createdAt: row.createdAt,
60
+ updatedAt: row.updatedAt,
61
+ ...(row.terminalAt === null ? {} : { terminalAt: row.terminalAt })
62
+ };
63
+ }
64
+ export function decodeJobAttempt(candidate) {
65
+ const row = workflowJobAttemptSelectSchema.parse(candidate);
66
+ const owner = ownerFromColumns(row);
67
+ return {
68
+ id: row.id,
69
+ jobId: row.jobId,
70
+ attemptNumber: row.attemptNumber,
71
+ state: row.state,
72
+ ...(row.childSessionId === null ? {} : { childSessionId: row.childSessionId }),
73
+ ...(row.openEffectId === null ? {} : { openEffectId: row.openEffectId }),
74
+ ...(row.configureEffectId === null ? {} : { configureEffectId: row.configureEffectId }),
75
+ ...(row.taskEffectId === null ? {} : { taskEffectId: row.taskEffectId }),
76
+ ...(row.batonEffectId === null ? {} : { batonEffectId: row.batonEffectId }),
77
+ ...jsonProperty('outcome', row.outcome),
78
+ ...jsonProperty('failureEvidence', row.failureEvidence),
79
+ ...(owner ? { owner } : {}),
80
+ createdAt: row.createdAt,
81
+ updatedAt: row.updatedAt,
82
+ ...(row.terminalAt === null ? {} : { terminalAt: row.terminalAt })
83
+ };
84
+ }
85
+ export function decodeEffect(candidate) {
86
+ const row = workflowEffectSelectSchema.parse(candidate);
87
+ const owner = ownerFromColumns(row);
88
+ const externalProcess = externalFromColumns(row);
89
+ return {
90
+ id: row.id,
91
+ runId: row.runId,
92
+ actionId: row.actionId,
93
+ ...(row.jobId === null ? {} : { jobId: row.jobId }),
94
+ kind: row.kind,
95
+ state: row.state,
96
+ ...jsonProperty('target', row.target),
97
+ ...jsonProperty('inputs', row.inputs),
98
+ ...jsonProperty('baseline', row.baseline),
99
+ ...jsonProperty('cursor', row.cursor),
100
+ ...jsonProperty('receipt', row.receipt),
101
+ ...(row.errorCode === null ? {} : { errorCode: row.errorCode }),
102
+ ...(row.errorMessage === null ? {} : { errorMessage: row.errorMessage }),
103
+ ...(owner ? { owner } : {}),
104
+ ...(row.launchNonce === null ? {} : { launchNonce: row.launchNonce }),
105
+ ...(externalProcess ? { externalProcess } : {}),
106
+ mayExecute: row.mayExecute,
107
+ attemptCount: row.attemptCount,
108
+ createdAt: row.createdAt,
109
+ updatedAt: row.updatedAt,
110
+ ...(row.terminalAt === null ? {} : { terminalAt: row.terminalAt })
111
+ };
112
+ }
113
+ export function decodeEffectAttempt(candidate) {
114
+ const row = workflowEffectAttemptSelectSchema.parse(candidate);
115
+ const id = row.id;
116
+ const owner = ownerFromColumns(row);
117
+ if (!owner)
118
+ throw new OrchestrationError(`Workflow effect attempt ${id} has no owner`);
119
+ const externalProcess = externalFromColumns(row);
120
+ return {
121
+ id,
122
+ effectId: row.effectId,
123
+ attemptNumber: row.attemptNumber,
124
+ state: row.state,
125
+ owner,
126
+ ...(row.launchNonce === null ? {} : { launchNonce: row.launchNonce }),
127
+ ...(externalProcess ? { externalProcess } : {}),
128
+ mayExecute: row.mayExecute,
129
+ ...jsonProperty('receipt', row.receipt),
130
+ ...jsonProperty('evidence', row.evidence),
131
+ ...(row.errorCode === null ? {} : { errorCode: row.errorCode }),
132
+ ...(row.errorMessage === null ? {} : { errorMessage: row.errorMessage }),
133
+ createdAt: row.createdAt,
134
+ updatedAt: row.updatedAt,
135
+ ...(row.terminalAt === null ? {} : { terminalAt: row.terminalAt })
136
+ };
137
+ }
138
+ export function decodeEvent(candidate) {
139
+ const row = workflowEventSelectSchema.parse(candidate);
140
+ return {
141
+ id: row.id,
142
+ runId: row.runId,
143
+ eventKey: row.eventKey,
144
+ type: row.type,
145
+ ...jsonProperty('data', row.data),
146
+ createdAt: row.createdAt
147
+ };
148
+ }