@opencorelabs/lucidity 0.7.0 → 0.8.0

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 (219) hide show
  1. package/README.md +9 -2
  2. package/dist/assets/speech/lucidity-speech +0 -0
  3. package/dist/automations/agent.d.ts.map +1 -1
  4. package/dist/automations/agent.js +2 -0
  5. package/dist/automations/designer.d.ts +1 -1
  6. package/dist/chat/server.d.ts +1 -0
  7. package/dist/chat/server.d.ts.map +1 -1
  8. package/dist/chat/server.js +6 -1
  9. package/dist/coding/conduct.d.ts +1 -22
  10. package/dist/coding/conduct.d.ts.map +1 -1
  11. package/dist/coding/conduct.js +9 -94
  12. package/dist/coding/runCodeTurn.d.ts +3 -16
  13. package/dist/coding/runCodeTurn.d.ts.map +1 -1
  14. package/dist/coding/runCodeTurn.js +157 -165
  15. package/dist/coding/workspaceRegistry.d.ts +24 -0
  16. package/dist/coding/workspaceRegistry.d.ts.map +1 -0
  17. package/dist/coding/workspaceRegistry.js +230 -0
  18. package/dist/coding/worktree.d.ts +11 -14
  19. package/dist/coding/worktree.d.ts.map +1 -1
  20. package/dist/coding/worktree.js +41 -21
  21. package/dist/config.d.ts +2 -0
  22. package/dist/config.d.ts.map +1 -1
  23. package/dist/daemonLease.d.ts +12 -0
  24. package/dist/daemonLease.d.ts.map +1 -0
  25. package/dist/daemonLease.js +32 -0
  26. package/dist/goals/assessment.d.ts +115 -0
  27. package/dist/goals/assessment.d.ts.map +1 -0
  28. package/dist/goals/assessment.js +67 -0
  29. package/dist/goals/notes.d.ts +18 -0
  30. package/dist/goals/notes.d.ts.map +1 -0
  31. package/dist/goals/notes.js +72 -0
  32. package/dist/index.js +57 -15
  33. package/dist/jobs/goals.d.ts +15 -0
  34. package/dist/jobs/goals.d.ts.map +1 -0
  35. package/dist/jobs/goals.js +286 -0
  36. package/dist/jobs/weeklyReview.d.ts.map +1 -1
  37. package/dist/jobs/weeklyReview.js +3 -2
  38. package/dist/queue.d.ts +1 -0
  39. package/dist/queue.d.ts.map +1 -1
  40. package/dist/queue.js +4 -0
  41. package/dist/room/client.d.ts +5 -0
  42. package/dist/room/client.d.ts.map +1 -1
  43. package/dist/room/client.js +116 -101
  44. package/dist/room/computer.d.ts.map +1 -1
  45. package/dist/room/computer.js +1 -0
  46. package/dist/room/durablePublish.d.ts +6 -0
  47. package/dist/room/durablePublish.d.ts.map +1 -0
  48. package/dist/room/durablePublish.js +19 -0
  49. package/dist/room/incidents.d.ts +1 -1
  50. package/dist/room/incidents.d.ts.map +1 -1
  51. package/dist/room/incidents.js +14 -7
  52. package/dist/room/turnQueue.d.ts.map +1 -1
  53. package/dist/room/turnQueue.js +27 -24
  54. package/dist/runtimeStore.d.ts +44 -0
  55. package/dist/runtimeStore.d.ts.map +1 -0
  56. package/dist/runtimeStore.js +188 -0
  57. package/dist/setup/server.js +1 -1
  58. package/dist/turnLog.d.ts +10 -40
  59. package/dist/turnLog.d.ts.map +1 -1
  60. package/dist/turnLog.js +33 -56
  61. package/package.json +4 -4
  62. package/src/automations/agent.ts +2 -0
  63. package/src/chat/server.ts +7 -1
  64. package/src/coding/conduct.ts +10 -147
  65. package/src/coding/runCodeTurn.ts +42 -61
  66. package/src/coding/workspaceRegistry.ts +210 -0
  67. package/src/coding/worktree.ts +44 -20
  68. package/src/config.ts +2 -0
  69. package/src/daemonLease.ts +33 -0
  70. package/src/goals/assessment.ts +106 -0
  71. package/src/goals/notes.ts +88 -0
  72. package/src/index.ts +57 -18
  73. package/src/jobs/goals.ts +384 -0
  74. package/src/jobs/weeklyReview.ts +4 -3
  75. package/src/queue.ts +4 -0
  76. package/src/room/client.ts +77 -74
  77. package/src/room/computer.ts +1 -0
  78. package/src/room/durablePublish.ts +25 -0
  79. package/src/room/incidents.ts +16 -8
  80. package/src/room/turnQueue.ts +26 -27
  81. package/src/runtimeStore.ts +190 -0
  82. package/src/setup/server.ts +1 -1
  83. package/src/turnLog.ts +32 -75
  84. package/vendor/mcp-server/dist/index.js +2 -0
  85. package/vendor/mcp-server/dist/tools/goals.d.ts +4 -0
  86. package/vendor/mcp-server/dist/tools/goals.d.ts.map +1 -0
  87. package/vendor/mcp-server/dist/tools/goals.js +38 -0
  88. package/vendor/mcp-server/package.json +1 -1
  89. package/vendor/mcp-server/src/index.ts +2 -0
  90. package/vendor/mcp-server/src/tools/goals.ts +62 -0
  91. package/vendor/runtime/README.md +2 -2
  92. package/vendor/runtime/dist/executor/asyncQueue.d.ts +1 -0
  93. package/vendor/runtime/dist/executor/asyncQueue.d.ts.map +1 -1
  94. package/vendor/runtime/dist/executor/asyncQueue.js +3 -0
  95. package/vendor/runtime/dist/executor/claudeAgent.d.ts +1 -1
  96. package/vendor/runtime/dist/executor/claudeAgent.d.ts.map +1 -1
  97. package/vendor/runtime/dist/executor/claudeAgent.js +20 -9
  98. package/vendor/runtime/dist/executor/codex.d.ts +1 -0
  99. package/vendor/runtime/dist/executor/codex.d.ts.map +1 -1
  100. package/vendor/runtime/dist/executor/codex.js +68 -36
  101. package/vendor/runtime/dist/executor/codexProtocol/FunctionCallOutputContentItem.d.ts +4 -1
  102. package/vendor/runtime/dist/executor/codexProtocol/FunctionCallOutputContentItem.d.ts.map +1 -1
  103. package/vendor/runtime/dist/executor/codexProtocol/Personality.d.ts +3 -0
  104. package/vendor/runtime/dist/executor/codexProtocol/Personality.d.ts.map +1 -1
  105. package/vendor/runtime/dist/executor/codexProtocol/PlanType.d.ts +1 -1
  106. package/vendor/runtime/dist/executor/codexProtocol/PlanType.d.ts.map +1 -1
  107. package/vendor/runtime/dist/executor/codexProtocol/v2/CyberAccessProgram.d.ts +6 -0
  108. package/vendor/runtime/dist/executor/codexProtocol/v2/CyberAccessProgram.d.ts.map +1 -0
  109. package/vendor/runtime/dist/executor/codexProtocol/v2/CyberAccessProgram.js +2 -0
  110. package/vendor/runtime/dist/executor/codexProtocol/v2/GetAccountRateLimitsResponse.d.ts +5 -0
  111. package/vendor/runtime/dist/executor/codexProtocol/v2/GetAccountRateLimitsResponse.d.ts.map +1 -1
  112. package/vendor/runtime/dist/executor/codexProtocol/v2/Model.d.ts +8 -0
  113. package/vendor/runtime/dist/executor/codexProtocol/v2/Model.d.ts.map +1 -1
  114. package/vendor/runtime/dist/executor/codexProtocol/v2/ModelAccessPrograms.d.ts +11 -0
  115. package/vendor/runtime/dist/executor/codexProtocol/v2/ModelAccessPrograms.d.ts.map +1 -0
  116. package/vendor/runtime/dist/executor/codexProtocol/v2/ModelAccessPrograms.js +2 -0
  117. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitSnapshot.d.ts +4 -0
  118. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitSnapshot.d.ts.map +1 -1
  119. package/vendor/runtime/dist/executor/codexProtocol/v2/ReviewStartParams.d.ts +2 -0
  120. package/vendor/runtime/dist/executor/codexProtocol/v2/ReviewStartParams.d.ts.map +1 -1
  121. package/vendor/runtime/dist/executor/codexProtocol/v2/ThreadResumeParams.d.ts +4 -1
  122. package/vendor/runtime/dist/executor/codexProtocol/v2/ThreadResumeParams.d.ts.map +1 -1
  123. package/vendor/runtime/dist/executor/codexProtocol/v2/ThreadStartParams.d.ts +3 -1
  124. package/vendor/runtime/dist/executor/codexProtocol/v2/ThreadStartParams.d.ts.map +1 -1
  125. package/vendor/runtime/dist/executor/codexProtocol/v2/TurnStartParams.d.ts +7 -2
  126. package/vendor/runtime/dist/executor/codexProtocol/v2/TurnStartParams.d.ts.map +1 -1
  127. package/vendor/runtime/dist/executor/codexProtocol/v2/UserInput.d.ts +3 -0
  128. package/vendor/runtime/dist/executor/codexProtocol/v2/UserInput.d.ts.map +1 -1
  129. package/vendor/runtime/dist/executor/codexRpc.d.ts +10 -3
  130. package/vendor/runtime/dist/executor/codexRpc.d.ts.map +1 -1
  131. package/vendor/runtime/dist/executor/codexRpc.js +18 -3
  132. package/vendor/runtime/dist/executor/codexSessions.d.ts +30 -0
  133. package/vendor/runtime/dist/executor/codexSessions.d.ts.map +1 -0
  134. package/vendor/runtime/dist/executor/codexSessions.js +88 -0
  135. package/vendor/runtime/dist/executor/health.d.ts +2 -1
  136. package/vendor/runtime/dist/executor/health.d.ts.map +1 -1
  137. package/vendor/runtime/dist/executor/health.js +17 -5
  138. package/vendor/runtime/dist/executor/liveTurns.d.ts +2 -1
  139. package/vendor/runtime/dist/executor/liveTurns.d.ts.map +1 -1
  140. package/vendor/runtime/dist/executor/liveTurns.js +12 -5
  141. package/vendor/runtime/dist/executor/ownership.d.ts +35 -0
  142. package/vendor/runtime/dist/executor/ownership.d.ts.map +1 -0
  143. package/vendor/runtime/dist/executor/ownership.js +99 -0
  144. package/vendor/runtime/dist/executor/providerRouter.d.ts +1 -0
  145. package/vendor/runtime/dist/executor/providerRouter.d.ts.map +1 -1
  146. package/vendor/runtime/dist/executor/providerRouter.js +5 -0
  147. package/vendor/runtime/dist/executor/types.d.ts +2 -0
  148. package/vendor/runtime/dist/executor/types.d.ts.map +1 -1
  149. package/vendor/runtime/dist/index.d.ts +1 -0
  150. package/vendor/runtime/dist/index.d.ts.map +1 -1
  151. package/vendor/runtime/dist/index.js +1 -0
  152. package/vendor/runtime/src/executor/asyncQueue.ts +3 -0
  153. package/vendor/runtime/src/executor/claudeAgent.ts +16 -9
  154. package/vendor/runtime/src/executor/codex.ts +75 -44
  155. package/vendor/runtime/src/executor/codexProtocol/FunctionCallOutputContentItem.ts +1 -1
  156. package/vendor/runtime/src/executor/codexProtocol/Personality.ts +3 -0
  157. package/vendor/runtime/src/executor/codexProtocol/PlanType.ts +1 -1
  158. package/vendor/runtime/src/executor/codexProtocol/README.md +2 -2
  159. package/vendor/runtime/src/executor/codexProtocol/v2/CyberAccessProgram.ts +9 -0
  160. package/vendor/runtime/src/executor/codexProtocol/v2/GetAccountRateLimitsResponse.ts +5 -0
  161. package/vendor/runtime/src/executor/codexProtocol/v2/Model.ts +11 -2
  162. package/vendor/runtime/src/executor/codexProtocol/v2/ModelAccessPrograms.ts +13 -0
  163. package/vendor/runtime/src/executor/codexProtocol/v2/RateLimitSnapshot.ts +5 -1
  164. package/vendor/runtime/src/executor/codexProtocol/v2/ReviewStartParams.ts +2 -0
  165. package/vendor/runtime/src/executor/codexProtocol/v2/ThreadResumeParams.ts +5 -1
  166. package/vendor/runtime/src/executor/codexProtocol/v2/ThreadStartParams.ts +4 -1
  167. package/vendor/runtime/src/executor/codexProtocol/v2/TurnStartParams.ts +7 -2
  168. package/vendor/runtime/src/executor/codexProtocol/v2/UserInput.ts +1 -1
  169. package/vendor/runtime/src/executor/codexRpc.ts +22 -4
  170. package/vendor/runtime/src/executor/codexSessions.ts +108 -0
  171. package/vendor/runtime/src/executor/health.ts +16 -6
  172. package/vendor/runtime/src/executor/liveTurns.ts +12 -5
  173. package/vendor/runtime/src/executor/ownership.ts +76 -0
  174. package/vendor/runtime/src/executor/providerRouter.ts +6 -0
  175. package/vendor/runtime/src/executor/types.ts +2 -0
  176. package/vendor/runtime/src/index.ts +1 -0
  177. package/vendor/shared/dist/agentCommands.d.ts +1 -0
  178. package/vendor/shared/dist/agentCommands.d.ts.map +1 -1
  179. package/vendor/shared/dist/cardStudio.d.ts +41 -0
  180. package/vendor/shared/dist/cardStudio.d.ts.map +1 -1
  181. package/vendor/shared/dist/cardStudio.js +13 -3
  182. package/vendor/shared/dist/computer.d.ts +7 -1
  183. package/vendor/shared/dist/computer.d.ts.map +1 -1
  184. package/vendor/shared/dist/computer.js +12 -2
  185. package/vendor/shared/dist/constants.d.ts +3 -3
  186. package/vendor/shared/dist/constants.d.ts.map +1 -1
  187. package/vendor/shared/dist/constants.js +5 -4
  188. package/vendor/shared/dist/goalNotes.d.ts +4 -0
  189. package/vendor/shared/dist/goalNotes.d.ts.map +1 -0
  190. package/vendor/shared/dist/goalNotes.js +23 -0
  191. package/vendor/shared/dist/goals.d.ts +835 -0
  192. package/vendor/shared/dist/goals.d.ts.map +1 -0
  193. package/vendor/shared/dist/goals.js +198 -0
  194. package/vendor/shared/dist/index.d.ts +3 -0
  195. package/vendor/shared/dist/index.d.ts.map +1 -1
  196. package/vendor/shared/dist/index.js +3 -0
  197. package/vendor/shared/dist/schemas/harness.d.ts +101 -0
  198. package/vendor/shared/dist/schemas/harness.d.ts.map +1 -1
  199. package/vendor/shared/dist/schemas/harness.js +6 -0
  200. package/vendor/shared/dist/workspaces.d.ts +138 -0
  201. package/vendor/shared/dist/workspaces.d.ts.map +1 -0
  202. package/vendor/shared/dist/workspaces.js +40 -0
  203. package/vendor/shared/src/agentCommands.ts +1 -0
  204. package/vendor/shared/src/cardStudio.ts +13 -3
  205. package/vendor/shared/src/computer.ts +16 -2
  206. package/vendor/shared/src/constants.ts +5 -4
  207. package/vendor/shared/src/goalNotes.ts +23 -0
  208. package/vendor/shared/src/goals.ts +237 -0
  209. package/vendor/shared/src/index.ts +4 -0
  210. package/vendor/shared/src/schemas/harness.ts +6 -0
  211. package/vendor/shared/src/workspaces.ts +48 -0
  212. package/dist/coding/fleetIntegrate.d.ts +0 -37
  213. package/dist/coding/fleetIntegrate.d.ts.map +0 -1
  214. package/dist/coding/fleetIntegrate.js +0 -64
  215. package/dist/coding/openFleetPr.d.ts +0 -41
  216. package/dist/coding/openFleetPr.d.ts.map +0 -1
  217. package/dist/coding/openFleetPr.js +0 -121
  218. package/src/coding/fleetIntegrate.ts +0 -95
  219. package/src/coding/openFleetPr.ts +0 -148
@@ -1,3 +1,4 @@
1
+ import { publishDurably } from './durablePublish.js';
1
2
  import { computerId, computerRuntime } from './computer.js';
2
3
  import { DurableTurnQueue } from './turnQueue.js';
3
4
  import type { AgentControls } from '../agentControls.js';
@@ -54,6 +55,7 @@ import { handoffPrompt } from '../handoff.js';
54
55
  import { createHash } from 'node:crypto';
55
56
  import { join } from 'node:path';
56
57
  import { uuidv7 } from 'uuidv7';
58
+ import type { WorkspaceRegistry } from '../coding/workspaceRegistry.js';
57
59
 
58
60
  /** Frame `type`s that carry recoverable turn output — the ones written to the durable
59
61
  * turn log and stamped with a `seq`. Buffered responses (`kind` replies) and any other
@@ -128,7 +130,7 @@ export type ConductHandler = (
128
130
  /** A quick incremental spawn: skip the dogfood task graph (no parent task, no subtask). */
129
131
  ephemeral?: boolean;
130
132
  },
131
- ctx: { send: (obj: unknown) => void; signal?: AbortSignal },
133
+ ctx: { send: (obj: unknown) => void; signal?: AbortSignal; runWorker: NonNullable<import('../coding/conduct.js').RunConductTurnDeps['runWorker']> },
132
134
  ) => Promise<void>;
133
135
 
134
136
  /** One row of the phone's repo picker: which repo, what branch it sits on right now,
@@ -143,6 +145,7 @@ export interface RepoInfo {
143
145
  }
144
146
 
145
147
  export interface DispatchDeps {
148
+ workspaces?: WorkspaceRegistry;
146
149
  speech?: Pick<SpeechService, 'transcribe'>;
147
150
  captures?: Pick<VoiceCaptureService, 'submit' | 'status'>;
148
151
  turnQueue?: DurableTurnQueue;
@@ -282,8 +285,16 @@ export async function dispatchRequest(
282
285
  }
283
286
  const req = parsed.data;
284
287
  const structured = req.kind === 'ask' && (req.dayPlan ? 'day-plan' : req.projectPlan ? 'project-plan' : undefined);
285
- const send = (frame: unknown) => sendFrame(structured
286
- ? { ...(frame as Record<string, unknown>), purpose: structured } : frame);
288
+ let deferTerminal = false;
289
+ let terminal: Record<string, unknown> | undefined;
290
+ const send = (frame: unknown) => {
291
+ const event = frame as Record<string, unknown>;
292
+ if (deferTerminal && event?.requestId === req.id && (['done', 'error', 'cancelled'].includes(String(event.type)) || ['ask', 'briefing', 'attention'].includes(String(event.kind)))) {
293
+ terminal ??= event;
294
+ return;
295
+ }
296
+ sendFrame(structured ? { ...event, purpose: structured } : frame);
297
+ };
287
298
  if (req.kind === 'voice-capture' || req.kind === 'voice-capture-status') {
288
299
  try {
289
300
  if (!deps.captures)
@@ -488,12 +499,13 @@ export async function dispatchRequest(
488
499
  const controller = inFlight?.get(req.targetId);
489
500
  if (controller) {
490
501
  controller.abort();
491
- // Route through `send` so the terminal is logged (shares the turn's seq counter,
492
- // landing at maxSeq+1) — a later pull then sees a settled turn.
493
- send({ type: 'cancelled', requestId: req.targetId });
502
+ // The owner publishes cancellation after the provider and workspace are released.
494
503
  } else {
495
- // Conductor workers have provider-owned request IDs, separate from the parent lane.
496
504
  await deps.controls?.interrupt(req.targetId);
505
+ // Completion can beat Stop while its terminal frame is lost in transit. Replay
506
+ // the actual outcome so the phone settles without rewriting finished work.
507
+ const state = deps.turnLogs.read(req.targetId);
508
+ if (state.terminated) for (const frame of state.frames) deps.sendRaw(frame);
497
509
  }
498
510
  return;
499
511
  }
@@ -523,23 +535,6 @@ export async function dispatchRequest(
523
535
  // restores its controls instead of waiting forever for another model token.
524
536
  if (!state.terminated && inFlight?.has(req.targetId))
525
537
  deps.controls?.publishPending(req.targetId);
526
- // Open log (no terminal) with no live run owning it → the subprocess died (the daemon
527
- // restarted mid-turn). Settle it with a synthesized, persisted terminal so the phone
528
- // stops waiting and a repeat pull is idempotent. If it's still in `inFlight`, live
529
- // frames past maxSeq keep flowing on the current socket (deduped by seq) — leave it.
530
- if (
531
- !state.terminated &&
532
- !inFlight?.has(req.targetId) &&
533
- !deps.turnQueue?.owns(req.targetId)
534
- ) {
535
- sendRaw(
536
- turnLogs.append(req.targetId, {
537
- type: 'error',
538
- requestId: req.targetId,
539
- message: 'Lucid restarted before finishing this turn.',
540
- }),
541
- );
542
- }
543
538
  return;
544
539
  }
545
540
 
@@ -564,33 +559,16 @@ export async function dispatchRequest(
564
559
  req.kind,
565
560
  )
566
561
  ) {
567
- const previous = deps.turnLogs.read(req.id);
568
- if (previous.exists || inFlight?.has(req.id)) {
569
- for (const frame of previous.frames) deps.sendRaw(frame);
570
- return;
571
- }
572
- // Record intent before any model call or workspace change. A restart can recover output,
573
- // but cannot mistake a previously accepted request for fresh work.
574
- const accepted = deps.turnLogs.append(req.id, {
575
- type: 'accepted',
576
- requestId: req.id,
577
- scope: {
578
- kind: req.kind,
579
- ...('repoId' in req ? { repoId: req.repoId } : {}),
580
- ...('workerId' in req ? { workerId: req.workerId } : {}),
581
- ...('mode' in req ? { mode: req.mode } : {}),
582
- },
583
- });
584
- if (!deps.turnLogs.read(req.id).exists) {
585
- send({
586
- type: 'error',
587
- requestId: req.id,
588
- message:
589
- 'Cannot save the request safely on this computer. Check available disk space and retry.',
590
- });
562
+ try {
563
+ deps.turnLogs.read(req.id); // Adopt legacy receipts before admission.
564
+ const receipt = deps.turnLogs.runtime.accept(req);
565
+ for (const frame of receipt.frames) deps.sendRaw(frame);
566
+ if (receipt.duplicate || inFlight?.has(req.id)) return;
567
+ } catch (error) {
568
+ deps.sendRaw({ type: 'error', requestId: req.id,
569
+ message: `Cannot accept this request safely: ${error instanceof Error ? error.message : String(error)}` });
591
570
  return;
592
571
  }
593
- deps.sendRaw(accepted);
594
572
  }
595
573
 
596
574
  // Own abort controller per request, combined with the daemon-shutdown signal, so a
@@ -598,6 +576,7 @@ export async function dispatchRequest(
598
576
  const ownController = new AbortController();
599
577
  const signal = combineSignals(outerSignal, ownController.signal);
600
578
  inFlight?.set(req.id, ownController);
579
+ deferTerminal = true;
601
580
 
602
581
  // Wait for the lane INSIDE the try, and after `inFlight.set` above — a turn waiting its turn
603
582
  // must still be cancellable, and the `signal?.aborted` checks below mean a cancel that lands
@@ -752,6 +731,9 @@ export async function dispatchRequest(
752
731
  entries: result.entries,
753
732
  nextBefore: result.nextBefore,
754
733
  });
734
+ } else if (req.kind === 'workspaces') {
735
+ if (!deps.workspaces) throw new Error('Update Lucidity on the computer to use persistent workers.');
736
+ send({ requestId: req.id, kind: 'workspaces', snapshot: await deps.workspaces.command(req.command, req.id) });
755
737
  } else if (req.kind === 'repos') {
756
738
  send({
757
739
  requestId: req.id,
@@ -826,25 +808,16 @@ export async function dispatchRequest(
826
808
  }
827
809
  } else if (req.kind === 'conduct') {
828
810
  if (deps.conductHandler) {
829
- // The whole fleet holds the repo's lane: its workers write isolated worktrees, but
830
- // integration resets and merges onto lucid/<repo>, so no other turn on this repo (a
831
- // bare code turn, or a second fleet) may run meanwhile.
832
- await onLane(`room:code:${req.repoId}`, () =>
833
- deps.conductHandler!(
834
- {
835
- id: req.id,
836
- repoId: req.repoId,
837
- phase: req.phase,
838
- prompt: req.prompt,
839
- images: req.images,
840
- plan: req.plan,
841
- resume: req.resume,
842
- // Forward it or a quick spawn silently mints a parent task + subtask anyway: the
843
- // phone sends `ephemeral`, conduct honours it, and this hop used to drop it.
844
- ephemeral: req.ephemeral,
845
- },
846
- { send, signal },
847
- ),
811
+ await deps.conductHandler(
812
+ { id: req.id, repoId: req.repoId, phase: req.phase, prompt: req.prompt,
813
+ images: req.images, plan: req.plan, resume: req.resume, ephemeral: req.ephemeral },
814
+ {
815
+ send, signal,
816
+ runWorker: (worker, workerDeps) => dispatchRequest(
817
+ JSON.stringify({ ...worker, kind: 'code', stream: true, mode: 'worktree' }),
818
+ { ...deps, signal, send: workerDeps.send, recordAcceptance: true },
819
+ ),
820
+ },
848
821
  );
849
822
  } else {
850
823
  send({
@@ -888,17 +861,24 @@ export async function dispatchRequest(
888
861
  } catch (err) {
889
862
  // A deadline/cancel abort surfaces as an AbortError ("The operation was aborted").
890
863
  // Never forward that literal text to the phone — end the turn quietly instead.
891
- if (isAbortError(err)) return;
864
+ if (isAbortError(err)) {
865
+ send({ type: 'cancelled', requestId: req.id });
866
+ return;
867
+ }
892
868
  const message = err instanceof Error ? err.message : String(err);
893
869
  deps.telemetry?.record('dispatch-error', message, req.id);
894
870
  send({ type: 'error', requestId: req.id, message });
895
871
  } finally {
896
872
  deps.controls?.end(req.id);
897
873
  inFlight?.delete(req.id);
874
+ deferTerminal = false;
875
+ if (signal?.aborted) send({ type: 'cancelled', requestId: req.id });
876
+ else if (terminal) send(terminal);
898
877
  }
899
878
  }
900
879
 
901
880
  export interface RoomClientOptions {
881
+ workspaces?: WorkspaceRegistry;
902
882
  speech?: SpeechService;
903
883
  capturesDir?: string;
904
884
  computerId?: string;
@@ -945,6 +925,7 @@ export interface RoomClientOptions {
945
925
 
946
926
  export interface RoomClientHandle {
947
927
  stop(): void;
928
+ drain(): Promise<void>;
948
929
  /**
949
930
  * Send an unsolicited frame to the phone (#320).
950
931
  *
@@ -1121,11 +1102,22 @@ export function startRoomClient(opts: RoomClientOptions): RoomClientHandle {
1121
1102
  STREAM_EVENT_TYPES.has(rec.type) &&
1122
1103
  typeof rec.requestId === 'string'
1123
1104
  ) {
1124
- sendRaw(turnLogs.append(rec.requestId, rec));
1105
+ publishDurably(turnLogs, { ...rec, requestId: rec.requestId }, inFlight, sendRaw);
1125
1106
  durableQueue?.wake();
1126
1107
  return;
1127
1108
  }
1128
1109
  }
1110
+ const buffered = obj as Record<string, unknown>;
1111
+ if (buffered && typeof buffered.requestId === 'string' && ['ask', 'briefing', 'attention'].includes(String(buffered.kind))) {
1112
+ publishDurably(turnLogs, { ...buffered, type: 'done', requestId: buffered.requestId }, inFlight,
1113
+ (frame) => {
1114
+ const saved = frame as Record<string, unknown>;
1115
+ if (saved.type === 'error') sendRaw(frame);
1116
+ else sendRaw({ ...buffered, seq: saved.seq });
1117
+ });
1118
+ durableQueue?.wake();
1119
+ return;
1120
+ }
1129
1121
  sendRaw(obj);
1130
1122
  };
1131
1123
 
@@ -1183,8 +1175,10 @@ export function startRoomClient(opts: RoomClientOptions): RoomClientHandle {
1183
1175
  reconnectTimer.unref?.();
1184
1176
  }
1185
1177
 
1186
- const dispatch = (raw: string, overrides: Partial<DispatchDeps> = {}) =>
1187
- dispatchRequest(raw, {
1178
+ const pendingRequests = new Set<Promise<void>>();
1179
+ const dispatch = (raw: string, overrides: Partial<DispatchDeps> = {}): Promise<void> => {
1180
+ if (stopped) return Promise.resolve();
1181
+ const pending = dispatchRequest(raw, {
1188
1182
  harness,
1189
1183
  recordAcceptance: true,
1190
1184
  runtime: opts.providerHealth ? () => computerRuntime(opts) : undefined,
@@ -1196,6 +1190,7 @@ export function startRoomClient(opts: RoomClientOptions): RoomClientHandle {
1196
1190
  send: turnSend,
1197
1191
  sendRaw,
1198
1192
  turnLogs,
1193
+ workspaces: opts.workspaces,
1199
1194
  signal,
1200
1195
  codeHandler,
1201
1196
  conductHandler,
@@ -1225,7 +1220,10 @@ export function startRoomClient(opts: RoomClientOptions): RoomClientHandle {
1225
1220
 
1226
1221
  turnQueue: durableQueue,
1227
1222
  ...overrides,
1228
- });
1223
+ }).finally(() => { pendingRequests.delete(pending); });
1224
+ pendingRequests.add(pending);
1225
+ return pending;
1226
+ };
1229
1227
  durableQueue = new DurableTurnQueue({
1230
1228
  dir: turnLogs.queueDirectory(),
1231
1229
  logs: turnLogs,
@@ -1240,6 +1238,7 @@ export function startRoomClient(opts: RoomClientOptions): RoomClientHandle {
1240
1238
  ? (targetId, prompt) => opts.controls!.steer(targetId, prompt)
1241
1239
  : undefined,
1242
1240
  });
1241
+ turnLogs.reconcile((id) => durableQueue!.owns(id));
1243
1242
  durableQueue.wake();
1244
1243
 
1245
1244
  if (opts.speech) {
@@ -1384,6 +1383,7 @@ export function startRoomClient(opts: RoomClientOptions): RoomClientHandle {
1384
1383
  stopped = true;
1385
1384
  captures?.stop();
1386
1385
  durableQueue?.stop();
1386
+ for (const controller of inFlight.values()) controller.abort();
1387
1387
  clearInterval(redialWatchdog);
1388
1388
  unsubscribeHealth?.();
1389
1389
  if (reconnectTimer) {
@@ -1400,5 +1400,8 @@ export function startRoomClient(opts: RoomClientOptions): RoomClientHandle {
1400
1400
  }
1401
1401
  if (!stopped) connect();
1402
1402
 
1403
- return { stop, push: sendRaw, pushRepos };
1403
+ return { stop, push: sendRaw, pushRepos, async drain() {
1404
+ while (pendingRequests.size) await Promise.allSettled(pendingRequests);
1405
+ await executionLanes.drain();
1406
+ } };
1404
1407
  }
@@ -58,6 +58,7 @@ export function computerRuntime(opts: RoomClientOptions): ComputerRuntime {
58
58
  ...(opts.commands ? ['commands'] : []),
59
59
  ...(opts.controls ? ['permission', 'steer'] : []),
60
60
  ...(opts.codeHandler ? ['code'] : []),
61
+ ...(opts.workspaces ? ['workspaces', 'checkout-history'] : []),
61
62
  ...(opts.conductHandler ? ['conduct'] : []),
62
63
  ...(opts.cloneHandler ? ['clone'] : []),
63
64
  ...(opts.attention ? ['attention'] : []),
@@ -0,0 +1,25 @@
1
+ import type { TurnLogStore } from '../turnLog.js';
2
+
3
+ const terminalTypes = new Set(['done', 'error', 'cancelled']);
4
+
5
+ /** A durability failure stops owned work. Its uncertain outcome is reported only after release. */
6
+ export function publishDurably(
7
+ logs: TurnLogStore,
8
+ event: Record<string, unknown> & { requestId: string },
9
+ inFlight: Map<string, AbortController>,
10
+ send: (frame: unknown) => void,
11
+ ): void {
12
+ let frame: unknown;
13
+ try {
14
+ frame = logs.append(event.requestId, event);
15
+ } catch (error) {
16
+ for (const controller of inFlight.values()) controller.abort();
17
+ if (terminalTypes.has(String(event.type)) && !inFlight.has(event.requestId)) {
18
+ send({ type: 'error', requestId: event.requestId, code: 'durability_fault',
19
+ message: "Computer storage failed. This turn's final outcome could not be saved. Free disk space and restart Lucidity, then inspect the workspace before retrying." });
20
+ return;
21
+ }
22
+ throw error;
23
+ }
24
+ send(frame);
25
+ }
@@ -31,7 +31,9 @@ import {
31
31
  */
32
32
 
33
33
  export type IncidentClass =
34
- | 'ok' // delivered cleanly (a normal reply, or a delivered daemon error)
34
+ | 'ok' // delivered a completed answer
35
+ | 'execution-error' // delivery succeeded; execution failed
36
+ | 'history-unavailable' // no retained receipt; acceptance cannot be established
35
37
  | 'cancelled' // the user stopped it — not a failure
36
38
  | 'pending' // still plausibly in flight — too early to call a loss
37
39
  | 'outbound-loss'
@@ -154,7 +156,9 @@ export interface IncidentBundle {
154
156
 
155
157
  /** Severity for picking which turn a bundle headlines. Higher = worse. */
156
158
  const SEVERITY: Record<IncidentClass, number> = {
159
+ 'execution-error': 4,
157
160
  'outbound-loss': 4,
161
+ 'history-unavailable': 1,
158
162
  'session-reset': 3,
159
163
  'inbound-loss': 2,
160
164
  pending: 1,
@@ -175,7 +179,8 @@ export function classifyTurn(
175
179
  if (phone.sessionReset) return 'session-reset';
176
180
  // The phone got a terminal: a real reply, or a daemon error that reached it. Either way the
177
181
  // connection worked — an error the phone displayed is not a connection loss.
178
- if (phone.state === 'done' || phone.state === 'error') return 'ok';
182
+ if (phone.state === 'error') return 'execution-error';
183
+ if (phone.state === 'done') return 'ok';
179
184
  if (phone.state === 'cancelled') return 'cancelled';
180
185
 
181
186
  const phoneSeq = phone.seq ?? 0;
@@ -187,15 +192,14 @@ export function classifyTurn(
187
192
  return 'pending'; // Mac still working, phone has caught up — no loss yet
188
193
  }
189
194
 
190
- // No turn log for this id: the prompt either never arrived, or arrived and hasn't produced
191
- // its first frame. The phone having GIVEN UP (or having routed the send to a frozen outbox)
192
- // is what turns "no record" into a real outbound loss.
195
+ // Missing legacy logs may have expired. Even a settled phone request is not proof
196
+ // that the daemon never accepted it.
193
197
  const settled =
194
198
  phone.state === 'timeout' ||
195
199
  phone.state === 'lost' ||
196
200
  phone.endedAt != null;
197
201
  if (phone.staleSend || phone.transport === 'outbox' || settled)
198
- return 'outbound-loss';
202
+ return 'history-unavailable';
199
203
  return 'pending';
200
204
  }
201
205
 
@@ -212,6 +216,10 @@ function noteFor(t: JoinedTurn): string {
212
216
  const id = requestId.slice(0, 8);
213
217
  const missed = Math.max(0, daemon.maxSeq - (phone.seq ?? 0));
214
218
  switch (t.class) {
219
+ case 'execution-error':
220
+ return `Turn ${id} delivered an execution error${daemon.terminalDetail ? `: ${daemon.terminalDetail}` : '.'} Inspect that failure before retrying; delivery and execution are separate outcomes.`;
221
+ case 'history-unavailable':
222
+ return `No retained receipt for turn ${id}. Its earlier history may have expired or it may never have been accepted. The outcome is unknown; do not rerun it automatically.`;
215
223
  case 'outbound-loss':
216
224
  return `Turn ${id} (${phone.kind}) left the phone ${
217
225
  phone.staleSend ? 'on a socket that only looked open' : 'via the outbox'
@@ -224,7 +232,7 @@ function noteFor(t: JoinedTurn): string {
224
232
  daemon.terminalDetail ? ` ("${daemon.terminalDetail}")` : ''
225
233
  } at seq ${daemon.maxSeq}; the phone settled '${phone.state}' at seq ${
226
234
  phone.seq ?? 0
227
- } — the turn died mid-flight (a daemon restart or crash), so there's no reply to pull. Re-send it.`;
235
+ }. The recorded error is available by pull. Inspect workspace and provider state before choosing to retry.`;
228
236
  if (daemon.terminalType === 'done')
229
237
  return `The Mac ran turn ${id} to completion (done at seq ${daemon.maxSeq}) but the phone settled '${phone.state}' at seq ${
230
238
  phone.seq ?? 0
@@ -252,7 +260,7 @@ function pickOffender(
252
260
  ): JoinedTurn | null {
253
261
  if (focusRequestId) {
254
262
  const f = turns.find((t) => t.requestId === focusRequestId);
255
- if (f && SEVERITY[f.class] >= 1) return f;
263
+ if (f) return f;
256
264
  }
257
265
  const candidates = turns.filter((t) => SEVERITY[t.class] >= 1);
258
266
  if (!candidates.length) return null;
@@ -2,8 +2,6 @@ import {
2
2
  mkdirSync,
3
3
  readFileSync,
4
4
  readdirSync,
5
- renameSync,
6
- writeFileSync,
7
5
  statSync,
8
6
  unlinkSync,
9
7
  } from 'node:fs';
@@ -18,6 +16,7 @@ type Entry = {
18
16
  state: 'queued' | 'running' | 'steering' | 'done' | 'failed' | 'skipped';
19
17
  action?: 'cancel' | 'steer';
20
18
  resume?: string;
19
+ failure?: { message: string; code?: string };
21
20
  };
22
21
  export function turnLane(req: Request): string {
23
22
  return req.kind === 'ask'
@@ -43,6 +42,8 @@ export class DurableTurnQueue {
43
42
  },
44
43
  ) {
45
44
  mkdirSync(deps.dir, { recursive: true, mode: 0o700 });
45
+ for (const entry of deps.logs.runtime.list<Entry>('queue'))
46
+ this.entries.set(entry.request.id, entry);
46
47
  for (const name of readdirSync(deps.dir)
47
48
  .filter((name) => name.endsWith('.json'))
48
49
  .sort()) {
@@ -56,6 +57,11 @@ export class DurableTurnQueue {
56
57
  unlinkSync(join(deps.dir, name));
57
58
  continue;
58
59
  }
60
+ if (this.entries.has(entry.request.id)) continue;
61
+ this.deps.logs.runtime.set('queue', entry.request.id, entry);
62
+ this.entries.set(entry.request.id, entry);
63
+ }
64
+ for (const entry of this.entries.values()) {
59
65
  const parsed = HarnessRequestSchema.parse(entry.request);
60
66
  if (parsed.kind !== 'ask' && parsed.kind !== 'code')
61
67
  throw new Error('Invalid queued turn');
@@ -72,7 +78,8 @@ export class DurableTurnQueue {
72
78
  } else {
73
79
  this.fail(
74
80
  entry,
75
- 'Lucid restarted during this turn. It was not run again. Review the result before resending.',
81
+ 'Lucid restarted during this turn. It was not run again. Review its work before continuing.',
82
+ 'interrupted_unknown',
76
83
  );
77
84
  }
78
85
  } else if (entry.state === 'skipped' && !terminal) {
@@ -83,8 +90,8 @@ export class DurableTurnQueue {
83
90
  } else if (entry.state === 'failed' && !terminal) {
84
91
  this.publish(parsed.id, {
85
92
  type: 'error',
86
- message:
87
- 'This queued turn could not finish. Review it before resending.',
93
+ ...(entry.failure ?? { message:
94
+ 'This queued turn could not finish. Review it before resending.' }),
88
95
  });
89
96
  }
90
97
  }
@@ -104,12 +111,7 @@ export class DurableTurnQueue {
104
111
  }
105
112
 
106
113
  private save(entry: Entry): void {
107
- const path = join(this.deps.dir, `${entry.request.id}.json`);
108
- writeFileSync(`${path}.tmp`, JSON.stringify(entry), {
109
- mode: 0o600,
110
- flush: true,
111
- });
112
- renameSync(`${path}.tmp`, path);
114
+ this.deps.logs.runtime.set('queue', entry.request.id, entry);
113
115
  this.entries.set(entry.request.id, entry);
114
116
  }
115
117
  private publish(id: string, event: Record<string, unknown>): void {
@@ -137,10 +139,11 @@ export class DurableTurnQueue {
137
139
  .find((frame) => typeof frame.sessionId === 'string')?.sessionId;
138
140
  return typeof value === 'string' ? value : undefined;
139
141
  }
140
- private fail(entry: Entry, message: string): void {
141
- this.save({ ...entry, state: 'failed' });
142
+ private fail(entry: Entry, message: string, code?: string): void {
143
+ const failure = { message, ...(code ? { code } : {}) };
144
+ this.save({ ...entry, state: 'failed', failure });
142
145
  if (!this.deps.logs.read(entry.request.id).terminated)
143
- this.publish(entry.request.id, { type: 'error', message });
146
+ this.publish(entry.request.id, { type: 'error', ...failure });
144
147
  this.wake();
145
148
  }
146
149
  owns(id: string): boolean {
@@ -199,13 +202,9 @@ export class DurableTurnQueue {
199
202
  );
200
203
  }
201
204
  const entry: Entry = { request, state: 'queued' };
202
- this.save(entry);
203
- try {
204
- this.publish(request.id, { type: 'queue_state', state: 'queued' });
205
- } catch (error) {
206
- this.save({ ...entry, state: 'failed' });
207
- throw error;
208
- }
205
+ const accepted = this.deps.logs.runtime.accept(request, entry);
206
+ this.entries.set(request.id, entry);
207
+ for (const frame of accepted.frames) this.deps.sendRaw(frame);
209
208
  this.wake();
210
209
  }
211
210
 
@@ -254,11 +253,11 @@ export class DurableTurnQueue {
254
253
  return { ready: true, resume };
255
254
  }
256
255
  wake(): void {
257
- if (this.stopped || this.pumping) return;
256
+ if (this.stopped || this.pumping || !this.deps.logs.runtime.writable) return;
258
257
  this.pumping = true;
259
258
  queueMicrotask(() => {
260
259
  this.pumping = false;
261
- if (this.stopped) return;
260
+ if (this.stopped || !this.deps.logs.runtime.writable) return;
262
261
  const occupied = new Set<string>();
263
262
  for (const [id, entry] of this.entries) {
264
263
  const lane = turnLane(entry.request);
@@ -276,7 +275,7 @@ export class DurableTurnQueue {
276
275
  void this.deps.lanes
277
276
  .run(turnLane(entry.request), async () => {
278
277
  const current = this.entries.get(id)!;
279
- if (this.stopped || current.state !== 'queued') return;
278
+ if (this.stopped || !this.deps.logs.runtime.writable || current.state !== 'queued') return;
280
279
  const previous = this.predecessor(current);
281
280
  if (!previous.ready) return;
282
281
  this.save({ ...current, state: 'running' });
@@ -299,9 +298,9 @@ export class DurableTurnQueue {
299
298
  'The turn ended before completion. Review it before resending.',
300
299
  );
301
300
  })
302
- .catch((error) =>
303
- this.fail(this.entries.get(id)!, String(error.message)),
304
- )
301
+ .catch((error) => {
302
+ if (this.deps.logs.runtime.writable) this.fail(this.entries.get(id)!, String(error.message));
303
+ })
305
304
  .finally(() => {
306
305
  this.scheduled.delete(id);
307
306
  this.wake();