chatroom-cli 1.98.4 → 1.98.6

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.
package/dist/index.js CHANGED
@@ -83544,7 +83544,9 @@ var DaemonMachineService, DaemonMachineServiceLive = (ops) => exports_Layer.succ
83544
83544
  clearStuckStoppingSlot: (chatroomId, role) => exports_Effect.promise(() => mgr.clearStuckStoppingSlot(chatroomId, role)),
83545
83545
  whenTurnEndsIdle: () => exports_Effect.promise(() => mgr.whenTurnEndsIdle()),
83546
83546
  resumeTurnForSlot: (args2) => exports_Effect.promise(() => mgr.resumeTurnForSlot(args2)),
83547
- setLastInFlightTask: (chatroomId, role, taskId) => exports_Effect.sync(() => mgr.setLastInFlightTask(chatroomId, role, taskId))
83547
+ setLastInFlightTask: (chatroomId, role, taskId) => exports_Effect.sync(() => mgr.setLastInFlightTask(chatroomId, role, taskId)),
83548
+ clearLastInFlightTaskIfMatches: (chatroomId, role, taskId) => exports_Effect.sync(() => mgr.clearLastInFlightTaskIfMatches(chatroomId, role, taskId)),
83549
+ reconcileNativeTurnPhaseIdle: (chatroomId, role) => exports_Effect.sync(() => mgr.reconcileNativeTurnPhaseIdle(chatroomId, role))
83548
83550
  }), DaemonSessionService, DaemonMutableStateService;
83549
83551
  var init_daemon_services = __esm(() => {
83550
83552
  init_esm();
@@ -98686,40 +98688,18 @@ var init_convex_id = __esm(() => {
98686
98688
  init_zod();
98687
98689
  });
98688
98690
 
98689
- // ../../services/backend/src/domain/usecase/machine/assigned-task-monitor-contract.ts
98690
- function parseAssignedTaskSignal(raw) {
98691
- return assignedTaskSignalSchema.parse(raw);
98691
+ // ../../services/backend/src/domain/usecase/machine/assigned-task-snapshot-contract.ts
98692
+ function parseAssignedTaskSnapshotRow(raw) {
98693
+ return assignedTaskSnapshotRowSchema.parse(raw);
98692
98694
  }
98693
- function parseAssignedTaskPresenceSignal(raw) {
98694
- const full = assignedTaskPresenceSignalSchema.safeParse(raw);
98695
- if (full.success)
98696
- return full.data;
98697
- const delta = assignedTaskPresenceDeltaSchema.safeParse(raw);
98698
- if (delta.success) {
98699
- const presenceUpdatedAt = Number(delta.data.presenceKey.split(":")[0]);
98700
- const resolvedAt = Number.isFinite(presenceUpdatedAt) ? presenceUpdatedAt : 0;
98701
- return {
98702
- taskId: delta.data.taskId,
98703
- chatroomId: "",
98704
- role: delta.data.role,
98705
- lastSeenAt: resolvedAt,
98706
- presenceUpdatedAt: resolvedAt,
98707
- presenceKey: delta.data.presenceKey
98708
- };
98709
- }
98710
- return assignedTaskPresenceSignalSchema.parse(raw);
98711
- }
98712
- function parseAssignedTaskMonitorRow(raw) {
98713
- return assignedTaskMonitorRowSchema.parse(raw);
98714
- }
98715
- function parseAssignedTaskMonitorRows(raw) {
98695
+ function parseAssignedTaskSnapshotRows(raw) {
98716
98696
  if (!Array.isArray(raw)) {
98717
98697
  throw new Error("Expected hydrate tasks array");
98718
98698
  }
98719
- return raw.map((row) => parseAssignedTaskMonitorRow(row));
98699
+ return raw.map((row) => parseAssignedTaskSnapshotRow(row));
98720
98700
  }
98721
- var ACTIVE_TASK_STATUSES, activeTaskStatusSchema, ASSIGNED_TASK_SIGNAL_TYPES, assignedTaskSignalTypeSchema, SESSION_AUGMENTATION_MODES, sessionAugmentationSchema, AGENT_DESIRED_STATES, agentDesiredStateSchema, AGENT_CIRCUIT_STATES, agentCircuitStateSchema, chatroomTaskIdSchema, chatroomRoomIdSchema, assignedTaskAgentConfigSchema, assignedTaskParticipantSchema, assignedTaskSignalBootstrapFields, assignedTaskSignalSchema, assignedTaskPresenceSignalSchema, assignedTaskPresenceDeltaSchema, assignedTaskMonitorRowSchema;
98722
- var init_assigned_task_monitor_contract = __esm(() => {
98701
+ var ACTIVE_TASK_STATUSES, activeTaskStatusSchema, ASSIGNED_TASK_SIGNAL_TYPES, assignedTaskSignalTypeSchema, SESSION_AUGMENTATION_MODES, sessionAugmentationSchema, AGENT_DESIRED_STATES, agentDesiredStateSchema, AGENT_CIRCUIT_STATES, agentCircuitStateSchema, chatroomTaskIdSchema, chatroomRoomIdSchema, assignedTaskAgentConfigSchema, assignedTaskParticipantSchema, assignedTaskSignalBootstrapFields, assignedTaskSignalSchema, assignedTaskPresenceSignalSchema, assignedTaskPresenceDeltaSchema, assignedTaskSnapshotRowSchema;
98702
+ var init_assigned_task_snapshot_contract = __esm(() => {
98723
98703
  init_zod();
98724
98704
  init_convex_id();
98725
98705
  ACTIVE_TASK_STATUSES = ["pending", "acknowledged", "in_progress"];
@@ -98782,7 +98762,7 @@ var init_assigned_task_monitor_contract = __esm(() => {
98782
98762
  role: exports_external.string(),
98783
98763
  presenceKey: exports_external.string()
98784
98764
  });
98785
- assignedTaskMonitorRowSchema = exports_external.object({
98765
+ assignedTaskSnapshotRowSchema = exports_external.object({
98786
98766
  taskId: chatroomTaskIdSchema,
98787
98767
  chatroomId: chatroomRoomIdSchema,
98788
98768
  status: activeTaskStatusSchema,
@@ -98943,6 +98923,19 @@ function getNativeDeliverySession() {
98943
98923
  }
98944
98924
  var registered = null;
98945
98925
 
98926
+ // src/daemon/entry/native-delivery/native-stale-turn-phase.ts
98927
+ function isStaleTurnInFlightWhileWaiting(task, slot) {
98928
+ if (!slot || isTurnPhaseIdle(slot.nativeTurnPhase ?? "idle"))
98929
+ return false;
98930
+ if (task.status !== "pending")
98931
+ return false;
98932
+ return task.participant?.lastSeenAction === NATIVE_WAITING_ACTION;
98933
+ }
98934
+ var init_native_stale_turn_phase = __esm(() => {
98935
+ init_participant();
98936
+ init_check_agent_slot();
98937
+ });
98938
+
98946
98939
  // src/daemon/domain/native-integration/predicates.ts
98947
98940
  function isStaleCliGetNextTaskWaiting(task) {
98948
98941
  const lastSeenAt = task.participant?.lastSeenAt ?? 0;
@@ -99002,8 +98995,21 @@ function explainNativeDeliveryBlock(task, opts) {
99002
98995
  return `acknowledged_wrong_role (assignedTo=${assignedTo ?? "none"}, role=${role})`;
99003
98996
  }
99004
98997
  }
98998
+ const inFlightBlock = explainInFlightDeliveryBlock(task, opts.slot);
98999
+ if (inFlightBlock)
99000
+ return inFlightBlock;
99005
99001
  return explainAgentReadyForNativeDeliveryBlock(task, opts.slot);
99006
99002
  }
99003
+ function explainInFlightDeliveryBlock(task, slot) {
99004
+ if (!slot?.lastInFlightTaskId || slot.lastInFlightTaskId !== task.taskId)
99005
+ return null;
99006
+ if (task.status === "pending")
99007
+ return null;
99008
+ if (task.status === "acknowledged") {
99009
+ return "already_delivered_to_slot (lastInFlightTaskId match, status=acknowledged)";
99010
+ }
99011
+ return null;
99012
+ }
99007
99013
  function explainLedgerDeliveryBlock(taskId, harnessSessionId, ledger) {
99008
99014
  if (ledger.isDelivered(taskId, harnessSessionId)) {
99009
99015
  return "already_delivered_this_session";
@@ -99403,28 +99409,21 @@ function mapAssignedTaskSnapshotList(rows) {
99403
99409
  return rows.map(mapAssignedTaskSnapshot);
99404
99410
  }
99405
99411
 
99406
- // src/infrastructure/stores/assigned-task-snapshot-store.ts
99407
- function replaceAssignedTaskSnapshots(next4) {
99408
- rows = [...next4];
99409
- hasSnapshot = true;
99410
- }
99411
- function clearAssignedTaskSnapshots() {
99412
- rows = [];
99413
- hasSnapshot = false;
99414
- }
99415
- function hasAssignedTaskSnapshot() {
99416
- return hasSnapshot;
99417
- }
99418
- function listAssignedTaskSnapshots() {
99419
- return [...rows];
99412
+ // src/daemon/infrastructure/inbox/fetch-machine-assigned-task-snapshots.ts
99413
+ async function fetchMachineAssignedTaskSnapshots(sessionDeps, machineId) {
99414
+ const result = await sessionDeps.backend.query(api.machines.listMachineAssignedTaskSnapshots, {
99415
+ sessionId: sessionDeps.sessionId,
99416
+ machineId
99417
+ });
99418
+ return mapAssignedTaskSnapshotList(parseAssignedTaskSnapshotRows(result?.tasks ?? []));
99420
99419
  }
99421
- function listAssignedTaskSnapshotsForRole(chatroomId, role) {
99420
+ function filterSnapshotsForRole(snapshots, chatroomId, role) {
99422
99421
  const roleLower = role.toLowerCase();
99423
- return rows.filter((row) => row.chatroomId === chatroomId && row.agentConfig.role.toLowerCase() === roleLower);
99422
+ return snapshots.filter((row) => row.chatroomId === chatroomId && row.agentConfig.role.toLowerCase() === roleLower);
99424
99423
  }
99425
- var rows, hasSnapshot = false;
99426
- var init_assigned_task_snapshot_store = __esm(() => {
99427
- rows = [];
99424
+ var init_fetch_machine_assigned_task_snapshots = __esm(() => {
99425
+ init_assigned_task_snapshot_contract();
99426
+ init_api3();
99428
99427
  });
99429
99428
 
99430
99429
  // src/daemon/entry/restart-orchestrator-in-flight.ts
@@ -99518,18 +99517,22 @@ class NativeTaskDeliveryCoordinator {
99518
99517
  if (!session2)
99519
99518
  return;
99520
99519
  const { runtime: runtime4, effectContext: effectContext2, agentMgr, sessionDeps, machineId } = session2;
99521
- const tasks = listAssignedTaskSnapshotsForRole(chatroomId, role);
99522
- if (tasks.length === 0) {
99523
- logNativeDeliveryNoTasks(role, chatroomId);
99524
- return;
99525
- }
99526
- this.reconcileAssignedTasks({
99527
- tasks,
99528
- runtime: runtime4,
99529
- effectContext: effectContext2,
99530
- agentMgr,
99531
- sessionDeps,
99532
- machineId
99520
+ fetchMachineAssignedTaskSnapshots(sessionDeps, machineId).then((all8) => {
99521
+ const tasks = filterSnapshotsForRole(all8, chatroomId, role);
99522
+ if (tasks.length === 0) {
99523
+ logNativeDeliveryNoTasks(role, chatroomId);
99524
+ return;
99525
+ }
99526
+ this.reconcileAssignedTasks({
99527
+ tasks,
99528
+ runtime: runtime4,
99529
+ effectContext: effectContext2,
99530
+ agentMgr,
99531
+ sessionDeps,
99532
+ machineId
99533
+ });
99534
+ }).catch((err) => {
99535
+ console.warn(`[NativeTaskDelivery] rehydrate failed for ${role}@${chatroomId}: ${getErrorMessage(err)}`);
99533
99536
  });
99534
99537
  }
99535
99538
  reconcileAssignedTasks(params) {
@@ -99549,7 +99552,18 @@ class NativeTaskDeliveryCoordinator {
99549
99552
  for (const row of pendingFirst) {
99550
99553
  const { role } = row.agentConfig;
99551
99554
  const slot = agentMgr.getSlot(row.chatroomId, role);
99552
- const blockReason = explainNativeDeliveryBlock(row, { slot });
99555
+ if (row.status === "pending" && slot?.lastInFlightTaskId === row.taskId) {
99556
+ exports_Effect.runSync(agentMgr.clearLastInFlightTaskIfMatches(row.chatroomId, role, row.taskId));
99557
+ }
99558
+ if (isStaleTurnInFlightWhileWaiting(row, slot)) {
99559
+ if (agentMgr.reconcileNativeTurnPhaseIdle) {
99560
+ exports_Effect.runSync(agentMgr.reconcileNativeTurnPhaseIdle(row.chatroomId, role));
99561
+ }
99562
+ logNativeDeliveryFallback("stale-turn-phase", role, row.chatroomId, row.taskId);
99563
+ }
99564
+ const blockReason = explainNativeDeliveryBlock(row, {
99565
+ slot: agentMgr.getSlot(row.chatroomId, role)
99566
+ });
99553
99567
  if (blockReason) {
99554
99568
  if (isDeliverableTaskStatus(row.status)) {
99555
99569
  logNativeDeliverySkip(role, row.chatroomId, row.taskId, blockReason);
@@ -99638,12 +99652,13 @@ function notifyNativeTurnIdle(params) {
99638
99652
  var coordinator;
99639
99653
  var init_native_task_delivery_coordinator = __esm(() => {
99640
99654
  init_esm();
99655
+ init_native_stale_turn_phase();
99641
99656
  init_native_task_injector_logic();
99642
99657
  init_native_task_injector();
99643
99658
  init_api3();
99644
99659
  init_assigned_task();
99645
- init_assigned_task_snapshot_store();
99646
99660
  init_convex_error();
99661
+ init_fetch_machine_assigned_task_snapshots();
99647
99662
  init_restart_orchestrator_in_flight();
99648
99663
  });
99649
99664
 
@@ -99718,7 +99733,7 @@ async function listDeliverableSnapshots(deps, event) {
99718
99733
  machineId: deps.session.machineId
99719
99734
  });
99720
99735
  const slot = deps.agentMgr.getSlot(event.chatroomId, event.role);
99721
- return mapAssignedTaskSnapshotList(parseAssignedTaskMonitorRows(result.tasks ?? [])).filter((t) => t.chatroomId === event.chatroomId && t.agentConfig.role.toLowerCase() === event.role.toLowerCase() && isDeliverableTaskStatus(t.status) && isAgentReadyForNativeDelivery(t, slot)).sort((a, b) => a.createdAt - b.createdAt);
99736
+ return mapAssignedTaskSnapshotList(parseAssignedTaskSnapshotRows(result.tasks ?? [])).filter((t) => t.chatroomId === event.chatroomId && t.agentConfig.role.toLowerCase() === event.role.toLowerCase() && isDeliverableTaskStatus(t.status) && isAgentReadyForNativeDelivery(t, slot)).sort((a, b) => a.createdAt - b.createdAt);
99722
99737
  }
99723
99738
  async function deliverOneTask(deps, event, snapshot) {
99724
99739
  const slot = deps.agentMgr.getSlot(event.chatroomId, event.role);
@@ -99740,6 +99755,11 @@ async function deliverOneTask(deps, event, snapshot) {
99740
99755
  console.warn(`[RestartOrchestrator] skip task ${snapshot.taskId} — ${ledgerBlock}`);
99741
99756
  return false;
99742
99757
  }
99758
+ const deliveryBlock = explainNativeDeliveryBlock(snapshot, { slot });
99759
+ if (deliveryBlock) {
99760
+ console.warn(`[RestartOrchestrator] skip task ${snapshot.taskId} — ${deliveryBlock}`);
99761
+ return false;
99762
+ }
99743
99763
  if (!ledger.tryAcquire(snapshot.taskId, harnessSessionId)) {
99744
99764
  console.warn(`[RestartOrchestrator] skip task ${snapshot.taskId} — delivery_ledger_busy`);
99745
99765
  return false;
@@ -99843,7 +99863,7 @@ var init_restart_orchestrator = __esm(() => {
99843
99863
  init_reliability();
99844
99864
  init_participant();
99845
99865
  init_build_agent_restart_event();
99846
- init_assigned_task_monitor_contract();
99866
+ init_assigned_task_snapshot_contract();
99847
99867
  init_esm();
99848
99868
  init_api3();
99849
99869
  init_native_ready_invariant();
@@ -101527,6 +101547,7 @@ class AgentProcessManager {
101527
101547
  }
101528
101548
  if (slot) {
101529
101549
  setNativeTurnPhase(slot, defaultNativeTurnPhase());
101550
+ this.clearLastInFlightTask(opts.chatroomId, opts.role);
101530
101551
  }
101531
101552
  notifyNativeTurnIdle({ chatroomId: opts.chatroomId, role: opts.role });
101532
101553
  console.log(`[AgentProcessManager] ✅ Native agent_end handled for ${opts.role}`);
@@ -101542,6 +101563,9 @@ class AgentProcessManager {
101542
101563
  }
101543
101564
  const stopReason = resolveStopReason(opts.code, opts.signal);
101544
101565
  const ctx = this.captureExitContext(slot, opts, stopReason);
101566
+ if (slot.harness && getHarnessCapabilities(slot.harness).supportsNativeIntegration) {
101567
+ setNativeTurnPhase(slot, defaultNativeTurnPhase());
101568
+ }
101545
101569
  this.maybeEmitProviderUnavailable(opts.chatroomId, opts.role, slot);
101546
101570
  notifyNativeHarnessSessionLostOnExit({
101547
101571
  chatroomId: opts.chatroomId,
@@ -101843,6 +101867,21 @@ class AgentProcessManager {
101843
101867
  const slot = this.getOrCreateSlot(agentKey3(chatroomId, role));
101844
101868
  slot.lastInFlightTaskId = taskId;
101845
101869
  }
101870
+ clearLastInFlightTaskIfMatches(chatroomId, role, taskId) {
101871
+ const slot = this.slots.get(agentKey3(chatroomId, role));
101872
+ if (slot?.lastInFlightTaskId === taskId)
101873
+ slot.lastInFlightTaskId = undefined;
101874
+ }
101875
+ reconcileNativeTurnPhaseIdle(chatroomId, role) {
101876
+ const slot = this.getSlot(chatroomId, role);
101877
+ if (slot)
101878
+ setNativeTurnPhase(slot, defaultNativeTurnPhase());
101879
+ }
101880
+ clearLastInFlightTask(chatroomId, role) {
101881
+ const slot = this.slots.get(agentKey3(chatroomId, role));
101882
+ if (slot)
101883
+ slot.lastInFlightTaskId = undefined;
101884
+ }
101846
101885
  listActive() {
101847
101886
  const result = [];
101848
101887
  for (const [key, slot] of this.slots) {
@@ -102512,6 +102551,9 @@ class AgentProcessManager {
102512
102551
  setNativeTurnPhase(slot, defaultNativeTurnPhase());
102513
102552
  }
102514
102553
  await this.emitNativeWaiting(opts.chatroomId, opts.role, opts.agentHarness);
102554
+ if (getHarnessCapabilities(opts.agentHarness).supportsNativeIntegration) {
102555
+ getNativeTaskDeliveryCoordinator().tryInjectNextForRole(opts.chatroomId, opts.role);
102556
+ }
102515
102557
  }
102516
102558
  async emitNativeWaiting(chatroomId, role, harness) {
102517
102559
  return emitNativeWaitingAfterSpawn({
@@ -108647,12 +108689,17 @@ function handleRefreshCapabilitiesEffect(event, tracker) {
108647
108689
  })));
108648
108690
  });
108649
108691
  }
108650
- async function handleInboundCommandEvent(commandId, tracker, effectContext2, session2) {
108651
- const result = await session2.backend.query(api.machines.getCommandEvents, {
108652
- sessionId: session2.sessionId,
108653
- machineId: session2.machineId
108654
- });
108655
- const event = result?.events?.find((e) => e._id.toString() === commandId);
108692
+ async function handleInboundCommandEvent(commandId, tracker, effectContext2, session2, commandEvent) {
108693
+ let event;
108694
+ if (commandEvent?._id.toString() === commandId) {
108695
+ event = commandEvent;
108696
+ } else {
108697
+ const result = await session2.backend.query(api.machines.getCommandEvents, {
108698
+ sessionId: session2.sessionId,
108699
+ machineId: session2.machineId
108700
+ });
108701
+ event = result?.events?.find((e) => e._id.toString() === commandId);
108702
+ }
108656
108703
  if (!event)
108657
108704
  return;
108658
108705
  await exports_Effect.runPromise(dispatchCommandEventEffect(event, tracker).pipe(exports_Effect.provide(effectContext2)));
@@ -114154,27 +114201,27 @@ function createFifoBatchedOutbox(o) {
114154
114201
  return running3;
114155
114202
  running3 = (async () => {
114156
114203
  while (true) {
114157
- const rows2 = o.store.claimNextBatch(o.deliveryKey, o.batchSize);
114158
- if (!rows2.length)
114204
+ const rows = o.store.claimNextBatch(o.deliveryKey, o.batchSize);
114205
+ if (!rows.length)
114159
114206
  break;
114160
114207
  try {
114161
- const results = await o.send(rows2.map((r) => o.deserialize(r.payloadJson)));
114208
+ const results = await o.send(rows.map((r) => o.deserialize(r.payloadJson)));
114162
114209
  let hasRetry = false;
114163
114210
  for (let i2 = 0;i2 < results.length; i2++) {
114164
- const item = o.deserialize(rows2[i2].payloadJson);
114211
+ const item = o.deserialize(rows[i2].payloadJson);
114165
114212
  const outcome = o.classifyOutcome?.(results[i2], item) ?? { kind: "success" };
114166
114213
  if (outcome.kind === "retry") {
114167
- o.store.updatePayload(rows2[i2].id, o.serialize(outcome.item));
114168
- o.store.markPending(rows2[i2].id);
114214
+ o.store.updatePayload(rows[i2].id, o.serialize(outcome.item));
114215
+ o.store.markPending(rows[i2].id);
114169
114216
  hasRetry = true;
114170
114217
  continue;
114171
114218
  }
114172
- o.store.markDone(rows2[i2].id);
114173
- waiters.get(rows2[i2].id)?.resolve(results[i2]);
114174
- waiters.delete(rows2[i2].id);
114219
+ o.store.markDone(rows[i2].id);
114220
+ waiters.get(rows[i2].id)?.resolve(results[i2]);
114221
+ waiters.delete(rows[i2].id);
114175
114222
  }
114176
- for (let i2 = results.length;i2 < rows2.length; i2++)
114177
- o.store.markPending(rows2[i2].id);
114223
+ for (let i2 = results.length;i2 < rows.length; i2++)
114224
+ o.store.markPending(rows[i2].id);
114178
114225
  if (hasRetry) {
114179
114226
  scheduleRetry();
114180
114227
  break;
@@ -114182,7 +114229,7 @@ function createFifoBatchedOutbox(o) {
114182
114229
  retryAttempt = 0;
114183
114230
  } catch (e) {
114184
114231
  o.onError?.(e);
114185
- for (const r of rows2)
114232
+ for (const r of rows)
114186
114233
  o.store.markPendingRetry(r.id, e);
114187
114234
  scheduleRetry();
114188
114235
  break;
@@ -115710,20 +115757,7 @@ var init_command_run_subscription = __esm(() => {
115710
115757
  dispatchedStop = new Set;
115711
115758
  });
115712
115759
 
115713
- // src/daemon/entry/assigned-task-monitor-registry.ts
115714
- function registerAssignedTaskMonitorHandler(h) {
115715
- handler6 = h;
115716
- }
115717
- function unregisterAssignedTaskMonitorHandler() {
115718
- handler6 = undefined;
115719
- }
115720
- async function dispatchAssignedTaskMonitorEvent(event) {
115721
- if (handler6)
115722
- await handler6(event);
115723
- }
115724
- var handler6;
115725
-
115726
- // src/daemon/entry/task-monitor/task-monitor-logic.ts
115760
+ // src/daemon/entry/task-delivery/task-delivery-logic.ts
115727
115761
  function isPendingAliveRunningTask(task) {
115728
115762
  const { agentConfig, status: status3 } = task;
115729
115763
  return status3 === "pending" && agentConfig.spawnedAgentPid != null && isAgentDesiredRunning(agentConfig.desiredState);
@@ -115782,9 +115816,29 @@ function listNativeTasksNeedingRevive(tasks, health, now, cooldown) {
115782
115816
  const { chatroomId, agentConfig } = task;
115783
115817
  if (!agentConfig.workingDir)
115784
115818
  return false;
115785
- if (!cooldown.canNudge(chatroomId, agentConfig.role, now))
115819
+ if (!cooldown.canAttempt(chatroomId, agentConfig.role, "revive", now))
115820
+ return false;
115821
+ cooldown.recordAttempt(chatroomId, agentConfig.role, "revive", now);
115822
+ return true;
115823
+ });
115824
+ }
115825
+ function isNativePendingTaskNeedingWake(task) {
115826
+ if (!isNativeHarness(task.agentConfig.agentHarness))
115827
+ return false;
115828
+ if (task.status !== "pending")
115829
+ return false;
115830
+ if (isAgentDesiredRunning(task.agentConfig.desiredState))
115831
+ return false;
115832
+ return Boolean(task.agentConfig.workingDir);
115833
+ }
115834
+ function listNativePendingTasksNeedingWake(tasks, cooldown, now) {
115835
+ return tasks.filter((task) => {
115836
+ if (!isNativePendingTaskNeedingWake(task))
115837
+ return false;
115838
+ const { chatroomId, agentConfig } = task;
115839
+ if (!cooldown.canAttempt(chatroomId, agentConfig.role, "wake", now))
115786
115840
  return false;
115787
- cooldown.recordNudge(chatroomId, agentConfig.role, now);
115841
+ cooldown.recordAttempt(chatroomId, agentConfig.role, "wake", now);
115788
115842
  return true;
115789
115843
  });
115790
115844
  }
@@ -115808,23 +115862,20 @@ function shouldNudgeNativePendingTask(task, now, pendingIdleThresholdMs, slot) {
115808
115862
  const idleSince = lastSeenAt > 0 ? now - lastSeenAt : now - task.createdAt;
115809
115863
  return idleSince > pendingIdleThresholdMs;
115810
115864
  }
115811
- function shouldEscalateNativeNudgeToRestart(chatroomId, role, failures3) {
115812
- return failures3 >= NATIVE_NUDGE_ESCALATION_THRESHOLD;
115813
- }
115814
115865
 
115815
- class NudgeCooldown {
115866
+ class RecoveryCooldown {
115816
115867
  cooldownMs;
115817
- lastNudgedAt = new Map;
115868
+ lastAttemptAt = new Map;
115818
115869
  constructor(cooldownMs = NUDGE_COOLDOWN_MS) {
115819
115870
  this.cooldownMs = cooldownMs;
115820
115871
  }
115821
- canNudge(chatroomId, role, now) {
115822
- const key = `${chatroomId}:${role}`;
115823
- const last2 = this.lastNudgedAt.get(key);
115872
+ canAttempt(chatroomId, role, kind, now) {
115873
+ const key = `${kind}:${chatroomId}:${role}`;
115874
+ const last2 = this.lastAttemptAt.get(key);
115824
115875
  return last2 === undefined || now - last2 >= this.cooldownMs;
115825
115876
  }
115826
- recordNudge(chatroomId, role, now) {
115827
- this.lastNudgedAt.set(`${chatroomId}:${role}`, now);
115877
+ recordAttempt(chatroomId, role, kind, now) {
115878
+ this.lastAttemptAt.set(`${kind}:${chatroomId}:${role}`, now);
115828
115879
  }
115829
115880
  }
115830
115881
  function isTaskReadyForNudge(task, now, cooldown, getSlot) {
@@ -115836,7 +115887,7 @@ function isTaskReadyForNudge(task, now, cooldown, getSlot) {
115836
115887
  return false;
115837
115888
  }
115838
115889
  const { chatroomId, agentConfig } = task;
115839
- if (!cooldown.canNudge(chatroomId, agentConfig.role, now))
115890
+ if (!cooldown.canAttempt(chatroomId, agentConfig.role, "nudge", now))
115840
115891
  return false;
115841
115892
  if (!agentConfig.workingDir)
115842
115893
  return false;
@@ -115846,12 +115897,12 @@ function listTasksReadyForNudge(tasks, now, cooldown, getSlot) {
115846
115897
  return tasks.filter((task) => {
115847
115898
  if (!isTaskReadyForNudge(task, now, cooldown, getSlot))
115848
115899
  return false;
115849
- cooldown.recordNudge(task.chatroomId, task.agentConfig.role, now);
115900
+ cooldown.recordAttempt(task.chatroomId, task.agentConfig.role, "nudge", now);
115850
115901
  return true;
115851
115902
  });
115852
115903
  }
115853
- var PENDING_IDLE_NUDGE_MS = 15000, NUDGE_COOLDOWN_MS = 60000, NATIVE_NUDGE_ESCALATION_THRESHOLD = 2;
115854
- var init_task_monitor_logic = __esm(() => {
115904
+ var PENDING_IDLE_NUDGE_MS = 15000, NUDGE_COOLDOWN_MS = 60000;
115905
+ var init_task_delivery_logic = __esm(() => {
115855
115906
  init_assigned_task();
115856
115907
  init_check_agent_slot();
115857
115908
  init_predicates();
@@ -115860,7 +115911,7 @@ var init_task_monitor_logic = __esm(() => {
115860
115911
  init_native_task_injector_logic();
115861
115912
  });
115862
115913
 
115863
- // src/daemon/entry/task-monitor-runtime.ts
115914
+ // src/daemon/entry/native-delivery/task-delivery-processor.ts
115864
115915
  function resolveTaskWantResume(task) {
115865
115916
  return sessionAugmentationToWantResume(resolveSessionAugmentationForTask({ content: task.taskContent ?? "", startInNewSession: task.startInNewSession }, task.agentConfig.role));
115866
115917
  }
@@ -115950,6 +116001,24 @@ function runNativeReviveEffect(task, runtime4, effectContext2, agentMgr) {
115950
116001
  });
115951
116002
  }).pipe(exports_Effect.provide(effectContext2), exports_Effect.catchAll((err) => exports_Effect.sync(() => console.warn(`[TaskMonitor] native revive failed for ${role}@${chatroomId}: ${getErrorMessage(err)}`)))));
115952
116003
  }
116004
+ function runNativeWakeEffect(task, runtime4, effectContext2, agentMgr) {
116005
+ const ctx = resolveTaskRunnerContextFromFull(task);
116006
+ if (!ctx)
116007
+ return;
116008
+ const { chatroomId, agentConfig, role, workingDir, wantResume } = ctx;
116009
+ console.log(`[TaskMonitor] native wake ${role}@${chatroomId} — desiredState=stopped with pending task ${task.taskId}`);
116010
+ exports_Runtime.runFork(runtime4)(exports_Effect.gen(function* () {
116011
+ yield* agentMgr.ensureRunning({
116012
+ chatroomId,
116013
+ role,
116014
+ agentHarness: agentConfig.agentHarness,
116015
+ model: agentConfig.model,
116016
+ workingDir,
116017
+ reason: "platform.pending_task_wake",
116018
+ wantResume
116019
+ });
116020
+ }).pipe(exports_Effect.provide(effectContext2), exports_Effect.catchAll((err) => exports_Effect.sync(() => console.warn(`[TaskMonitor] native wake failed for ${role}@${chatroomId}: ${getErrorMessage(err)}`)))));
116021
+ }
115953
116022
  async function fetchTaskForAction(sessionDeps, machineId, snapshotRow) {
115954
116023
  const result = await sessionDeps.backend.query(api.machines.getAssignedTaskForAction, {
115955
116024
  sessionId: sessionDeps.sessionId,
@@ -115971,43 +116040,9 @@ async function clearStuckStoppingSlotIfNeeded(agentMgr, chatroomId, role) {
115971
116040
  }
115972
116041
  async function nudgeStuckTasks(tasks, now, cooldown, runtime4, effectContext2, agentMgr, sessionDeps, machineId) {
115973
116042
  const getSlot = (chatroomId, role) => agentMgr.getSlot(chatroomId, role);
115974
- for (const row of listTasksReadyForNudge(tasks, now, cooldown, getSlot)) {
116043
+ const cliTasks = tasks.filter((task) => !isNativeHarness(task.agentConfig.agentHarness));
116044
+ for (const row of listTasksReadyForNudge(cliTasks, now, cooldown, getSlot)) {
115975
116045
  await clearStuckStoppingSlotIfNeeded(agentMgr, row.chatroomId, row.agentConfig.role);
115976
- if (isNativeHarness(row.agentConfig.agentHarness)) {
115977
- const { chatroomId, agentConfig } = row;
115978
- const { role } = agentConfig;
115979
- if (!isTeamAgentRole(role))
115980
- continue;
115981
- const deliveryState = getRoleDeliveryState();
115982
- const failures3 = deliveryState.recordNativeNudgeFailure(chatroomId, role);
115983
- if (shouldEscalateNativeNudgeToRestart(chatroomId, role, failures3)) {
115984
- const full2 = await fetchTaskForAction(sessionDeps, machineId, row);
115985
- if (!full2)
115986
- continue;
115987
- console.log(`[TaskMonitor] native nudge escalate restart ${role}@${chatroomId} — pending task ${row.taskId}`);
115988
- runCliNudgeEffect(full2, runtime4, effectContext2, agentMgr, sessionDeps, machineId);
115989
- deliveryState.clearNativeNudgeFailures(chatroomId, role);
115990
- continue;
115991
- }
115992
- resetRoleDeliveryState(chatroomId, role);
115993
- await sessionDeps.backend.mutation(api.participants.join, {
115994
- sessionId: sessionDeps.sessionId,
115995
- chatroomId,
115996
- role,
115997
- action: NATIVE_WAITING_ACTION
115998
- });
115999
- console.log(`[TaskMonitor] native light nudge ${role}@${chatroomId} — redeliver pending task ${row.taskId}`);
116000
- logNativeDeliveryFallback("native-light-nudge", role, chatroomId, row.taskId);
116001
- getNativeTaskDeliveryCoordinator().reconcileAssignedTasks({
116002
- tasks: [row],
116003
- runtime: runtime4,
116004
- effectContext: effectContext2,
116005
- agentMgr,
116006
- sessionDeps,
116007
- machineId
116008
- });
116009
- continue;
116010
- }
116011
116046
  const full = await fetchTaskForAction(sessionDeps, machineId, row);
116012
116047
  if (!full)
116013
116048
  continue;
@@ -116025,7 +116060,19 @@ async function reviveNativeTasks(tasks, localHealth, now, cooldown, runtime4, ef
116025
116060
  runNativeReviveEffect(full, runtime4, effectContext2, agentMgr);
116026
116061
  }
116027
116062
  }
116028
- async function processTasksUpdate(tasks, runtime4, effectContext2, cooldown, agentMgr, sessionDeps, machineId, _pass) {
116063
+ async function wakeStoppedAgentsForPendingTasks(tasks, now, cooldown, runtime4, effectContext2, agentMgr, sessionDeps, machineId) {
116064
+ for (const row of listNativePendingTasksNeedingWake(tasks, cooldown, now)) {
116065
+ if (isRestartOrchestratorInFlight(row.chatroomId, row.agentConfig.role))
116066
+ continue;
116067
+ await clearStuckStoppingSlotIfNeeded(agentMgr, row.chatroomId, row.agentConfig.role);
116068
+ const full = await fetchTaskForAction(sessionDeps, machineId, row);
116069
+ if (!full)
116070
+ continue;
116071
+ runNativeWakeEffect(full, runtime4, effectContext2, agentMgr);
116072
+ }
116073
+ }
116074
+ async function processTasksUpdate(runtime4, effectContext2, cooldown, agentMgr, sessionDeps, machineId, _pass, options) {
116075
+ const tasks = options?.snapshots ? [...options.snapshots] : await fetchMachineAssignedTaskSnapshots(sessionDeps, machineId);
116029
116076
  const filteredTasks = filterSnapshotsExcludingRestartInFlight(tasks);
116030
116077
  if (filteredTasks.length === 0)
116031
116078
  return;
@@ -116034,10 +116081,11 @@ async function processTasksUpdate(tasks, runtime4, effectContext2, cooldown, age
116034
116081
  getSlot: (chatroomId, role) => agentMgr.getSlot(chatroomId, role),
116035
116082
  isPidAlive: (pid) => isProcessAlive((p) => process.kill(p, 0), pid)
116036
116083
  };
116084
+ await wakeStoppedAgentsForPendingTasks(filteredTasks, now, cooldown, runtime4, effectContext2, agentMgr, sessionDeps, machineId);
116037
116085
  await reviveNativeTasks(filteredTasks, localHealth, now, cooldown, runtime4, effectContext2, agentMgr, sessionDeps, machineId);
116038
116086
  if (filteredTasks.length > 0) {
116039
116087
  const first = filteredTasks[0];
116040
- logNativeDeliveryFallback("signal-presence", first.agentConfig.role, first.chatroomId, first.taskId);
116088
+ logNativeDeliveryFallback(_pass, first.agentConfig.role, first.chatroomId, first.taskId);
116041
116089
  }
116042
116090
  getNativeTaskDeliveryCoordinator().reconcileAssignedTasks({
116043
116091
  tasks: filteredTasks,
@@ -116049,60 +116097,317 @@ async function processTasksUpdate(tasks, runtime4, effectContext2, cooldown, age
116049
116097
  });
116050
116098
  await nudgeStuckTasks(filteredTasks, now, cooldown, runtime4, effectContext2, agentMgr, sessionDeps, machineId);
116051
116099
  }
116052
- function listDeliverablePendingFromStore(agentMgr) {
116053
- if (!hasAssignedTaskSnapshot())
116054
- return [];
116055
- return listAssignedTaskSnapshots().filter((row) => {
116056
- if (row.status !== "pending")
116057
- return false;
116058
- const slot = agentMgr.getSlot(row.chatroomId, row.agentConfig.role);
116059
- return isAgentReadyForNativeDelivery(row, slot);
116060
- });
116100
+ var init_task_delivery_processor = __esm(() => {
116101
+ init_parse_session_augmentation();
116102
+ init_esm();
116103
+ init_native_task_delivery_coordinator();
116104
+ init_native_task_injector_logic();
116105
+ init_api3();
116106
+ init_convex_error();
116107
+ init_fetch_machine_assigned_task_snapshots();
116108
+ init_restart_orchestrator_in_flight();
116109
+ init_task_delivery_logic();
116110
+ });
116111
+
116112
+ // src/daemon/infrastructure/inbox/store/schema.ts
116113
+ var SCHEMA_VERSION = 1, MIGRATIONS;
116114
+ var init_schema = __esm(() => {
116115
+ MIGRATIONS = [
116116
+ `CREATE TABLE IF NOT EXISTS schema_meta (
116117
+ key TEXT PRIMARY KEY,
116118
+ value TEXT NOT NULL
116119
+ )`,
116120
+ `CREATE TABLE IF NOT EXISTS inbox_state (
116121
+ inbox_type TEXT NOT NULL,
116122
+ scope_key TEXT NOT NULL,
116123
+ state_json TEXT NOT NULL,
116124
+ created_at INTEGER NOT NULL,
116125
+ updated_at INTEGER NOT NULL,
116126
+ PRIMARY KEY (inbox_type, scope_key)
116127
+ )`,
116128
+ `CREATE INDEX IF NOT EXISTS idx_inbox_state_type_updated
116129
+ ON inbox_state(inbox_type, updated_at DESC)`,
116130
+ `CREATE INDEX IF NOT EXISTS idx_inbox_state_updated
116131
+ ON inbox_state(updated_at DESC)`
116132
+ ];
116133
+ });
116134
+
116135
+ // src/daemon/infrastructure/inbox/store/open-database.ts
116136
+ import { mkdirSync as mkdirSync8 } from "node:fs";
116137
+ import { dirname as dirname15 } from "node:path";
116138
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
116139
+ function openDatabase(dbPath) {
116140
+ mkdirSync8(dirname15(dbPath), { recursive: true });
116141
+ const db = new DatabaseSync3(dbPath);
116142
+ for (const sql of MIGRATIONS) {
116143
+ db.exec(sql);
116144
+ }
116145
+ db.prepare(`INSERT INTO schema_meta(key, value) VALUES('version', ?)
116146
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(String(SCHEMA_VERSION));
116147
+ return db;
116061
116148
  }
116062
- function runLocalStoreReconcilePass(params) {
116063
- const { stopped, monitorPassInFlight, agentMgr, runtime: runtime4, effectContext: effectContext2, sessionDeps, machineId } = params;
116064
- if (stopped || monitorPassInFlight)
116065
- return;
116066
- const deliverable = filterSnapshotsExcludingRestartInFlight(listDeliverablePendingFromStore(agentMgr));
116067
- if (deliverable.length === 0)
116149
+ var init_open_database = __esm(() => {
116150
+ init_schema();
116151
+ });
116152
+
116153
+ // src/daemon/infrastructure/inbox/store/state-store.ts
116154
+ function assertKeyPart(value, name) {
116155
+ if (value.trim().length === 0) {
116156
+ throw new Error(`${name} cannot be empty`);
116157
+ }
116158
+ }
116159
+ function encodeState(state) {
116160
+ const encoded = JSON.stringify(state);
116161
+ if (encoded === undefined) {
116162
+ throw new Error("Inbox state must be JSON serializable");
116163
+ }
116164
+ return encoded;
116165
+ }
116166
+ function decodeRow(row) {
116167
+ return {
116168
+ inboxType: row.inbox_type,
116169
+ scopeKey: row.scope_key,
116170
+ state: JSON.parse(row.state_json),
116171
+ createdAt: row.created_at,
116172
+ updatedAt: row.updated_at
116173
+ };
116174
+ }
116175
+ function buildQuery(options) {
116176
+ const clauses = [];
116177
+ const params = [];
116178
+ if (options.inboxType !== undefined) {
116179
+ clauses.push("inbox_type = ?");
116180
+ params.push(options.inboxType);
116181
+ }
116182
+ if (options.scopeKey !== undefined) {
116183
+ clauses.push("scope_key = ?");
116184
+ params.push(options.scopeKey);
116185
+ }
116186
+ if (options.scopePrefix !== undefined) {
116187
+ clauses.push("scope_key LIKE ?");
116188
+ params.push(`${options.scopePrefix}%`);
116189
+ }
116190
+ if (options.updatedAfter !== undefined) {
116191
+ clauses.push("updated_at > ?");
116192
+ params.push(options.updatedAfter);
116193
+ }
116194
+ const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
116195
+ const limit = Math.min(Math.max(options.limit ?? MAX_QUERY_LIMIT, 1), MAX_QUERY_LIMIT);
116196
+ return {
116197
+ sql: `SELECT inbox_type, scope_key, state_json, created_at, updated_at
116198
+ FROM inbox_state ${where}
116199
+ ORDER BY updated_at DESC, inbox_type ASC, scope_key ASC
116200
+ LIMIT ?`,
116201
+ params: [...params, limit]
116202
+ };
116203
+ }
116204
+ function getInboxState(db, key) {
116205
+ assertKeyPart(key.inboxType, "inboxType");
116206
+ assertKeyPart(key.scopeKey, "scopeKey");
116207
+ const row = db.prepare(`SELECT inbox_type, scope_key, state_json, created_at, updated_at
116208
+ FROM inbox_state
116209
+ WHERE inbox_type = ? AND scope_key = ?`).get(key.inboxType, key.scopeKey);
116210
+ return row ? decodeRow(row) : null;
116211
+ }
116212
+ function saveInboxState(db, key, state, updatedAt = Date.now()) {
116213
+ assertKeyPart(key.inboxType, "inboxType");
116214
+ assertKeyPart(key.scopeKey, "scopeKey");
116215
+ const stateJson = encodeState(state);
116216
+ db.prepare(`INSERT INTO inbox_state(inbox_type, scope_key, state_json, created_at, updated_at)
116217
+ VALUES(?, ?, ?, ?, ?)
116218
+ ON CONFLICT(inbox_type, scope_key) DO UPDATE SET
116219
+ state_json = excluded.state_json,
116220
+ updated_at = excluded.updated_at`).run(key.inboxType, key.scopeKey, stateJson, updatedAt, updatedAt);
116221
+ }
116222
+ function queryInboxState(db, options = {}) {
116223
+ const { sql, params } = buildQuery(options);
116224
+ return db.prepare(sql).all(...params).map((row) => decodeRow(row));
116225
+ }
116226
+ function deleteInboxState(db, key) {
116227
+ assertKeyPart(key.inboxType, "inboxType");
116228
+ assertKeyPart(key.scopeKey, "scopeKey");
116229
+ db.prepare("DELETE FROM inbox_state WHERE inbox_type = ? AND scope_key = ?").run(key.inboxType, key.scopeKey);
116230
+ }
116231
+ var MAX_QUERY_LIMIT = 1000;
116232
+
116233
+ // src/daemon/infrastructure/inbox/store/inbox-state-store.ts
116234
+ function createInboxStateStore(dbPath) {
116235
+ const db = openDatabase(dbPath);
116236
+ return {
116237
+ get: (key) => getInboxState(db, key),
116238
+ save: (key, state, updatedAt) => saveInboxState(db, key, state, updatedAt),
116239
+ query: (options) => queryInboxState(db, options),
116240
+ delete: (key) => deleteInboxState(db, key),
116241
+ close: () => db.close()
116242
+ };
116243
+ }
116244
+ var init_inbox_state_store = __esm(() => {
116245
+ init_open_database();
116246
+ });
116247
+
116248
+ // src/daemon/infrastructure/inbox/store/inbox-db-path.ts
116249
+ import { homedir as homedir10 } from "node:os";
116250
+ import { join as join26 } from "node:path";
116251
+ function resolveInboxDbPath(machineId) {
116252
+ return join26(homedir10(), ".chatroom", "daemon", machineId, "inboxes.sqlite");
116253
+ }
116254
+ var init_inbox_db_path = () => {};
116255
+
116256
+ // src/daemon/infrastructure/inbox/index.ts
116257
+ var init_inbox = __esm(() => {
116258
+ init_inbox_state_store();
116259
+ init_inbox_db_path();
116260
+ });
116261
+
116262
+ // src/daemon/infrastructure/inbox/task-inbox-delivery.ts
116263
+ async function handleTaskInboxUpdate(update6, deps) {
116264
+ if (update6.snapshots.length === 0)
116068
116265
  return;
116069
- const first = deliverable[0];
116070
- logNativeDeliveryFallback("periodic-reconcile", first.agentConfig.role, first.chatroomId, first.taskId);
116071
- getNativeTaskDeliveryCoordinator().reconcileAssignedTasks({
116072
- tasks: deliverable,
116073
- runtime: runtime4,
116074
- effectContext: effectContext2,
116075
- agentMgr,
116076
- sessionDeps,
116077
- machineId
116078
- });
116266
+ await processTasksUpdate(deps.runtime, deps.effectContext, deps.cooldown, deps.agentMgr, deps.sessionDeps, deps.machineId, "inbox-signal");
116267
+ }
116268
+ var init_task_inbox_delivery = __esm(() => {
116269
+ init_task_delivery_processor();
116270
+ });
116271
+
116272
+ // src/daemon/infrastructure/inbox/task.ts
116273
+ function taskSignalCursorAt(timestamp) {
116274
+ return `${String(Math.max(0, Math.floor(timestamp))).padStart(16, "0")}:`;
116275
+ }
116276
+ function abortError() {
116277
+ const error51 = new Error("Task inbox stopped");
116278
+ error51.name = "AbortError";
116279
+ return error51;
116280
+ }
116281
+ function throwIfAborted(signal) {
116282
+ if (signal?.aborted)
116283
+ throw abortError();
116079
116284
  }
116080
- function subscribeAssignedTaskSnapshotStore(wsClient2, args2, isStopped) {
116081
- return wsClient2.onUpdate(api.machines.listMachineAssignedTaskSnapshots, args2, (result) => {
116082
- if (isStopped())
116285
+ function waitForTaskSignalPage(options, afterSignalKey) {
116286
+ return new Promise((resolve8, reject) => {
116287
+ let unsubscribe;
116288
+ let settled = false;
116289
+ const cleanup = () => {
116290
+ unsubscribe?.();
116291
+ unsubscribe = undefined;
116292
+ options.signal?.removeEventListener("abort", onAbort);
116293
+ };
116294
+ const settle2 = (fn2) => {
116295
+ if (settled)
116296
+ return;
116297
+ settled = true;
116298
+ cleanup();
116299
+ fn2();
116300
+ };
116301
+ const onAbort = () => {
116302
+ settle2(() => reject(abortError()));
116303
+ };
116304
+ options.signal?.addEventListener("abort", onAbort, { once: true });
116305
+ try {
116306
+ throwIfAborted(options.signal);
116307
+ } catch (error51) {
116308
+ settle2(() => reject(error51));
116083
116309
  return;
116084
- const tasks = mapAssignedTaskSnapshotList(parseAssignedTaskMonitorRows(result?.tasks ?? []));
116085
- replaceAssignedTaskSnapshots(tasks);
116086
- }, (err) => {
116087
- console.warn(`[${formatTimestamp()}] ⚠️ Assigned-task snapshot subscription error: ${getErrorMessage(err)}`);
116310
+ }
116311
+ unsubscribe = options.client.onUpdate(api.messageList.subscribeTaskStatusSignalsSince, {
116312
+ sessionId: options.sessionId,
116313
+ machineId: options.machineId,
116314
+ afterKey: afterSignalKey,
116315
+ limit: options.signalPageLimit ?? DEFAULT_SIGNAL_PAGE_LIMIT
116316
+ }, (result) => {
116317
+ if (!result || typeof result !== "object")
116318
+ return;
116319
+ const page = result;
116320
+ const items = page.items;
116321
+ const highKey = page.highKey;
116322
+ if (!items?.length || !highKey)
116323
+ return;
116324
+ settle2(() => resolve8({
116325
+ items,
116326
+ afterSignalKey,
116327
+ highSignalKey: highKey
116328
+ }));
116329
+ }, (error51) => {
116330
+ settle2(() => reject(error51));
116331
+ });
116088
116332
  });
116089
116333
  }
116090
- function handleInboundAssignedTaskEvent(event, runMonitorPass) {
116091
- const row = listAssignedTaskSnapshots().find((snapshot) => snapshot.taskId === event.taskId && snapshot.agentConfig.role === event.role);
116092
- if (!row)
116334
+ async function* createTaskSignalIterator(options) {
116335
+ let afterSignalKey = options.initialAfterSignalKey ?? taskSignalCursorAt(options.serviceStartedAt ?? Date.now());
116336
+ while (!options.signal?.aborted) {
116337
+ const page = await waitForTaskSignalPage(options, afterSignalKey);
116338
+ yield page;
116339
+ afterSignalKey = page.highSignalKey;
116340
+ }
116341
+ }
116342
+ async function fetchSnapshotsForSignalPage(options, page) {
116343
+ const snapshots = [];
116344
+ let afterSignalKey = page.afterSignalKey;
116345
+ while (true) {
116346
+ throwIfAborted(options.signal);
116347
+ const result = await options.client.query(api.tasks.listTasksForMachineSignalRange, {
116348
+ sessionId: options.sessionId,
116349
+ machineId: options.machineId,
116350
+ afterSignalKey,
116351
+ throughSignalKey: page.highSignalKey,
116352
+ limit: options.taskPageLimit ?? DEFAULT_TASK_PAGE_LIMIT
116353
+ });
116354
+ snapshots.push(...result.snapshots);
116355
+ if (!result.hasMore || !result.nextSignalKey)
116356
+ break;
116357
+ afterSignalKey = result.nextSignalKey;
116358
+ }
116359
+ return snapshots;
116360
+ }
116361
+ async function runTaskInbox(options, onUpdate) {
116362
+ for await (const page of createTaskSignalIterator(options)) {
116363
+ const snapshots = await fetchSnapshotsForSignalPage(options, page);
116364
+ await onUpdate({
116365
+ signals: page.items,
116366
+ snapshots,
116367
+ afterSignalKey: page.afterSignalKey,
116368
+ throughSignalKey: page.highSignalKey
116369
+ });
116370
+ }
116371
+ }
116372
+ var DEFAULT_SIGNAL_PAGE_LIMIT = 100, DEFAULT_TASK_PAGE_LIMIT = 500;
116373
+ var init_task = __esm(() => {
116374
+ init_api3();
116375
+ });
116376
+
116377
+ // src/daemon/entry/task-inbox-runtime.ts
116378
+ async function bootstrapMachineAssignedTaskSnapshots(deps) {
116379
+ await deps.sessionDeps.backend.mutation(api.machines.syncMachineAssignedTaskSnapshotsMutation, {
116380
+ sessionId: deps.sessionDeps.sessionId,
116381
+ machineId: deps.machineId
116382
+ });
116383
+ const tasks = await fetchMachineAssignedTaskSnapshots(deps.sessionDeps, deps.machineId);
116384
+ if (!tasks.length)
116093
116385
  return;
116094
- const pass = event.type === "assigned-task.signal" ? "signal" : "presence";
116095
- runMonitorPass([row], pass);
116386
+ await processTasksUpdate(deps.runtime, deps.effectContext, deps.cooldown, deps.agentMgr, deps.sessionDeps, deps.machineId, "bootstrap", { snapshots: tasks });
116387
+ }
116388
+ function isAbortError(error51) {
116389
+ return error51 instanceof Error && error51.name === "AbortError";
116390
+ }
116391
+ async function runInboxLoopWithRestart(options, onUpdate, isStopped) {
116392
+ let backoffMs = INBOX_RESTART_INITIAL_MS;
116393
+ while (!isStopped()) {
116394
+ try {
116395
+ await runTaskInbox(options, onUpdate);
116396
+ return;
116397
+ } catch (error51) {
116398
+ if (isStopped() || isAbortError(error51))
116399
+ return;
116400
+ console.warn(`[TaskInbox] loop error, restarting in ${backoffMs}ms:`, error51);
116401
+ await new Promise((resolve8) => setTimeout(resolve8, backoffMs));
116402
+ backoffMs = Math.min(backoffMs * 2, INBOX_RESTART_MAX_MS);
116403
+ }
116404
+ }
116096
116405
  }
116097
- var startTaskMonitorEffect = (wsClient2) => exports_Effect.gen(function* () {
116406
+ var INBOX_RESTART_INITIAL_MS = 1000, INBOX_RESTART_MAX_MS = 30000, startTaskInboxEffect = (wsClient2) => exports_Effect.gen(function* () {
116098
116407
  const session2 = yield* DaemonSessionService;
116099
116408
  const agentMgr = yield* DaemonAgentProcessManagerService;
116100
116409
  const effectContext2 = yield* exports_Effect.context();
116101
116410
  const runtime4 = yield* exports_Effect.runtime();
116102
- console.log(`[${formatTimestamp()}] \uD83D\uDCCB Starting task-monitor (incremental subscribe)`);
116103
- const cooldown = new NudgeCooldown;
116104
- let stopped = false;
116105
- let monitorPassInFlight = false;
116106
116411
  const sessionDeps = {
116107
116412
  sessionId: session2.sessionId,
116108
116413
  convexUrl: session2.convexUrl,
@@ -116113,6 +116418,14 @@ var startTaskMonitorEffect = (wsClient2) => exports_Effect.gen(function* () {
116113
116418
  query: (fn2, args2) => session2.backend.query(fn2, args2)
116114
116419
  }
116115
116420
  };
116421
+ console.log(`[${formatTimestamp()}] \uD83D\uDCEC Starting task-inbox (machine-scoped signals)`);
116422
+ const inboxStore = createInboxStateStore(resolveInboxDbPath(session2.machineId));
116423
+ const persisted = inboxStore.get({
116424
+ inboxType: "task",
116425
+ scopeKey: session2.machineId
116426
+ });
116427
+ const abort = new AbortController;
116428
+ let stopped = false;
116116
116429
  registerNativeDeliverySession({
116117
116430
  runtime: runtime4,
116118
116431
  effectContext: effectContext2,
@@ -116120,61 +116433,64 @@ var startTaskMonitorEffect = (wsClient2) => exports_Effect.gen(function* () {
116120
116433
  sessionDeps,
116121
116434
  machineId: session2.machineId
116122
116435
  });
116123
- const unsubscribeSnapshotStore = subscribeAssignedTaskSnapshotStore(wsClient2, { sessionId: session2.sessionId, machineId: session2.machineId }, () => stopped);
116124
- const runMonitorPass = (tasks, pass) => {
116125
- if (stopped || monitorPassInFlight || tasks.length === 0)
116126
- return;
116127
- monitorPassInFlight = true;
116128
- processTasksUpdate(tasks, runtime4, effectContext2, cooldown, agentMgr, sessionDeps, session2.machineId, pass).finally(() => {
116129
- monitorPassInFlight = false;
116130
- });
116436
+ const cooldown = new RecoveryCooldown;
116437
+ const inboxOptions = {
116438
+ client: wsClient2,
116439
+ sessionId: session2.sessionId,
116440
+ machineId: session2.machineId,
116441
+ serviceStartedAt: Date.now(),
116442
+ initialAfterSignalKey: persisted?.state.afterSignalKey,
116443
+ signal: abort.signal
116131
116444
  };
116132
- registerAssignedTaskMonitorHandler(async (event) => {
116133
- handleInboundAssignedTaskEvent(event, runMonitorPass);
116134
- });
116135
- const reconcileTimer = setInterval(() => {
116136
- runLocalStoreReconcilePass({
116137
- stopped,
116138
- monitorPassInFlight,
116139
- agentMgr,
116445
+ const inboxHandler = async (update6) => {
116446
+ await handleTaskInboxUpdate(update6, {
116140
116447
  runtime: runtime4,
116141
116448
  effectContext: effectContext2,
116449
+ cooldown,
116450
+ agentMgr,
116142
116451
  sessionDeps,
116143
116452
  machineId: session2.machineId
116144
116453
  });
116454
+ inboxStore.save({ inboxType: "task", scopeKey: session2.machineId }, { afterSignalKey: update6.throughSignalKey });
116455
+ };
116456
+ const reconcileTimer = setInterval(() => {
116457
+ if (stopped)
116458
+ return;
116459
+ processTasksUpdate(runtime4, effectContext2, cooldown, agentMgr, sessionDeps, session2.machineId, "periodic-reconcile");
116145
116460
  }, NATIVE_DELIVERY_RECONCILE_MS);
116146
- yield* exports_Effect.tryPromise(() => session2.backend.mutation(api.machines.syncMachineAssignedTaskSnapshotsMutation, {
116147
- sessionId: session2.sessionId,
116461
+ yield* exports_Effect.tryPromise(() => bootstrapMachineAssignedTaskSnapshots({
116462
+ sessionDeps,
116463
+ runtime: runtime4,
116464
+ effectContext: effectContext2,
116465
+ cooldown,
116466
+ agentMgr,
116148
116467
  machineId: session2.machineId
116149
- })).pipe(exports_Effect.catchAll(() => exports_Effect.void));
116468
+ })).pipe(exports_Effect.catchAll((error51) => {
116469
+ console.warn("[TaskInbox] bootstrap failed:", error51);
116470
+ return exports_Effect.void;
116471
+ }));
116472
+ runInboxLoopWithRestart(inboxOptions, inboxHandler, () => stopped);
116150
116473
  return {
116151
116474
  stop() {
116152
116475
  stopped = true;
116153
- unregisterAssignedTaskMonitorHandler();
116154
- unsubscribeSnapshotStore();
116155
- clearAssignedTaskSnapshots();
116156
- unregisterNativeDeliverySession();
116476
+ abort.abort();
116157
116477
  clearInterval(reconcileTimer);
116158
- console.log(`[${formatTimestamp()}] \uD83D\uDCCB Task-monitor stopped`);
116478
+ unregisterNativeDeliverySession();
116479
+ inboxStore.close();
116159
116480
  }
116160
116481
  };
116161
116482
  });
116162
- var init_task_monitor_runtime = __esm(() => {
116483
+ var init_task_inbox_runtime = __esm(() => {
116163
116484
  init_reliability();
116164
- init_participant();
116165
- init_parse_session_augmentation();
116166
- init_assigned_task_monitor_contract();
116167
116485
  init_esm();
116168
116486
  init_daemon_services();
116169
- init_native_ready_invariant();
116170
- init_native_task_delivery_coordinator();
116171
- init_native_task_injector_logic();
116172
- init_restart_orchestrator_in_flight();
116173
- init_task_monitor_logic();
116174
116487
  init_api3();
116175
- init_assigned_task_snapshot_store();
116176
- init_convex_error();
116177
- init_execution_kind();
116488
+ init_task_delivery_processor();
116489
+ init_task_delivery_logic();
116490
+ init_fetch_machine_assigned_task_snapshots();
116491
+ init_inbox();
116492
+ init_task_inbox_delivery();
116493
+ init_task();
116178
116494
  });
116179
116495
 
116180
116496
  // src/daemon/entry/workspace-git/git-subscription.ts
@@ -116524,16 +116840,16 @@ var init_workspace_list_subscription = __esm(() => {
116524
116840
 
116525
116841
  // src/daemon/entry/workspace-git-inbound-registry.ts
116526
116842
  function registerWorkspaceGitInboundHandler(h) {
116527
- handler7 = h;
116843
+ handler6 = h;
116528
116844
  }
116529
116845
  function unregisterWorkspaceGitInboundHandler() {
116530
- handler7 = undefined;
116846
+ handler6 = undefined;
116531
116847
  }
116532
116848
  async function dispatchWorkspaceGitInboundEvent(event) {
116533
- if (handler7)
116534
- await handler7(event);
116849
+ if (handler6)
116850
+ await handler6(event);
116535
116851
  }
116536
- var handler7;
116852
+ var handler6;
116537
116853
 
116538
116854
  // src/events/lifecycle/on-daemon-shutdown.ts
116539
116855
  var onDaemonShutdownEffect;
@@ -116574,7 +116890,7 @@ function createDaemonRuntime(deps) {
116574
116890
  let directHarnessWorkerHandle = null;
116575
116891
  let agenticQueryWorkerHandle = null;
116576
116892
  let enhancerWorkerHandle = null;
116577
- let taskMonitorHandle = null;
116893
+ let taskInboxHandle = null;
116578
116894
  const activeSessions = new Map;
116579
116895
  const harnesses = new Map;
116580
116896
  let signalCount = 0;
@@ -116609,7 +116925,7 @@ function createDaemonRuntime(deps) {
116609
116925
  gitSubscriptionHandle?.stop();
116610
116926
  fileTreeSubscriptionHandle?.stop();
116611
116927
  workspaceListSubscriptionHandle?.stop();
116612
- taskMonitorHandle?.stop();
116928
+ taskInboxHandle?.stop();
116613
116929
  logObserverSubscriptionHandle?.stop();
116614
116930
  directHarnessWorkerHandle?.stop();
116615
116931
  agenticQueryWorkerHandle?.stop();
@@ -116715,7 +117031,7 @@ function createDaemonRuntime(deps) {
116715
117031
  break;
116716
117032
  }
116717
117033
  });
116718
- taskMonitorHandle = yield* startTaskMonitorEffect(deps.wsClient);
117034
+ taskInboxHandle = yield* startTaskInboxEffect(deps.wsClient);
116719
117035
  logObserverSubscriptionHandle = startLogObserverSubscription({ sessionId: session2.sessionId, machineId: session2.machineId }, deps.wsClient);
116720
117036
  const commandRunRuntime = yield* exports_Effect.runtime();
116721
117037
  if (featureFlags.directHarnessWorkers) {
@@ -116741,7 +117057,7 @@ Listening for commands...`);
116741
117057
  registerCommandInboundHandler(async (event) => {
116742
117058
  evictStaleDedupEntries(dedupTracker);
116743
117059
  if (event.type === "command.received") {
116744
- await handleInboundCommandEvent(event.commandId, dedupTracker, effectContext2, session2);
117060
+ await handleInboundCommandEvent(event.commandId, dedupTracker, effectContext2, session2, event.commandEvent);
116745
117061
  } else {
116746
117062
  await drainActionableCommandRuns(session2, commandRunRuntime);
116747
117063
  }
@@ -116775,7 +117091,7 @@ var init_daemon_runtime = __esm(() => {
116775
117091
  init_command_run_subscription();
116776
117092
  init_log_observer_sync();
116777
117093
  init_init_daemon();
116778
- init_task_monitor_runtime();
117094
+ init_task_inbox_runtime();
116779
117095
  init_git_heartbeat();
116780
117096
  init_git_subscription();
116781
117097
  init_api3();
@@ -116803,24 +117119,6 @@ var init_agentic_query_bridge = __esm(() => {
116803
117119
  init_process_agentic_query_prompt();
116804
117120
  });
116805
117121
 
116806
- // src/daemon/domain/usecase/deliver-assigned-task.ts
116807
- async function deliverAssignedTaskInbound(deps, event) {
116808
- await deps.dispatchInbound(event);
116809
- }
116810
-
116811
- // src/daemon/entry/bridge/assigned-task-bridge.ts
116812
- function createDeliverAssignedTaskDeps() {
116813
- return { dispatchInbound: dispatchAssignedTaskMonitorEvent };
116814
- }
116815
- function createAssignedTaskRouterDeps() {
116816
- return {
116817
- deliverInbound: async (event) => {
116818
- await deliverAssignedTaskInbound(createDeliverAssignedTaskDeps(), event);
116819
- }
116820
- };
116821
- }
116822
- var init_assigned_task_bridge = () => {};
116823
-
116824
117122
  // src/daemon/domain/usecase/handle-command-event.ts
116825
117123
  async function handleCommandEvent(deps, event) {
116826
117124
  await deps.dispatchInbound(event);
@@ -116938,7 +117236,6 @@ var init_workspace_git_bridge = () => {};
116938
117236
  // src/daemon/entry/default-router-deps.ts
116939
117237
  function createDefaultEventRouterDeps() {
116940
117238
  return {
116941
- assignedTask: createAssignedTaskRouterDeps(),
116942
117239
  directHarness: createDirectHarnessRouterDeps(),
116943
117240
  command: createCommandRouterDeps(),
116944
117241
  workspaceGit: createWorkspaceGitRouterDeps(),
@@ -116949,7 +117246,6 @@ function createDefaultEventRouterDeps() {
116949
117246
  }
116950
117247
  var init_default_router_deps = __esm(() => {
116951
117248
  init_agentic_query_bridge();
116952
- init_assigned_task_bridge();
116953
117249
  init_command_bridge();
116954
117250
  init_direct_harness_bridge();
116955
117251
  init_enhancer_bridge();
@@ -117330,10 +117626,10 @@ var init_deps = __esm(() => {
117330
117626
  });
117331
117627
 
117332
117628
  // src/daemon/entry/persistence-path.ts
117333
- import { homedir as homedir10 } from "node:os";
117334
- import { join as join26 } from "node:path";
117629
+ import { homedir as homedir11 } from "node:os";
117630
+ import { join as join27 } from "node:path";
117335
117631
  function resolvePersistenceDbPath(machineId) {
117336
- return join26(homedir10(), ".chatroom", "daemon", machineId, "events.sqlite");
117632
+ return join27(homedir11(), ".chatroom", "daemon", machineId, "events.sqlite");
117337
117633
  }
117338
117634
  var init_persistence_path = () => {};
117339
117635
 
@@ -117344,13 +117640,6 @@ async function handleAgenticQueryInbound(deps, event) {
117344
117640
  }
117345
117641
  }
117346
117642
 
117347
- // src/daemon/domain/usecase/handle-assigned-task-inbound.ts
117348
- async function handleAssignedTaskInbound(deps, event) {
117349
- if (deps.deliverInbound) {
117350
- await deps.deliverInbound(event);
117351
- }
117352
- }
117353
-
117354
117643
  // src/daemon/domain/usecase/handle-command-inbound.ts
117355
117644
  async function handleCommandInbound(deps, event) {
117356
117645
  if (deps.deliverInbound) {
@@ -117389,10 +117678,6 @@ async function handleWorkspaceGitInbound(deps, event) {
117389
117678
  // src/daemon/entry/event-router.ts
117390
117679
  async function routeInboundEvent(deps, event) {
117391
117680
  switch (event.type) {
117392
- case "assigned-task.signal":
117393
- case "assigned-task.presence":
117394
- await handleAssignedTaskInbound(deps.assignedTask, event);
117395
- break;
117396
117681
  case "direct-harness.session-opened":
117397
117682
  case "direct-harness.prompt":
117398
117683
  case "direct-harness.command":
@@ -117491,403 +117776,6 @@ var init_agentic_query_session = __esm(() => {
117491
117776
  init_api3();
117492
117777
  });
117493
117778
 
117494
- // src/infrastructure/incremental-sync/layers.ts
117495
- var IntervalClock, IntervalClockLive;
117496
- var init_layers = __esm(() => {
117497
- init_esm();
117498
- IntervalClock = class IntervalClock extends exports_Context.Tag("IntervalClock")() {
117499
- };
117500
- IntervalClockLive = exports_Layer.succeed(IntervalClock, {
117501
- sleep: (ms) => exports_Effect.promise(() => new Promise((resolve8) => setTimeout(resolve8, ms)))
117502
- });
117503
- });
117504
-
117505
- // src/infrastructure/incremental-sync/message-buffer.ts
117506
- class MessageBuffer {
117507
- keyOf;
117508
- queue = [];
117509
- inBuffer = new Set;
117510
- inFlight = new Map;
117511
- recentlyAcked = new Map;
117512
- dedupe;
117513
- dedupeTtlMs;
117514
- maxSize;
117515
- constructor(config4, keyOf) {
117516
- this.keyOf = keyOf;
117517
- this.dedupe = config4.dedupe ?? true;
117518
- this.dedupeTtlMs = config4.dedupeTtlMs ?? 0;
117519
- this.maxSize = config4.maxSize;
117520
- }
117521
- enqueue(items) {
117522
- this.pruneRecentlyAcked();
117523
- let enqueued = 0;
117524
- for (const item of items) {
117525
- const key = this.keyOf(item);
117526
- if (this.dedupe && this.shouldSkip(key)) {
117527
- continue;
117528
- }
117529
- this.queue.push({ key, item });
117530
- this.inBuffer.add(key);
117531
- enqueued++;
117532
- }
117533
- if (enqueued > 0) {
117534
- this.queue.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
117535
- }
117536
- this.enforceMaxSize();
117537
- return enqueued;
117538
- }
117539
- dequeue() {
117540
- this.pruneRecentlyAcked();
117541
- const next4 = this.queue.shift();
117542
- if (!next4)
117543
- return;
117544
- this.inBuffer.delete(next4.key);
117545
- this.inFlight.set(next4.key, next4.item);
117546
- return next4.item;
117547
- }
117548
- ack(key) {
117549
- this.inFlight.delete(key);
117550
- if (this.dedupe) {
117551
- this.recentlyAcked.set(key, Date.now());
117552
- }
117553
- }
117554
- nack(key, requeue = false) {
117555
- const item = this.inFlight.get(key);
117556
- this.inFlight.delete(key);
117557
- if (requeue && item !== undefined) {
117558
- this.enqueue([item]);
117559
- }
117560
- }
117561
- size() {
117562
- return this.queue.length;
117563
- }
117564
- highKeyOf(items) {
117565
- if (items.length === 0)
117566
- return null;
117567
- let high = null;
117568
- for (const item of items) {
117569
- const key = this.keyOf(item);
117570
- if (high === null || key > high) {
117571
- high = key;
117572
- }
117573
- }
117574
- return high;
117575
- }
117576
- shouldSkip(key) {
117577
- if (this.inBuffer.has(key) || this.inFlight.has(key)) {
117578
- return true;
117579
- }
117580
- if (this.dedupeTtlMs > 0) {
117581
- const ackedAt = this.recentlyAcked.get(key);
117582
- if (ackedAt !== undefined && Date.now() - ackedAt < this.dedupeTtlMs) {
117583
- return true;
117584
- }
117585
- } else if (this.recentlyAcked.has(key)) {
117586
- return true;
117587
- }
117588
- return false;
117589
- }
117590
- pruneRecentlyAcked() {
117591
- if (this.dedupeTtlMs <= 0)
117592
- return;
117593
- const now = Date.now();
117594
- for (const [key, ackedAt] of this.recentlyAcked) {
117595
- if (now - ackedAt >= this.dedupeTtlMs) {
117596
- this.recentlyAcked.delete(key);
117597
- }
117598
- }
117599
- }
117600
- enforceMaxSize() {
117601
- while (this.queue.length > this.maxSize) {
117602
- const dropped = this.queue.shift();
117603
- if (dropped) {
117604
- this.inBuffer.delete(dropped.key);
117605
- console.warn(`[incremental-sync] Buffer full — dropped oldest unacked item (key=${dropped.key})`);
117606
- }
117607
- }
117608
- }
117609
- }
117610
- // src/infrastructure/incremental-sync/resolve-high-key.ts
117611
- function resolveHighKey(def, buffer, page) {
117612
- if (page.highKey !== null)
117613
- return page.highKey;
117614
- const fromItems = buffer.highKeyOf(page.items);
117615
- if (fromItems !== null)
117616
- return fromItems;
117617
- if (def.itemToKey && page.items.length > 0) {
117618
- let high = null;
117619
- for (const item of page.items) {
117620
- const key = def.itemToKey(item);
117621
- if (high === null || key > high)
117622
- high = key;
117623
- }
117624
- return high;
117625
- }
117626
- return null;
117627
- }
117628
-
117629
- // src/infrastructure/incremental-sync/subscribe-loop.ts
117630
- function parseFeedItems(def, items, onError3) {
117631
- if (!def.parseItem) {
117632
- return items;
117633
- }
117634
- const parsed = [];
117635
- for (const raw of items) {
117636
- try {
117637
- parsed.push(def.parseItem(raw));
117638
- } catch (err) {
117639
- onError3?.(err);
117640
- }
117641
- }
117642
- return parsed;
117643
- }
117644
- function startSubscribeLoop(opts) {
117645
- let afterKey = opts.initialAfterKey ?? null;
117646
- let stopped = false;
117647
- let unsubscribe;
117648
- let drainInFlight = false;
117649
- const subscribe = () => {
117650
- if (stopped)
117651
- return;
117652
- unsubscribe?.();
117653
- unsubscribe = opts.wsClient.onUpdate(opts.target.query, opts.target.buildArgs(opts.args, afterKey, opts.config.limit), (result) => {
117654
- if (stopped)
117655
- return;
117656
- const page = opts.target.parsePage(result);
117657
- drainPages(page);
117658
- }, (err) => {
117659
- opts.onError?.(err);
117660
- });
117661
- };
117662
- const fetchPage = async (cursor) => {
117663
- const result = await opts.wsClient.query(opts.target.query, opts.target.buildArgs(opts.args, cursor, opts.config.limit));
117664
- return opts.target.parsePage(result);
117665
- };
117666
- const drainPages = async (initialPage) => {
117667
- if (stopped || drainInFlight)
117668
- return;
117669
- drainInFlight = true;
117670
- try {
117671
- const cursorAtStart = afterKey;
117672
- let page = initialPage;
117673
- while (!stopped && page.items.length > 0) {
117674
- const items = parseFeedItems(opts.def, page.items, opts.onError);
117675
- if (items.length > 0) {
117676
- opts.buffer.enqueue(items);
117677
- }
117678
- const nextKey = resolveHighKey(opts.def, opts.buffer, page);
117679
- if (nextKey === null) {
117680
- break;
117681
- }
117682
- afterKey = nextKey;
117683
- if (!page.hasMore) {
117684
- break;
117685
- }
117686
- page = await fetchPage(afterKey);
117687
- }
117688
- if (!stopped && afterKey !== cursorAtStart) {
117689
- subscribe();
117690
- }
117691
- } catch (err) {
117692
- opts.onError?.(err);
117693
- } finally {
117694
- drainInFlight = false;
117695
- }
117696
- };
117697
- subscribe();
117698
- return {
117699
- stop: () => {
117700
- stopped = true;
117701
- unsubscribe?.();
117702
- unsubscribe = undefined;
117703
- },
117704
- getAfterKey: () => afterKey
117705
- };
117706
- }
117707
- var init_subscribe_loop = () => {};
117708
-
117709
- // src/infrastructure/incremental-sync/feed-runtime.ts
117710
- function runWorkerLoop(feedName, buffer, keyOf, onItem) {
117711
- return exports_Effect.gen(function* () {
117712
- while (true) {
117713
- const item = buffer.dequeue();
117714
- if (item === undefined) {
117715
- yield* exports_Effect.sleep("10 millis");
117716
- continue;
117717
- }
117718
- const key = keyOf(item);
117719
- const ctx = {
117720
- item,
117721
- feedName,
117722
- ack: () => buffer.ack(key),
117723
- nack: (opts) => buffer.nack(key, opts?.requeue ?? false)
117724
- };
117725
- yield* onItem(ctx).pipe(exports_Effect.catchAll(() => exports_Effect.void));
117726
- }
117727
- });
117728
- }
117729
- var runIncrementalSubscribeLive = (opts) => exports_Effect.gen(function* () {
117730
- const buffer = new MessageBuffer(opts.buffer, opts.def.itemKey);
117731
- const subscribeHandle = startSubscribeLoop({
117732
- wsClient: opts.wsClient,
117733
- target: opts.target,
117734
- args: opts.args,
117735
- buffer,
117736
- def: opts.def,
117737
- config: opts.subscribe,
117738
- initialAfterKey: opts.initialAfterKey ?? null,
117739
- onError: opts.onError
117740
- });
117741
- const workerFiber = yield* exports_Effect.forkDaemon(runWorkerLoop(opts.def.name, buffer, opts.def.itemKey, opts.onItem));
117742
- return {
117743
- buffer,
117744
- stop: () => exports_Effect.gen(function* () {
117745
- subscribeHandle.stop();
117746
- yield* exports_Fiber.interrupt(workerFiber);
117747
- })
117748
- };
117749
- });
117750
- var init_feed_runtime = __esm(() => {
117751
- init_esm();
117752
- init_layers();
117753
- init_subscribe_loop();
117754
- });
117755
-
117756
- // src/infrastructure/incremental-sync/feeds/assigned-task-presence.ts
117757
- var assignedTaskPresenceFeedDef, assignedTaskPresenceSubscribeTarget, ASSIGNED_TASK_PRESENCE_FEED_LIMIT = 50, ASSIGNED_TASK_PRESENCE_FEED_BUFFER;
117758
- var init_assigned_task_presence = __esm(() => {
117759
- init_assigned_task_monitor_contract();
117760
- init_api3();
117761
- assignedTaskPresenceFeedDef = {
117762
- name: "assigned-task-presence",
117763
- itemKey: (item) => item.presenceKey,
117764
- parseItem: parseAssignedTaskPresenceSignal
117765
- };
117766
- assignedTaskPresenceSubscribeTarget = {
117767
- query: api.machines.subscribeAssignedTaskPresenceSince,
117768
- buildArgs: (args2, afterKey, limit) => ({
117769
- sessionId: args2.sessionId,
117770
- machineId: args2.machineId,
117771
- afterPresenceKey: afterKey ?? undefined,
117772
- limit
117773
- }),
117774
- parsePage: (result) => {
117775
- const page = result;
117776
- return {
117777
- items: page.items,
117778
- highKey: page.highPresenceKey,
117779
- hasMore: page.hasMore
117780
- };
117781
- }
117782
- };
117783
- ASSIGNED_TASK_PRESENCE_FEED_BUFFER = {
117784
- maxSize: 200,
117785
- dedupe: true
117786
- };
117787
- });
117788
-
117789
- // src/daemon/infrastructure/convex/subscribers/assigned-task-presence.ts
117790
- function startAssignedTaskPresenceSubscriber(deps, onEvent) {
117791
- let stopped = false;
117792
- const startPromise = exports_Effect.runPromise(runIncrementalSubscribeLive({
117793
- wsClient: deps.wsClient,
117794
- def: assignedTaskPresenceFeedDef,
117795
- target: assignedTaskPresenceSubscribeTarget,
117796
- args: { sessionId: deps.sessionId, machineId: deps.machineId },
117797
- buffer: ASSIGNED_TASK_PRESENCE_FEED_BUFFER,
117798
- subscribe: { limit: ASSIGNED_TASK_PRESENCE_FEED_LIMIT },
117799
- onItem: ({ item, ack }) => exports_Effect.sync(() => {
117800
- if (stopped)
117801
- return;
117802
- ack();
117803
- onEvent({ type: "assigned-task.presence", taskId: item.taskId, role: item.role });
117804
- }),
117805
- onError: (err) => {
117806
- console.warn(`[daemon] assigned-task-presence subscriber error: ${String(err)}`);
117807
- }
117808
- }));
117809
- let feedHandle;
117810
- startPromise.then((handle) => {
117811
- feedHandle = handle;
117812
- });
117813
- return {
117814
- async stop() {
117815
- stopped = true;
117816
- const handle = feedHandle ?? await startPromise;
117817
- await exports_Effect.runPromise(handle.stop());
117818
- }
117819
- };
117820
- }
117821
- var init_assigned_task_presence2 = __esm(() => {
117822
- init_esm();
117823
- init_feed_runtime();
117824
- init_assigned_task_presence();
117825
- });
117826
-
117827
- // src/infrastructure/incremental-sync/feeds/assigned-task-signals.ts
117828
- var assignedTaskSignalsFeedDef, assignedTaskSignalsSubscribeTarget, ASSIGNED_TASK_SIGNAL_FEED_LIMIT = 50, ASSIGNED_TASK_SIGNAL_FEED_BUFFER;
117829
- var init_assigned_task_signals = __esm(() => {
117830
- init_assigned_task_monitor_contract();
117831
- init_api3();
117832
- assignedTaskSignalsFeedDef = {
117833
- name: "assigned-task-signals",
117834
- itemKey: (item) => item.revisionKey,
117835
- parseItem: parseAssignedTaskSignal
117836
- };
117837
- assignedTaskSignalsSubscribeTarget = {
117838
- query: api.machines.subscribeAssignedTaskSignalsSince,
117839
- buildArgs: (args2, afterKey, limit) => ({
117840
- sessionId: args2.sessionId,
117841
- machineId: args2.machineId,
117842
- afterKey: afterKey ?? undefined,
117843
- limit
117844
- }),
117845
- parsePage: (result) => result
117846
- };
117847
- ASSIGNED_TASK_SIGNAL_FEED_BUFFER = {
117848
- maxSize: 200,
117849
- dedupe: true
117850
- };
117851
- });
117852
-
117853
- // src/daemon/infrastructure/convex/subscribers/assigned-task-signals.ts
117854
- function startAssignedTaskSignalsSubscriber(deps, onEvent) {
117855
- let stopped = false;
117856
- const startPromise = exports_Effect.runPromise(runIncrementalSubscribeLive({
117857
- wsClient: deps.wsClient,
117858
- def: assignedTaskSignalsFeedDef,
117859
- target: assignedTaskSignalsSubscribeTarget,
117860
- args: { sessionId: deps.sessionId, machineId: deps.machineId },
117861
- buffer: ASSIGNED_TASK_SIGNAL_FEED_BUFFER,
117862
- subscribe: { limit: ASSIGNED_TASK_SIGNAL_FEED_LIMIT },
117863
- onItem: ({ item, ack }) => exports_Effect.sync(() => {
117864
- if (stopped)
117865
- return;
117866
- ack();
117867
- onEvent({ type: "assigned-task.signal", taskId: item.taskId, role: item.role });
117868
- }),
117869
- onError: (err) => {
117870
- console.warn(`[daemon] assigned-task-signals subscriber error: ${String(err)}`);
117871
- }
117872
- }));
117873
- let feedHandle;
117874
- startPromise.then((handle) => {
117875
- feedHandle = handle;
117876
- });
117877
- return {
117878
- async stop() {
117879
- stopped = true;
117880
- const handle = feedHandle ?? await startPromise;
117881
- await exports_Effect.runPromise(handle.stop());
117882
- }
117883
- };
117884
- }
117885
- var init_assigned_task_signals2 = __esm(() => {
117886
- init_esm();
117887
- init_feed_runtime();
117888
- init_assigned_task_signals();
117889
- });
117890
-
117891
117779
  // src/daemon/infrastructure/convex/subscribers/command-events.ts
117892
117780
  function startCommandEventsSubscriber(deps, onEvent) {
117893
117781
  const seen = new Set;
@@ -117898,7 +117786,11 @@ function startCommandEventsSubscriber(deps, onEvent) {
117898
117786
  if (seen.has(event._id))
117899
117787
  continue;
117900
117788
  seen.add(event._id);
117901
- onEvent({ type: "command.received", commandId: event._id });
117789
+ onEvent({
117790
+ type: "command.received",
117791
+ commandId: event._id,
117792
+ commandEvent: event
117793
+ });
117902
117794
  }
117903
117795
  }, (err) => {
117904
117796
  console.warn(`[daemon] command-events subscriber error: ${err instanceof Error ? err.message : String(err)}`);
@@ -118295,8 +118187,6 @@ function startAllSubscribers(deps) {
118295
118187
  const onEvent = (event) => {
118296
118188
  routeInboundEvent(deps.router, event);
118297
118189
  };
118298
- const signals = startAssignedTaskSignalsSubscriber(deps, onEvent);
118299
- const presence = startAssignedTaskPresenceSubscriber(deps, onEvent);
118300
118190
  const session2 = startDirectHarnessSessionSubscriber(deps, onEvent);
118301
118191
  const prompt = startDirectHarnessPromptSubscriber(deps, onEvent);
118302
118192
  const directHarnessCommand = startDirectHarnessCommandSubscriber(deps, onEvent);
@@ -118314,8 +118204,6 @@ function startAllSubscribers(deps) {
118314
118204
  return {
118315
118205
  async stopAll() {
118316
118206
  await Promise.all([
118317
- signals.stop(),
118318
- presence.stop(),
118319
118207
  session2.stop(),
118320
118208
  prompt.stop(),
118321
118209
  directHarnessCommand.stop(),
@@ -118338,8 +118226,6 @@ var init_subscriber_registry = __esm(() => {
118338
118226
  init_event_router();
118339
118227
  init_agentic_query_prompt();
118340
118228
  init_agentic_query_session();
118341
- init_assigned_task_presence2();
118342
- init_assigned_task_signals2();
118343
118229
  init_command_events();
118344
118230
  init_command_run();
118345
118231
  init_direct_harness_command();
@@ -118369,19 +118255,19 @@ function resolveEnvSlug(convexUrl) {
118369
118255
  }
118370
118256
 
118371
118257
  // src/infrastructure/log-server/resolve-logs-db-path.ts
118372
- import { homedir as homedir11 } from "node:os";
118373
- import { join as join27 } from "node:path";
118258
+ import { homedir as homedir12 } from "node:os";
118259
+ import { join as join28 } from "node:path";
118374
118260
  function resolveLogsDbPath(convexUrl) {
118375
- return join27(homedir11(), ".chatroom", resolveEnvSlug(convexUrl ?? getConvexUrl()), "logs.sqlite");
118261
+ return join28(homedir12(), ".chatroom", resolveEnvSlug(convexUrl ?? getConvexUrl()), "logs.sqlite");
118376
118262
  }
118377
118263
  var init_resolve_logs_db_path = __esm(() => {
118378
118264
  init_client2();
118379
118265
  });
118380
118266
 
118381
118267
  // src/infrastructure/log-server/log-schema.ts
118382
- var SCHEMA_VERSION = 2, MIGRATIONS;
118268
+ var SCHEMA_VERSION2 = 2, MIGRATIONS2;
118383
118269
  var init_log_schema = __esm(() => {
118384
- MIGRATIONS = [
118270
+ MIGRATIONS2 = [
118385
118271
  `CREATE TABLE IF NOT EXISTS schema_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
118386
118272
  `CREATE TABLE IF NOT EXISTS log_entries (
118387
118273
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -118405,18 +118291,18 @@ var init_log_schema = __esm(() => {
118405
118291
  });
118406
118292
 
118407
118293
  // src/infrastructure/log-server/open-log-database.ts
118408
- import { mkdirSync as mkdirSync8 } from "node:fs";
118409
- import { dirname as dirname15 } from "node:path";
118410
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
118294
+ import { mkdirSync as mkdirSync9 } from "node:fs";
118295
+ import { dirname as dirname16 } from "node:path";
118296
+ import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
118411
118297
  function openLogDatabase(dbPath) {
118412
- mkdirSync8(dirname15(dbPath), { recursive: true });
118413
- const db = new DatabaseSync3(dbPath);
118298
+ mkdirSync9(dirname16(dbPath), { recursive: true });
118299
+ const db = new DatabaseSync4(dbPath);
118414
118300
  db.exec("PRAGMA journal_mode = WAL");
118415
118301
  db.exec("PRAGMA busy_timeout = 5000");
118416
118302
  db.exec("PRAGMA synchronous = NORMAL");
118417
- for (const migration of MIGRATIONS)
118303
+ for (const migration of MIGRATIONS2)
118418
118304
  db.exec(migration);
118419
- db.prepare(`INSERT INTO schema_meta(key,value) VALUES('version',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value`).run(String(SCHEMA_VERSION));
118305
+ db.prepare(`INSERT INTO schema_meta(key,value) VALUES('version',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value`).run(String(SCHEMA_VERSION2));
118420
118306
  return db;
118421
118307
  }
118422
118308
  var init_open_log_database = __esm(() => {
@@ -118465,8 +118351,8 @@ function queryEventStream(db, input) {
118465
118351
  ...input.toTimestamp !== undefined ? [input.toTimestamp] : [],
118466
118352
  clamp4(input.limit)
118467
118353
  ];
118468
- const rows2 = db.prepare(`SELECT * FROM event_stream_entries WHERE 1=1 ${filters} ORDER BY id DESC LIMIT ?`).all(...values3);
118469
- return rows2.reverse().map((row) => ({
118354
+ const rows = db.prepare(`SELECT * FROM event_stream_entries WHERE 1=1 ${filters} ORDER BY id DESC LIMIT ?`).all(...values3);
118355
+ return rows.reverse().map((row) => ({
118470
118356
  id: Number(row.id),
118471
118357
  timestamp: Number(row.timestamp),
118472
118358
  type: row.type,
@@ -118492,8 +118378,8 @@ function queryAfterId(db, afterId = 0, limit = 100, source, chatroomId, role, ha
118492
118378
  ...toTimestamp !== undefined ? [toTimestamp] : [],
118493
118379
  clamp4(limit)
118494
118380
  ];
118495
- const rows2 = db.prepare(`SELECT * FROM log_entries WHERE id > ? ${filters} ORDER BY id ASC LIMIT ?`).all(...values3);
118496
- return rows2.map(map19);
118381
+ const rows = db.prepare(`SELECT * FROM log_entries WHERE id > ? ${filters} ORDER BY id ASC LIMIT ?`).all(...values3);
118382
+ return rows.map(map19);
118497
118383
  }
118498
118384
  function queryHistory(db, beforeId, limit = 100, source, chatroomId, role, harness, fromTimestamp, toTimestamp) {
118499
118385
  const filters = [
@@ -118515,8 +118401,8 @@ function queryHistory(db, beforeId, limit = 100, source, chatroomId, role, harne
118515
118401
  ...toTimestamp !== undefined ? [toTimestamp] : [],
118516
118402
  clamp4(limit)
118517
118403
  ];
118518
- const rows2 = db.prepare(`SELECT * FROM log_entries WHERE 1=1 ${filters} ORDER BY id DESC LIMIT ?`).all(...values3);
118519
- return rows2.map(map19).reverse();
118404
+ const rows = db.prepare(`SELECT * FROM log_entries WHERE 1=1 ${filters} ORDER BY id DESC LIMIT ?`).all(...values3);
118405
+ return rows.map(map19).reverse();
118520
118406
  }
118521
118407
  function listLogDimensions(db, chatroomId, limit = 100) {
118522
118408
  const clamped = clamp4(limit);
@@ -118605,9 +118491,9 @@ function appendOutboundEvent(db, event) {
118605
118491
  }
118606
118492
 
118607
118493
  // src/daemon/infrastructure/persistence/schema.ts
118608
- var SCHEMA_VERSION2 = 1, MIGRATIONS2;
118609
- var init_schema = __esm(() => {
118610
- MIGRATIONS2 = [
118494
+ var SCHEMA_VERSION3 = 1, MIGRATIONS3;
118495
+ var init_schema2 = __esm(() => {
118496
+ MIGRATIONS3 = [
118611
118497
  `CREATE TABLE IF NOT EXISTS schema_meta (
118612
118498
  key TEXT PRIMARY KEY,
118613
118499
  value TEXT NOT NULL
@@ -118636,21 +118522,21 @@ var init_schema = __esm(() => {
118636
118522
  });
118637
118523
 
118638
118524
  // src/daemon/infrastructure/persistence/open-database.ts
118639
- import { mkdirSync as mkdirSync9 } from "node:fs";
118640
- import { dirname as dirname16 } from "node:path";
118641
- import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
118642
- function openDatabase(dbPath) {
118643
- mkdirSync9(dirname16(dbPath), { recursive: true });
118644
- const db = new DatabaseSync4(dbPath);
118645
- for (const sql of MIGRATIONS2) {
118525
+ import { mkdirSync as mkdirSync10 } from "node:fs";
118526
+ import { dirname as dirname17 } from "node:path";
118527
+ import { DatabaseSync as DatabaseSync5 } from "node:sqlite";
118528
+ function openDatabase2(dbPath) {
118529
+ mkdirSync10(dirname17(dbPath), { recursive: true });
118530
+ const db = new DatabaseSync5(dbPath);
118531
+ for (const sql of MIGRATIONS3) {
118646
118532
  db.exec(sql);
118647
118533
  }
118648
118534
  db.prepare(`INSERT INTO schema_meta(key, value) VALUES('version', ?)
118649
- ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(String(SCHEMA_VERSION2));
118535
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(String(SCHEMA_VERSION3));
118650
118536
  return db;
118651
118537
  }
118652
- var init_open_database = __esm(() => {
118653
- init_schema();
118538
+ var init_open_database2 = __esm(() => {
118539
+ init_schema2();
118654
118540
  });
118655
118541
 
118656
118542
  // src/daemon/infrastructure/persistence/outbox.ts
@@ -118668,10 +118554,10 @@ function listPendingOutbox(db, limit = 100) {
118668
118554
  // src/daemon/infrastructure/persistence/read-model.ts
118669
118555
  function listHarnessStreamLines(db, opts = {}) {
118670
118556
  const limit = opts.limit ?? 500;
118671
- const rows2 = db.prepare(`SELECT payload_json FROM outbound_events
118557
+ const rows = db.prepare(`SELECT payload_json FROM outbound_events
118672
118558
  WHERE event_type = 'harness.stream'
118673
118559
  ORDER BY id DESC LIMIT ?`).all(limit);
118674
- const parsed = rows2.map((row) => JSON.parse(row.payload_json)).filter((event) => event.type === "harness.stream");
118560
+ const parsed = rows.map((row) => JSON.parse(row.payload_json)).filter((event) => event.type === "harness.stream");
118675
118561
  if (!opts.harness)
118676
118562
  return parsed.reverse();
118677
118563
  return parsed.filter((e) => e.harness === opts.harness).reverse();
@@ -118679,7 +118565,7 @@ function listHarnessStreamLines(db, opts = {}) {
118679
118565
 
118680
118566
  // src/daemon/infrastructure/persistence/persistence-store.ts
118681
118567
  function createPersistenceStore(dbPath) {
118682
- const db = openDatabase(dbPath);
118568
+ const db = openDatabase2(dbPath);
118683
118569
  return {
118684
118570
  append(event) {
118685
118571
  const eventId = appendOutboundEvent(db, event);
@@ -118693,7 +118579,7 @@ function createPersistenceStore(dbPath) {
118693
118579
  };
118694
118580
  }
118695
118581
  var init_persistence_store = __esm(() => {
118696
- init_open_database();
118582
+ init_open_database2();
118697
118583
  });
118698
118584
 
118699
118585
  // src/daemon/infrastructure/persistence/index.ts
@@ -121426,9 +121312,9 @@ var require_event_target2 = __commonJS((exports, module) => {
121426
121312
  }
121427
121313
  Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
121428
121314
  var EventTarget = {
121429
- addEventListener(type, handler8, options = {}) {
121315
+ addEventListener(type, handler7, options = {}) {
121430
121316
  for (const listener of this.listeners(type)) {
121431
- if (!options[kForOnEventAttribute] && listener[kListener] === handler8 && !listener[kForOnEventAttribute]) {
121317
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler7 && !listener[kForOnEventAttribute]) {
121432
121318
  return;
121433
121319
  }
121434
121320
  }
@@ -121439,7 +121325,7 @@ var require_event_target2 = __commonJS((exports, module) => {
121439
121325
  data: isBinary ? data : data.toString()
121440
121326
  });
121441
121327
  event[kTarget] = this;
121442
- callListener(handler8, this, event);
121328
+ callListener(handler7, this, event);
121443
121329
  };
121444
121330
  } else if (type === "close") {
121445
121331
  wrapper = function onClose(code2, message) {
@@ -121449,7 +121335,7 @@ var require_event_target2 = __commonJS((exports, module) => {
121449
121335
  wasClean: this._closeFrameReceived && this._closeFrameSent
121450
121336
  });
121451
121337
  event[kTarget] = this;
121452
- callListener(handler8, this, event);
121338
+ callListener(handler7, this, event);
121453
121339
  };
121454
121340
  } else if (type === "error") {
121455
121341
  wrapper = function onError3(error51) {
@@ -121458,28 +121344,28 @@ var require_event_target2 = __commonJS((exports, module) => {
121458
121344
  message: error51.message
121459
121345
  });
121460
121346
  event[kTarget] = this;
121461
- callListener(handler8, this, event);
121347
+ callListener(handler7, this, event);
121462
121348
  };
121463
121349
  } else if (type === "open") {
121464
121350
  wrapper = function onOpen() {
121465
121351
  const event = new Event2("open");
121466
121352
  event[kTarget] = this;
121467
- callListener(handler8, this, event);
121353
+ callListener(handler7, this, event);
121468
121354
  };
121469
121355
  } else {
121470
121356
  return;
121471
121357
  }
121472
121358
  wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
121473
- wrapper[kListener] = handler8;
121359
+ wrapper[kListener] = handler7;
121474
121360
  if (options.once) {
121475
121361
  this.once(type, wrapper);
121476
121362
  } else {
121477
121363
  this.on(type, wrapper);
121478
121364
  }
121479
121365
  },
121480
- removeEventListener(type, handler8) {
121366
+ removeEventListener(type, handler7) {
121481
121367
  for (const listener of this.listeners(type)) {
121482
- if (listener[kListener] === handler8 && !listener[kForOnEventAttribute]) {
121368
+ if (listener[kListener] === handler7 && !listener[kForOnEventAttribute]) {
121483
121369
  this.removeListener(type, listener);
121484
121370
  break;
121485
121371
  }
@@ -122008,16 +121894,16 @@ var require_websocket2 = __commonJS((exports, module) => {
122008
121894
  }
122009
121895
  return null;
122010
121896
  },
122011
- set(handler8) {
121897
+ set(handler7) {
122012
121898
  for (const listener of this.listeners(method)) {
122013
121899
  if (listener[kForOnEventAttribute]) {
122014
121900
  this.removeListener(method, listener);
122015
121901
  break;
122016
121902
  }
122017
121903
  }
122018
- if (typeof handler8 !== "function")
121904
+ if (typeof handler7 !== "function")
122019
121905
  return;
122020
- this.addEventListener(method, handler8, {
121906
+ this.addEventListener(method, handler7, {
122021
121907
  [kForOnEventAttribute]: true
122022
121908
  });
122023
121909
  }
@@ -132351,19 +132237,19 @@ function routeRequest(req, res, deps) {
132351
132237
 
132352
132238
  // src/daemon/local-web/server/serve-static.ts
132353
132239
  import { existsSync as existsSync10, readFileSync as readFileSync11 } from "node:fs";
132354
- import { dirname as dirname17, join as join28 } from "node:path";
132240
+ import { dirname as dirname18, join as join29 } from "node:path";
132355
132241
  import { fileURLToPath as fileURLToPath7 } from "node:url";
132356
132242
  function clientDistCandidates(here) {
132357
132243
  return [
132358
- join28(here, "client/build"),
132359
- join28(here, "../client/build"),
132360
- join28(here, "../src/daemon/local-web/client/build")
132244
+ join29(here, "client/build"),
132245
+ join29(here, "../client/build"),
132246
+ join29(here, "../src/daemon/local-web/client/build")
132361
132247
  ];
132362
132248
  }
132363
- function resolveClientDistDir(here = dirname17(fileURLToPath7(import.meta.url))) {
132249
+ function resolveClientDistDir(here = dirname18(fileURLToPath7(import.meta.url))) {
132364
132250
  const candidates = clientDistCandidates(here);
132365
132251
  for (const dir of candidates) {
132366
- if (existsSync10(join28(dir, "index.html")))
132252
+ if (existsSync10(join29(dir, "index.html")))
132367
132253
  return dir;
132368
132254
  }
132369
132255
  return candidates[0];
@@ -132376,7 +132262,7 @@ function tryServeStatic(req, res, distDir) {
132376
132262
  return false;
132377
132263
  }
132378
132264
  const safePath = pathname === "/" ? "/index.html" : pathname;
132379
- const filePath = join28(distDir, safePath);
132265
+ const filePath = join29(distDir, safePath);
132380
132266
  if (!filePath.startsWith(distDir)) {
132381
132267
  res.writeHead(403);
132382
132268
  res.end();
@@ -132393,7 +132279,7 @@ function tryServeStatic(req, res, distDir) {
132393
132279
  }
132394
132280
  return true;
132395
132281
  }
132396
- const indexPath = join28(distDir, "index.html");
132282
+ const indexPath = join29(distDir, "index.html");
132397
132283
  if (existsSync10(indexPath)) {
132398
132284
  res.writeHead(200, { "Content-Type": "text/html" });
132399
132285
  if (req.method === "HEAD") {
@@ -132975,7 +132861,7 @@ async function harnessStatus() {
132975
132861
  };
132976
132862
  const program2 = exports_Effect.forEach(services, detectOne, { concurrency: "unbounded" });
132977
132863
  const results = await exports_Effect.runPromise(program2);
132978
- const rows2 = results.map(({ id: id3, displayName, result }) => {
132864
+ const rows = results.map(({ id: id3, displayName, result }) => {
132979
132865
  if (isInstalled(result)) {
132980
132866
  return { id: id3, displayName, status: "installed" };
132981
132867
  }
@@ -132987,13 +132873,13 @@ async function harnessStatus() {
132987
132873
  }
132988
132874
  return { id: id3, displayName, status: "not-installed" };
132989
132875
  });
132990
- const idWidth = Math.max(4, ...rows2.map((r) => r.id.length));
132991
- const nameWidth = Math.max(11, ...rows2.map((r) => r.displayName.length));
132876
+ const idWidth = Math.max(4, ...rows.map((r) => r.id.length));
132877
+ const nameWidth = Math.max(11, ...rows.map((r) => r.displayName.length));
132992
132878
  const header = `${"ID".padEnd(idWidth)} ${"DISPLAY NAME".padEnd(nameWidth)} STATUS`;
132993
132879
  const divider = `${"-".repeat(idWidth)} ${"-".repeat(nameWidth)} ------`;
132994
132880
  console.log(header);
132995
132881
  console.log(divider);
132996
- for (const row of rows2) {
132882
+ for (const row of rows) {
132997
132883
  const statusIcon = row.status === "installed" ? "✅ installed" : row.status === "error" ? "⚠️ error" : "❌ not installed";
132998
132884
  const line = `${row.id.padEnd(idWidth)} ${row.displayName.padEnd(nameWidth)} ${statusIcon}`;
132999
132885
  console.log(line);
@@ -133002,8 +132888,8 @@ async function harnessStatus() {
133002
132888
  }
133003
132889
  }
133004
132890
  console.log("");
133005
- const installedCount = rows2.filter((r) => r.status === "installed").length;
133006
- const totalCount = rows2.length;
132891
+ const installedCount = rows.filter((r) => r.status === "installed").length;
132892
+ const totalCount = rows.length;
133007
132893
  console.log(`${installedCount}/${totalCount} harnesses available on this machine.`);
133008
132894
  }
133009
132895
  var init_harness_status = __esm(() => {
@@ -134124,4 +134010,4 @@ program2.hook("preAction", async (_thisCommand, actionCommand) => {
134124
134010
  });
134125
134011
  program2.parse();
134126
134012
 
134127
- //# debugId=6381A1F83F16A2C964756E2164756E21
134013
+ //# debugId=654C294BE572C9D764756E2164756E21