chatroom-cli 1.113.0 → 1.115.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -30221,17 +30221,7 @@ class AgentProcessManager {
30221
30221
  }
30222
30222
  this.maybeEmitProviderUnavailable(opts.chatroomId, opts.role, slot);
30223
30223
  if (slot.harness && getHarnessCapabilities(slot.harness).supportsNativeIntegration) {
30224
- for (const handler of this.agentSessionLostHandlers) {
30225
- try {
30226
- handler({
30227
- chatroomId: opts.chatroomId,
30228
- role: opts.role,
30229
- harnessSessionId: ctx.harnessSessionId
30230
- });
30231
- } catch (error) {
30232
- console.warn(`[AgentProcessManager] native session-loss cleanup failed for ${opts.role}@${opts.chatroomId}: ${error instanceof Error ? error.message : String(error)}`);
30233
- }
30234
- }
30224
+ this.notifyAgentSessionLost(opts.chatroomId, opts.role, ctx.harnessSessionId);
30235
30225
  }
30236
30226
  const lifecyclePromise = this.lifecycle.runPromise(exports_Effect.gen(function* () {
30237
30227
  const svc = yield* AgentLifecycleService;
@@ -30522,12 +30512,22 @@ class AgentProcessManager {
30522
30512
  async syncSlotsAfterScopedStop(result) {
30523
30513
  for (const { target } of result.targets) {
30524
30514
  const slot = this.slots.get(agentKey2(target.chatroomId, target.role));
30515
+ this.notifyAgentSessionLost(target.chatroomId, target.role, slot?.pid === target.pid ? slot.harnessSessionId : undefined);
30525
30516
  if (!slot || slot.pid !== target.pid)
30526
30517
  continue;
30527
30518
  this.resetSlotAfterStop(slot);
30528
30519
  await this.clearAgentPidQuietly(target.chatroomId, target.role);
30529
30520
  }
30530
30521
  }
30522
+ notifyAgentSessionLost(chatroomId, role, harnessSessionId) {
30523
+ for (const handler of this.agentSessionLostHandlers) {
30524
+ try {
30525
+ handler({ chatroomId, role, ...harnessSessionId ? { harnessSessionId } : {} });
30526
+ } catch (error) {
30527
+ console.warn(`[AgentProcessManager] native session-loss cleanup failed for ${role}@${chatroomId}: ${error instanceof Error ? error.message : String(error)}`);
30528
+ }
30529
+ }
30530
+ }
30531
30531
  queueExitRetry(item) {
30532
30532
  this.exitRetryQueue.push(item);
30533
30533
  if (this.exitRetryTimer === null) {
@@ -31407,17 +31407,6 @@ function isTurnPhaseIdle(phase) {
31407
31407
  }
31408
31408
  var init_check_agent_slot = () => {};
31409
31409
 
31410
- // src/daemon/services/task-service/domain/entities/operational-agent.ts
31411
- function isOperationalDesiredRunning(row) {
31412
- return row?.operationalState === "running" || row?.operationalState === "starting";
31413
- }
31414
- function isOperationalCircuitOpen(row) {
31415
- return row?.operationalState === "circuit_open";
31416
- }
31417
- function isOperationalStopIntentActive(row) {
31418
- return row?.stopState === "stopped" || row?.stopState === "stopping" || row?.stopState === "pending";
31419
- }
31420
-
31421
31410
  // src/daemon/services/task-service/domain/usecase/native-cold-session-delivery.ts
31422
31411
  function snapshotRequestsNativeColdSession(task) {
31423
31412
  return task.requestsNativeColdSession === true;
@@ -31430,18 +31419,12 @@ function isColdStartEligibleSlotState(slot) {
31430
31419
  function isNativeColdSessionDeliveryOwnedSpawn(task, slot) {
31431
31420
  return snapshotRequestsNativeColdSession(task) && isColdStartEligibleSlotState(slot);
31432
31421
  }
31433
- function explainColdSessionDeliveryBlock(task, slot, operational) {
31422
+ function explainColdSessionDeliveryBlock(task, slot) {
31434
31423
  if (!snapshotRequestsNativeColdSession(task))
31435
31424
  return null;
31436
31425
  if (isChatroomStopScopeActive(task.chatroomId)) {
31437
31426
  return "chatroom_stop_scope_active";
31438
31427
  }
31439
- if (isOperationalStopIntentActive(operational)) {
31440
- return "operational_stop_intent_active";
31441
- }
31442
- if (isOperationalCircuitOpen(operational)) {
31443
- return "operational_circuit_open";
31444
- }
31445
31428
  if (slot && isSlotSpawning(slot.state)) {
31446
31429
  return `slot_spawning (slotState=${slot.state})`;
31447
31430
  }
@@ -31462,25 +31445,21 @@ function isDeliverableTaskStatus(status3) {
31462
31445
  var init_assigned_task = () => {};
31463
31446
 
31464
31447
  // src/daemon/services/task-service/domain/usecase/native-ready-invariant.ts
31465
- function isAgentReadyForNativeDelivery(task, slot, operational) {
31466
- return explainAgentReadyForNativeDeliveryBlock(task, slot, operational) === null;
31448
+ function isAgentReadyForNativeDelivery(task, slot) {
31449
+ return explainAgentReadyForNativeDeliveryBlock(task, slot) === null;
31467
31450
  }
31468
- function explainAgentReadyForNativeDeliveryBlock(task, slot, explicitOperational) {
31451
+ function explainAgentReadyForNativeDeliveryBlock(task, slot) {
31469
31452
  const { agentConfig } = task;
31470
31453
  if (!isNativeHarness(agentConfig.agentHarness)) {
31471
31454
  return `not_native_harness (harness=${agentConfig.agentHarness})`;
31472
31455
  }
31473
- const operational = explicitOperational;
31474
- const coldBlock = explainColdSessionDeliveryBlock(task, slot, operational);
31456
+ const coldBlock = explainColdSessionDeliveryBlock(task, slot);
31475
31457
  if (coldBlock) {
31476
31458
  return coldBlock;
31477
31459
  }
31478
31460
  if (isNativeColdSessionDeliveryOwnedSpawn(task, slot)) {
31479
31461
  return null;
31480
31462
  }
31481
- if (!isOperationalDesiredRunning(operational)) {
31482
- return `operational_state_not_running (state=${operational?.operationalState ?? "missing"})`;
31483
- }
31484
31463
  if (!slot) {
31485
31464
  return agentConfig.spawnedAgentPid == null ? "spawned_pid_missing" : `slot_missing (expectedPid=${agentConfig.spawnedAgentPid})`;
31486
31465
  }
@@ -31533,7 +31512,7 @@ function explainNativeDeliveryBlock(task, opts) {
31533
31512
  return `acknowledged_wrong_role (assignedTo=${assignedTo ?? "none"}, role=${role})`;
31534
31513
  }
31535
31514
  }
31536
- return explainAgentReadyForNativeDeliveryBlock(task, opts.slot, opts.operational);
31515
+ return explainAgentReadyForNativeDeliveryBlock(task, opts.slot);
31537
31516
  }
31538
31517
  function buildNativeInjectionPrompt(params) {
31539
31518
  const preamble = AUGMENTATION_PREAMBLES[params.augmentationMode];
@@ -31820,6 +31799,55 @@ function logNativeDeliveryInjecting(role, chatroomId, taskId) {
31820
31799
  console.log(`[NativeDelivery:inject] ${role}@${chatroomId} task ${taskId} — starting injection`);
31821
31800
  }
31822
31801
 
31802
+ // src/daemon/services/task-service/service/native-delivery/role-delivery-state.ts
31803
+ function roleKey(chatroomId, role) {
31804
+ return `${chatroomId}:${role.toLowerCase()}`;
31805
+ }
31806
+
31807
+ class RoleDeliveryState {
31808
+ generation = new Map;
31809
+ inFlight = new Set;
31810
+ nativeNudgeFailures = new Map;
31811
+ getGeneration(chatroomId, role) {
31812
+ return this.generation.get(roleKey(chatroomId, role)) ?? 0;
31813
+ }
31814
+ resetDeliveryState(chatroomId, role) {
31815
+ const key = roleKey(chatroomId, role);
31816
+ const next4 = (this.generation.get(key) ?? 0) + 1;
31817
+ this.generation.set(key, next4);
31818
+ this.inFlight.delete(key);
31819
+ this.nativeNudgeFailures.delete(key);
31820
+ return next4;
31821
+ }
31822
+ tryAcquireDelivery(chatroomId, role) {
31823
+ const key = roleKey(chatroomId, role);
31824
+ if (this.inFlight.has(key))
31825
+ return false;
31826
+ this.inFlight.add(key);
31827
+ return true;
31828
+ }
31829
+ releaseDelivery(chatroomId, role) {
31830
+ this.inFlight.delete(roleKey(chatroomId, role));
31831
+ }
31832
+ recordNativeNudgeFailure(chatroomId, role) {
31833
+ const key = roleKey(chatroomId, role);
31834
+ const count3 = (this.nativeNudgeFailures.get(key) ?? 0) + 1;
31835
+ this.nativeNudgeFailures.set(key, count3);
31836
+ return count3;
31837
+ }
31838
+ clearNativeNudgeFailures(chatroomId, role) {
31839
+ this.nativeNudgeFailures.delete(roleKey(chatroomId, role));
31840
+ }
31841
+ getNativeNudgeFailures(chatroomId, role) {
31842
+ return this.nativeNudgeFailures.get(roleKey(chatroomId, role)) ?? 0;
31843
+ }
31844
+ }
31845
+ function getRoleDeliveryState() {
31846
+ shared ??= new RoleDeliveryState;
31847
+ return shared;
31848
+ }
31849
+ var shared;
31850
+
31823
31851
  // src/daemon/services/task-service/service/native-delivery/delivery-decision.ts
31824
31852
  function taskSort(a, b) {
31825
31853
  const pendingOrder = Number(b.status === "pending") - Number(a.status === "pending");
@@ -31831,9 +31859,6 @@ function stableBlockReason(reason) {
31831
31859
  "task_status_not_deliverable",
31832
31860
  "acknowledged_wrong_role",
31833
31861
  "chatroom_stop_scope_active",
31834
- "operational_stop_intent_active",
31835
- "operational_circuit_open",
31836
- "operational_state_not_running",
31837
31862
  "slot_missing",
31838
31863
  "slot_not_running",
31839
31864
  "slot_pid_missing",
@@ -31871,8 +31896,7 @@ function decideNextDelivery(tasks, context5) {
31871
31896
  return { kind: "wait", taskId: task.taskId, reason: "agent_start_in_flight" };
31872
31897
  }
31873
31898
  const blockReason = context5.explainNativeDeliveryBlock(task, {
31874
- slot: context5.slot,
31875
- operational: context5.operational
31899
+ slot: context5.slot
31876
31900
  });
31877
31901
  if (blockReason === null) {
31878
31902
  return {
@@ -31902,112 +31926,27 @@ var init_delivery_decision = __esm(() => {
31902
31926
  init_check_agent_slot();
31903
31927
  });
31904
31928
 
31905
- // src/infrastructure/mappers/map-assigned-task.ts
31906
- function mapAssignedTaskSnapshot(row) {
31907
- return {
31908
- taskId: row.taskId,
31909
- chatroomId: row.chatroomId,
31910
- status: row.status,
31911
- assignedTo: row.assignedTo,
31912
- updatedAt: row.updatedAt,
31913
- createdAt: row.createdAt,
31914
- agentConfig: {
31915
- role: row.agentConfig.role,
31916
- machineId: row.agentConfig.machineId,
31917
- agentHarness: row.agentConfig.agentHarness,
31918
- model: row.agentConfig.model,
31919
- workingDir: row.agentConfig.workingDir,
31920
- spawnedAgentPid: row.agentConfig.spawnedAgentPid,
31921
- desiredState: row.agentConfig.desiredState,
31922
- circuitState: row.agentConfig.circuitState,
31923
- configLifecycleRevision: row.agentConfig.configLifecycleRevision
31924
- },
31925
- participant: row.participant,
31926
- requestsNativeColdSession: row.requestsNativeColdSession
31927
- };
31928
- }
31929
- function mapAssignedTaskView(row) {
31930
- return {
31931
- ...mapAssignedTaskSnapshot(row),
31932
- taskContent: row.taskContent,
31933
- taskEnvelope: row.taskEnvelope,
31934
- startInNewSession: row.startInNewSession
31935
- };
31936
- }
31937
- function mapAssignedTaskSnapshotList(rows) {
31938
- return rows.map(mapAssignedTaskSnapshot);
31939
- }
31940
-
31941
31929
  // src/daemon/entry/restart-orchestrator-in-flight.ts
31942
- function roleKey(chatroomId, role) {
31930
+ function roleKey2(chatroomId, role) {
31943
31931
  return `${chatroomId}:${role.toLowerCase()}`;
31944
31932
  }
31945
31933
  function markRestartOrchestratorInFlight(chatroomId, role, correlationId) {
31946
- inFlight.set(roleKey(chatroomId, role), correlationId);
31934
+ inFlight.set(roleKey2(chatroomId, role), correlationId);
31947
31935
  }
31948
31936
  function clearRestartOrchestratorInFlight(chatroomId, role, correlationId) {
31949
- const key = roleKey(chatroomId, role);
31937
+ const key = roleKey2(chatroomId, role);
31950
31938
  if (correlationId !== undefined && inFlight.get(key) !== correlationId)
31951
31939
  return;
31952
31940
  inFlight.delete(key);
31953
31941
  }
31954
31942
  function isRestartOrchestratorInFlight(chatroomId, role) {
31955
- return inFlight.has(roleKey(chatroomId, role));
31943
+ return inFlight.has(roleKey2(chatroomId, role));
31956
31944
  }
31957
31945
  var inFlight;
31958
31946
  var init_restart_orchestrator_in_flight = __esm(() => {
31959
31947
  inFlight = new Map;
31960
31948
  });
31961
31949
 
31962
- // src/daemon/entry/role-delivery-state.ts
31963
- function roleKey2(chatroomId, role) {
31964
- return `${chatroomId}:${role.toLowerCase()}`;
31965
- }
31966
-
31967
- class RoleDeliveryState {
31968
- generation = new Map;
31969
- inFlight = new Set;
31970
- nativeNudgeFailures = new Map;
31971
- getGeneration(chatroomId, role) {
31972
- return this.generation.get(roleKey2(chatroomId, role)) ?? 0;
31973
- }
31974
- resetDeliveryState(chatroomId, role) {
31975
- const key = roleKey2(chatroomId, role);
31976
- const next4 = (this.generation.get(key) ?? 0) + 1;
31977
- this.generation.set(key, next4);
31978
- this.inFlight.delete(key);
31979
- this.nativeNudgeFailures.delete(key);
31980
- return next4;
31981
- }
31982
- tryAcquireDelivery(chatroomId, role) {
31983
- const key = roleKey2(chatroomId, role);
31984
- if (this.inFlight.has(key))
31985
- return false;
31986
- this.inFlight.add(key);
31987
- return true;
31988
- }
31989
- releaseDelivery(chatroomId, role) {
31990
- this.inFlight.delete(roleKey2(chatroomId, role));
31991
- }
31992
- recordNativeNudgeFailure(chatroomId, role) {
31993
- const key = roleKey2(chatroomId, role);
31994
- const count3 = (this.nativeNudgeFailures.get(key) ?? 0) + 1;
31995
- this.nativeNudgeFailures.set(key, count3);
31996
- return count3;
31997
- }
31998
- clearNativeNudgeFailures(chatroomId, role) {
31999
- this.nativeNudgeFailures.delete(roleKey2(chatroomId, role));
32000
- }
32001
- getNativeNudgeFailures(chatroomId, role) {
32002
- return this.nativeNudgeFailures.get(roleKey2(chatroomId, role)) ?? 0;
32003
- }
32004
- }
32005
- function getRoleDeliveryState() {
32006
- shared ??= new RoleDeliveryState;
32007
- return shared;
32008
- }
32009
- var shared;
32010
-
32011
31950
  // src/daemon/services/task-service/service/native-delivery/native-task-delivery-coordinator.ts
32012
31951
  class NativeTaskDeliveryCoordinator {
32013
31952
  resetRoleDeliveryState(chatroomId, role) {
@@ -32017,17 +31956,7 @@ class NativeTaskDeliveryCoordinator {
32017
31956
  const tasks = params.tasks;
32018
31957
  if (tasks.length === 0)
32019
31958
  return;
32020
- const {
32021
- runtime: runtime4,
32022
- effectContext: effectContext2,
32023
- agentMgr,
32024
- sessionDeps,
32025
- operationalModel,
32026
- isTaskActive,
32027
- machineId,
32028
- onTaskDelivered,
32029
- executors
32030
- } = params;
31959
+ const { runtime: runtime4, effectContext: effectContext2, agentMgr, isTaskActive, onTaskDelivered, executors } = params;
32031
31960
  const deliveryState = getRoleDeliveryState();
32032
31961
  const taskService = params.taskService;
32033
31962
  const groups = new Map;
@@ -32050,12 +31979,10 @@ class NativeTaskDeliveryCoordinator {
32050
31979
  continue;
32051
31980
  const { role } = firstTask.agentConfig;
32052
31981
  const slot = agentMgr.getSlot(firstTask.chatroomId, role);
32053
- const operational = operationalModel.get(firstTask.chatroomId, role);
32054
31982
  const activeTaskId = roleTasks.find((candidate) => isTaskActive({ chatroomId: candidate.chatroomId, role, taskId: candidate.taskId }))?.taskId;
32055
31983
  const decision = decideNextDelivery(roleTasks, {
32056
31984
  role,
32057
31985
  slot,
32058
- operational,
32059
31986
  activeTaskId,
32060
31987
  deliveryInFlight: false,
32061
31988
  agentLifecycleInFlight: isRestartOrchestratorInFlight(firstTask.chatroomId, role),
@@ -32070,8 +31997,7 @@ class NativeTaskDeliveryCoordinator {
32070
31997
  attemptId,
32071
31998
  slotState: slot?.state ?? "missing",
32072
31999
  nativeTurnPhase: slot?.nativeTurnPhase ?? "unknown",
32073
- harnessSessionPresent: Boolean(slot?.harnessSessionId),
32074
- operationalState: operational?.operationalState ?? "missing"
32000
+ harnessSessionPresent: Boolean(slot?.harnessSessionId)
32075
32001
  });
32076
32002
  const row = ("taskId" in decision ? sortedTasks.find((candidate) => candidate.taskId === decision.taskId) : firstTask) ?? firstTask;
32077
32003
  if (decision.kind === "idle" || decision.kind === "blocked" || decision.kind === "wait") {
@@ -32089,7 +32015,7 @@ class NativeTaskDeliveryCoordinator {
32089
32015
  continue;
32090
32016
  try {
32091
32017
  if (executors) {
32092
- const startResult2 = await executors.startAgent(row, operational?.operationalState);
32018
+ const startResult2 = await executors.startAgent(row);
32093
32019
  console.log(`[NativeDelivery:execution] attempt=${attemptId} role=${role} chatroom=${row.chatroomId} task=${row.taskId} operation=start-agent result=${startResult2 && typeof startResult2 === "object" && "success" in startResult2 ? startResult2.success : "completed"}`);
32094
32020
  continue;
32095
32021
  }
@@ -32099,7 +32025,7 @@ class NativeTaskDeliveryCoordinator {
32099
32025
  agentHarness: row.agentConfig.agentHarness,
32100
32026
  model: row.agentConfig.model ?? "",
32101
32027
  workingDir: row.agentConfig.workingDir,
32102
- reason: operational?.operationalState === "running" ? AgentStartReasonEnum["platform.task_monitor_nudge"] : AgentStartReasonEnum["platform.pending_task_wake"],
32028
+ reason: AgentStartReasonEnum["platform.pending_task_wake"],
32103
32029
  wantResume: false,
32104
32030
  lifecycleRevision: row.agentConfig.configLifecycleRevision,
32105
32031
  taskId: row.taskId
@@ -32134,17 +32060,15 @@ class NativeTaskDeliveryCoordinator {
32134
32060
  continue;
32135
32061
  }
32136
32062
  await exports_Runtime.runPromise(runtime4)(exports_Effect.gen(function* () {
32137
- const backend2 = yield* exports_Effect.tryPromise(() => sessionDeps.backend.query(api.machines.getAssignedTaskForAction, {
32138
- sessionId: sessionDeps.sessionId,
32139
- machineId,
32140
- taskId: row.taskId,
32141
- role: row.agentConfig.role
32063
+ const full = yield* exports_Effect.tryPromise(() => taskService.loadAssignedTaskForAction({
32064
+ chatroomId: row.chatroomId,
32065
+ role: row.agentConfig.role,
32066
+ taskId: row.taskId
32142
32067
  }));
32143
- if (!backend2) {
32068
+ if (!full) {
32144
32069
  console.warn(`[NativeDelivery:execution] attempt=${attemptId} role=${role} chatroom=${row.chatroomId} task=${row.taskId} operation=inject result=task_hydration_missing`);
32145
32070
  return;
32146
32071
  }
32147
- const full = mapAssignedTaskView(backend2);
32148
32072
  yield* exports_Effect.tryPromise(() => taskService.deliverNativeTask(full, harnessSessionId, (delivered) => {
32149
32073
  onTaskDelivered?.(delivered);
32150
32074
  deliveryState.clearNativeNudgeFailures(delivered.chatroomId, delivered.role);
@@ -32168,40 +32092,37 @@ var init_native_task_delivery_coordinator = __esm(() => {
32168
32092
  init_agent();
32169
32093
  init_esm();
32170
32094
  init_delivery_decision();
32171
- init_api3();
32172
32095
  init_convex_error();
32173
32096
  init_check_agent_slot();
32174
32097
  init_restart_orchestrator_in_flight();
32175
32098
  });
32176
32099
 
32177
32100
  // src/daemon/services/task-service/service/native-delivery/task-delivery-processor.ts
32178
- async function processTasksUpdate(runtime4, effectContext2, agentMgr, runSerializedForAgent, taskService, sessionDeps, machineId, pass, lifecycleOutbox, operationalModel, isTaskActive, options) {
32101
+ async function processTasksUpdate(runtime4, effectContext2, agentMgr, runSerializedForAgent, taskService, sessionDeps, machineId, pass, lifecycleOutbox, isTaskActive, options) {
32179
32102
  const first = options.snapshots[0];
32180
32103
  if (!first)
32181
32104
  return;
32182
32105
  logNativeDeliveryTrigger(pass, first.agentConfig.role, first.chatroomId, first.taskId);
32183
32106
  const executors = {
32184
- startAgent: (task, operationalState) => runSerializedForAgent({ chatroomId: task.chatroomId, role: task.agentConfig.role }, { timeoutMs: 120000 }, (ops, context5) => ops.startAgent({
32107
+ startAgent: (task) => runSerializedForAgent({ chatroomId: task.chatroomId, role: task.agentConfig.role }, { timeoutMs: 120000 }, (ops, context5) => ops.startAgent({
32185
32108
  chatroomId: task.chatroomId,
32186
32109
  role: task.agentConfig.role,
32187
32110
  agentHarness: task.agentConfig.agentHarness,
32188
32111
  model: task.agentConfig.model ?? "",
32189
32112
  workingDir: task.agentConfig.workingDir,
32190
- reason: operationalState === "running" ? AgentStartReasonEnum["platform.task_monitor_nudge"] : AgentStartReasonEnum["platform.pending_task_wake"],
32113
+ reason: AgentStartReasonEnum["platform.pending_task_wake"],
32191
32114
  wantResume: false,
32192
32115
  lifecycleRevision: task.agentConfig.configLifecycleRevision,
32193
32116
  taskId: task.taskId
32194
32117
  }, context5.signal)),
32195
32118
  injectTask: async (task, harnessSessionId) => {
32196
- const backend2 = await sessionDeps.backend.query(api.machines.getAssignedTaskForAction, {
32197
- sessionId: sessionDeps.sessionId,
32198
- machineId,
32199
- taskId: task.taskId,
32200
- role: task.agentConfig.role
32119
+ const full = await taskService.loadAssignedTaskForAction({
32120
+ chatroomId: task.chatroomId,
32121
+ role: task.agentConfig.role,
32122
+ taskId: task.taskId
32201
32123
  });
32202
- if (!backend2)
32124
+ if (!full)
32203
32125
  return { kind: "task-unavailable" };
32204
- const full = mapAssignedTaskView(backend2);
32205
32126
  let delivered;
32206
32127
  await taskService.deliverNativeTask(full, harnessSessionId, (result) => {
32207
32128
  delivered = result;
@@ -32219,7 +32140,6 @@ async function processTasksUpdate(runtime4, effectContext2, agentMgr, runSeriali
32219
32140
  taskService,
32220
32141
  sessionDeps,
32221
32142
  lifecycleOutbox,
32222
- operationalModel,
32223
32143
  isTaskActive,
32224
32144
  machineId,
32225
32145
  onTaskDelivered: options.onTaskDelivered,
@@ -32229,7 +32149,6 @@ async function processTasksUpdate(runtime4, effectContext2, agentMgr, runSeriali
32229
32149
  var init_task_delivery_processor = __esm(() => {
32230
32150
  init_agent();
32231
32151
  init_native_task_delivery_coordinator();
32232
- init_api3();
32233
32152
  });
32234
32153
 
32235
32154
  // src/daemon/services/task-service/service/native-delivery/native-delivery-service.ts
@@ -32250,6 +32169,7 @@ class NativeDeliveryService {
32250
32169
  this.unsubscribeTaskService = deps.taskService.subscribe?.((notification) => this.handleTaskServiceNotification(notification));
32251
32170
  }
32252
32171
  async handleAgentStarted(event) {
32172
+ this.deps.agentTaskState.clear({ chatroomId: event.chatroomId, role: event.role });
32253
32173
  await this.requestReconcile({
32254
32174
  chatroomId: event.chatroomId,
32255
32175
  role: event.role,
@@ -32262,7 +32182,7 @@ class NativeDeliveryService {
32262
32182
  this.requestReconcile({
32263
32183
  chatroomId: event.chatroomId,
32264
32184
  role: event.role,
32265
- source: "operational-signal"
32185
+ source: "agent-session-lost"
32266
32186
  }).catch((error) => {
32267
32187
  console.warn(`[NativeDelivery:failure] role=${event.role} chatroom=${event.chatroomId} operation=session-loss-reconcile error=${error instanceof Error ? error.message : String(error)}`);
32268
32188
  });
@@ -32276,6 +32196,19 @@ class NativeDeliveryService {
32276
32196
  });
32277
32197
  const errorDetail = completion.error;
32278
32198
  console.error(`[NativeDelivery:turn-failed] chatroom=${event.chatroomId} role=${event.role} task=${activeTask?.taskId ?? "none"} turn=${completion.turnId} status=${completion.status} source=${completion.source} error=${errorDetail ?? "none"}`);
32199
+ if (activeTask) {
32200
+ try {
32201
+ await this.deps.taskService.releaseTaskAfterTurnFailure({
32202
+ chatroomId: event.chatroomId,
32203
+ role: event.role,
32204
+ taskId: activeTask.taskId
32205
+ });
32206
+ } catch (error) {
32207
+ console.error(`[NativeDelivery:turn-failed-recovery-error] chatroom=${event.chatroomId} role=${event.role} task=${activeTask.taskId} turn=${completion.turnId} error=${error instanceof Error ? error.stack ?? error.message : String(error)}`);
32208
+ return { kind: "hold-slot", reason: "task-recovery-failed" };
32209
+ }
32210
+ this.deps.agentTaskState.clear({ chatroomId: event.chatroomId, role: event.role });
32211
+ }
32279
32212
  const fact = {
32280
32213
  kind: "turn_failed",
32281
32214
  chatroomId: event.chatroomId,
@@ -32297,10 +32230,13 @@ class NativeDeliveryService {
32297
32230
  await this.deps.lifecycleOutbox.enqueue(fact);
32298
32231
  } catch (error) {
32299
32232
  console.error(`[NativeDelivery:turn-failed-outbox-error] chatroom=${event.chatroomId} role=${event.role} turn=${completion.turnId} error=${error instanceof Error ? error.stack ?? error.message : String(error)}`);
32233
+ if (activeTask)
32234
+ return { kind: "release-slot" };
32300
32235
  return { kind: "hold-slot", reason: "turn-failed-outbox-enqueue-failed" };
32301
32236
  }
32302
32237
  return { kind: "release-slot" };
32303
32238
  }
32239
+ this.deps.agentTaskState.clear({ chatroomId: event.chatroomId, role: event.role });
32304
32240
  this.scheduleRoleDelivery(event.chatroomId, event.role);
32305
32241
  return { kind: "release-slot" };
32306
32242
  }
@@ -32392,6 +32328,19 @@ class NativeDeliveryService {
32392
32328
  this.reconcileStates.set(key, state);
32393
32329
  await state.promise;
32394
32330
  }
32331
+ async reconcileAfterAgentRestart(args2) {
32332
+ const delivered = [];
32333
+ await this.deps.taskService.syncAssignedTaskSnapshots();
32334
+ await this.requestReconcile({
32335
+ chatroomId: args2.chatroomId,
32336
+ role: args2.role,
32337
+ source: "restart-completed",
32338
+ onTaskDelivered: ({ taskId }) => {
32339
+ delivered.push(taskId);
32340
+ }
32341
+ });
32342
+ return delivered;
32343
+ }
32395
32344
  async requestReconcileForSnapshots(snapshots, source) {
32396
32345
  const roles = new Set(snapshots.map((snapshot) => `${snapshot.chatroomId}:${snapshot.agentConfig.role.toLowerCase()}`));
32397
32346
  await Promise.all([...roles].map((key) => {
@@ -32406,7 +32355,7 @@ class NativeDeliveryService {
32406
32355
  async reconcileRole(pass, snapshots, onTaskDelivered) {
32407
32356
  if (snapshots.length === 0)
32408
32357
  return;
32409
- await processTasksUpdate(this.deps.runtime, this.deps.effectContext, this.deps.agentMgr, this.deps.runSerializedForAgent, this.deps.taskService, this.deps.sessionDeps, this.deps.machineId, pass, this.deps.lifecycleOutbox, this.deps.agentOperationalReadModel, ({ chatroomId, role, taskId }) => this.deps.agentTaskState.get({ chatroomId, role })?.taskId === taskId, {
32358
+ await processTasksUpdate(this.deps.runtime, this.deps.effectContext, this.deps.agentMgr, this.deps.runSerializedForAgent, this.deps.taskService, this.deps.sessionDeps, this.deps.machineId, pass, this.deps.lifecycleOutbox, ({ chatroomId, role, taskId }) => this.deps.agentTaskState.get({ chatroomId, role })?.taskId === taskId, {
32410
32359
  snapshots,
32411
32360
  onTaskDelivered: (args2) => {
32412
32361
  this.recordTaskDelivered(args2);
@@ -32423,8 +32372,8 @@ var init_native_delivery_service = __esm(() => {
32423
32372
  init_task_delivery_processor();
32424
32373
  });
32425
32374
 
32426
- // src/daemon/services/task-service/service/task-outbox.ts
32427
- class TaskOutbox {
32375
+ // src/daemon/services/task-service/service/native-task-delivery-queue.ts
32376
+ class NativeTaskDeliveryQueue {
32428
32377
  sender;
32429
32378
  tails = new Map;
32430
32379
  constructor(sender) {
@@ -47172,6 +47121,42 @@ var init_assigned_task_snapshot_contract = __esm(() => {
47172
47121
  }));
47173
47122
  });
47174
47123
 
47124
+ // src/infrastructure/mappers/map-assigned-task.ts
47125
+ function mapAssignedTaskSnapshot(row) {
47126
+ return {
47127
+ taskId: row.taskId,
47128
+ chatroomId: row.chatroomId,
47129
+ status: row.status,
47130
+ assignedTo: row.assignedTo,
47131
+ updatedAt: row.updatedAt,
47132
+ createdAt: row.createdAt,
47133
+ agentConfig: {
47134
+ role: row.agentConfig.role,
47135
+ machineId: row.agentConfig.machineId,
47136
+ agentHarness: row.agentConfig.agentHarness,
47137
+ model: row.agentConfig.model,
47138
+ workingDir: row.agentConfig.workingDir,
47139
+ spawnedAgentPid: row.agentConfig.spawnedAgentPid,
47140
+ desiredState: row.agentConfig.desiredState,
47141
+ circuitState: row.agentConfig.circuitState,
47142
+ configLifecycleRevision: row.agentConfig.configLifecycleRevision
47143
+ },
47144
+ participant: row.participant,
47145
+ requestsNativeColdSession: row.requestsNativeColdSession
47146
+ };
47147
+ }
47148
+ function mapAssignedTaskView(row) {
47149
+ return {
47150
+ ...mapAssignedTaskSnapshot(row),
47151
+ taskContent: row.taskContent,
47152
+ taskEnvelope: row.taskEnvelope,
47153
+ startInNewSession: row.startInNewSession
47154
+ };
47155
+ }
47156
+ function mapAssignedTaskSnapshotList(rows) {
47157
+ return rows.map(mapAssignedTaskSnapshot);
47158
+ }
47159
+
47175
47160
  // src/daemon/infrastructure/inbox/fetch-machine-assigned-task-snapshots.ts
47176
47161
  async function fetchMachineAssignedTaskSnapshots(sessionDeps, machineId) {
47177
47162
  const result = await sessionDeps.backend.query(api.machines.listMachineAssignedTaskSnapshots, {
@@ -47339,6 +47324,11 @@ var init_inbox = __esm(() => {
47339
47324
  function snapshotKey(taskId, role) {
47340
47325
  return `${taskId}:${role.toLowerCase()}`;
47341
47326
  }
47327
+ function isStaleStatusPatch(snapshot, status3, updatedAt) {
47328
+ if (snapshot.updatedAt > updatedAt)
47329
+ return true;
47330
+ return snapshot.updatedAt === updatedAt && snapshot.status === "completed" && status3 !== "completed";
47331
+ }
47342
47332
 
47343
47333
  class MachineTaskSnapshotState {
47344
47334
  snapshots = new Map;
@@ -47382,6 +47372,16 @@ class MachineTaskSnapshotState {
47382
47372
  this.snapshots.set(snapshotKey(snapshot.taskId, snapshot.agentConfig.role), snapshot);
47383
47373
  }
47384
47374
  }
47375
+ markStatus(chatroomId, role, taskId, status3, updatedAt) {
47376
+ const key = snapshotKey(taskId, role);
47377
+ const snapshot = this.snapshots.get(key);
47378
+ if (!snapshot || snapshot.chatroomId !== chatroomId)
47379
+ return false;
47380
+ if (isStaleStatusPatch(snapshot, status3, updatedAt))
47381
+ return false;
47382
+ this.snapshots.set(key, { ...snapshot, status: status3, updatedAt });
47383
+ return true;
47384
+ }
47385
47385
  }
47386
47386
 
47387
47387
  // src/daemon/infrastructure/inbox/task-signal-contract.ts
@@ -47521,6 +47521,7 @@ function createConvexNativeTaskDeliveryGateway(backend2) {
47521
47521
  claimPendingTask: async (args2) => {
47522
47522
  await backend2.mutation(api.tasks.claimTask, args2);
47523
47523
  },
47524
+ releaseTaskAfterTurnFailure: (args2) => backend2.mutation(api.tasks.releaseTaskAfterTurnFailure, args2),
47524
47525
  loadDeliveryPrompt: (args2) => backend2.query(api.messages.getTaskDeliveryPrompt, args2),
47525
47526
  recordReceipt: async (args2) => {
47526
47527
  await backend2.mutation(api.taskDeliveryReceipts.record, {
@@ -47536,6 +47537,23 @@ function createConvexNativeTaskDeliveryGateway(backend2) {
47536
47537
  },
47537
47538
  recordSessionAugmentation: async (args2) => {
47538
47539
  await backend2.mutation(api.daemon.agentEvents.sessionAugmented, args2);
47540
+ },
47541
+ loadAssignedTaskForAction: async (args2) => {
47542
+ const row = await backend2.query(api.machines.getAssignedTaskForAction, {
47543
+ sessionId: args2.sessionId,
47544
+ machineId: args2.machineId,
47545
+ taskId: args2.taskId,
47546
+ role: args2.role
47547
+ });
47548
+ if (!row)
47549
+ return null;
47550
+ return mapAssignedTaskView(row);
47551
+ },
47552
+ syncAssignedTaskSnapshots: async ({ sessionId, machineId }) => {
47553
+ await backend2.mutation(api.machines.syncMachineAssignedTaskSnapshotsMutation, {
47554
+ sessionId,
47555
+ machineId
47556
+ });
47539
47557
  }
47540
47558
  };
47541
47559
  }
@@ -47566,7 +47584,7 @@ function createTaskService(deps) {
47566
47584
  let inboxClient;
47567
47585
  let serviceStartedAt = 0;
47568
47586
  let stopped = false;
47569
- const taskOutbox = new TaskOutbox(async (entry) => {
47587
+ const nativeTaskDeliveryQueue = new NativeTaskDeliveryQueue(async (entry) => {
47570
47588
  await exports_Effect.runPromise(runNativeInjectionEffect(entry.task, entry.harnessSessionId, {
47571
47589
  ...deps,
47572
47590
  agentMgr,
@@ -47633,14 +47651,7 @@ function createTaskService(deps) {
47633
47651
  inboxStore = createInboxStateStore(resolveInboxDbPath(deps.machineId));
47634
47652
  serviceStartedAt = Date.now();
47635
47653
  try {
47636
- await deps.backend.mutation(api.machines.backfillAgentOperationalStatusForMachine, {
47637
- sessionId: deps.sessionId,
47638
- machineId: deps.machineId
47639
- });
47640
- await deps.backend.mutation(api.machines.syncMachineAssignedTaskSnapshotsMutation, {
47641
- sessionId: deps.sessionId,
47642
- machineId: deps.machineId
47643
- });
47654
+ await service4.syncAssignedTaskSnapshots();
47644
47655
  const snapshots = await fetchMachineAssignedTaskSnapshots({ ...deps, convexUrl: deps.convexUrl }, deps.machineId);
47645
47656
  taskSnapshotState.replace(snapshots);
47646
47657
  inboxClient = client2;
@@ -47666,16 +47677,43 @@ function createTaskService(deps) {
47666
47677
  for (const controller of roomControllers.values())
47667
47678
  controller.abort();
47668
47679
  roomControllers.clear();
47669
- taskOutbox.stop();
47680
+ nativeTaskDeliveryQueue.stop();
47670
47681
  inboxStore?.close();
47671
47682
  inboxStore = undefined;
47672
47683
  },
47673
47684
  listTasksForRole: (chatroomId, role) => taskSnapshotState.listForRole(chatroomId, role),
47674
47685
  listAllTasks: () => taskSnapshotState.listAll(),
47675
47686
  taskSnapshotState,
47676
- deliverNativeTask: (task, harnessSessionId, onTaskDelivered) => taskOutbox.enqueue({ task, harnessSessionId, onTaskDelivered }),
47687
+ deliverNativeTask: (task, harnessSessionId, onTaskDelivered) => nativeTaskDeliveryQueue.enqueue({ task, harnessSessionId, onTaskDelivered }),
47677
47688
  isNativeHarness,
47689
+ releaseTaskAfterTurnFailure: async (args2) => {
47690
+ const result = await gateway.releaseTaskAfterTurnFailure({
47691
+ sessionId: deps.sessionId,
47692
+ chatroomId: args2.chatroomId,
47693
+ role: args2.role,
47694
+ taskId: args2.taskId
47695
+ });
47696
+ taskSnapshotState.markStatus(args2.chatroomId, args2.role, args2.taskId, result.status, result.updatedAt);
47697
+ return result;
47698
+ },
47678
47699
  snapshotRequestsNativeColdSession,
47700
+ loadAssignedTaskForAction: async ({ chatroomId, role, taskId }) => {
47701
+ const task = await gateway.loadAssignedTaskForAction({
47702
+ sessionId: deps.sessionId,
47703
+ machineId: deps.machineId,
47704
+ taskId,
47705
+ role
47706
+ });
47707
+ return task?.chatroomId === chatroomId ? task : null;
47708
+ },
47709
+ syncAssignedTaskSnapshots: async () => {
47710
+ await gateway.syncAssignedTaskSnapshots({
47711
+ sessionId: deps.sessionId,
47712
+ machineId: deps.machineId
47713
+ });
47714
+ const snapshots = await fetchMachineAssignedTaskSnapshots({ ...deps, convexUrl: deps.convexUrl }, deps.machineId);
47715
+ taskSnapshotState.replace(snapshots);
47716
+ },
47679
47717
  explainNativeDeliveryBlock: (task, options) => explainNativeDeliveryBlock(task, options),
47680
47718
  createNativeDeliveryService: (deliveryDeps) => {
47681
47719
  const nativeDelivery = new NativeDeliveryService({
@@ -47693,7 +47731,6 @@ var init_task_service = __esm(() => {
47693
47731
  init_esm();
47694
47732
  init_native_delivery_service();
47695
47733
  init_native_task_injector();
47696
- init_api3();
47697
47734
  init_fetch_machine_assigned_task_snapshots();
47698
47735
  init_inbox();
47699
47736
  init_task();
@@ -111168,25 +111205,6 @@ async function forceNativeWaiting(deps, event) {
111168
111205
  action: NATIVE_WAITING_ACTION
111169
111206
  });
111170
111207
  }
111171
- async function syncAssignedTaskSnapshots(deps) {
111172
- await deps.session.backend.mutation(api.machines.syncMachineAssignedTaskSnapshotsMutation, {
111173
- sessionId: deps.session.sessionId,
111174
- machineId: deps.session.machineId
111175
- });
111176
- }
111177
- async function deliverPendingTasks(deps, event) {
111178
- const delivered = [];
111179
- await syncAssignedTaskSnapshots(deps);
111180
- await deps.nativeDelivery.requestReconcile({
111181
- chatroomId: event.chatroomId,
111182
- role: event.role,
111183
- source: "restart-completed",
111184
- onTaskDelivered: ({ taskId }) => {
111185
- delivered.push(taskId);
111186
- }
111187
- });
111188
- return delivered;
111189
- }
111190
111208
  async function runRestartOrchestrator(deps, event) {
111191
111209
  const { chatroomId, role } = event;
111192
111210
  markRestartOrchestratorInFlight(chatroomId, role, event.correlationId);
@@ -111220,7 +111238,10 @@ async function runRestartOrchestrator(deps, event) {
111220
111238
  await forceNativeWaiting(deps, event);
111221
111239
  await emitPhase(deps, event, "ready");
111222
111240
  await emitPhase(deps, event, "deliver");
111223
- const deliveredTaskIds = await deliverPendingTasks(deps, event);
111241
+ const deliveredTaskIds = await deps.nativeDelivery.reconcileAfterAgentRestart({
111242
+ chatroomId,
111243
+ role
111244
+ });
111224
111245
  await emitPhase(deps, event, "completed");
111225
111246
  await logDaemonAuditEvent(deps.session.logEvent, buildAgentRestartCompletedEvent({
111226
111247
  chatroomId: event.chatroomId,
@@ -118040,313 +118061,20 @@ var init_command_run_subscription = __esm(() => {
118040
118061
  dispatchedStop = new Set;
118041
118062
  });
118042
118063
 
118043
- // src/daemon/entry/task-inbox-membership-registry.ts
118044
- function registerTaskInboxRoomMembershipRefresh(refresh) {
118064
+ // src/daemon/entry/workspace-membership-refresh-registry.ts
118065
+ function registerWorkspaceMembershipRefresh(refresh) {
118045
118066
  refreshRoomMembership = refresh;
118046
118067
  }
118047
- function unregisterTaskInboxRoomMembershipRefresh() {
118068
+ function unregisterWorkspaceMembershipRefresh() {
118048
118069
  refreshRoomMembership = null;
118049
118070
  }
118050
- async function refreshTaskInboxRoomMembership() {
118071
+ async function refreshWorkspaceMembership() {
118051
118072
  await refreshRoomMembership?.();
118052
118073
  }
118053
118074
  var refreshRoomMembership = null;
118054
118075
 
118055
- // src/daemon/infrastructure/agent-operational/operational-signal-feeds.ts
118056
- function chatroomId(value) {
118057
- return value;
118058
- }
118059
- function signalPage(result) {
118060
- if (!result || typeof result !== "object")
118061
- return null;
118062
- const page = result;
118063
- if (!page.items?.length || !page.highKey)
118064
- return null;
118065
- return {
118066
- items: page.items,
118067
- afterSignalKey: "",
118068
- highSignalKey: page.highKey
118069
- };
118070
- }
118071
- function createFeed(input) {
118072
- return input;
118073
- }
118074
- function subscribeArgs(input) {
118075
- return {
118076
- sessionId: input.sessionId,
118077
- machineId: input.machineId,
118078
- chatroomId: chatroomId(input.chatroomId),
118079
- afterKey: input.afterKey,
118080
- limit: input.limit
118081
- };
118082
- }
118083
- function rangeArgs(input) {
118084
- return {
118085
- sessionId: input.sessionId,
118086
- machineId: input.machineId,
118087
- chatroomId: chatroomId(input.chatroomId),
118088
- afterSignalKey: input.afterSignalKey,
118089
- throughSignalKey: input.throughSignalKey,
118090
- limit: input.limit
118091
- };
118092
- }
118093
- function ackArgs(input) {
118094
- return {
118095
- sessionId: input.sessionId,
118096
- machineId: input.machineId,
118097
- chatroomId: chatroomId(input.chatroomId),
118098
- throughSignalKey: input.throughSignalKey
118099
- };
118100
- }
118101
- var createMachineFeed = (config4) => createFeed({
118102
- kind: config4.kind,
118103
- subscribe: (client4, input, onResult, onError3) => client4.onUpdate(config4.subscribe, subscribeArgs(input), (result) => {
118104
- const page = signalPage(result);
118105
- onResult(page ? { ...page, afterSignalKey: input.afterKey } : result);
118106
- }, onError3),
118107
- hydrate: async (client4, input) => await client4.query(config4.hydrate, rangeArgs(input)),
118108
- acknowledge: async (sessionDeps, input) => await sessionDeps.backend.mutation(config4.acknowledge, ackArgs({
118109
- ...input,
118110
- sessionId: sessionDeps.sessionId
118111
- }))
118112
- }), operationalSignalFeeds;
118113
- var init_operational_signal_feeds = __esm(() => {
118114
- init_api3();
118115
- operationalSignalFeeds = {
118116
- "agent-operational": createMachineFeed({
118117
- kind: "agent-operational",
118118
- subscribe: api.machines.subscribeMachineAgentOperationalSignalsSince,
118119
- hydrate: api.machines.listMachineAgentOperationalStatusForSignalRange,
118120
- acknowledge: api.machines.ackMachineAgentOperationalSignals
118121
- }),
118122
- connectivity: createMachineFeed({
118123
- kind: "connectivity",
118124
- subscribe: api.machines.subscribeMachineConnectivitySignalsSince,
118125
- hydrate: api.machines.listMachineConnectivityStatusForSignalRange,
118126
- acknowledge: api.machines.ackMachineConnectivitySignals
118127
- }),
118128
- "agent-stop": createMachineFeed({
118129
- kind: "agent-stop",
118130
- subscribe: api.machines.subscribeMachineAgentStopSignalsSince,
118131
- hydrate: api.machines.listMachineAgentStopStatusForSignalRange,
118132
- acknowledge: api.machines.ackMachineAgentStopSignals
118133
- }),
118134
- "agent-removal": createMachineFeed({
118135
- kind: "agent-removal",
118136
- subscribe: api.machines.subscribeMachineAgentRemovalSignalsSince,
118137
- hydrate: api.machines.listMachineAgentRemovalStatusForSignalRange,
118138
- acknowledge: api.machines.ackMachineAgentRemovalSignals
118139
- })
118140
- };
118141
- });
118142
-
118143
- // src/daemon/infrastructure/agent-operational/ack-machine-operational-signals.ts
118144
- async function ackMachineSignal(sessionDeps, machineId, chatroomId2, throughSignalKey, kind) {
118145
- const feed = operationalSignalFeeds[kind];
118146
- while (true) {
118147
- const result = await feed.acknowledge(sessionDeps, {
118148
- machineId,
118149
- chatroomId: chatroomId2,
118150
- throughSignalKey
118151
- });
118152
- if (!result.hasMore)
118153
- return;
118154
- if (result.deletedCount === 0) {
118155
- throw new Error(`${kind} signal ack reported more work without progress`);
118156
- }
118157
- }
118158
- }
118159
- var init_ack_machine_operational_signals = __esm(() => {
118160
- init_operational_signal_feeds();
118161
- });
118162
-
118163
- // src/daemon/infrastructure/agent-operational/agent-operational-read-model.ts
118164
- class AgentOperationalReadModel {
118165
- rows = new Map;
118166
- replace(rows) {
118167
- const changed = [];
118168
- const nextKeys = new Set;
118169
- for (const row of rows) {
118170
- const key = roleKey3(row.chatroomId, row.role);
118171
- nextKeys.add(key);
118172
- const prev = this.rows.get(key);
118173
- if (!prev || prev.revisionKey !== row.revisionKey)
118174
- changed.push({ chatroomId: row.chatroomId, role: row.role });
118175
- this.rows.set(key, row);
118176
- }
118177
- for (const [key, prev] of this.rows) {
118178
- if (!nextKeys.has(key)) {
118179
- changed.push({ chatroomId: prev.chatroomId, role: prev.role });
118180
- this.rows.delete(key);
118181
- }
118182
- }
118183
- return changed;
118184
- }
118185
- applySignalPage(rows, removed) {
118186
- const changed = [];
118187
- for (const row of rows) {
118188
- const key = roleKey3(row.chatroomId, row.role);
118189
- const prev = this.rows.get(key);
118190
- if (!prev || prev.revisionKey !== row.revisionKey) {
118191
- changed.push({ chatroomId: row.chatroomId, role: row.role });
118192
- }
118193
- this.rows.set(key, row);
118194
- }
118195
- for (const item of removed) {
118196
- const key = roleKey3(item.chatroomId, item.role);
118197
- if (this.rows.has(key))
118198
- changed.push(item);
118199
- this.rows.delete(key);
118200
- }
118201
- return changed;
118202
- }
118203
- get(chatroomId2, role) {
118204
- return this.rows.get(roleKey3(chatroomId2, role));
118205
- }
118206
- }
118207
- var roleKey3 = (chatroomId2, role) => `${chatroomId2}:${role.toLowerCase()}`;
118208
-
118209
- // src/daemon/infrastructure/agent-operational/fetch-machine-agent-operational-status.ts
118210
- async function fetchMachineAgentOperationalStatus(sessionDeps, machineId) {
118211
- const result = await sessionDeps.backend.query(api.machines.listMachineAgentOperationalStatus, {
118212
- sessionId: sessionDeps.sessionId,
118213
- machineId
118214
- });
118215
- return result;
118216
- }
118217
- var init_fetch_machine_agent_operational_status = __esm(() => {
118218
- init_api3();
118219
- });
118220
-
118221
- // src/daemon/infrastructure/agent-operational/operational-inbox.ts
118222
- function operationalSignalCursorAt(timestamp) {
118223
- return `${String(Math.max(0, Math.floor(timestamp))).padStart(16, "0")}:`;
118224
- }
118225
- function abortError2() {
118226
- const error51 = new Error("Operational inbox stopped");
118227
- error51.name = "AbortError";
118228
- return error51;
118229
- }
118230
- function throwIfAborted2(signal) {
118231
- if (signal?.aborted)
118232
- throw abortError2();
118233
- }
118234
- function feedFor(options) {
118235
- return options.feed ?? operationalSignalFeeds["agent-operational"];
118236
- }
118237
- function waitForOperationalSignalPage(options, afterSignalKey) {
118238
- return new Promise((resolve8, reject) => {
118239
- let unsubscribe;
118240
- let settled = false;
118241
- const cleanup = () => {
118242
- unsubscribe?.();
118243
- unsubscribe = undefined;
118244
- options.signal?.removeEventListener("abort", onAbort);
118245
- };
118246
- const settle2 = (fn2) => {
118247
- if (settled)
118248
- return;
118249
- settled = true;
118250
- cleanup();
118251
- fn2();
118252
- };
118253
- const onAbort = () => {
118254
- settle2(() => reject(abortError2()));
118255
- };
118256
- options.signal?.addEventListener("abort", onAbort, { once: true });
118257
- try {
118258
- throwIfAborted2(options.signal);
118259
- } catch (error51) {
118260
- settle2(() => reject(error51));
118261
- return;
118262
- }
118263
- unsubscribe = feedFor(options).subscribe(options.client, {
118264
- sessionId: options.sessionId,
118265
- machineId: options.machineId,
118266
- chatroomId: options.chatroomId,
118267
- afterKey: afterSignalKey,
118268
- limit: options.signalPageLimit ?? DEFAULT_SIGNAL_PAGE_LIMIT2
118269
- }, (result) => {
118270
- const page = result;
118271
- if (!page)
118272
- return;
118273
- settle2(() => resolve8(page));
118274
- }, (error51) => {
118275
- settle2(() => reject(error51));
118276
- });
118277
- });
118278
- }
118279
- async function* createOperationalSignalIterator(options) {
118280
- let afterSignalKey = options.initialAfterSignalKey ?? operationalSignalCursorAt(options.serviceStartedAt ?? Date.now());
118281
- while (!options.signal?.aborted) {
118282
- const page = await waitForOperationalSignalPage(options, afterSignalKey);
118283
- yield page;
118284
- afterSignalKey = page.highSignalKey;
118285
- }
118286
- }
118287
- async function fetchRowsForSignalPage(options, page) {
118288
- const rows = [];
118289
- const removed = [];
118290
- let afterSignalKey = page.afterSignalKey;
118291
- while (true) {
118292
- throwIfAborted2(options.signal);
118293
- const result = await feedFor(options).hydrate(options.client, {
118294
- sessionId: options.sessionId,
118295
- machineId: options.machineId,
118296
- chatroomId: options.chatroomId,
118297
- afterSignalKey,
118298
- throughSignalKey: page.highSignalKey,
118299
- limit: options.operationalPageLimit ?? DEFAULT_OPERATIONAL_PAGE_LIMIT
118300
- });
118301
- rows.push(...result.rows);
118302
- removed.push(...result.removed);
118303
- if (!result.hasMore || !result.nextSignalKey)
118304
- break;
118305
- afterSignalKey = result.nextSignalKey;
118306
- }
118307
- return { rows, removed };
118308
- }
118309
- async function runOperationalInbox(options, onUpdate) {
118310
- for await (const page of createOperationalSignalIterator(options)) {
118311
- const hydrated = await fetchRowsForSignalPage(options, page);
118312
- await onUpdate({
118313
- chatroomId: options.chatroomId,
118314
- signals: page.items,
118315
- rows: hydrated.rows,
118316
- removed: hydrated.removed,
118317
- afterSignalKey: page.afterSignalKey,
118318
- throughSignalKey: page.highSignalKey
118319
- });
118320
- }
118321
- }
118322
- var DEFAULT_SIGNAL_PAGE_LIMIT2 = 100, DEFAULT_OPERATIONAL_PAGE_LIMIT = 500;
118323
- var init_operational_inbox = __esm(() => {
118324
- init_operational_signal_feeds();
118325
- });
118326
-
118327
118076
  // src/daemon/entry/task-inbox-runtime.ts
118328
- function isAbortError2(error51) {
118329
- return error51 instanceof Error && error51.name === "AbortError";
118330
- }
118331
- function roomScopeKey(machineId, chatroomId2) {
118332
- return JSON.stringify([machineId, chatroomId2]);
118333
- }
118334
- async function runOperationalInboxLoopWithRestart(options, onUpdate, isStopped) {
118335
- let backoffMs = INBOX_RESTART_INITIAL_MS;
118336
- while (!isStopped()) {
118337
- try {
118338
- await runOperationalInbox(options, onUpdate);
118339
- return;
118340
- } catch (error51) {
118341
- if (isStopped() || isAbortError2(error51))
118342
- return;
118343
- console.warn(`[OperationalInbox room=${options.chatroomId}] loop error, restarting in ${backoffMs}ms:`, error51);
118344
- await new Promise((resolve8) => setTimeout(resolve8, backoffMs));
118345
- backoffMs = Math.min(backoffMs * 2, INBOX_RESTART_MAX_MS);
118346
- }
118347
- }
118348
- }
118349
- var INBOX_RESTART_INITIAL_MS = 1000, INBOX_RESTART_MAX_MS = 30000, startTaskInboxEffect = (wsClient2) => exports_Effect.gen(function* () {
118077
+ var startTaskInboxEffect = (wsClient2) => exports_Effect.gen(function* () {
118350
118078
  const session2 = yield* DaemonSessionService;
118351
118079
  const agentMgr = yield* DaemonAgentProcessManagerService;
118352
118080
  const commandService = yield* DaemonAgentProcessManagerCommandService;
@@ -118366,12 +118094,6 @@ var INBOX_RESTART_INITIAL_MS = 1000, INBOX_RESTART_MAX_MS = 30000, startTaskInbo
118366
118094
  query: (fn2, args2) => session2.backend.query(fn2, args2)
118367
118095
  }
118368
118096
  };
118369
- console.log(`[${formatTimestamp()}] \uD83D\uDCEC Starting task-inbox (chatroom-scoped operational signals)`);
118370
- const inboxStore = createInboxStateStore(resolveInboxDbPath(session2.machineId));
118371
- const serviceStartedAt = Date.now();
118372
- const abort = new AbortController;
118373
- let stopped = false;
118374
- const agentOperationalReadModel = new AgentOperationalReadModel;
118375
118097
  const agentTaskState = createAgentTaskStateService();
118376
118098
  const nativeDelivery = session2.taskService.createNativeDeliveryService({
118377
118099
  runtime: runtime4,
@@ -118381,96 +118103,19 @@ var INBOX_RESTART_INITIAL_MS = 1000, INBOX_RESTART_MAX_MS = 30000, startTaskInbo
118381
118103
  sessionDeps,
118382
118104
  machineId: session2.machineId,
118383
118105
  agentTaskState,
118384
- agentOperationalReadModel,
118385
118106
  lifecycleOutbox
118386
118107
  });
118387
118108
  yield* exports_Effect.tryPromise(() => session2.taskService.startTaskInbox(wsClient2)).pipe(exports_Effect.catchAll((error51) => {
118388
- console.warn("[TaskInbox] service bootstrap failed:", error51);
118109
+ console.warn("[TaskService] task inbox bootstrap failed:", error51);
118389
118110
  return exports_Effect.void;
118390
118111
  }));
118391
- const knownRoomIds = new Set;
118112
+ let stopped = false;
118392
118113
  const roomWatchers = new Map;
118393
- const bootstrapSucceeded = yield* exports_Effect.tryPromise(async () => {
118394
- const rows = await fetchMachineAgentOperationalStatus(sessionDeps, session2.machineId);
118395
- agentOperationalReadModel.replace(rows);
118396
- for (const row of rows)
118397
- knownRoomIds.add(row.chatroomId);
118398
- return true;
118399
- }).pipe(exports_Effect.catchAll((error51) => {
118400
- console.warn("[OperationalInbox] bootstrap failed:", error51);
118401
- return exports_Effect.succeed(false);
118402
- }));
118403
- const operationalHandler = async (kind, update6) => {
118404
- const chatroomId2 = update6.chatroomId;
118405
- const changed = agentOperationalReadModel.applySignalPage(update6.rows, update6.removed);
118406
- await Promise.all(changed.map(({ chatroomId: roomId, role }) => nativeDelivery.requestReconcile({
118407
- chatroomId: roomId,
118408
- role,
118409
- source: "operational-signal"
118410
- })));
118411
- inboxStore.save({
118412
- inboxType: `operational:${kind}`,
118413
- scopeKey: roomScopeKey(session2.machineId, chatroomId2)
118414
- }, { afterSignalKey: update6.throughSignalKey });
118415
- try {
118416
- await ackMachineSignal(sessionDeps, session2.machineId, chatroomId2, update6.throughSignalKey, kind);
118417
- } catch (error51) {
118418
- console.warn(`[OperationalInbox kind=${kind} room=${chatroomId2}] signal cleanup failed:`, error51);
118419
- }
118420
- };
118421
- const ensureRoomInboxes = (chatroomId2) => {
118422
- const existing = roomWatchers.get(chatroomId2);
118423
- if (existing)
118424
- return existing.startPromise;
118425
- const controller = new AbortController;
118426
- const entry = {
118427
- controller,
118428
- startPromise: Promise.resolve()
118429
- };
118430
- roomWatchers.set(chatroomId2, entry);
118431
- entry.startPromise = (async () => {
118432
- if (!knownRoomIds.has(chatroomId2)) {
118433
- try {
118434
- const current = await fetchMachineAgentOperationalStatus(sessionDeps, session2.machineId);
118435
- agentOperationalReadModel.replace(current);
118436
- for (const row of current)
118437
- knownRoomIds.add(row.chatroomId);
118438
- } catch (error51) {
118439
- console.warn(`[OperationalInbox room=${chatroomId2}] operational hydration failed:`, error51);
118440
- }
118441
- }
118442
- await Promise.all(["agent-operational", "connectivity", "agent-stop", "agent-removal"].map(async (kind) => {
118443
- const operationalRoomKey = {
118444
- inboxType: `operational:${kind}`,
118445
- scopeKey: roomScopeKey(session2.machineId, chatroomId2)
118446
- };
118447
- const persistedRoom = inboxStore.get(operationalRoomKey);
118448
- let cursor = persistedRoom?.state.afterSignalKey;
118449
- if (!cursor) {
118450
- cursor = operationalSignalCursorAt(serviceStartedAt);
118451
- try {
118452
- inboxStore.save(operationalRoomKey, { afterSignalKey: cursor });
118453
- } catch (error51) {
118454
- console.warn(`[OperationalInbox kind=${kind} room=${chatroomId2}] failed to persist bootstrap baseline:`, error51);
118455
- }
118456
- }
118457
- if (persistedRoom || bootstrapSucceeded) {
118458
- ackMachineSignal(sessionDeps, session2.machineId, chatroomId2, cursor, kind).catch((error51) => console.warn(`[OperationalInbox kind=${kind} room=${chatroomId2}] startup signal cleanup failed:`, error51));
118459
- }
118460
- runOperationalInboxLoopWithRestart({
118461
- client: wsClient2,
118462
- sessionId: session2.sessionId,
118463
- machineId: session2.machineId,
118464
- chatroomId: chatroomId2,
118465
- feed: operationalSignalFeeds[kind],
118466
- serviceStartedAt,
118467
- initialAfterSignalKey: cursor,
118468
- signal: controller.signal
118469
- }, (update6) => operationalHandler(kind, update6), () => stopped);
118470
- }));
118471
- await session2.taskService.registerTaskChatroom(chatroomId2);
118472
- })();
118473
- return entry.startPromise;
118114
+ const ensureRoom = async (chatroomId) => {
118115
+ if (roomWatchers.has(chatroomId))
118116
+ return;
118117
+ roomWatchers.set(chatroomId, new AbortController);
118118
+ await session2.taskService.registerTaskChatroom(chatroomId);
118474
118119
  };
118475
118120
  const refreshRoomMembership2 = async () => {
118476
118121
  try {
@@ -118481,41 +118126,33 @@ var INBOX_RESTART_INITIAL_MS = 1000, INBOX_RESTART_MAX_MS = 30000, startTaskInbo
118481
118126
  if (stopped)
118482
118127
  return;
118483
118128
  const chatroomIds = [
118484
- ...new Set((workspaces ?? []).map((workspace) => workspace.chatroomId))
118129
+ ...new Set((workspaces ?? []).map((workspace) => String(workspace.chatroomId)))
118485
118130
  ];
118486
118131
  const activeChatroomIds = new Set(chatroomIds);
118487
- for (const [chatroomId2, watcher] of roomWatchers) {
118488
- if (activeChatroomIds.has(chatroomId2))
118132
+ for (const [chatroomId, controller] of roomWatchers) {
118133
+ if (activeChatroomIds.has(chatroomId))
118489
118134
  continue;
118490
- watcher.controller.abort();
118491
- session2.taskService.unregisterTaskChatroom(chatroomId2);
118492
- roomWatchers.delete(chatroomId2);
118493
- knownRoomIds.delete(chatroomId2);
118135
+ controller.abort();
118136
+ session2.taskService.unregisterTaskChatroom(chatroomId);
118137
+ roomWatchers.delete(chatroomId);
118494
118138
  }
118495
- await Promise.all(chatroomIds.map((chatroomId2) => ensureRoomInboxes(chatroomId2)));
118139
+ await Promise.all(chatroomIds.map((chatroomId) => ensureRoom(chatroomId)));
118496
118140
  } catch (error51) {
118497
- console.warn("[TaskInbox] room membership refresh failed:", error51);
118141
+ console.warn("[WorkspaceMembership] room membership refresh failed:", error51);
118498
118142
  }
118499
118143
  };
118500
- registerTaskInboxRoomMembershipRefresh(refreshRoomMembership2);
118144
+ registerWorkspaceMembershipRefresh(refreshRoomMembership2);
118501
118145
  yield* exports_Effect.promise(refreshRoomMembership2);
118502
- yield* exports_Effect.tryPromise(() => Promise.all([...knownRoomIds].map((chatroomId2) => ensureRoomInboxes(chatroomId2)))).pipe(exports_Effect.catchAll((error51) => {
118503
- console.warn("[OperationalInbox] initial watcher start failed:", error51);
118504
- return exports_Effect.void;
118505
- }));
118506
118146
  return {
118507
118147
  nativeDelivery,
118508
118148
  stop() {
118509
118149
  stopped = true;
118510
- abort.abort();
118511
- for (const watcher of roomWatchers.values()) {
118512
- watcher.controller.abort();
118513
- }
118514
- unregisterTaskInboxRoomMembershipRefresh();
118150
+ for (const controller of roomWatchers.values())
118151
+ controller.abort();
118152
+ unregisterWorkspaceMembershipRefresh();
118515
118153
  session2.taskService.stopTaskInbox();
118516
118154
  nativeDelivery.dispose();
118517
118155
  nativeDelivery.agentTaskState.clearAll();
118518
- inboxStore.close();
118519
118156
  }
118520
118157
  };
118521
118158
  });
@@ -118523,11 +118160,6 @@ var init_task_inbox_runtime = __esm(() => {
118523
118160
  init_esm();
118524
118161
  init_daemon_services();
118525
118162
  init_api3();
118526
- init_ack_machine_operational_signals();
118527
- init_fetch_machine_agent_operational_status();
118528
- init_operational_inbox();
118529
- init_operational_signal_feeds();
118530
- init_inbox();
118531
118163
  init_service_interfaces();
118532
118164
  });
118533
118165
 
@@ -118872,11 +118504,11 @@ var init_on_daemon_shutdown = __esm(() => {
118872
118504
  console.log(`[${formatTimestamp()}] Stopping ${activeAgents.length} agent(s) locally...`);
118873
118505
  let totalStopped = 0;
118874
118506
  let totalFailed = 0;
118875
- yield* exports_Effect.all(activeAgents.map(({ chatroomId: chatroomId2, role }) => exports_Effect.promise(() => agentPm.stopAgent({ chatroomId: chatroomId2, role, reason: "daemon.shutdown" })).pipe(exports_Effect.tap(() => exports_Effect.sync(() => {
118507
+ yield* exports_Effect.all(activeAgents.map(({ chatroomId, role }) => exports_Effect.promise(() => agentPm.stopAgent({ chatroomId, role, reason: "daemon.shutdown" })).pipe(exports_Effect.tap(() => exports_Effect.sync(() => {
118876
118508
  totalStopped += 1;
118877
118509
  })), exports_Effect.catchAll((e) => exports_Effect.sync(() => {
118878
118510
  totalFailed += 1;
118879
- console.log(` ⚠️ Failed to stop ${role}@${chatroomId2}: ${e.message}`);
118511
+ console.log(` ⚠️ Failed to stop ${role}@${chatroomId}: ${e.message}`);
118880
118512
  })))), { concurrency: "unbounded" });
118881
118513
  if (totalFailed > 0) {
118882
118514
  console.log(`[${formatTimestamp()}] Shutdown stops: ${totalStopped} stopped, ${totalFailed} failed`);
@@ -119698,15 +119330,15 @@ function startEnhancerJobSubscriber2(deps, onEvent) {
119698
119330
  const onError3 = (err) => {
119699
119331
  console.warn(`[daemon] enhancer-job subscriber error: ${err instanceof Error ? err.message : String(err)}`);
119700
119332
  };
119701
- const watchChatroom = (chatroomId2) => {
119702
- if (watchers.has(chatroomId2) || stopped)
119333
+ const watchChatroom = (chatroomId) => {
119334
+ if (watchers.has(chatroomId) || stopped)
119703
119335
  return;
119704
119336
  const unsub = deps.wsClient.onUpdate(api.daemon.enhancer.index.pendingForChatroom, {
119705
119337
  sessionId: deps.sessionId,
119706
119338
  machineId: deps.machineId,
119707
- chatroomId: chatroomId2
119339
+ chatroomId
119708
119340
  }, onPendingJobs, onError3);
119709
- watchers.set(chatroomId2, unsub);
119341
+ watchers.set(chatroomId, unsub);
119710
119342
  };
119711
119343
  const refreshChatrooms = async () => {
119712
119344
  if (refreshInFlight)
@@ -120026,7 +119658,7 @@ function startAllSubscribers(deps) {
120026
119658
  if (claimed.type === "daemon.workspaceListChanged") {
120027
119659
  enhancerJob.refreshChatrooms();
120028
119660
  gitRequest.refreshWorkspaces();
120029
- refreshTaskInboxRoomMembership();
119661
+ refreshWorkspaceMembership();
120030
119662
  }
120031
119663
  await dispatchCommandInboundEvent({
120032
119664
  type: "command.received",
@@ -120191,10 +119823,10 @@ function queryEventStream(db, input) {
120191
119823
  payload: JSON.parse(row.payload_json)
120192
119824
  }));
120193
119825
  }
120194
- function queryAfterId(db, afterId = 0, limit = 100, source, chatroomId2, role, harness, fromTimestamp, toTimestamp) {
119826
+ function queryAfterId(db, afterId = 0, limit = 100, source, chatroomId, role, harness, fromTimestamp, toTimestamp) {
120195
119827
  const filters = [
120196
119828
  source ? "AND source = ?" : "",
120197
- chatroomId2 ? "AND json_extract(metadata_json, '$.chatroomId') = ?" : "",
119829
+ chatroomId ? "AND json_extract(metadata_json, '$.chatroomId') = ?" : "",
120198
119830
  role ? "AND json_extract(metadata_json, '$.role') = ?" : "",
120199
119831
  harness ? "AND (json_extract(metadata_json, '$.harness') = ? OR source = ?)" : "",
120200
119832
  fromTimestamp !== undefined ? "AND timestamp >= ?" : "",
@@ -120203,7 +119835,7 @@ function queryAfterId(db, afterId = 0, limit = 100, source, chatroomId2, role, h
120203
119835
  const values3 = [
120204
119836
  afterId,
120205
119837
  ...source ? [source] : [],
120206
- ...chatroomId2 ? [chatroomId2] : [],
119838
+ ...chatroomId ? [chatroomId] : [],
120207
119839
  ...role ? [role] : [],
120208
119840
  ...harness ? [harness, `harness:${harness}`] : [],
120209
119841
  ...fromTimestamp !== undefined ? [fromTimestamp] : [],
@@ -120213,11 +119845,11 @@ function queryAfterId(db, afterId = 0, limit = 100, source, chatroomId2, role, h
120213
119845
  const rows = db.prepare(`SELECT * FROM log_entries WHERE id > ? ${filters} ORDER BY id ASC LIMIT ?`).all(...values3);
120214
119846
  return rows.map(map19);
120215
119847
  }
120216
- function queryHistory(db, beforeId, limit = 100, source, chatroomId2, role, harness, fromTimestamp, toTimestamp) {
119848
+ function queryHistory(db, beforeId, limit = 100, source, chatroomId, role, harness, fromTimestamp, toTimestamp) {
120217
119849
  const filters = [
120218
119850
  beforeId ? "AND id < ?" : "",
120219
119851
  source ? "AND source = ?" : "",
120220
- chatroomId2 ? "AND json_extract(metadata_json, '$.chatroomId') = ?" : "",
119852
+ chatroomId ? "AND json_extract(metadata_json, '$.chatroomId') = ?" : "",
120221
119853
  role ? "AND json_extract(metadata_json, '$.role') = ?" : "",
120222
119854
  harness ? "AND (json_extract(metadata_json, '$.harness') = ? OR source = ?)" : "",
120223
119855
  fromTimestamp !== undefined ? "AND timestamp >= ?" : "",
@@ -120226,7 +119858,7 @@ function queryHistory(db, beforeId, limit = 100, source, chatroomId2, role, harn
120226
119858
  const values3 = [
120227
119859
  ...beforeId ? [beforeId] : [],
120228
119860
  ...source ? [source] : [],
120229
- ...chatroomId2 ? [chatroomId2] : [],
119861
+ ...chatroomId ? [chatroomId] : [],
120230
119862
  ...role ? [role] : [],
120231
119863
  ...harness ? [harness, `harness:${harness}`] : [],
120232
119864
  ...fromTimestamp !== undefined ? [fromTimestamp] : [],
@@ -120236,9 +119868,9 @@ function queryHistory(db, beforeId, limit = 100, source, chatroomId2, role, harn
120236
119868
  const rows = db.prepare(`SELECT * FROM log_entries WHERE 1=1 ${filters} ORDER BY id DESC LIMIT ?`).all(...values3);
120237
119869
  return rows.map(map19).reverse();
120238
119870
  }
120239
- function listLogDimensions(db, chatroomId2, limit = 100) {
119871
+ function listLogDimensions(db, chatroomId, limit = 100) {
120240
119872
  const clamped = clamp4(limit);
120241
- const values3 = (sql) => db.prepare(sql).all(chatroomId2, clamped).map((r) => r.v);
119873
+ const values3 = (sql) => db.prepare(sql).all(chatroomId, clamped).map((r) => r.v);
120242
119874
  const roles = values3("SELECT DISTINCT json_extract(metadata_json, '$.role') AS v FROM log_entries WHERE json_extract(metadata_json, '$.chatroomId') = ? AND json_extract(metadata_json, '$.role') IS NOT NULL ORDER BY v LIMIT ?");
120243
119875
  const meta3 = values3("SELECT DISTINCT json_extract(metadata_json, '$.harness') AS v FROM log_entries WHERE json_extract(metadata_json, '$.chatroomId') = ? AND json_extract(metadata_json, '$.harness') IS NOT NULL ORDER BY v LIMIT ?");
120244
119876
  const source = values3("SELECT DISTINCT substr(source, 9) AS v FROM log_entries WHERE json_extract(metadata_json, '$.chatroomId') = ? AND source LIKE 'harness:%' ORDER BY v LIMIT ?");
@@ -120422,17 +120054,17 @@ var init_persistence = __esm(() => {
120422
120054
  // src/daemon/infrastructure/repository/log-repository.ts
120423
120055
  function createLogRepository(db) {
120424
120056
  return {
120425
- queryAfterId(afterId = 0, limit = 100, source, chatroomId2, role, harness, fromTimestamp, toTimestamp) {
120426
- return queryAfterId(db, afterId, limit, source, chatroomId2, role, harness, fromTimestamp, toTimestamp);
120057
+ queryAfterId(afterId = 0, limit = 100, source, chatroomId, role, harness, fromTimestamp, toTimestamp) {
120058
+ return queryAfterId(db, afterId, limit, source, chatroomId, role, harness, fromTimestamp, toTimestamp);
120427
120059
  },
120428
- queryHistory(beforeId, limit = 100, source, chatroomId2, role, harness, fromTimestamp, toTimestamp) {
120429
- return queryHistory(db, beforeId, limit, source, chatroomId2, role, harness, fromTimestamp, toTimestamp);
120060
+ queryHistory(beforeId, limit = 100, source, chatroomId, role, harness, fromTimestamp, toTimestamp) {
120061
+ return queryHistory(db, beforeId, limit, source, chatroomId, role, harness, fromTimestamp, toTimestamp);
120430
120062
  },
120431
120063
  listSources(limit = 100) {
120432
120064
  return listDistinctSources(db, limit);
120433
120065
  },
120434
- listDimensions(chatroomId2, limit = 100) {
120435
- return listLogDimensions(db, chatroomId2, limit);
120066
+ listDimensions(chatroomId, limit = 100) {
120067
+ return listLogDimensions(db, chatroomId, limit);
120436
120068
  },
120437
120069
  writeChatroomEvent(event) {
120438
120070
  return appendChatroomEvent(db, event);
@@ -134244,8 +133876,8 @@ function listLogHistory(reader, input) {
134244
133876
  const entries2 = input.afterId !== undefined ? reader.queryAfterId(input.afterId, limit, input.source, input.chatroomId, input.role, input.harness, input.fromTimestamp, input.toTimestamp) : reader.queryHistory(input.beforeId, limit, input.source, input.chatroomId, input.role, input.harness, input.fromTimestamp, input.toTimestamp);
134245
133877
  return { entries: entries2 };
134246
133878
  }
134247
- function listLogDimensions2(reader, chatroomId2, limit = 100) {
134248
- return reader.listDimensions ? reader.listDimensions(chatroomId2, limit) : { roles: [], harnesses: [] };
133879
+ function listLogDimensions2(reader, chatroomId, limit = 100) {
133880
+ return reader.listDimensions ? reader.listDimensions(chatroomId, limit) : { roles: [], harnesses: [] };
134249
133881
  }
134250
133882
  function listLogSources(reader, limit = 100) {
134251
133883
  return { sources: reader.listSources(limit) };
@@ -135463,7 +135095,7 @@ handoffCommandGroup.option("--chatroom-id <id>", "Chatroom identifier").option("
135463
135095
  console.error(`error: required option '${flag} <...>' not specified`);
135464
135096
  process.exit(1);
135465
135097
  }
135466
- const { chatroomId: chatroomId2, role, nextRole } = options;
135098
+ const { chatroomId, role, nextRole } = options;
135467
135099
  await maybeRequireAuth();
135468
135100
  const { decode: decode6 } = await Promise.resolve().then(() => exports_decode);
135469
135101
  const stdinContent = await readStdin();
@@ -135482,7 +135114,7 @@ handoffCommandGroup.option("--chatroom-id <id>", "Chatroom identifier").option("
135482
135114
  process.exit(1);
135483
135115
  }
135484
135116
  const { handoff: handoff2 } = await Promise.resolve().then(() => (init_handoff(), exports_handoff));
135485
- await handoff2(chatroomId2, {
135117
+ await handoff2(chatroomId, {
135486
135118
  role,
135487
135119
  message,
135488
135120
  nextRole
@@ -135806,18 +135438,18 @@ registerChatroomRoleCommand(program2, {
135806
135438
  name: "get-system-prompt",
135807
135439
  description: "Fetch the system prompt for your role in a chatroom",
135808
135440
  maybeRequireAuth,
135809
- run: async (chatroomId2, { role }) => {
135441
+ run: async (chatroomId, { role }) => {
135810
135442
  const { getSystemPrompt: getSystemPrompt2 } = await Promise.resolve().then(() => (init_get_system_prompt(), exports_get_system_prompt));
135811
- await getSystemPrompt2(chatroomId2, { role });
135443
+ await getSystemPrompt2(chatroomId, { role });
135812
135444
  }
135813
135445
  });
135814
135446
  registerChatroomRoleCommand(program2, {
135815
135447
  name: "get-role-guidance",
135816
135448
  description: "Fetch role-specific operating-model guidance for your role in a chatroom",
135817
135449
  maybeRequireAuth,
135818
- run: async (chatroomId2, { role }) => {
135450
+ run: async (chatroomId, { role }) => {
135819
135451
  const { getRoleGuidance: getRoleGuidance2 } = await Promise.resolve().then(() => (init_get_role_guidance(), exports_get_role_guidance));
135820
- await getRoleGuidance2(chatroomId2, { role });
135452
+ await getRoleGuidance2(chatroomId, { role });
135821
135453
  }
135822
135454
  });
135823
135455
  var telegramCommand = program2.command("telegram").description("Telegram integration commands");
@@ -135852,9 +135484,9 @@ opencodeCommand.command("install").description("Install chatroom as an OpenCode
135852
135484
  });
135853
135485
  program2.hook("preAction", async (_thisCommand, actionCommand) => {
135854
135486
  const opts = actionCommand.opts();
135855
- const chatroomId2 = opts["chatroomId"];
135487
+ const chatroomId = opts["chatroomId"];
135856
135488
  const role = opts["role"];
135857
- if (!chatroomId2 || !role)
135489
+ if (!chatroomId || !role)
135858
135490
  return;
135859
135491
  const { getSessionId: getSessionId2 } = await Promise.resolve().then(() => (init_storage(), exports_storage));
135860
135492
  const { getConvexClient: getConvexClient2 } = await Promise.resolve().then(() => (init_client2(), exports_client));
@@ -135863,8 +135495,8 @@ program2.hook("preAction", async (_thisCommand, actionCommand) => {
135863
135495
  if (!sessionId)
135864
135496
  return;
135865
135497
  const client4 = await getConvexClient2();
135866
- sendLifecycleHeartbeat2(client4, { sessionId, chatroomId: chatroomId2, role });
135498
+ sendLifecycleHeartbeat2(client4, { sessionId, chatroomId, role });
135867
135499
  });
135868
135500
  program2.parse();
135869
135501
 
135870
- //# debugId=2166B04C5CAC31EC64756E2164756E21
135502
+ //# debugId=CAC291D8342AA60364756E2164756E21