@sema-agent/cli 1.0.123 → 1.0.124

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/sema-main.js CHANGED
@@ -4320,6 +4320,29 @@ var init_unrefTimer = __esm({
4320
4320
  }
4321
4321
  });
4322
4322
 
4323
+ // node_modules/@sema-agent/client-core/dist/panelRunningHistory.js
4324
+ function notePanelRowRunning(taskId) {
4325
+ if (!ids.has(taskId) && (ids.add(taskId), ids.size > 4096)) {
4326
+ overflowed = !0;
4327
+ let oldest = ids.values().next().value;
4328
+ oldest !== void 0 && ids.delete(oldest);
4329
+ }
4330
+ }
4331
+ function retirePanelRowRunning(taskId) {
4332
+ ids.delete(taskId);
4333
+ }
4334
+ function panelRowNeverPublishedRunning(taskId) {
4335
+ return !overflowed && !ids.has(taskId);
4336
+ }
4337
+ function __resetPanelRunningHistoryForTests() {
4338
+ ids.clear(), overflowed = !1;
4339
+ }
4340
+ var ids, overflowed, init_panelRunningHistory = __esm({
4341
+ "node_modules/@sema-agent/client-core/dist/panelRunningHistory.js"() {
4342
+ ids = /* @__PURE__ */ new Set(), overflowed = !1;
4343
+ }
4344
+ });
4345
+
4323
4346
  // node_modules/@sema-agent/client-core/dist/engineAgentPanelStore.js
4324
4347
  function markEnginePanelTaskResident(taskId) {
4325
4348
  residentTaskIds.add(taskId);
@@ -4331,7 +4354,14 @@ function isEnginePanelTaskResident(taskId) {
4331
4354
  return residentTaskIds.has(taskId);
4332
4355
  }
4333
4356
  function launchAnchorChanged(prev, next) {
4334
- return prev.kind !== "fleet-row" || next.kind !== "fleet-row" ? !1 : prev.cycleSeq !== void 0 && next.cycleSeq !== void 0 && prev.cycleSeq !== next.cycleSeq ? !0 : prev.startedAt !== void 0 && next.startedAt !== void 0 && prev.startedAt !== next.startedAt;
4357
+ return prev.kind !== "fleet-row" || next.kind !== "fleet-row" ? !1 : isNewEngineAgentPanelCycle(prev, next);
4358
+ }
4359
+ function isNewEngineAgentPanelCycle(prev, next) {
4360
+ let pc = cycleSeqOf(prev), nc = cycleSeqOf(next);
4361
+ if (pc !== void 0 && nc !== void 0)
4362
+ return pc !== nc;
4363
+ let ps = startedAtOf(prev), ns = startedAtOf(next);
4364
+ return ps !== void 0 && ns !== void 0 && ps !== ns;
4335
4365
  }
4336
4366
  function cycleSeqOf(v2) {
4337
4367
  let n2 = v2?.cycleSeq;
@@ -4348,6 +4378,51 @@ function isStaleEngineAgentPanelEnd(end, current6) {
4348
4378
  let es = startedAtOf(end), cs = startedAtOf(current6);
4349
4379
  return es !== void 0 && cs !== void 0 ? es < cs : !1;
4350
4380
  }
4381
+ function bounded(map2, key, value) {
4382
+ if (map2.delete(key), map2.set(key, value), map2.size > MAX_IDENTITY_KEYS) {
4383
+ let oldest = map2.keys().next().value;
4384
+ oldest !== void 0 && map2.delete(oldest);
4385
+ }
4386
+ }
4387
+ function boundedOwnership(map2, key, value) {
4388
+ if (map2.delete(key), map2.set(key, value), map2.size <= MAX_OWNERSHIP_KEYS)
4389
+ return;
4390
+ for (let [k2, v2] of map2)
4391
+ if (v2.retired) {
4392
+ map2.delete(k2);
4393
+ return;
4394
+ }
4395
+ let oldest = map2.keys().next().value;
4396
+ oldest !== void 0 && map2.delete(oldest);
4397
+ }
4398
+ function notePublishedWire(ev) {
4399
+ boundedOwnership(publishedWireIds, ev.taskId, { retired: publishedWireIds.get(ev.taskId)?.retired ?? !1 }), ev.parentToolCallId !== void 0 && ev.parentToolCallId.length > 0 && bounded(publishedWireByParent, ev.parentToolCallId, ev.taskId);
4400
+ }
4401
+ function retireWire(wireId) {
4402
+ let w2 = publishedWireIds.get(wireId);
4403
+ w2 !== void 0 && (w2.retired = !0);
4404
+ for (let o of wireIdByFleetId.values())
4405
+ o.wireId === wireId && (o.retired = !0);
4406
+ }
4407
+ function publishedWireFor(ev) {
4408
+ if (ev.transcriptId !== void 0 && publishedWireIds.has(ev.transcriptId))
4409
+ return ev.transcriptId;
4410
+ if (ev.parentToolCallId !== void 0) {
4411
+ let u = publishedWireByParent.get(ev.parentToolCallId);
4412
+ if (u !== void 0 && publishedWireIds.get(u)?.retired === !1)
4413
+ return u;
4414
+ }
4415
+ }
4416
+ function wireOwnerOf(fleetId, current6, transcriptId) {
4417
+ let o = wireIdByFleetId.get(fleetId);
4418
+ if (o === void 0)
4419
+ return;
4420
+ if (transcriptId !== void 0 && transcriptId !== (o.transcriptId ?? o.wireId) || current6 !== void 0 && isStaleEngineAgentPanelEnd(o, current6)) {
4421
+ wireIdByFleetId.delete(fleetId), retireWire(o.wireId);
4422
+ return;
4423
+ }
4424
+ return o.wireId;
4425
+ }
4351
4426
  function remember(map2, key, alias2) {
4352
4427
  if (map2.delete(key), map2.set(key, alias2), map2.size > MAX_IDENTITY_KEYS) {
4353
4428
  let oldest = map2.keys().next().value;
@@ -4389,27 +4464,47 @@ function normalizedTick(ev, fleetId) {
4389
4464
  }
4390
4465
  function asIsTick(ev) {
4391
4466
  let { cardBound: _cardBound, ...rest } = ev;
4392
- return { ...rest, taskIdOrigin: "wire" };
4467
+ return notePublishedWire(ev), { ...rest, taskIdOrigin: "wire" };
4468
+ }
4469
+ function staleWireTick(id) {
4470
+ return isStaleEngineAgentPanelEnd(id, latestCycleByFleetId.get(id.taskId));
4393
4471
  }
4394
4472
  function flushHeld(wireTaskId) {
4395
4473
  let held = heldWireTicks.get(wireTaskId);
4396
4474
  if (held === void 0)
4397
4475
  return;
4398
- heldWireTicks.delete(wireTaskId);
4476
+ if (heldWireTicks.delete(wireTaskId), publishedWireIds.has(held.ev.taskId)) {
4477
+ deliverEngineAgentPanelEvent(asIsTick(held.ev));
4478
+ return;
4479
+ }
4399
4480
  let id = resolveEnginePanelTaskId(held.ev.taskId, held.ev.parentToolCallId);
4400
- id.origin === "fleet-row" && rememberResolvedWire(held.ev.taskId, id), deliverEngineAgentPanelEvent(id.origin === "fleet-row" ? normalizedTick(held.ev, id.taskId) : asIsTick(held.ev));
4481
+ if (id.origin === "fleet-row") {
4482
+ if (staleWireTick(id))
4483
+ return;
4484
+ rememberResolvedWire(held.ev.taskId, id), deliverEngineAgentPanelEvent(normalizedTick(held.ev, id.taskId));
4485
+ return;
4486
+ }
4487
+ deliverEngineAgentPanelEvent(asIsTick(held.ev));
4401
4488
  }
4402
- function clearEnginePanelTaskResidentByWire(wireTaskId) {
4489
+ function clearEnginePanelTaskResidentByWire(wireTaskId, cycle) {
4403
4490
  residentTaskIds.delete(wireTaskId);
4491
+ let owner = wireIdByFleetId.get(wireTaskId);
4492
+ owner !== void 0 && !(cycle !== void 0 && isStaleEngineAgentPanelEnd(cycle, owner)) && residentTaskIds.delete(owner.wireId);
4404
4493
  let id = resolveEnginePanelTaskId(wireTaskId);
4405
4494
  id.taskId !== wireTaskId && (isStaleEngineAgentPanelEnd(id, latestCycleByFleetId.get(id.taskId)) || residentTaskIds.delete(id.taskId));
4406
4495
  }
4407
4496
  function __resetEngineAgentPanelIdentityForTests() {
4408
- fleetIdByTranscriptId.clear(), fleetIdByParentToolCallId.clear(), heldWireTicks.clear(), latestCycleByFleetId.clear();
4497
+ fleetIdByTranscriptId.clear(), fleetIdByParentToolCallId.clear(), heldWireTicks.clear(), latestCycleByFleetId.clear(), publishedWireIds.clear(), publishedWireByParent.clear(), wireIdByFleetId.clear();
4409
4498
  }
4410
4499
  function publishEngineAgentPanelEvent(ev) {
4411
4500
  switch ((ev.kind === "end" || ev.kind === "sweep") && ageHeld(ev.kind === "sweep" ? void 0 : ev.taskId), ev.kind) {
4412
4501
  case "fleet-row": {
4502
+ let rowCycle = { ...ev.cycleSeq !== void 0 ? { cycleSeq: ev.cycleSeq } : {}, ...ev.startedAt !== void 0 ? { startedAt: ev.startedAt } : {} }, published = wireOwnerOf(ev.taskId, rowCycle, ev.transcriptId) ?? publishedWireFor(ev);
4503
+ if (published !== void 0 && published !== ev.taskId) {
4504
+ let prev = wireIdByFleetId.get(ev.taskId);
4505
+ boundedOwnership(wireIdByFleetId, ev.taskId, { wireId: published, retired: prev?.wireId === published ? prev.retired : !1, ...ev.transcriptId !== void 0 ? { transcriptId: ev.transcriptId } : prev?.transcriptId !== void 0 ? { transcriptId: prev.transcriptId } : {}, ...rowCycle }), deliverEngineAgentPanelEvent({ ...ev, taskId: published, wireTaskId: ev.taskId, taskIdOrigin: "wire" }), ageHeld(void 0);
4506
+ return;
4507
+ }
4413
4508
  let alias2 = {
4414
4509
  fleetId: ev.taskId,
4415
4510
  ...ev.cycleSeq !== void 0 ? { cycleSeq: ev.cycleSeq } : {},
@@ -4426,9 +4521,15 @@ function publishEngineAgentPanelEvent(ev) {
4426
4521
  return;
4427
4522
  }
4428
4523
  case "tick": {
4524
+ if (publishedWireIds.has(ev.taskId)) {
4525
+ heldWireTicks.delete(ev.taskId), deliverEngineAgentPanelEvent(asIsTick(ev));
4526
+ return;
4527
+ }
4429
4528
  let id = resolveEnginePanelTaskId(ev.taskId, ev.parentToolCallId);
4430
4529
  if (id.origin === "fleet-row") {
4431
- heldWireTicks.delete(ev.taskId), rememberResolvedWire(ev.taskId, id), deliverEngineAgentPanelEvent(normalizedTick(ev, id.taskId));
4530
+ if (heldWireTicks.delete(ev.taskId), staleWireTick(id))
4531
+ return;
4532
+ rememberResolvedWire(ev.taskId, id), deliverEngineAgentPanelEvent(normalizedTick(ev, id.taskId));
4432
4533
  return;
4433
4534
  }
4434
4535
  if (ev.cardBound === !0) {
@@ -4447,9 +4548,28 @@ function publishEngineAgentPanelEvent(ev) {
4447
4548
  return;
4448
4549
  }
4449
4550
  case "end": {
4551
+ let wireOwner = wireOwnerOf(ev.taskId, ev);
4552
+ if (wireOwner !== void 0) {
4553
+ let ownerRec = wireIdByFleetId.get(ev.taskId);
4554
+ deliverEngineAgentPanelEvent({ ...ev, taskId: wireOwner, wireTaskId: ev.taskId, taskIdOrigin: "wire" }), isStaleEngineAgentPanelEnd(ev, ownerRec) || (retireWire(wireOwner), retirePanelRowRunning(ev.taskId), retirePanelRowRunning(wireOwner));
4555
+ return;
4556
+ }
4557
+ if (publishedWireIds.has(ev.taskId)) {
4558
+ flushHeld(ev.taskId), deliverEngineAgentPanelEvent(ev), retireWire(ev.taskId), retirePanelRowRunning(ev.taskId);
4559
+ for (let [fleetId, o] of wireIdByFleetId)
4560
+ o.wireId === ev.taskId && !isStaleEngineAgentPanelEnd(ev, o) && retirePanelRowRunning(fleetId);
4561
+ let alias2 = fleetIdByTranscriptId.get(ev.taskId);
4562
+ alias2 !== void 0 && !isStaleEngineAgentPanelEnd(ev, alias2) && retirePanelRowRunning(alias2.fleetId);
4563
+ return;
4564
+ }
4450
4565
  let id = resolveEnginePanelTaskId(ev.taskId);
4451
4566
  if (id.origin === "fleet-row" && id.taskId !== ev.taskId) {
4452
- flushHeld(ev.taskId), migrateResidency(ev.taskId, id.taskId), deliverEngineAgentPanelEvent({
4567
+ flushHeld(ev.taskId), migrateResidency(ev.taskId, id.taskId);
4568
+ let effectiveEnd = {
4569
+ ...ev.cycleSeq !== void 0 ? { cycleSeq: ev.cycleSeq } : id.cycleSeq !== void 0 ? { cycleSeq: id.cycleSeq } : {},
4570
+ ...ev.startedAt !== void 0 ? { startedAt: ev.startedAt } : id.startedAt !== void 0 ? { startedAt: id.startedAt } : {}
4571
+ };
4572
+ isStaleEngineAgentPanelEnd(effectiveEnd, latestCycleByFleetId.get(id.taskId)) || retirePanelRowRunning(id.taskId), deliverEngineAgentPanelEvent({
4453
4573
  ...ev,
4454
4574
  taskId: id.taskId,
4455
4575
  wireTaskId: ev.taskId,
@@ -4460,7 +4580,7 @@ function publishEngineAgentPanelEvent(ev) {
4460
4580
  });
4461
4581
  return;
4462
4582
  }
4463
- flushHeld(ev.taskId), deliverEngineAgentPanelEvent(ev);
4583
+ flushHeld(ev.taskId), deliverEngineAgentPanelEvent(ev), retireWire(ev.taskId), isStaleEngineAgentPanelEnd(ev, latestCycleByFleetId.get(ev.taskId)) || retirePanelRowRunning(ev.taskId);
4464
4584
  return;
4465
4585
  }
4466
4586
  default:
@@ -4526,7 +4646,8 @@ function subscribeEngineAgentPanel(fn2) {
4526
4646
  };
4527
4647
  }
4528
4648
  function publishEngineAgentPanelAbsence(ev) {
4529
- if (absenceListener) {
4649
+ let owner = wireOwnerOf(ev.taskId);
4650
+ if (owner !== void 0 && (ev = { ...ev, taskId: owner, wireTaskId: ev.taskId }), absenceListener) {
4530
4651
  try {
4531
4652
  absenceListener(ev);
4532
4653
  } catch {
@@ -4555,14 +4676,15 @@ function subscribeEngineAgentPanelAbsence(fn2) {
4555
4676
  function __resetEngineAgentPanelAbsenceForTests() {
4556
4677
  absenceListener = null, absenceBuffer.clear();
4557
4678
  }
4558
- var PANEL_TOOLUSES_LANE_POLICY, residentTaskIds, MAX_BUFFER, listener, buffer, MAX_IDENTITY_KEYS, MAX_HELD_WIRE_TICKS, MAX_HELD_WIRE_TICK_BEATS, fleetIdByTranscriptId, fleetIdByParentToolCallId, heldWireTicks, latestCycleByFleetId, MAX_ABSENCE_BUFFER, absenceListener, absenceBuffer, init_engineAgentPanelStore = __esm({
4679
+ var PANEL_TOOLUSES_LANE_POLICY, residentTaskIds, MAX_BUFFER, listener, buffer, MAX_IDENTITY_KEYS, MAX_HELD_WIRE_TICKS, MAX_HELD_WIRE_TICK_BEATS, fleetIdByTranscriptId, fleetIdByParentToolCallId, heldWireTicks, latestCycleByFleetId, MAX_OWNERSHIP_KEYS, publishedWireIds, publishedWireByParent, wireIdByFleetId, MAX_ABSENCE_BUFFER, absenceListener, absenceBuffer, init_engineAgentPanelStore = __esm({
4559
4680
  "node_modules/@sema-agent/client-core/dist/engineAgentPanelStore.js"() {
4681
+ init_panelRunningHistory();
4560
4682
  PANEL_TOOLUSES_LANE_POLICY = {
4561
4683
  tick: "required-engine-always-emits",
4562
4684
  "fleet-row": "optional-tolerate-absent"
4563
4685
  }, residentTaskIds = /* @__PURE__ */ new Set();
4564
4686
  MAX_BUFFER = 200, listener = null, buffer = [];
4565
- MAX_IDENTITY_KEYS = 2048, MAX_HELD_WIRE_TICKS = 64, MAX_HELD_WIRE_TICK_BEATS = 16, fleetIdByTranscriptId = /* @__PURE__ */ new Map(), fleetIdByParentToolCallId = /* @__PURE__ */ new Map(), heldWireTicks = /* @__PURE__ */ new Map(), latestCycleByFleetId = /* @__PURE__ */ new Map();
4687
+ MAX_IDENTITY_KEYS = 2048, MAX_HELD_WIRE_TICKS = 64, MAX_HELD_WIRE_TICK_BEATS = 16, fleetIdByTranscriptId = /* @__PURE__ */ new Map(), fleetIdByParentToolCallId = /* @__PURE__ */ new Map(), heldWireTicks = /* @__PURE__ */ new Map(), latestCycleByFleetId = /* @__PURE__ */ new Map(), MAX_OWNERSHIP_KEYS = 8192, publishedWireIds = /* @__PURE__ */ new Map(), publishedWireByParent = /* @__PURE__ */ new Map(), wireIdByFleetId = /* @__PURE__ */ new Map();
4566
4688
  MAX_ABSENCE_BUFFER = 200, absenceListener = null, absenceBuffer = /* @__PURE__ */ new Map();
4567
4689
  }
4568
4690
  });
@@ -5102,7 +5224,7 @@ function enqueueBgChildNotification(n2) {
5102
5224
  let terminal = isTaskNotificationTerminalStatus(n2.status);
5103
5225
  if (terminal && (markRunNotified(n2.taskId, cycle), cardEnqueuedRunIds.add(n2.taskId)), terminal)
5104
5226
  try {
5105
- clearEnginePanelTaskResident(n2.taskId), publishEngineAgentPanelEvent({
5227
+ clearEnginePanelTaskResidentByWire(n2.taskId, typeof n2.seq == "number" && Number.isInteger(n2.seq) && n2.seq >= BG_FIRST_SEQ ? { cycleSeq: n2.seq } : void 0), publishEngineAgentPanelEvent({
5106
5228
  kind: "end",
5107
5229
  taskId: n2.taskId,
5108
5230
  // L-215②(0.65.0):读**单铸谓词**而不是内联两词 —— 修前这里只认 `failed`/`killed`,
@@ -7769,9 +7891,9 @@ function rememberSegment(s, text2) {
7769
7891
  function scheduleNotify(taskId) {
7770
7892
  pendingNotify.add(taskId), !notifyTimer && (notifyTimer = setTimeout(() => {
7771
7893
  notifyTimer = null;
7772
- let ids = [...pendingNotify];
7894
+ let ids2 = [...pendingNotify];
7773
7895
  if (pendingNotify.clear(), !!notifyListener)
7774
- for (let id of ids)
7896
+ for (let id of ids2)
7775
7897
  try {
7776
7898
  notifyListener(id);
7777
7899
  } catch {
@@ -9343,7 +9465,7 @@ function seenFor(sessionKey) {
9343
9465
  return m2 || (m2 = /* @__PURE__ */ new Map(), seen.set(sessionKey, m2)), m2;
9344
9466
  }
9345
9467
  function resetFleetAgentPanelProjection() {
9346
- seen.clear();
9468
+ seen.clear(), __resetPanelRunningHistoryForTests();
9347
9469
  }
9348
9470
  function resetFleetAgentPanelProjectionFor(sessionKey) {
9349
9471
  seen.delete(sessionKey);
@@ -9372,7 +9494,8 @@ function projectFleetAgentRowsFor(sessionKey, rows3, nowMs2 = Date.now()) {
9372
9494
  let rowNewerCycle = prev !== void 0 && isStaleEngineAgentPanelEnd(prevIdentity, rowIdentity), sameCycle = prev !== void 0 && !prev.settled && (startedAt === void 0 || prev.startedAt === void 0 || prev.startedAt === startedAt) && // 0.74.0:代际号变了同样是新周期(两条都报了才比;任一条没报 = 这一帧没说)
9373
9495
  (cycleSeq === void 0 || prev.cycleSeq === void 0 || prev.cycleSeq === cycleSeq), knownTokens = tokens !== void 0 ? tokens : sameCycle ? prev?.tokens : void 0, carryIdentity = prev !== void 0 && !rowNewerCycle, knownStartedAt = startedAt !== void 0 ? startedAt : carryIdentity ? prev.startedAt : void 0, knownCycleSeq = cycleSeq !== void 0 ? cycleSeq : carryIdentity ? prev.cycleSeq : void 0;
9374
9496
  if (TERMINAL_FLEET_TASK_STATUSES.has(status3)) {
9375
- prev?.settled === !0 && !rowNewerCycle || // 0.74.0:周期身份本身推进(或首帧就带身份)也是变化 —— 消费端要先记下身份才能对 end 判陈旧。
9497
+ let newbornTerminal = prev === void 0 && panelRowNeverPublishedRunning(taskId);
9498
+ !(prev?.settled === !0 && !rowNewerCycle) && !newbornTerminal && // 0.74.0:周期身份本身推进(或首帧就带身份)也是变化 —— 消费端要先记下身份才能对 end 判陈旧。
9376
9499
  ((rowNewerCycle || cycleSeq !== void 0 && prev?.cycleSeq !== cycleSeq || // 含首帧(prev 缺席)就带身份的终态
9377
9500
  // 最终用量也算(终态帧常是唯一带全 usage 的一帧;消费端不更新非 running 行 ⇒ 必须赶在 end 之前发)
9378
9501
  tokens !== void 0 && prev?.tokens !== tokens || toolUses !== void 0 && prev?.toolUses !== toolUses || transcriptId !== void 0 && prev?.transcriptId !== transcriptId || parentToolCallId !== void 0 && prev?.parentToolCallId !== parentToolCallId || startedAt !== void 0 && prev?.startedAt !== startedAt) && publishEngineAgentPanelEvent({
@@ -9414,7 +9537,7 @@ function projectFleetAgentRowsFor(sessionKey, rows3, nowMs2 = Date.now()) {
9414
9537
  continue;
9415
9538
  }
9416
9539
  (!prev || prev.settled || prev.absentReportedAtMs !== void 0 || // 行回来了:即使值未变也发一条,消费端据此撤掉 absent 标
9417
- prev.status !== status3 || prev.tokens !== knownTokens || toolUses !== void 0 && prev.toolUses !== toolUses || transcriptId !== void 0 && prev.transcriptId !== transcriptId || parentToolCallId !== void 0 && prev.parentToolCallId !== parentToolCallId || startedAt !== void 0 && prev.startedAt !== startedAt || cycleSeq !== void 0 && prev.cycleSeq !== cycleSeq || currentToolKey !== void 0 && prev.currentToolKey !== currentToolKey) && publishEngineAgentPanelEvent({
9540
+ prev.status !== status3 || prev.tokens !== knownTokens || toolUses !== void 0 && prev.toolUses !== toolUses || transcriptId !== void 0 && prev.transcriptId !== transcriptId || parentToolCallId !== void 0 && prev.parentToolCallId !== parentToolCallId || startedAt !== void 0 && prev.startedAt !== startedAt || cycleSeq !== void 0 && prev.cycleSeq !== cycleSeq || currentToolKey !== void 0 && prev.currentToolKey !== currentToolKey) && (notePanelRowRunning(taskId), publishEngineAgentPanelEvent({
9418
9541
  kind: "fleet-row",
9419
9542
  taskId,
9420
9543
  ...row2.name ? { name: row2.name } : {},
@@ -9427,7 +9550,7 @@ function projectFleetAgentRowsFor(sessionKey, rows3, nowMs2 = Date.now()) {
9427
9550
  ...knownStartedAt !== void 0 ? { startedAt: knownStartedAt } : {},
9428
9551
  ...knownCycleSeq !== void 0 ? { cycleSeq: knownCycleSeq } : {},
9429
9552
  ...currentTool !== void 0 ? { currentTool } : {}
9430
- }), seenMap.set(taskId, {
9553
+ })), seenMap.set(taskId, {
9431
9554
  status: status3,
9432
9555
  tokens: knownTokens,
9433
9556
  toolUses: toolUses !== void 0 ? toolUses : prev?.toolUses,
@@ -9461,6 +9584,7 @@ function projectFleetAgentRowsFor(sessionKey, rows3, nowMs2 = Date.now()) {
9461
9584
  var ABSENT_SETTLE_MS, SETTLED_RETENTION_MS, seen, init_fleetAgentPanelProjection = __esm({
9462
9585
  "node_modules/@sema-agent/client-core/dist/fleetAgentPanelProjection.js"() {
9463
9586
  init_engineAgentPanelStore();
9587
+ init_panelRunningHistory();
9464
9588
  init_workflow();
9465
9589
  init_fleetProjection();
9466
9590
  init_sessionSlot();
@@ -10431,10 +10555,17 @@ var LEADER_RUN_STATUSES, LEADER_REJ_HEAD_DISPLAY_MAX, DETAIL_FILES_MAX, DETAIL_P
10431
10555
  function nonNegFinite(v2) {
10432
10556
  return typeof v2 == "number" && Number.isFinite(v2) && v2 >= 0 ? v2 : void 0;
10433
10557
  }
10558
+ function runResultHolder(r) {
10559
+ let inner = r.result;
10560
+ if (inner === null || typeof inner != "object" || Array.isArray(inner))
10561
+ return r;
10562
+ let o = inner;
10563
+ return Object.hasOwn(o, "terminal") || Object.hasOwn(o, "status") || Object.hasOwn(o, "cancelContext") ? o : r;
10564
+ }
10434
10565
  function readRunCancelContext(record3) {
10435
10566
  if (record3 === null || typeof record3 != "object")
10436
10567
  return;
10437
- let r = record3, holder = r.result !== null && typeof r.result == "object" ? r.result : r;
10568
+ let holder = runResultHolder(record3);
10438
10569
  if (!Object.hasOwn(holder, "cancelContext") || holder.cancelContext === void 0)
10439
10570
  return { kind: "not_reported" };
10440
10571
  let c3 = holder.cancelContext;
@@ -10454,7 +10585,7 @@ function readRunCancelContext(record3) {
10454
10585
  function classifyRunAbortCause(record3) {
10455
10586
  if (record3 === null || typeof record3 != "object")
10456
10587
  return { kind: "unknown" };
10457
- let r = record3, status3 = typeof r.status == "string" && r.status.length > 0 ? r.status : void 0, holder = r.result !== null && typeof r.result == "object" ? r.result : record3, read = readRunTerminal(holder);
10588
+ let r = record3, status3 = typeof r.status == "string" && r.status.length > 0 ? r.status : void 0, read = readRunTerminal(runResultHolder(r));
10458
10589
  if (read !== null && read.kind === "failed") {
10459
10590
  if (read.code === RUN_CANCELLED_CODE) {
10460
10591
  let cc = readRunCancelContext(record3);
@@ -11061,7 +11192,7 @@ function eventToSdkMessage(ev, ctx) {
11061
11192
  // 臂上**还没有座位** ⇒ 这里是防御 raw 读(同 `label` / `model` 的既有姿势)。退役条件 =
11062
11193
  // sdk 补上该位的当天,`run-compaction-boundary-projection-test.mjs` F10 行当场红逼复核。
11063
11194
  case "compacted": {
11064
- let raw2 = ev, attachedFiles = raw2.attachedFiles, seg = raw2.preserved_segment, firstKeptEntryId = typeof seg == "object" && seg !== null && !Array.isArray(seg) ? seg.firstKeptEntryId : void 0, clampedRatio = raw2.clampedRatio;
11195
+ let raw2 = ev, freedTokens = typeof raw2.freedTokens == "number" && Number.isFinite(raw2.freedTokens) && raw2.freedTokens >= 0 ? raw2.freedTokens : void 0, attachedFiles = raw2.attachedFiles, seg = raw2.preserved_segment, firstKeptEntryId = typeof seg == "object" && seg !== null && !Array.isArray(seg) ? seg.firstKeptEntryId : void 0, clampedRatio = raw2.clampedRatio;
11065
11196
  return projected(stamp(ctx, {
11066
11197
  type: "system",
11067
11198
  subtype: "compact_boundary",
@@ -11073,7 +11204,8 @@ function eventToSdkMessage(ev, ctx) {
11073
11204
  trigger: typeof ev.trigger == "string" && ev.trigger.length > 0 ? ev.trigger : "auto",
11074
11205
  pre_tokens: ev.tokensBefore ?? 0,
11075
11206
  ...typeof firstKeptEntryId == "string" && firstKeptEntryId.length > 0 ? { _sema_preserved_segment: { firstKeptEntryId } } : {},
11076
- ...typeof clampedRatio == "number" && Number.isFinite(clampedRatio) ? { _sema_clamped_ratio: clampedRatio } : {}
11207
+ ...typeof clampedRatio == "number" && Number.isFinite(clampedRatio) ? { _sema_clamped_ratio: clampedRatio } : {},
11208
+ ...freedTokens !== void 0 ? { _sema_freed_tokens: freedTokens } : {}
11077
11209
  },
11078
11210
  ...Array.isArray(attachedFiles) && attachedFiles.length > 0 ? { attachedFiles } : {}
11079
11211
  }));
@@ -13055,11 +13187,11 @@ function toolNameKey(name) {
13055
13187
  function classifierDenyDisplay(toolName2, args) {
13056
13188
  let fallback = toolName2.length > 0 ? toolName2 : "tool", key = DISPLAY_ARG_KEY_BY_TOOL.get(toolNameKey(toolName2));
13057
13189
  if (key === void 0 || args === null || typeof args != "object")
13058
- return bounded(fallback);
13190
+ return bounded2(fallback);
13059
13191
  let raw2 = args[key];
13060
- return typeof raw2 != "string" || raw2.trim().length === 0 ? bounded(fallback) : bounded(raw2);
13192
+ return typeof raw2 != "string" || raw2.trim().length === 0 ? bounded2(fallback) : bounded2(raw2);
13061
13193
  }
13062
- function bounded(s) {
13194
+ function bounded2(s) {
13063
13195
  if (s.length <= CLASSIFIER_DENY_DISPLAY_MAX)
13064
13196
  return s;
13065
13197
  let keep = CLASSIFIER_DENY_DISPLAY_MAX - 1, cut = s.slice(0, keep), last4 = cut.charCodeAt(cut.length - 1), next = s.charCodeAt(keep);
@@ -20490,6 +20622,25 @@ var DEFAULT_DENY_REASON, MAX_DENY_REASON_CHARS, PLAN_REVIEW_MODE_AFTER_WORDS, Hi
20490
20622
  }
20491
20623
  });
20492
20624
 
20625
+ // node_modules/@sema-agent/client-core/dist/hitl/approvalOutcomeNote.js
20626
+ function nonEmpty4(v2) {
20627
+ return typeof v2 == "string" && v2.length > 0 ? v2 : void 0;
20628
+ }
20629
+ function approvalOutcomeNoteOf(frame, outcome) {
20630
+ let retracted = outcome.retracted === !0, refusal = outcome.respondRefusal, detail = retracted ? APPROVAL_NOTE_RETRACTED_DETAIL : outcome.editRefused === !0 ? APPROVAL_NOTE_EDIT_REFUSED_DETAIL : [nonEmpty4(refusal?.errorCode), nonEmpty4(refusal?.message)].filter((x3) => x3 !== void 0).join(" \xB7 ");
20631
+ return {
20632
+ approvalId: frame.approvalId,
20633
+ settled: outcome.decision !== "unresolved",
20634
+ ...retracted ? { retracted: !0 } : {},
20635
+ ...detail.length > 0 ? { detail } : {}
20636
+ };
20637
+ }
20638
+ var APPROVAL_NOTE_RETRACTED_DETAIL, APPROVAL_NOTE_EDIT_REFUSED_DETAIL, init_approvalOutcomeNote = __esm({
20639
+ "node_modules/@sema-agent/client-core/dist/hitl/approvalOutcomeNote.js"() {
20640
+ APPROVAL_NOTE_RETRACTED_DETAIL = "the card was retracted (this host no longer has a decision port for it)", APPROVAL_NOTE_EDIT_REFUSED_DETAIL = "edits are not accepted on this card";
20641
+ }
20642
+ });
20643
+
20493
20644
  // node_modules/@sema-agent/client-core/dist/hitl/gateIdentity.js
20494
20645
  function approvalCallKey(gatedCallId, taskId) {
20495
20646
  return gatedCallId ?? taskId;
@@ -25192,6 +25343,8 @@ __export(dist_exports, {
25192
25343
  ADAPTER_DIVERGENCES: () => ADAPTER_DIVERGENCES,
25193
25344
  AGENT_MEMORY_WORDS: () => AGENT_MEMORY_WORDS,
25194
25345
  AGENT_MESSAGE_TAG: () => AGENT_MESSAGE_TAG,
25346
+ APPROVAL_NOTE_EDIT_REFUSED_DETAIL: () => APPROVAL_NOTE_EDIT_REFUSED_DETAIL,
25347
+ APPROVAL_NOTE_RETRACTED_DETAIL: () => APPROVAL_NOTE_RETRACTED_DETAIL,
25195
25348
  ASK_ORIGIN_WORDS: () => ASK_ORIGIN_WORDS,
25196
25349
  ASK_PARK_GATE_KINDS: () => ASK_PARK_GATE_KINDS,
25197
25350
  ASK_PARK_ROW_POLL_MS: () => ASK_PARK_ROW_POLL_MS,
@@ -25566,6 +25719,7 @@ __export(dist_exports, {
25566
25719
  approvalCardPortFor: () => approvalCardPortFor,
25567
25720
  approvalCardPortMisses: () => approvalCardPortMisses,
25568
25721
  approvalCardPortMissesFor: () => approvalCardPortMissesFor,
25722
+ approvalOutcomeNoteOf: () => approvalOutcomeNoteOf,
25569
25723
  approvalsStreamLiveDoctorDetail: () => approvalsStreamLiveDoctorDetail,
25570
25724
  armDetachCancel: () => armDetachCancel,
25571
25725
  armPlanReviewApproval: () => armPlanReviewApproval,
@@ -25861,6 +26015,7 @@ __export(dist_exports, {
25861
26015
  isLoopbackWireUrl: () => isLoopbackWireUrl,
25862
26016
  isModelOutputErrorRowText: () => isModelOutputErrorRowText,
25863
26017
  isModelOutputErrorText: () => isModelOutputErrorText,
26018
+ isNewEngineAgentPanelCycle: () => isNewEngineAgentPanelCycle,
25864
26019
  isOutcomeUnknownRowText: () => isOutcomeUnknownRowText,
25865
26020
  isOwnEngineRun: () => isOwnEngineRun,
25866
26021
  isOwnWorkflowRun: () => isOwnWorkflowRun,
@@ -26424,6 +26579,7 @@ var init_dist = __esm({
26424
26579
  init_providerPresets2();
26425
26580
  init_hitlBridge();
26426
26581
  init_suspendedReopen();
26582
+ init_approvalOutcomeNote();
26427
26583
  init_frameRouter();
26428
26584
  init_frameRouter();
26429
26585
  init_hitlHostSurface();
@@ -26590,12 +26746,13 @@ function publishEngineContextUsage(frame) {
26590
26746
  }, lastFrameSessionId = currentSessionIdOrNull3());
26591
26747
  }
26592
26748
  function noteEngineCompaction(record3) {
26593
- let preTokens = finiteOrUndefined(record3.preTokens), postTokens = finiteOrUndefined(record3.postTokens), triggerTokensBefore = finiteOrUndefined(record3.triggerTokensBefore), trigger = typeof record3.trigger == "string" && record3.trigger.length > 0 ? record3.trigger : void 0;
26749
+ let preTokens = finiteOrUndefined(record3.preTokens), postTokens = finiteOrUndefined(record3.postTokens), triggerTokensBefore = finiteOrUndefined(record3.triggerTokensBefore), freedRaw = finiteOrUndefined(record3.freedTokens), freedTokens = freedRaw !== void 0 && freedRaw >= 0 ? freedRaw : void 0, trigger = typeof record3.trigger == "string" && record3.trigger.length > 0 ? record3.trigger : void 0;
26594
26750
  lastCompaction = {
26595
26751
  atMs: record3.atMs ?? Date.now(),
26596
26752
  ...preTokens !== void 0 ? { preTokens } : {},
26597
26753
  ...postTokens !== void 0 ? { postTokens } : {},
26598
26754
  ...triggerTokensBefore !== void 0 ? { triggerTokensBefore } : {},
26755
+ ...freedTokens !== void 0 ? { freedTokens } : {},
26599
26756
  ...trigger !== void 0 ? { trigger } : {}
26600
26757
  }, lastCompactionSessionId = currentSessionIdOrNull3();
26601
26758
  }
@@ -27586,9 +27743,9 @@ function getSessionCronTasks() {
27586
27743
  function addSessionCronTask(task) {
27587
27744
  STATE.sessionCronTasks.push(task);
27588
27745
  }
27589
- function removeSessionCronTasks(ids) {
27590
- if (ids.length === 0) return 0;
27591
- let idSet = new Set(ids), remaining = STATE.sessionCronTasks.filter((t2) => !idSet.has(t2.id)), removed = STATE.sessionCronTasks.length - remaining.length;
27746
+ function removeSessionCronTasks(ids2) {
27747
+ if (ids2.length === 0) return 0;
27748
+ let idSet = new Set(ids2), remaining = STATE.sessionCronTasks.filter((t2) => !idSet.has(t2.id)), removed = STATE.sessionCronTasks.length - remaining.length;
27592
27749
  return removed === 0 ? 0 : (STATE.sessionCronTasks = remaining, removed);
27593
27750
  }
27594
27751
  function setSessionTrustAccepted(accepted) {
@@ -39912,8 +40069,8 @@ function emoji() {
39912
40069
  return new RegExp(_emoji, "u");
39913
40070
  }
39914
40071
  function timeSource(args) {
39915
- let hhmm = "(?:[01]\\d|2[0-3]):[0-5]\\d";
39916
- return typeof args.precision == "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
40072
+ let hhmm2 = "(?:[01]\\d|2[0-3]):[0-5]\\d";
40073
+ return typeof args.precision == "number" ? args.precision === -1 ? `${hhmm2}` : args.precision === 0 ? `${hhmm2}:[0-5]\\d` : `${hhmm2}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm2}(?::[0-5]\\d(?:\\.\\d+)?)?`;
39917
40074
  }
39918
40075
  function time(args) {
39919
40076
  return new RegExp(`^${timeSource(args)}$`);
@@ -41124,12 +41281,12 @@ var $ZodType, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, $ZodU
41124
41281
  return `shape[${k2}]._zod.run({ value: input[${k2}], issues: [] }, ctx)`;
41125
41282
  };
41126
41283
  doc.write("const input = payload.value;");
41127
- let ids = /* @__PURE__ */ Object.create(null), counter = 0;
41284
+ let ids2 = /* @__PURE__ */ Object.create(null), counter = 0;
41128
41285
  for (let key of normalized.keys)
41129
- ids[key] = `key_${counter++}`;
41286
+ ids2[key] = `key_${counter++}`;
41130
41287
  doc.write("const newResult = {};");
41131
41288
  for (let key of normalized.keys) {
41132
- let id = ids[key], k2 = esc(key), schema = shape[key], isOptionalIn = schema?._zod?.optin === "optional", isOptionalOut = schema?._zod?.optout === "optional";
41289
+ let id = ids2[key], k2 = esc(key), schema = shape[key], isOptionalIn = schema?._zod?.optin === "optional", isOptionalOut = schema?._zod?.optout === "optional";
41133
41290
  doc.write(`const ${id} = ${parseStr(key)};`), isOptionalIn && isOptionalOut ? doc.write(`
41134
41291
  if (${id}.issues.length) {
41135
41292
  if (${k2} in input) {
@@ -77744,7 +77901,7 @@ __export(modelRoutingEnvPrecedence_exports, {
77744
77901
  modelRoutingEnvNote: () => modelRoutingEnvNote
77745
77902
  });
77746
77903
  function classifyModelRoutingEnv(env6, entryBaseUrl) {
77747
- let rawUrl = nonEmpty4(servedEndpointRawValue("openai-completions", env6)), provider = nonEmpty4(env6.MODEL_PROVIDER);
77904
+ let rawUrl = nonEmpty5(servedEndpointRawValue("openai-completions", env6)), provider = nonEmpty5(env6.MODEL_PROVIDER);
77748
77905
  if (rawUrl === void 0 || provider === void 0) return { kind: "not-applicable" };
77749
77906
  let envEndpoint = normalizeEndpoint(rawUrl);
77750
77907
  if (envEndpoint === "") return { kind: "not-applicable" };
@@ -77766,12 +77923,12 @@ function modelRoutingEnvClause(env6, hop) {
77766
77923
  let v2 = classifyModelRoutingEnv(env6);
77767
77924
  return v2.kind !== "gateway-wins" ? null : providerNotDecidingClause(v2.provider);
77768
77925
  }
77769
- var ANTHROPIC_ROUTE_PROVIDERS, GATEWAY_ROUTE_PROVIDERS, nonEmpty4, init_modelRoutingEnvPrecedence = __esm({
77926
+ var ANTHROPIC_ROUTE_PROVIDERS, GATEWAY_ROUTE_PROVIDERS, nonEmpty5, init_modelRoutingEnvPrecedence = __esm({
77770
77927
  "build-src/src/sema/modelRoutingEnvPrecedence.ts"() {
77771
77928
  init_untrustedDisplayText();
77772
77929
  init_displaySafeUrl();
77773
77930
  init_servedEndpointEnv();
77774
- ANTHROPIC_ROUTE_PROVIDERS = /* @__PURE__ */ new Set(["anthropic"]), GATEWAY_ROUTE_PROVIDERS = /* @__PURE__ */ new Set(["gateway", "vllm"]), nonEmpty4 = (v2) => typeof v2 == "string" && v2.trim().length > 0 ? v2.trim() : void 0;
77931
+ ANTHROPIC_ROUTE_PROVIDERS = /* @__PURE__ */ new Set(["anthropic"]), GATEWAY_ROUTE_PROVIDERS = /* @__PURE__ */ new Set(["gateway", "vllm"]), nonEmpty5 = (v2) => typeof v2 == "string" && v2.trim().length > 0 ? v2.trim() : void 0;
77775
77932
  }
77776
77933
  });
77777
77934
 
@@ -77906,9 +78063,9 @@ function classifyAnthropicEnvRouting(env6, opts) {
77906
78063
  let catalogPresent = modelCatalogPresent(opts?.configLocalDir), own2 = opts?.ownModelConfig ?? hasOwnModelConfig(env6), CATALOG_WHY = "a model catalog (config.d/models.json) drives routing \u2014 the env override is ignored";
77907
78064
  if (own2) {
77908
78065
  if (catalogPresent) return { kind: "ignored", why: CATALOG_WHY };
77909
- let nonEmpty5 = (v2) => typeof v2 == "string" && v2.length > 0 ? v2 : void 0, explicitProvider = nonEmpty5(env6.MODEL_PROVIDER);
78066
+ let nonEmpty6 = (v2) => typeof v2 == "string" && v2.length > 0 ? v2 : void 0, explicitProvider = nonEmpty6(env6.MODEL_PROVIDER);
77910
78067
  if (explicitProvider === "anthropic") return { kind: "honored", via: "explicit-anthropic-provider" };
77911
- let inferBaseUrl = baseUrl, inferCred = nonEmpty5(env6.ANTHROPIC_API_KEY) ?? authToken;
78068
+ let inferBaseUrl = baseUrl, inferCred = nonEmpty6(env6.ANTHROPIC_API_KEY) ?? authToken;
77912
78069
  if (explicitProvider === void 0 && inferBaseUrl && inferCred)
77913
78070
  return { kind: "honored", via: "engine-inferred-anthropic" };
77914
78071
  if (explicitProvider !== void 0) {
@@ -90411,10 +90568,10 @@ function patchPresent(intended, onDisk) {
90411
90568
  return intended === onDisk;
90412
90569
  }
90413
90570
  function keyEntriesOnDisk(pool, err8) {
90414
- let ids = err8.missingKeyEntries ?? [];
90415
- if (ids.length === 0) return !0;
90571
+ let ids2 = err8.missingKeyEntries ?? [];
90572
+ if (ids2.length === 0) return !0;
90416
90573
  let env6 = readSettingsEnv();
90417
- return ids.every((id) => {
90574
+ return ids2.every((id) => {
90418
90575
  let e = pool.find((p) => p.id === id);
90419
90576
  return !e?.apiKey || env6[keyEnvNameForEntry(id)] === e.apiKey;
90420
90577
  });
@@ -90595,13 +90752,13 @@ function mergeRenameErrors(stage1, stage2) {
90595
90752
  function poolWriteErrorNotice(error51, verb = "Saved") {
90596
90753
  let e = error51;
90597
90754
  if (!e.keyWriteOnly) return `Pool write failed: ${error51.message}`;
90598
- let ids = e.missingKeyEntries ?? [];
90599
- if (ids.length === 0)
90755
+ let ids2 = e.missingKeyEntries ?? [];
90756
+ if (ids2.length === 0)
90600
90757
  return `${verb}. A settings write failed (${error51.message}) \u2014 no API key was lost.`;
90601
- if (ids.length === 1)
90602
- return `${verb}, but the API key for "${ids[0]}" was not stored (${error51.message}). Open it in the Hub and set the key again.`;
90603
- let shown = ids.slice(0, 3).join(", ");
90604
- return `${verb}, but the API keys for ${ids.length} entries (${shown}${ids.length > 3 ? ", \u2026" : ""}) were not stored (${error51.message}). Open each one in the Hub and set its key again.`;
90758
+ if (ids2.length === 1)
90759
+ return `${verb}, but the API key for "${ids2[0]}" was not stored (${error51.message}). Open it in the Hub and set the key again.`;
90760
+ let shown = ids2.slice(0, 3).join(", ");
90761
+ return `${verb}, but the API keys for ${ids2.length} entries (${shown}${ids2.length > 3 ? ", \u2026" : ""}) were not stored (${error51.message}). Open each one in the Hub and set its key again.`;
90605
90762
  }
90606
90763
  function poolSaveFailureNotice(error51, renamedTo, failVerb) {
90607
90764
  let e = error51;
@@ -90911,10 +91068,10 @@ function readSemaAutoModeOverride(env6 = process.env, configHome = resolveConfig
90911
91068
  let enabled = !0;
90912
91069
  if (env6.SEMA_AUTO_MODE_ENABLED !== void 0 ? enabled = ENABLED_ENV_TRUE.has(env6.SEMA_AUTO_MODE_ENABLED.trim().toLowerCase()) : sj?.semaAutoModeEnabled !== void 0 && (enabled = sj.semaAutoModeEnabled === !0), enabled && allowModels === void 0)
90913
91070
  try {
90914
- let { readModelPool: readModelPool2 } = (init_modelChannels(), __toCommonJS(modelChannels_exports)), pool = readModelPool2(), ids = /* @__PURE__ */ new Set();
91071
+ let { readModelPool: readModelPool2 } = (init_modelChannels(), __toCommonJS(modelChannels_exports)), pool = readModelPool2(), ids2 = /* @__PURE__ */ new Set();
90915
91072
  for (let e of pool)
90916
- e.id && ids.add(e.id), e.modelId && ids.add(e.modelId);
90917
- env6.MODEL_ID?.trim() && ids.add(env6.MODEL_ID.trim()), ids.size > 0 && (allowModels = [...ids]);
91073
+ e.id && ids2.add(e.id), e.modelId && ids2.add(e.modelId);
91074
+ env6.MODEL_ID?.trim() && ids2.add(env6.MODEL_ID.trim()), ids2.size > 0 && (allowModels = [...ids2]);
90918
91075
  } catch {
90919
91076
  }
90920
91077
  if (!enabled && allowModels === void 0) return;
@@ -126477,6 +126634,7 @@ function watchEngineContextFrames(events3) {
126477
126634
  preTokens: c3.tokensBefore,
126478
126635
  postTokens: c3.tokensAfter,
126479
126636
  triggerTokensBefore: c3.triggerTokensBefore,
126637
+ freedTokens: c3.freedTokens,
126480
126638
  trigger: c3.trigger
126481
126639
  })
126482
126640
  ).catch(() => {
@@ -154034,7 +154192,7 @@ async function deliverToRunningAgentLane(core, id, access7, notification, opts)
154034
154192
  return { ok: !1, reason: "not_found" };
154035
154193
  if (handle2.status !== "running")
154036
154194
  return { ok: !1, reason: "not_running" };
154037
- let bounded2 = (p, fallback, onTimeout) => new Promise((resolve59) => {
154195
+ let bounded3 = (p, fallback, onTimeout) => new Promise((resolve59) => {
154038
154196
  let t2 = setTimeout(() => {
154039
154197
  try {
154040
154198
  onTimeout?.();
@@ -154052,12 +154210,12 @@ async function deliverToRunningAgentLane(core, id, access7, notification, opts)
154052
154210
  if (handle2.channelState !== "attaching")
154053
154211
  return { ok: !1, reason: "no_channel" };
154054
154212
  let q2 = handle2.preAttachQueue ??= [];
154055
- return q2.length >= 8 ? { ok: !1, reason: "queue_full" } : bounded2(new Promise((resolve59) => {
154213
+ return q2.length >= 8 ? { ok: !1, reason: "queue_full" } : bounded3(new Promise((resolve59) => {
154056
154214
  q2.push([notification, opts, resolve59]);
154057
154215
  }), { ok: !0, disposition: "pending" });
154058
154216
  }
154059
154217
  let detachOnTimeout;
154060
- return await bounded2(new Promise((resolve59) => {
154218
+ return await bounded3(new Promise((resolve59) => {
154061
154219
  let inflight4 = handle2.inFlightDirect ??= /* @__PURE__ */ new Set(), settleOnce = (r) => {
154062
154220
  inflight4.has(settleOnce) && (inflight4.delete(settleOnce), resolve59(r));
154063
154221
  };
@@ -184484,13 +184642,13 @@ var caPath, builtinRootBodies, init_tlsTrust = __esm({
184484
184642
  function nearestListed(body, modelId) {
184485
184643
  let data = body?.data;
184486
184644
  if (!Array.isArray(data)) return;
184487
- let ids = data.map((m2) => m2?.id).filter((x3) => typeof x3 == "string");
184488
- if (ids.includes(modelId)) return;
184645
+ let ids2 = data.map((m2) => m2?.id).filter((x3) => typeof x3 == "string");
184646
+ if (ids2.includes(modelId)) return;
184489
184647
  let norm3 = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, ""), target = norm3(modelId);
184490
184648
  for (let len of [6, 5, 4]) {
184491
184649
  let stem = target.slice(0, len);
184492
184650
  if (stem.length < len) continue;
184493
- let hit = ids.find((i) => norm3(i).startsWith(stem));
184651
+ let hit = ids2.find((i) => norm3(i).startsWith(stem));
184494
184652
  if (hit) return hit;
184495
184653
  }
184496
184654
  }
@@ -222584,7 +222742,7 @@ async function resolveDependencyClosure(rootId, lookup, alreadyEnabled, allowedC
222584
222742
  return err8 || { ok: !0, closure };
222585
222743
  }
222586
222744
  async function expandClosureFromManifestDeps(opts) {
222587
- let ids = [], skipped = [], seen2 = /* @__PURE__ */ new Set();
222745
+ let ids2 = [], skipped = [], seen2 = /* @__PURE__ */ new Set();
222588
222746
  for (let rawDep of opts.manifestDeps ?? []) {
222589
222747
  let dep = qualifyDependency(rawDep, opts.declaringId);
222590
222748
  if (seen2.has(dep) || opts.closureSet.has(dep) || opts.alreadyEnabled.has(dep)) continue;
@@ -222612,9 +222770,9 @@ async function expandClosureFromManifestDeps(opts) {
222612
222770
  });
222613
222771
  continue;
222614
222772
  }
222615
- seen2.add(dep), ids.push(dep);
222773
+ seen2.add(dep), ids2.push(dep);
222616
222774
  }
222617
- return { ok: !0, ids, skipped };
222775
+ return { ok: !0, ids: ids2, skipped };
222618
222776
  }
222619
222777
  function formatSkippedManifestDependency(s) {
222620
222778
  let depMkt = parsePluginIdentifier(s.dependency).marketplace;
@@ -224726,12 +224884,12 @@ function estimateMessageTokens(messages) {
224726
224884
  return Math.ceil(totalTokens * (4 / 3));
224727
224885
  }
224728
224886
  function collectCompactableToolIds(messages) {
224729
- let ids = [];
224887
+ let ids2 = [];
224730
224888
  for (let message of messages)
224731
224889
  if (message.type === "assistant" && Array.isArray(message.message.content))
224732
224890
  for (let block2 of message.message.content)
224733
- block2.type === "tool_use" && COMPACTABLE_TOOLS2.has(block2.name) && ids.push(block2.id);
224734
- return ids;
224891
+ block2.type === "tool_use" && COMPACTABLE_TOOLS2.has(block2.name) && ids2.push(block2.id);
224892
+ return ids2;
224735
224893
  }
224736
224894
  function isMainThreadSource(querySource) {
224737
224895
  return !querySource || querySource.startsWith("repl_main_thread");
@@ -232104,7 +232262,7 @@ function stripUnderlineAnsi(content) {
232104
232262
  }
232105
232263
  var import_compiler_runtime22, React15, import_jsx_runtime26, MAX_JSON_FORMAT_LENGTH, URL_IN_JSON, init_OutputLine = __esm({
232106
232264
  "build-src/src/components/shell/OutputLine.tsx"() {
232107
- import_compiler_runtime22 = __toESM(require_compiler_runtime()), React15 = __toESM(require_react());
232265
+ import_compiler_runtime22 = __toESM(require_compiler_runtime(), 1), React15 = __toESM(require_react(), 1);
232108
232266
  init_useTerminalSize();
232109
232267
  init_ink2();
232110
232268
  init_hyperlink();
@@ -232113,7 +232271,7 @@ var import_compiler_runtime22, React15, import_jsx_runtime26, MAX_JSON_FORMAT_LE
232113
232271
  init_MessageResponse();
232114
232272
  init_messageActions();
232115
232273
  init_ExpandShellOutputContext();
232116
- import_jsx_runtime26 = __toESM(require_jsx_runtime());
232274
+ import_jsx_runtime26 = __toESM(require_jsx_runtime(), 1);
232117
232275
  MAX_JSON_FORMAT_LENGTH = 1e4;
232118
232276
  URL_IN_JSON = /https?:\/\/[^\s"'<>\\]+/g;
232119
232277
  }
@@ -251984,17 +252142,28 @@ function markApprovalCardGateRow(toolCallId, row2, streamEpoch) {
251984
252142
  let handle2 = liveApprovalCards.get(born.callKey);
251985
252143
  return handle2 === void 0 ? !1 : handle2.windowClosed(row2 === "parked" ? "parked-frame" : "auto-denied");
251986
252144
  }
252145
+ function noteHumanApprovalCardDecision(callKey) {
252146
+ for (humanCardDecisions.delete(callKey), humanCardDecisions.add(callKey); humanCardDecisions.size > HUMAN_DECISION_MAX; ) {
252147
+ let oldest = humanCardDecisions.values().next().value;
252148
+ if (oldest === void 0) break;
252149
+ humanCardDecisions.delete(oldest);
252150
+ }
252151
+ }
252152
+ function takeHumanApprovalCardDecision(callKey) {
252153
+ return humanCardDecisions.delete(callKey);
252154
+ }
251987
252155
  function surfaceToolEndAutoDenied(ev, streamEpoch) {
251988
252156
  let r = resolveToolEndAutoDenied(ev, streamEpoch);
251989
252157
  if (r.kind !== "late") return r.kind;
251990
252158
  let [content, level] = r.row === "parked" ? [approvalMovedToDurableQueueLateRow(r.toolName), "info"] : [approvalAutoDeniedRow(r.toolName), "warning"];
251991
252159
  return surfaceLateDecideOutcome(content, level) ? "late" : "late-unsurfaced";
251992
252160
  }
251993
- var liveApprovalCards, callKeyByToolCallId, SETTLED_CARD_MAX, settledCardByToolCallId, settledKey, terminalSeenByToolCallId, init_liveApprovalCardHandles = __esm({
252161
+ var liveApprovalCards, callKeyByToolCallId, SETTLED_CARD_MAX, settledCardByToolCallId, settledKey, terminalSeenByToolCallId, HUMAN_DECISION_MAX, humanCardDecisions, init_liveApprovalCardHandles = __esm({
251994
252162
  "build-src/src/sema/liveApprovalCardHandles.ts"() {
251995
252163
  init_askParkExpiry();
251996
252164
  init_liveSessionStore();
251997
252165
  liveApprovalCards = /* @__PURE__ */ new Map(), callKeyByToolCallId = /* @__PURE__ */ new Map(), SETTLED_CARD_MAX = 64, settledCardByToolCallId = /* @__PURE__ */ new Map(), settledKey = (epoch, toolCallId) => `${String(epoch)}:${toolCallId}`, terminalSeenByToolCallId = /* @__PURE__ */ new Set();
252166
+ HUMAN_DECISION_MAX = 256, humanCardDecisions = /* @__PURE__ */ new Set();
251998
252167
  }
251999
252168
  });
252000
252169
 
@@ -329622,15 +329791,15 @@ async function bashToolHasPermission(input, context3, getCommandSubcommandPrefix
329622
329791
  if (permissionResult.behavior === "ask" || permissionResult.behavior === "passthrough") {
329623
329792
  let updates = "suggestions" in permissionResult ? permissionResult.suggestions : void 0, rules = extractRules(updates);
329624
329793
  for (let rule of rules) {
329625
- let ruleKey = permissionRuleValueToString(rule);
329626
- collectedRules.set(ruleKey, rule);
329794
+ let ruleKey2 = permissionRuleValueToString(rule);
329795
+ collectedRules.set(ruleKey2, rule);
329627
329796
  }
329628
329797
  if (permissionResult.behavior === "ask" && rules.length === 0 && permissionResult.decisionReason?.type !== "rule")
329629
329798
  for (let rule of extractRules(
329630
329799
  suggestionForExactCommand3(subcommand)
329631
329800
  )) {
329632
- let ruleKey = permissionRuleValueToString(rule);
329633
- collectedRules.set(ruleKey, rule);
329801
+ let ruleKey2 = permissionRuleValueToString(rule);
329802
+ collectedRules.set(ruleKey2, rule);
329634
329803
  }
329635
329804
  }
329636
329805
  let decisionReason = {
@@ -330563,10 +330732,10 @@ async function addCronTask(cron, prompt, recurring, durable, agentId) {
330563
330732
  await writeCronTasks([...current6, task], root2);
330564
330733
  }), id) : (addSessionCronTask({ ...task, ...agentId ? { agentId } : {} }), id);
330565
330734
  }
330566
- async function removeCronTasks(ids, dir) {
330567
- if (ids.length === 0 || dir === void 0 && removeSessionCronTasks(ids) === ids.length)
330735
+ async function removeCronTasks(ids2, dir) {
330736
+ if (ids2.length === 0 || dir === void 0 && removeSessionCronTasks(ids2) === ids2.length)
330568
330737
  return;
330569
- let idSet = new Set(ids);
330738
+ let idSet = new Set(ids2);
330570
330739
  await withCronFileLock(dir, async (current6, root2) => {
330571
330740
  let remaining = current6.filter((t2) => !idSet.has(t2.id));
330572
330741
  remaining.length !== current6.length && await writeCronTasks(remaining, root2);
@@ -332092,10 +332261,10 @@ function getToolUseIdsFromMessage(msg) {
332092
332261
  }).filter(Boolean) : [];
332093
332262
  }
332094
332263
  function getToolUseIdsFromCollapsedGroup(message) {
332095
- let ids = [];
332264
+ let ids2 = [];
332096
332265
  for (let msg of message.messages)
332097
- ids.push(...getToolUseIdsFromMessage(msg));
332098
- return ids;
332266
+ ids2.push(...getToolUseIdsFromMessage(msg));
332267
+ return ids2;
332099
332268
  }
332100
332269
  function hasAnyToolInProgress(message, inProgressToolUseIDs) {
332101
332270
  return getToolUseIdsFromCollapsedGroup(message).some(
@@ -358693,8 +358862,8 @@ function takeSuspendedAskRequeueBudget(approvalId, max2) {
358693
358862
  function forgetSuspendedAsk(approvalId) {
358694
358863
  claimed.delete(approvalId), decided.delete(approvalId), requeueUsed.delete(approvalId), submitting.delete(approvalId), seenInSnapshot.delete(approvalId);
358695
358864
  }
358696
- function noteSuspendedAsksListed(ids) {
358697
- for (let id of ids) boundedAdd(seenInSnapshot, id);
358865
+ function noteSuspendedAsksListed(ids2) {
358866
+ for (let id of ids2) boundedAdd(seenInSnapshot, id);
358698
358867
  }
358699
358868
  function pruneVanishedSuspendedAsks(liveIds) {
358700
358869
  let n2 = 0;
@@ -384245,12 +384414,12 @@ function resolveStopTargetByName(query2, appState) {
384245
384414
  tasks3
384246
384415
  ), namedExact = resolveNamedAgent((n2) => n2 === query2, appState);
384247
384416
  if (teammateExact.status !== "not_found" && namedExact) {
384248
- let ids = teammateExact.status === "found" ? [
384417
+ let ids2 = teammateExact.status === "found" ? [
384249
384418
  teammateExact.task.identity?.agentId ?? teammateExact.taskId
384250
384419
  ] : teammateExact.candidates;
384251
384420
  return {
384252
384421
  status: "ambiguous",
384253
- message: teammateVsNamedAgentMessage(query2, ids, namedExact.taskId)
384422
+ message: teammateVsNamedAgentMessage(query2, ids2, namedExact.taskId)
384254
384423
  };
384255
384424
  }
384256
384425
  if (teammateExact.status === "ambiguous")
@@ -384271,12 +384440,12 @@ function resolveStopTargetByName(query2, appState) {
384271
384440
  tasks3
384272
384441
  ), namedNorm = resolveNamedAgent((n2) => normalizeAgentName2(n2) === norm3, appState);
384273
384442
  if (teammateNorm.status !== "not_found" && namedNorm) {
384274
- let ids = teammateNorm.status === "found" ? [
384443
+ let ids2 = teammateNorm.status === "found" ? [
384275
384444
  teammateNorm.task.identity?.agentId ?? teammateNorm.taskId
384276
384445
  ] : teammateNorm.candidates;
384277
384446
  return {
384278
384447
  status: "ambiguous",
384279
- message: teammateVsNamedAgentMessage(query2, ids, namedNorm.taskId)
384448
+ message: teammateVsNamedAgentMessage(query2, ids2, namedNorm.taskId)
384280
384449
  };
384281
384450
  }
384282
384451
  return teammateNorm.status === "ambiguous" ? {
@@ -394558,6 +394727,48 @@ var SUBAGENT_OBSERVATION_EXEMPT_NAMES, WORKFLOW_ACCEPTED_EXEMPT_NAMES, latchedSe
394558
394727
  }
394559
394728
  });
394560
394729
 
394730
+ // build-src/src/sema/midTurnRuleNotice.ts
394731
+ function noteStampSentForRun(ruleKeys) {
394732
+ lastSentRuleKeys = [...ruleKeys];
394733
+ }
394734
+ function noteRunStreamStarted() {
394735
+ runStreamDepth += 1;
394736
+ }
394737
+ function noteRunStreamSettled() {
394738
+ runStreamDepth > 0 && (runStreamDepth -= 1);
394739
+ }
394740
+ function ruleKey(behavior, rule) {
394741
+ return `${behavior}:${rule}`;
394742
+ }
394743
+ function rulesMissFromInflightStamp(behavior, rules) {
394744
+ if (runStreamDepth <= 0 || lastSentRuleKeys === void 0) return !1;
394745
+ let sent = new Set(lastSentRuleKeys);
394746
+ return rules.some((r) => !sent.has(ruleKey(behavior, r)));
394747
+ }
394748
+ function describeRuleAppliesNextTurn(behavior, rules) {
394749
+ let shown = rules.slice(0, 5).map((r) => JSON.stringify(r)).join(", "), more = rules.length > 5 ? ` (+${String(rules.length - 5)} more)` : "";
394750
+ return `Added ${String(rules.length)} ${behavior} rule(s): ${shown}${more} \u2014 this rule applies from your next turn; the turn that is running now still uses the rules it started with.`;
394751
+ }
394752
+ function noteRestrictionRulesAdded(behavior, rules) {
394753
+ try {
394754
+ if (rules.length === 0 || !rulesMissFromInflightStamp(behavior, rules)) return;
394755
+ let text2 = describeRuleAppliesNextTurn(behavior, rules);
394756
+ surfaceTranscriptSystemNotice(text2, "warning") || process.stderr.write(`[sema] ${text2}
394757
+ `);
394758
+ } catch (e) {
394759
+ logForDebugging(
394760
+ `[sema][mid-turn-rule-notice] surface failed: ${e instanceof Error ? e.message : String(e)}`
394761
+ );
394762
+ }
394763
+ }
394764
+ var lastSentRuleKeys, runStreamDepth, init_midTurnRuleNotice = __esm({
394765
+ "build-src/src/sema/midTurnRuleNotice.ts"() {
394766
+ init_debug();
394767
+ init_transcriptSystemNotice();
394768
+ runStreamDepth = 0;
394769
+ }
394770
+ });
394771
+
394561
394772
  // build-src/src/sema/hooksWireCaps.ts
394562
394773
  var hooksWireCaps_exports = {};
394563
394774
  __export(hooksWireCaps_exports, {
@@ -400136,6 +400347,7 @@ async function* query(params) {
400136
400347
  }
400137
400348
  noteEngineTurnStart();
400138
400349
  let setInProgress = params.toolUseContext?.setInProgressToolUseIDs, engineOpenToolIds = /* @__PURE__ */ new Set(), foregroundRunRegistered = null, semaQuotaDeniedThisTurn = !1, listenedRuns = /* @__PURE__ */ new Set();
400350
+ noteRunStreamStarted();
400139
400351
  try {
400140
400352
  let sessionId = req2.sessionId ?? mockClientIds.sessionId;
400141
400353
  try {
@@ -400544,7 +400756,7 @@ ${notifSupplement}` : baseErrorContent
400544
400756
  }
400545
400757
  return void 0;
400546
400758
  } finally {
400547
- if (publishEngineAgentPanelEvent({ kind: "sweep" }), semaAutoResumeStore && !semaQuotaDeniedThisTurn && isMainLaneQuerySource(params.querySource) && !isBackgroundJournalSuppressed())
400759
+ if (noteRunStreamSettled(), publishEngineAgentPanelEvent({ kind: "sweep" }), semaAutoResumeStore && !semaQuotaDeniedThisTurn && isMainLaneQuerySource(params.querySource) && !isBackgroundJournalSuppressed())
400548
400760
  try {
400549
400761
  semaAutoResumeStore.noteUsageLimitAutoResumeTurnCompleted();
400550
400762
  } catch {
@@ -400980,6 +401192,7 @@ var transcriptUsageDriveSeq, BG_TEAR_MAX_RESENDS, BG_RECOVERY_WAIT_MS, DRAINING_
400980
401192
  init_dist();
400981
401193
  init_deferSessionExemption();
400982
401194
  init_debug();
401195
+ init_midTurnRuleNotice();
400983
401196
  init_hooksWireCaps2();
400984
401197
  init_dist();
400985
401198
  init_intl();
@@ -403235,10 +403448,10 @@ function getToolResultIds(message) {
403235
403448
  let content = message.message.content;
403236
403449
  if (!Array.isArray(content))
403237
403450
  return [];
403238
- let ids = [];
403451
+ let ids2 = [];
403239
403452
  for (let block2 of content)
403240
- block2.type === "tool_result" && ids.push(block2.tool_use_id);
403241
- return ids;
403453
+ block2.type === "tool_result" && ids2.push(block2.tool_use_id);
403454
+ return ids2;
403242
403455
  }
403243
403456
  function hasToolUseWithIds(message, toolUseIds) {
403244
403457
  if (message.type !== "assistant")
@@ -406092,8 +406305,8 @@ function isValidImagePaste(c3) {
406092
406305
  function getImagePasteIds(pastedContents) {
406093
406306
  if (!pastedContents)
406094
406307
  return;
406095
- let ids = Object.values(pastedContents).filter(isValidImagePaste).map((c3) => c3.id);
406096
- return ids.length > 0 ? ids : void 0;
406308
+ let ids2 = Object.values(pastedContents).filter(isValidImagePaste).map((c3) => c3.id);
406309
+ return ids2.length > 0 ? ids2 : void 0;
406097
406310
  }
406098
406311
  var init_textInputTypes = __esm({
406099
406312
  "build-src/src/types/textInputTypes.ts"() {
@@ -425053,7 +425266,7 @@ function applyPermissionUpdate(context3, update2) {
425053
425266
  );
425054
425267
  logForDebugging(
425055
425268
  `Applying permission update: Adding ${update2.rules.length} ${update2.behavior} rule(s) to destination '${update2.destination}': ${jsonStringify(ruleStrings)}`
425056
- );
425269
+ ), update2.behavior !== "allow" && noteRestrictionRulesAdded(update2.behavior, ruleStrings);
425057
425270
  let ruleKind = update2.behavior === "allow" ? "alwaysAllowRules" : update2.behavior === "deny" ? "alwaysDenyRules" : "alwaysAskRules";
425058
425271
  return {
425059
425272
  ...context3,
@@ -425290,6 +425503,7 @@ var init_PermissionUpdate = __esm({
425290
425503
  init_filesystem();
425291
425504
  init_permissionRuleParser();
425292
425505
  init_permissionsLoader();
425506
+ init_midTurnRuleNotice();
425293
425507
  }
425294
425508
  });
425295
425509
 
@@ -430063,20 +430277,20 @@ var sema_brand_default, init_sema_brand = __esm({
430063
430277
  _doc: "displayName/email \u7559 null = \u8FD0\u884C\u65F6\u56DE\u9000(\u540D\u5B57\u53D6\u672C\u673A OS \u7528\u6237\u540D,\u90AE\u7BB1\u4E0D\u663E\u793A)\u3002\u522B\u70E7\u4E2A\u4EBA\u4FE1\u606F\u8FDB\u54C1\u724C\u6587\u4EF6(F-S1-1:\u65B0\u7528\u6237\u66FE\u770B\u5230 Welcome back Clay!)\u3002"
430064
430278
  },
430065
430279
  whatsNew: {
430066
- version: "1.0.123",
430280
+ version: "1.0.124",
430067
430281
  notes: [
430068
- "Bundled engine 7.88.2 (core 7.23.5), client runtime 0.74.3, client SDK 9.8.1 and settings schema 3.0.0. /doctor and the engine line report 7.88.2.",
430069
- "A background subagent's approval card is withdrawn when the session, the engine or the credentials change, and withdrawing it no longer sends a decision on your behalf. An approval whose answer never reached the engine comes back on the next update instead of after two.",
430070
- "A background agent that starts a new round now shows that round: its status, timer and counters move together, and a late ending from the previous round no longer closes it. When the engine says why it removed an agent, the panel's cleanup line says so. The same agent no longer shows up as two rows.",
430071
- "Credentials that a remote echoes back no longer reach the terminal, the streamed output or the saved transcript, including passwords with punctuation and short values. On engine 7.88 and later a gateway URL that carries credentials in its userinfo stops the engine from starting, and sema shows that refusal by name without printing the credentials. 1.0.122 covered the interactive screen, the -p result frame and stderr; the -p transcript and stream-json frames, and punctuated or short secrets, are covered from this version.",
430072
- "Approving a plan no longer brings a second card even when the engine takes a while to resume.",
430073
- "The workflow list now says why a failed run failed.",
430074
- "A read-root suggestion that names a single file no longer tells you to add it as a directory.",
430075
- "mcp list and mcp get no longer print a password that the server echoed back."
430282
+ "Bundled engine 7.89.0 (core 7.23.5) and client runtime 0.74.5. /doctor and the engine line report 7.89.0.",
430283
+ "Permission rules you add during a session with /permissions now reach the engine on your next turn. When a run is in progress, sema says the new rule applies from the next turn; when settings cannot be re-read, sema says so and /doctor shows how old the settings in use are.",
430284
+ "A background subagent's approval card comes back after every failed delivery when you answered it, so the request never loses its card while it is still waiting on the engine. Automatic decisions keep a bounded retry.",
430285
+ "The /context compaction line shows the number of tokens the engine measured as freed, or says it was not reported. It no longer subtracts two counters that are not comparable.",
430286
+ "After reattaching to a session, the agent panel no longer shows completed rows for agents this session never saw running.",
430287
+ "The footer count of subagent approval requests waiting on you shows a dash when the engine's approval list cannot be read, instead of keeping a stale number.",
430288
+ "Cloud resource uploads detect credential-shaped values with the same rules the engine uses.",
430289
+ "Engine 7.89 refuses to start when a model route URL in your environment cannot be parsed, including a stale ANTHROPIC_BASE_URL you no longer use. sema shows the refusal and names the variable; unset it or fix it to start."
430076
430290
  ]
430077
430291
  },
430078
- productVersion: "1.0.123",
430079
- announcement: "sema 1.0.123 \u2014 engine 7.88.2 pickup (core 7.23.5), client runtime 0.74.3, client SDK 9.8.1, settings schema 3.0.0. Background subagent approval cards are withdrawn without deciding for you; a revived agent shows its new round; credentials echoed by a remote stay out of the transcript and streamed output; a gateway URL with credentials now stops the engine at startup; approving a plan brings no second card; the workflow list says why a run failed.",
430292
+ productVersion: "1.0.124",
430293
+ announcement: "sema 1.0.124 \u2014 engine 7.89.0 pickup (core 7.23.5), client runtime 0.74.5. Permission rules added during a session now reach the engine on your next turn, with a notice when a run is in progress; a background subagent's approval card comes back after every failed delivery you answered; /context shows the tokens the engine measured as freed; no ghost completed rows after reattaching; a dash instead of a stale count when the approval list cannot be read.",
430080
430294
  version: "1.0.91"
430081
430295
  };
430082
430296
  }
@@ -435642,6 +435856,9 @@ function modelBadge(model) {
435642
435856
  function autocompactSourceOf(data) {
435643
435857
  return data.autocompactSource ?? "auto";
435644
435858
  }
435859
+ function freedTail(freedTokens) {
435860
+ return freedTokens === void 0 ? " \xB7 freed: not reported by the engine" : ` \xB7 freed ${String(freedTokens)} ${freedTokens === 1 ? "token" : "tokens"}`;
435861
+ }
435645
435862
  function localStamp(atMs) {
435646
435863
  let d4 = new Date(atMs), p2 = (n2) => String(n2).padStart(2, "0");
435647
435864
  return `${p2(d4.getMonth() + 1)}-${p2(d4.getDate())} ${p2(d4.getHours())}:${p2(d4.getMinutes())}:${p2(d4.getSeconds())}`;
@@ -435649,12 +435866,12 @@ function localStamp(atMs) {
435649
435866
  function lastCompactionLine(data) {
435650
435867
  let rec = data._sema_lastCompaction;
435651
435868
  if (rec === void 0 || !Number.isFinite(rec.atMs)) return null;
435652
- let at = localStamp(rec.atMs);
435869
+ let at = localStamp(rec.atMs), freed = freedTail(rec.freedTokens);
435653
435870
  if (rec.triggerTokensBefore !== void 0 && rec.postTokens !== void 0) {
435654
- let shrank = rec.postTokens < rec.triggerTokensBefore, beforeText = formatTokens(rec.triggerTokensBefore), afterText = formatTokens(rec.postTokens), tail = shrank ? beforeText === afterText ? ` (shrank by ${rec.triggerTokensBefore - rec.postTokens} tokens \u2014 less than this display's precision)` : "" : " (context did not shrink)";
435655
- return `Last compaction seen at ${at} \xB7 ${beforeText} \u2192 ${afterText}` + tail;
435871
+ let shrank = rec.postTokens < rec.triggerTokensBefore, beforeText = formatTokens(rec.triggerTokensBefore), afterText = formatTokens(rec.postTokens), tail = shrank ? beforeText === afterText ? " (shrank by less than this display's precision)" : "" : " (context did not shrink)";
435872
+ return `Last compaction seen at ${at} \xB7 ${beforeText} \u2192 ${afterText}` + tail + freed;
435656
435873
  }
435657
- return rec.preTokens !== void 0 && rec.postTokens !== void 0 ? `Last compaction seen at ${at} \xB7 before ${formatTokens(rec.preTokens)} \xB7 after ${formatTokens(rec.postTokens)} (different scales \u2014 not a before/after delta)` : rec.preTokens !== void 0 ? `Last compaction seen at ${at} \xB7 before ${formatTokens(rec.preTokens)}` : rec.postTokens !== void 0 ? `Last compaction seen at ${at} \xB7 after ${formatTokens(rec.postTokens)}` : `Last compaction seen at ${at}`;
435874
+ return rec.preTokens !== void 0 && rec.postTokens !== void 0 ? `Last compaction seen at ${at} \xB7 before ${formatTokens(rec.preTokens)} \xB7 after ${formatTokens(rec.postTokens)} (different scales \u2014 not a before/after delta)` + freed : rec.preTokens !== void 0 ? `Last compaction seen at ${at} \xB7 before ${formatTokens(rec.preTokens)}` + freed : rec.postTokens !== void 0 ? `Last compaction seen at ${at} \xB7 after ${formatTokens(rec.postTokens)}` + freed : `Last compaction seen at ${at}` + freed;
435658
435875
  }
435659
435876
  function autocompactBufferSourceLine(data, bufferRowPresent) {
435660
435877
  return !bufferRowPresent || data._sema_autoCompactThresholdSource !== "engine" ? null : "Autocompact buffer = context window \u2212 the engine's compaction threshold (context_usage.compactAtTokens) \u2014 on a small context window it is the engine's policy, not the shell, that decides how much is reserved";
@@ -457355,20 +457572,20 @@ var require_sema_brand = __commonJS({
457355
457572
  _doc: "displayName/email \u7559 null = \u8FD0\u884C\u65F6\u56DE\u9000(\u540D\u5B57\u53D6\u672C\u673A OS \u7528\u6237\u540D,\u90AE\u7BB1\u4E0D\u663E\u793A)\u3002\u522B\u70E7\u4E2A\u4EBA\u4FE1\u606F\u8FDB\u54C1\u724C\u6587\u4EF6(F-S1-1:\u65B0\u7528\u6237\u66FE\u770B\u5230 Welcome back Clay!)\u3002"
457356
457573
  },
457357
457574
  whatsNew: {
457358
- version: "1.0.123",
457575
+ version: "1.0.124",
457359
457576
  notes: [
457360
- "Bundled engine 7.88.2 (core 7.23.5), client runtime 0.74.3, client SDK 9.8.1 and settings schema 3.0.0. /doctor and the engine line report 7.88.2.",
457361
- "A background subagent's approval card is withdrawn when the session, the engine or the credentials change, and withdrawing it no longer sends a decision on your behalf. An approval whose answer never reached the engine comes back on the next update instead of after two.",
457362
- "A background agent that starts a new round now shows that round: its status, timer and counters move together, and a late ending from the previous round no longer closes it. When the engine says why it removed an agent, the panel's cleanup line says so. The same agent no longer shows up as two rows.",
457363
- "Credentials that a remote echoes back no longer reach the terminal, the streamed output or the saved transcript, including passwords with punctuation and short values. On engine 7.88 and later a gateway URL that carries credentials in its userinfo stops the engine from starting, and sema shows that refusal by name without printing the credentials. 1.0.122 covered the interactive screen, the -p result frame and stderr; the -p transcript and stream-json frames, and punctuated or short secrets, are covered from this version.",
457364
- "Approving a plan no longer brings a second card even when the engine takes a while to resume.",
457365
- "The workflow list now says why a failed run failed.",
457366
- "A read-root suggestion that names a single file no longer tells you to add it as a directory.",
457367
- "mcp list and mcp get no longer print a password that the server echoed back."
457577
+ "Bundled engine 7.89.0 (core 7.23.5) and client runtime 0.74.5. /doctor and the engine line report 7.89.0.",
457578
+ "Permission rules you add during a session with /permissions now reach the engine on your next turn. When a run is in progress, sema says the new rule applies from the next turn; when settings cannot be re-read, sema says so and /doctor shows how old the settings in use are.",
457579
+ "A background subagent's approval card comes back after every failed delivery when you answered it, so the request never loses its card while it is still waiting on the engine. Automatic decisions keep a bounded retry.",
457580
+ "The /context compaction line shows the number of tokens the engine measured as freed, or says it was not reported. It no longer subtracts two counters that are not comparable.",
457581
+ "After reattaching to a session, the agent panel no longer shows completed rows for agents this session never saw running.",
457582
+ "The footer count of subagent approval requests waiting on you shows a dash when the engine's approval list cannot be read, instead of keeping a stale number.",
457583
+ "Cloud resource uploads detect credential-shaped values with the same rules the engine uses.",
457584
+ "Engine 7.89 refuses to start when a model route URL in your environment cannot be parsed, including a stale ANTHROPIC_BASE_URL you no longer use. sema shows the refusal and names the variable; unset it or fix it to start."
457368
457585
  ]
457369
457586
  },
457370
- productVersion: "1.0.123",
457371
- announcement: "sema 1.0.123 \u2014 engine 7.88.2 pickup (core 7.23.5), client runtime 0.74.3, client SDK 9.8.1, settings schema 3.0.0. Background subagent approval cards are withdrawn without deciding for you; a revived agent shows its new round; credentials echoed by a remote stay out of the transcript and streamed output; a gateway URL with credentials now stops the engine at startup; approving a plan brings no second card; the workflow list says why a run failed.",
457587
+ productVersion: "1.0.124",
457588
+ announcement: "sema 1.0.124 \u2014 engine 7.89.0 pickup (core 7.23.5), client runtime 0.74.5. Permission rules added during a session now reach the engine on your next turn, with a notice when a run is in progress; a background subagent's approval card comes back after every failed delivery you answered; /context shows the tokens the engine measured as freed; no ghost completed rows after reattaching; a dash instead of a stale count when the approval list cannot be read.",
457372
457589
  version: "1.0.91"
457373
457590
  };
457374
457591
  }
@@ -467914,15 +468131,15 @@ function PermissionRuleList(t0) {
467914
468131
  }
467915
468132
  return 0;
467916
468133
  }), lowerQuery = query2.toLowerCase();
467917
- for (let ruleKey of sortedRuleKeys) {
467918
- let rule_2 = rulesByKey.get(ruleKey);
468134
+ for (let ruleKey2 of sortedRuleKeys) {
468135
+ let rule_2 = rulesByKey.get(ruleKey2);
467919
468136
  if (rule_2) {
467920
468137
  let ruleString = permissionRuleValueToString(rule_2.ruleValue);
467921
468138
  if (query2 && !ruleString.toLowerCase().includes(lowerQuery))
467922
468139
  continue;
467923
468140
  options.push({
467924
468141
  label: ruleString,
467925
- value: ruleKey
468142
+ value: ruleKey2
467926
468143
  });
467927
468144
  }
467928
468145
  }
@@ -470714,15 +470931,15 @@ function PluginList({
470714
470931
  }) {
470715
470932
  let errors2 = useAppState((s) => s.plugins.errors), enabledPlugins = useAppState((s) => s.plugins.enabled), disabledPlugins = useAppState((s) => s.plugins.disabled);
470716
470933
  return (0, import_react190.useEffect)(() => {
470717
- let v2 = loadInstalledPluginsV2(), ids = Object.keys(v2.plugins).sort();
470718
- if (ids.length === 0) {
470934
+ let v2 = loadInstalledPluginsV2(), ids2 = Object.keys(v2.plugins).sort();
470935
+ if (ids2.length === 0) {
470719
470936
  onComplete(
470720
470937
  "No plugins installed. Use `/plugin install` to install a plugin."
470721
470938
  );
470722
470939
  return;
470723
470940
  }
470724
470941
  let enabledScopes = getPluginEditableScopes(), loadedEnabledSources = new Set(enabledPlugins.map((p) => p.source)), lines = ["Installed plugins:"], shown = 0;
470725
- for (let id of ids) {
470942
+ for (let id of ids2) {
470726
470943
  let name = id.split("@")[0] ?? id, isEnabled3 = enabledScopes.has(id);
470727
470944
  if (filter2 !== void 0 && filter2 === "enabled" !== isEnabled3) continue;
470728
470945
  let hasError = errors2.some(
@@ -480387,12 +480604,12 @@ function isLoggableMessage(m2) {
480387
480604
  return m2.type === "progress" ? !1 : m2.type === "attachment" && getUserType() !== "ant" ? !!(m2.attachment.type === "hook_additional_context" && isEnvTruthy(process.env.SEMA_CODE_SAVE_HOOK_ADDITIONAL_CONTEXT)) : !0;
480388
480605
  }
480389
480606
  function collectReplIds(messages) {
480390
- let ids = /* @__PURE__ */ new Set();
480607
+ let ids2 = /* @__PURE__ */ new Set();
480391
480608
  for (let m2 of messages)
480392
480609
  if (m2.type === "assistant" && Array.isArray(m2.message.content))
480393
480610
  for (let b3 of m2.message.content)
480394
- b3.type === "tool_use" && b3.name === REPL_TOOL_NAME && ids.add(b3.id);
480395
- return ids;
480611
+ b3.type === "tool_use" && b3.name === REPL_TOOL_NAME && ids2.add(b3.id);
480612
+ return ids2;
480396
480613
  }
480397
480614
  function transformMessagesForExternalTranscript(messages, replIds) {
480398
480615
  return messages.flatMap((m2) => {
@@ -483813,8 +484030,8 @@ function resolveEffective() {
483813
484030
  return resolveEffectiveSettings(consume88Layers());
483814
484031
  }
483815
484032
  function resolveSemaConfigWithEffective(opts) {
483816
- let eff = resolveEffectiveSettings(consume88Layers());
483817
- return { effective: eff, config: toEffectiveConfig(eff, opts) };
484033
+ let layers2 = consume88Layers(), eff = resolveEffectiveSettings(layers2);
484034
+ return { effective: eff, config: toEffectiveConfig(eff, opts), sources: layers2.map((l3) => l3.source) };
483818
484035
  }
483819
484036
  var init_settings5 = __esm({
483820
484037
  "build-src/src/sema/settings/index.ts"() {
@@ -484828,7 +485045,7 @@ function shellApprovalCardPort(req2) {
484828
485045
  let tool = lookup.kind === "tool" ? lookup.tool : genericGateTool(req2.toolName), { callKey, signal } = req2, askDeadlineMs = readAskDeadlineMs(req2) ?? readParkRowDeadline(req2.callKey);
484829
485046
  return new Promise((resolve59) => {
484830
485047
  let selectedPersistRule, selectedPersistRuleBatchOfferIndex, selectedPersistRuleEdited, windowClosedAtMs, lateApproveConfirmedOnce = !1, lateApproveConfirmShown = !1, stagedPermissionUpdates = [], lateDecideWatchdogTimer, settled2 = !1, saidWindowClosed = !1, bornEpoch = getLiveSessionEpoch(), settle3 = (o) => {
484831
- settled2 || (settled2 = !0, signal?.removeEventListener("abort", onAbortSignal), askWindowTimer !== void 0 && clearTimeout(askWindowTimer), askBackstopTimer !== void 0 && clearTimeout(askBackstopTimer), lateDecideWatchdogTimer !== void 0 && clearTimeout(lateDecideWatchdogTimer), liveApprovalCards.delete(callKey), forgetApprovalCardToolCallId(req2.toolCallId, callKey, bornEpoch, saidWindowClosed ? req2.toolName : void 0), journalGateResolved(callKey), resolve59(o));
485048
+ settled2 || (settled2 = !0, signal?.removeEventListener("abort", onAbortSignal), askWindowTimer !== void 0 && clearTimeout(askWindowTimer), askBackstopTimer !== void 0 && clearTimeout(askBackstopTimer), lateDecideWatchdogTimer !== void 0 && clearTimeout(lateDecideWatchdogTimer), liveApprovalCards.delete(callKey), forgetApprovalCardToolCallId(req2.toolCallId, callKey, bornEpoch, saidWindowClosed ? req2.toolName : void 0), journalGateResolved(callKey), (o.kind === "allow" || o.kind === "deny") && noteHumanApprovalCardDecision(callKey), resolve59(o));
484832
485049
  }, removeFromQueue = () => {
484833
485050
  try {
484834
485051
  setQueue((queue3) => queue3.filter((item) => item.toolUseID !== callKey));
@@ -485075,7 +485292,7 @@ function shellApprovalCardPort(req2) {
485075
485292
  onUserInteraction() {
485076
485293
  },
485077
485294
  onAbort() {
485078
- settle3({ kind: "aborted" });
485295
+ noteHumanApprovalCardDecision(callKey), settle3({ kind: "aborted" });
485079
485296
  },
485080
485297
  onAllow(updatedInput, permissionUpdates) {
485081
485298
  settleMaybeLate(buildAllowDecision(updatedInput, permissionUpdates), "approve");
@@ -485115,7 +485332,7 @@ function shellApprovalCardPort(req2) {
485115
485332
  onUserInteraction() {
485116
485333
  },
485117
485334
  onAbort() {
485118
- settle3({ kind: "aborted" });
485335
+ noteHumanApprovalCardDecision(callKey), settle3({ kind: "aborted" });
485119
485336
  },
485120
485337
  onAllow(updatedInput, permissionUpdates) {
485121
485338
  lateApproveConfirmedOnce = !0;
@@ -486215,6 +486432,8 @@ __export(agentsWire_exports, {
486215
486432
  ADAPTER_DIVERGENCES: () => ADAPTER_DIVERGENCES,
486216
486433
  AGENT_MEMORY_WORDS: () => AGENT_MEMORY_WORDS,
486217
486434
  AGENT_MESSAGE_TAG: () => AGENT_MESSAGE_TAG,
486435
+ APPROVAL_NOTE_EDIT_REFUSED_DETAIL: () => APPROVAL_NOTE_EDIT_REFUSED_DETAIL,
486436
+ APPROVAL_NOTE_RETRACTED_DETAIL: () => APPROVAL_NOTE_RETRACTED_DETAIL,
486218
486437
  ASK_ORIGIN_WORDS: () => ASK_ORIGIN_WORDS,
486219
486438
  ASK_PARK_GATE_KINDS: () => ASK_PARK_GATE_KINDS,
486220
486439
  ASK_PARK_ROW_POLL_MS: () => ASK_PARK_ROW_POLL_MS,
@@ -486589,6 +486808,7 @@ __export(agentsWire_exports, {
486589
486808
  approvalCardPortFor: () => approvalCardPortFor,
486590
486809
  approvalCardPortMisses: () => approvalCardPortMisses,
486591
486810
  approvalCardPortMissesFor: () => approvalCardPortMissesFor,
486811
+ approvalOutcomeNoteOf: () => approvalOutcomeNoteOf,
486592
486812
  approvalsStreamLiveDoctorDetail: () => approvalsStreamLiveDoctorDetail,
486593
486813
  armDetachCancel: () => armDetachCancel,
486594
486814
  armPlanReviewApproval: () => armPlanReviewApproval,
@@ -486885,6 +487105,7 @@ __export(agentsWire_exports, {
486885
487105
  isLoopbackWireUrl: () => isLoopbackWireUrl,
486886
487106
  isModelOutputErrorRowText: () => isModelOutputErrorRowText,
486887
487107
  isModelOutputErrorText: () => isModelOutputErrorText,
487108
+ isNewEngineAgentPanelCycle: () => isNewEngineAgentPanelCycle,
486888
487109
  isOutcomeUnknownRowText: () => isOutcomeUnknownRowText,
486889
487110
  isOwnEngineRun: () => isOwnEngineRun,
486890
487111
  isOwnWorkflowRun: () => isOwnWorkflowRun,
@@ -487708,8 +487929,8 @@ function readDisclosureLedger(scope) {
487708
487929
  try {
487709
487930
  let { readFileSync: readFileSync69 } = __require("node:fs"), raw2 = JSON.parse(readFileSync69(path28, "utf8"));
487710
487931
  if (typeof raw2 != "object" || raw2 === null) return EMPTY_LEDGER;
487711
- let ids = raw2.ids;
487712
- return Array.isArray(ids) ? { ids: ids.filter((x3) => typeof x3 == "string" && x3.length > 0) } : EMPTY_LEDGER;
487932
+ let ids2 = raw2.ids;
487933
+ return Array.isArray(ids2) ? { ids: ids2.filter((x3) => typeof x3 == "string" && x3.length > 0) } : EMPTY_LEDGER;
487713
487934
  } catch {
487714
487935
  return EMPTY_LEDGER;
487715
487936
  }
@@ -487718,8 +487939,8 @@ function writeDisclosureLedger(scope, next) {
487718
487939
  let path28 = ledgerPath(scope);
487719
487940
  if (path28 !== null)
487720
487941
  try {
487721
- let { writeFileSync: writeFileSync34, renameSync: renameSync21 } = __require("node:fs"), merged = [...readDisclosureLedger(scope).ids, ...next.ids], ids = [...new Set(merged)].slice(-DISCLOSURE_LEDGER_MAX_IDS), tmp = `${path28}.${String(process.pid)}.tmp`;
487722
- writeFileSync34(tmp, JSON.stringify({ v: 1, ids }), { mode: 384 }), renameSync21(tmp, path28);
487942
+ let { writeFileSync: writeFileSync34, renameSync: renameSync21 } = __require("node:fs"), merged = [...readDisclosureLedger(scope).ids, ...next.ids], ids2 = [...new Set(merged)].slice(-DISCLOSURE_LEDGER_MAX_IDS), tmp = `${path28}.${String(process.pid)}.tmp`;
487943
+ writeFileSync34(tmp, JSON.stringify({ v: 1, ids: ids2 }), { mode: 384 }), renameSync21(tmp, path28);
487723
487944
  } catch {
487724
487945
  }
487725
487946
  }
@@ -488256,16 +488477,17 @@ function createLiveConversationClient(config4) {
488256
488477
  // 🔴 为什么非它不可:帧腿在**出卡之前**就永久认领了这只 ask,而它那一发 respond 失败时壳
488257
488478
  // 这一侧此前看不到 —— 只能靠「连续两张快照都看到已认领∧没决断∧台账无活卡」这条间接
488258
488479
  // 判据把认领放回去(秒级两拍里审批入口是空的)。缺席 = 退回那条间接判据,零变化。
488480
+ // 🔴 **映射归包**(client-core 0.74.5 CC-88,接入档 §73 S-5):`{approvalId, settled,
488481
+ // retracted?, detail?}` 这张便签此前三端各手拼一份(壳这一份是语义母本),0.74.5 起由
488482
+ // `approvalOutcomeNoteOf` 单源出。壳这一格因此只剩**转交**,一条判定、一句文案都不再自铸:
488483
+ // 「落没落定」= `decision !== 'unresolved'`(不看 ack)、撤卡是**独立判别位**原样过境
488484
+ // (不折进 detail:撤卡 = 本端主动放手,与「引擎不收」在 `settled` 上同形却不同义,
488485
+ // 端口那一侧要靠它决定「释放认领但不扣重出卡预算」)、detail 三支的优先序与两句固定文案
488486
+ // (`APPROVAL_NOTE_RETRACTED_DETAIL` / `APPROVAL_NOTE_EDIT_REFUSED_DETAIL`)都在包里。
488487
+ // 切换前对拍 24 形逐键相等(六形骨架 = settled / retracted / editRefused /
488488
+ // respondRefusal 三位各缺其二 / 空 detail / 坏形),格在 suspendedSubagentAskWire.test.ts J8。
488259
488489
  onToolApprovalOutcome: (frame, outcome) => {
488260
- let detail = outcome.retracted === !0 ? "the card was retracted (this host no longer has a decision port for it)" : outcome.editRefused === !0 ? "edits are not accepted on this card" : [outcome.respondRefusal?.errorCode, outcome.respondRefusal?.message].filter((x3) => typeof x3 == "string" && x3 !== "").join(" \xB7 ");
488261
- noteStreamApprovalOutcome({
488262
- approvalId: frame.approvalId,
488263
- settled: outcome.decision !== "unresolved",
488264
- // 🔴 判别位**原样过境**(不折进 detail 文本):撤卡 = 本端主动放手,与「引擎不收」在
488265
- // `settled` 上同形却**不同义** —— 端口那一侧要靠它决定「释放认领但不扣重出卡预算」。
488266
- ...outcome.retracted === !0 ? { retracted: !0 } : {},
488267
- ...detail === "" ? {} : { detail }
488268
- });
488490
+ noteStreamApprovalOutcome(approvalOutcomeNoteOf(frame, outcome));
488269
488491
  }
488270
488492
  };
488271
488493
  }, approvalStreamDeps = {
@@ -488529,6 +488751,7 @@ var ENGINE_TO_CC_TOOL, SUGGESTIONS_TAIL_MAX_ATTEMPTS, SUGGESTIONS_TAIL_RETRY_MS,
488529
488751
  init_engineToolDetach();
488530
488752
  init_dist();
488531
488753
  init_dist();
488754
+ init_dist();
488532
488755
  init_engineSessionParam2();
488533
488756
  init_engineCompactWire2();
488534
488757
  init_liveSessionStore();
@@ -501914,8 +502137,17 @@ var RENDERED_UUID_PREFIX_LEN, init_rewindArm = __esm({
501914
502137
 
501915
502138
  // build-src/src/sema/fleetRowCycleProjection.ts
501916
502139
  function launchAnchorChanged2(existing, ev) {
501917
- let seqOf = (n2) => typeof n2 == "number" && Number.isFinite(n2) ? n2 : void 0, evSeq = seqOf(ev.cycleSeq), rowSeq = seqOf(existing.cycleSeq);
501918
- return evSeq !== void 0 && rowSeq !== void 0 ? evSeq !== rowSeq : typeof ev.startedAt != "number" || !Number.isFinite(ev.startedAt) || existing.startTimeFromWire !== !0 || typeof existing.startTime != "number" || !Number.isFinite(existing.startTime) ? !1 : existing.startTime !== ev.startedAt;
502140
+ return isNewEngineAgentPanelCycle(
502141
+ {
502142
+ ...existing.cycleSeq !== void 0 ? { cycleSeq: existing.cycleSeq } : {},
502143
+ // 见上:只有 wire 给的真锚才是「上一代的 startedAt」,猜测基准一律不交。
502144
+ ...existing.startTimeFromWire === !0 && existing.startTime !== void 0 ? { startedAt: existing.startTime } : {}
502145
+ },
502146
+ {
502147
+ ...ev.cycleSeq !== void 0 ? { cycleSeq: ev.cycleSeq } : {},
502148
+ ...ev.startedAt !== void 0 ? { startedAt: ev.startedAt } : {}
502149
+ }
502150
+ );
501919
502151
  }
501920
502152
  function progressAfterFleetRowFrame(existing, ev) {
501921
502153
  let num = (n2) => typeof n2 == "number" && Number.isFinite(n2), prior = launchAnchorChanged2(existing, ev) ? void 0 : existing.progress, toolUseCount = num(ev.toolUses) ? ev.toolUses : prior?.toolUseCount, tokenCount = num(ev.totalTokens) && (ev.totalTokens > 0 || num(ev.toolUses)) ? ev.totalTokens : prior?.tokenCount;
@@ -501924,6 +502156,7 @@ function progressAfterFleetRowFrame(existing, ev) {
501924
502156
  }
501925
502157
  var init_fleetRowCycleProjection = __esm({
501926
502158
  "build-src/src/sema/fleetRowCycleProjection.ts"() {
502159
+ init_dist();
501927
502160
  }
501928
502161
  });
501929
502162
 
@@ -502019,10 +502252,10 @@ function useEngineAgentPanelBridge(setAppState) {
502019
502252
  let ownedRows = engineOwnedRowIds, reapAbsentRows = React133.useCallback(() => {
502020
502253
  let reaped = [];
502021
502254
  setAppState((prev) => {
502022
- let ids = reapExpiredEngineAgentAbsences(prev.tasks ?? {}, ownedRows);
502023
- if (ids.length === 0) return prev;
502255
+ let ids2 = reapExpiredEngineAgentAbsences(prev.tasks ?? {}, ownedRows);
502256
+ if (ids2.length === 0) return prev;
502024
502257
  let nextTasks = { ...prev.tasks };
502025
- for (let id of ids) {
502258
+ for (let id of ids2) {
502026
502259
  let row2 = nextTasks[id];
502027
502260
  reaped.push({ id, label: row2?.description ?? id }), delete nextTasks[id];
502028
502261
  }
@@ -503210,7 +503443,7 @@ function readRestartInflightLine() {
503210
503443
  workflows,
503211
503444
  leaderStreaming,
503212
503445
  otherSessionsSharing: sharing
503213
- }), ids = (bgReading?.tasks ?? []).filter((t2) => t2.retiredByNotification !== !0).map((t2) => t2.id).sort(), key = JSON.stringify([ids, workflows, leaderStreaming, sharing.total, sharing.midTurn, unknown2]);
503446
+ }), ids2 = (bgReading?.tasks ?? []).filter((t2) => t2.retiredByNotification !== !0).map((t2) => t2.id).sort(), key = JSON.stringify([ids2, workflows, leaderStreaming, sharing.total, sharing.midTurn, unknown2]);
503214
503447
  if (unknown2.length === 0) return { line, key };
503215
503448
  let caveat = `\u26A0 could not read ${unknown2.join(" / ")} \u2014 this list may be incomplete`;
503216
503449
  return { line: line === null ? caveat : `${line}
@@ -539339,6 +539572,168 @@ var DEFAULT_DEBUG_LINES_READ, TAIL_READ_BYTES, init_debug3 = __esm({
539339
539572
  }
539340
539573
  });
539341
539574
 
539575
+ // build-src/src/sema/interactiveSettingsStamp.ts
539576
+ var interactiveSettingsStamp_exports = {};
539577
+ __export(interactiveSettingsStamp_exports, {
539578
+ STAMP_FALLBACK_TRACE: () => STAMP_FALLBACK_TRACE,
539579
+ STAMP_HOLD_ON_UNHEALTHY_READ_TRACE: () => STAMP_HOLD_ON_UNHEALTHY_READ_TRACE,
539580
+ STAMP_STALE_RECOVERED_TRACE: () => STAMP_STALE_RECOVERED_TRACE,
539581
+ _resetSettingsStampStaleForTest: () => _resetSettingsStampStaleForTest,
539582
+ assembleInteractiveWireStamp: () => assembleInteractiveWireStamp,
539583
+ describeSettingsStampStale: () => describeSettingsStampStale,
539584
+ readSettingsStampStale: () => readSettingsStampStale
539585
+ });
539586
+ function describeStampStaleEntered(reason, lastReadAt) {
539587
+ return `settings could not be re-read (${reason}); this turn continues with the settings last read at ${hhmm(lastReadAt)}; rules added since then are not in effect \u2014 run /doctor`;
539588
+ }
539589
+ function hhmm(at) {
539590
+ let d4 = new Date(at);
539591
+ return `${String(d4.getHours()).padStart(2, "0")}:${String(d4.getMinutes()).padStart(2, "0")}`;
539592
+ }
539593
+ function readSettingsStampStale() {
539594
+ return { ...staleState };
539595
+ }
539596
+ function describeSettingsStampStale(s) {
539597
+ return s.stale && s.since !== void 0 ? ` \xB7 stale since ${hhmm(s.since)}` : "";
539598
+ }
539599
+ function _resetSettingsStampStaleForTest() {
539600
+ staleState = { stale: !1 };
539601
+ }
539602
+ function readSessionRulesFromAppState() {
539603
+ try {
539604
+ let ctx = getAppStateStoreRef()?.getState?.()?.toolPermissionContext;
539605
+ return {
539606
+ deny: ctx?.alwaysDenyRules.session ?? [],
539607
+ ask: ctx?.alwaysAskRules.session ?? []
539608
+ };
539609
+ } catch (e) {
539610
+ return logForDebugging(
539611
+ `[sema][settings-stamp] session-rule read failed \u2014 this turn carries the on-disk rules only: ${e instanceof Error ? e.message : String(e)}`
539612
+ ), { deny: [], ask: [] };
539613
+ }
539614
+ }
539615
+ function mergeSessionRules(full, session2) {
539616
+ if (session2.deny.length === 0 && session2.ask.length === 0) return full;
539617
+ let perms = { ...full.permissions ?? {} }, deny2 = [.../* @__PURE__ */ new Set([...perms.deny ?? [], ...session2.deny])], ask2 = [.../* @__PURE__ */ new Set([...perms.ask ?? [], ...session2.ask])];
539618
+ return deny2.length > 0 && (perms.deny = deny2), ask2.length > 0 && (perms.ask = ask2), { ...full, permissions: perms };
539619
+ }
539620
+ function settingsReadHealth() {
539621
+ try {
539622
+ let errs = getSettingsWithErrors().errors;
539623
+ return { sig: JSON.stringify(errs.map((e) => `${e.file}|${e.path}`).sort()), hasProblem: errs.length > 0 };
539624
+ } catch (e) {
539625
+ return logForDebugging(
539626
+ `[sema][settings-stamp] settings health read failed: ${e instanceof Error ? e.message : String(e)}`
539627
+ ), { sig: "<unreadable>", hasProblem: !0 };
539628
+ }
539629
+ }
539630
+ function ruleNamesOf(full) {
539631
+ let perms = full.permissions ?? {};
539632
+ return [
539633
+ .../* @__PURE__ */ new Set([
539634
+ ...(perms.deny ?? []).map((r) => `deny:${r}`),
539635
+ ...(perms.ask ?? []).map((r) => `ask:${r}`)
539636
+ ])
539637
+ ].sort();
539638
+ }
539639
+ function rulesLost(next, prev) {
539640
+ let has2 = new Set(next);
539641
+ return prev.filter((r) => !has2.has(r));
539642
+ }
539643
+ function withRulesReadded(full, lostKeys) {
539644
+ if (lostKeys.length === 0) return full;
539645
+ let perms = { ...full.permissions ?? {} }, deny2 = [
539646
+ .../* @__PURE__ */ new Set([
539647
+ ...perms.deny ?? [],
539648
+ ...lostKeys.filter((k2) => k2.startsWith("deny:")).map((k2) => k2.slice(5))
539649
+ ])
539650
+ ], ask2 = [
539651
+ .../* @__PURE__ */ new Set([
539652
+ ...perms.ask ?? [],
539653
+ ...lostKeys.filter((k2) => k2.startsWith("ask:")).map((k2) => k2.slice(4))
539654
+ ])
539655
+ ];
539656
+ return deny2.length > 0 && (perms.deny = deny2), ask2.length > 0 && (perms.ask = ask2), { ...full, permissions: perms };
539657
+ }
539658
+ function assembleInteractiveWireStamp(opts) {
539659
+ let { stampMode, seamOpts } = opts, resolve59 = opts.resolve ?? (() => resolveSemaConfigWithEffective(seamOpts)), readSessionRules = opts.readSessionRules ?? readSessionRulesFromAppState, surfaceNotice = opts.surfaceNotice ?? ((text2) => surfaceTranscriptSystemNotice(text2, "warning")), announced = /* @__PURE__ */ new Set();
539660
+ function freshUnenforceableNotices(full) {
539661
+ try {
539662
+ let fresh = describeUnenforceableRules(unenforceableSettingsRules(full)).filter((l3) => !announced.has(l3));
539663
+ for (let line of fresh) announced.add(line);
539664
+ return fresh;
539665
+ } catch (e) {
539666
+ return logForDebugging(
539667
+ `[sema][settings-stamp] unenforceable-rule notice failed: ${e instanceof Error ? e.message : String(e)}`
539668
+ ), [];
539669
+ }
539670
+ }
539671
+ let lastGoodFull, lastGoodStamp, lastGoodRules = [], lastGoodSources = [], lastGoodErrSig, lastGoodAt = Date.now(), lastGoodSet = !1, pendingHoldObservation, fallbackAnnounced = !1, holdAnnounced = !1;
539672
+ staleState = { stale: !1 };
539673
+ let staleActive = !1;
539674
+ function recompute() {
539675
+ let { effective, config: config4, sources } = resolve59(), health = settingsReadHealth(), errSig = health.sig, nextFull = mergeSessionRules(toWireSettings(effective, config4), readSessionRules()), cliToolFlags = readCliToolFlagsWire(), nextRules = ruleNamesOf(nextFull), nextSources = [...sources].map(String).sort(), lost = lastGoodSet ? rulesLost(nextRules, lastGoodRules) : [], sourcesLost = lastGoodSet ? lastGoodSources.filter((s) => !nextSources.includes(s)) : [], incomplete = health.hasProblem || sourcesLost.length > 0, observation2 = `${errSig}|${nextSources.join(",")}|${nextRules.join(",")}`;
539676
+ if (lastGoodSet && lost.length > 0 && incomplete && observation2 !== pendingHoldObservation) {
539677
+ pendingHoldObservation = observation2, logForDebugging(
539678
+ `[sema][settings-stamp] incomplete settings read lost ${String(lost.length)} rule(s) \u2014 keeping the previous snapshot for one turn (lost: ${lost.join(",")}; sourcesLost: ${sourcesLost.join(",") || "none"}; readProblem=${String(health.hasProblem)})`
539679
+ ), holdAnnounced || (holdAnnounced = !0, say(STAMP_HOLD_ON_UNHEALTHY_READ_TRACE));
539680
+ let heldFull = withRulesReadded(nextFull, lost), heldStamp = buildWireSettingsStamp(stampMode, heldFull, { cliToolFlags });
539681
+ return setWireStampProvenance({ full: heldFull, sendMode: stampMode, cliToolFlags }), { full: heldFull, stamp: heldStamp };
539682
+ }
539683
+ pendingHoldObservation = void 0;
539684
+ let stamp2 = buildWireSettingsStamp(stampMode, nextFull, { cliToolFlags });
539685
+ return setWireStampProvenance({ full: nextFull, sendMode: stampMode, cliToolFlags }), lastGoodFull = nextFull, lastGoodStamp = stamp2, lastGoodRules = nextRules, lastGoodSources = nextSources, lastGoodErrSig = errSig, lastGoodAt = Date.now(), lastGoodSet = !0, { full: nextFull, stamp: stamp2 };
539686
+ }
539687
+ let say = (text2) => {
539688
+ surfaceNotice(`[sema] ${text2}`) || process.stderr.write(`[sema] ${text2}
539689
+ `);
539690
+ }, supplier = () => {
539691
+ try {
539692
+ let { full, stamp: stamp2 } = recompute();
539693
+ staleActive && (staleActive = !1, staleState = { stale: !1 }, say(STAMP_STALE_RECOVERED_TRACE)), noteStampSentForRun(ruleNamesOf(full));
539694
+ for (let line of freshUnenforceableNotices(full)) say(line);
539695
+ return stamp2;
539696
+ } catch (e) {
539697
+ let detail = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
539698
+ return lastGoodSet ? (logForDebugging(
539699
+ `[sema][settings-stamp] per-turn recompute threw \u2014 reusing the last good snapshot (rules still sent): ${detail}`
539700
+ ), staleActive || (staleActive = !0, staleState = { stale: !0, since: lastGoodAt, reason: detail }, say(describeStampStaleEntered(detail, lastGoodAt))), fallbackAnnounced || (fallbackAnnounced = !0, say(STAMP_FALLBACK_TRACE)), noteStampSentForRun(ruleNamesOf(lastGoodFull ?? {})), setWireStampProvenance({
539701
+ full: lastGoodFull ?? {},
539702
+ sendMode: stampMode,
539703
+ cliToolFlags: readCliToolFlagsWire()
539704
+ }), lastGoodStamp) : failOpen(
539705
+ "P-DEBT-cli.settings.stamp-recompute-never-resolved",
539706
+ void 0,
539707
+ detail
539708
+ );
539709
+ }
539710
+ }, bootWire = {}, bootStamp;
539711
+ try {
539712
+ let first = recompute();
539713
+ bootWire = first.full, bootStamp = first.stamp, freshUnenforceableNotices(first.full);
539714
+ } catch (e) {
539715
+ logForDebugging(
539716
+ `[sema][settings-stamp] boot recompute threw \u2014 the per-turn hook is still installed and will retry: ${e instanceof Error ? e.message : String(e)}`
539717
+ );
539718
+ }
539719
+ return { supplier, bootWire, bootStamp };
539720
+ }
539721
+ var STAMP_FALLBACK_TRACE, STAMP_HOLD_ON_UNHEALTHY_READ_TRACE, STAMP_STALE_RECOVERED_TRACE, staleState, init_interactiveSettingsStamp = __esm({
539722
+ "build-src/src/sema/interactiveSettingsStamp.ts"() {
539723
+ init_debug();
539724
+ init_appStateRef();
539725
+ init_failOpen();
539726
+ init_settingsRulesWire();
539727
+ init_settings5();
539728
+ init_settings2();
539729
+ init_transcriptSystemNotice();
539730
+ init_midTurnRuleNotice();
539731
+ STAMP_FALLBACK_TRACE = "settings-stamp: could not re-read settings this turn \u2014 keeping the previous snapshot (your permission rules are still being sent)", STAMP_HOLD_ON_UNHEALTHY_READ_TRACE = "settings-stamp: this settings read lost permission rules while it was incomplete (a settings file was unreadable, empty, or mid-save) \u2014 keeping those rules in place for one more turn, on top of everything this read did produce";
539732
+ STAMP_STALE_RECOVERED_TRACE = "settings re-read \u2014 your permission rules are current again";
539733
+ staleState = { stale: !1 };
539734
+ }
539735
+ });
539736
+
539342
539737
  // build-src/src/commands/doctor/permissionsPostureRow.ts
539343
539738
  function formatApprovalWindow(ms) {
539344
539739
  return !Number.isFinite(ms) || ms < 0 ? "not observed" : ms % 36e5 === 0 ? `${String(ms / 36e5)}h` : ms % 6e4 === 0 ? `${String(ms / 6e4)}m` : ms % 1e3 === 0 ? `${String(ms / 1e3)}s` : `${String(ms)}ms`;
@@ -539353,7 +539748,7 @@ function modeSegment(r) {
539353
539748
  function permissionsPostureDetail(r) {
539354
539749
  let parts = [];
539355
539750
  return parts.push(modeSegment(r)), parts.push(
539356
- r.wireRules === null ? `permission rules ${NOT_OBSERVED}` : describeWireRules(r.wireRules)
539751
+ (r.wireRules === null ? `permission rules ${NOT_OBSERVED}` : describeWireRules(r.wireRules)) + describeSettingsStampStale(r.wireStampStale)
539357
539752
  ), r.selfSpawnLane === !1 ? parts.push(`approval window ${NOT_OBSERVED} (external engine \u2014 this end does not set its env)`) : r.approvalWindowMs === null ? parts.push(`approval window ${NOT_OBSERVED}`) : parts.push(
539358
539753
  `approval window ${formatApprovalWindow(r.approvalWindowMs)}${r.approvalWindowSource === "env" ? " (env STREAM_ASK_WINDOW_MS, passed through to engines this shell starts)" : ""}`
539359
539754
  ), parts.push(
@@ -539367,6 +539762,7 @@ function permissionsPostureDetail(r) {
539367
539762
  var NOT_OBSERVED, init_permissionsPostureRow = __esm({
539368
539763
  "build-src/src/commands/doctor/permissionsPostureRow.ts"() {
539369
539764
  init_settingsRulesWire();
539765
+ init_interactiveSettingsStamp();
539370
539766
  NOT_OBSERVED = "not observed";
539371
539767
  }
539372
539768
  });
@@ -539721,9 +540117,16 @@ async function readLivePermissionsPosture(engineTarget) {
539721
540117
  } catch {
539722
540118
  classifier = null;
539723
540119
  }
540120
+ let wireStampStale = { stale: !1 };
540121
+ try {
540122
+ let { readSettingsStampStale: readSettingsStampStale2 } = await Promise.resolve().then(() => (init_interactiveSettingsStamp(), interactiveSettingsStamp_exports));
540123
+ wireStampStale = readSettingsStampStale2();
540124
+ } catch {
540125
+ wireStampStale = { stale: !1 };
540126
+ }
539724
540127
  let wireRules = null;
539725
540128
  try {
539726
- let { wireRuleSurface: wireRuleSurface2, resolveSendSettingsMode: resolveSendSettingsMode2, readWireStampProvenance: readWireStampProvenance2 } = await Promise.resolve().then(() => (init_settingsRulesWire(), settingsRulesWire_exports)), frozen = readWireStampProvenance2();
540129
+ let { wireRuleSurface: wireRuleSurface2, resolveSendSettingsMode: resolveSendSettingsMode3, readWireStampProvenance: readWireStampProvenance2 } = await Promise.resolve().then(() => (init_settingsRulesWire(), settingsRulesWire_exports)), frozen = readWireStampProvenance2();
539727
540130
  if (frozen !== void 0)
539728
540131
  wireRules = wireRuleSurface2(frozen.full, {
539729
540132
  sendMode: frozen.sendMode,
@@ -539737,7 +540140,7 @@ async function readLivePermissionsPosture(engineTarget) {
539737
540140
  {
539738
540141
  // 🔴 总开关也是这一段的输入:`SEMA_SEND_SETTINGS=off` 时规则整份不发,读面若不看它
539739
540142
  // 就会报一个不存在的安全姿态。env 视图与播种同律取。
539740
- sendMode: resolveSendSettingsMode2(envView.SEMA_SEND_SETTINGS)
540143
+ sendMode: resolveSendSettingsMode3(envView.SEMA_SEND_SETTINGS)
539741
540144
  }
539742
540145
  );
539743
540146
  }
@@ -539788,6 +540191,7 @@ async function readLivePermissionsPosture(engineTarget) {
539788
540191
  readDenyTiers,
539789
540192
  selfSpawnLane,
539790
540193
  wireRules,
540194
+ wireStampStale,
539791
540195
  writeProtection,
539792
540196
  readFace,
539793
540197
  readFaceDisagreement: readFaceDisagreement2,
@@ -551435,7 +551839,7 @@ async function ensurePrintModeEngine() {
551435
551839
  async function printLaneWireSettings(knobs) {
551436
551840
  if (knobs.mockScenario) return;
551437
551841
  let { resolveSemaConfigWithEffective: resolveSemaConfigWithEffective2 } = await Promise.resolve().then(() => (init_settings5(), settings_exports4)), {
551438
- resolveSendSettingsMode: resolveSendSettingsMode2,
551842
+ resolveSendSettingsMode: resolveSendSettingsMode3,
551439
551843
  buildWireSettingsStamp: buildWireSettingsStamp2,
551440
551844
  toWireSettings: toWireSettings2,
551441
551845
  unenforceableSettingsRules: unenforceableSettingsRules2,
@@ -551447,7 +551851,7 @@ async function printLaneWireSettings(knobs) {
551447
551851
  } = await Promise.resolve().then(() => (init_settingsRulesWire(), settingsRulesWire_exports)), { effective, config: config4 } = resolveSemaConfigWithEffective2(), fullWire = toWireSettings2(effective, config4);
551448
551852
  for (let msg of describeUnenforceableRules2(unenforceableSettingsRules2(fullWire))) emitPrintLaneRuleNotice(msg);
551449
551853
  emitPrintLaneRuleNotice(describeHeadlessAskContentRules2(askContentRulesDeniedHeadless2(fullWire)));
551450
- let stampMode = resolveSendSettingsMode2(knobs.sendSettings), cliToolFlags = readCliToolFlagsWire2();
551854
+ let stampMode = resolveSendSettingsMode3(knobs.sendSettings), cliToolFlags = readCliToolFlagsWire2();
551451
551855
  return setWireStampProvenance2({ full: fullWire, sendMode: stampMode, cliToolFlags }), buildWireSettingsStamp2(stampMode, fullWire, {
551452
551856
  // L-66①:`--tools` / `--disallowedTools` 的壳本地快照。**求值点必须在这里**(晚绑定供给器内),
551453
551857
  // 不能在前置步就读:前置步跑在 `import('../main.js')` 之前,那时 commander 还没解析 argv,
@@ -551713,8 +552117,8 @@ function syncEntriesToTranscriptLines(entries, ctx) {
551713
552117
  leafUuid: lines.length > 0 ? lines[lines.length - 1].uuid : ctx.startingParentUuid ?? null
551714
552118
  };
551715
552119
  }
551716
- function selectEntriesByIds(entries, ids) {
551717
- let want = new Set(ids);
552120
+ function selectEntriesByIds(entries, ids2) {
552121
+ let want = new Set(ids2);
551718
552122
  return entries.filter((e) => want.has(e.id));
551719
552123
  }
551720
552124
  function lastLineUuid(jsonlBody) {
@@ -552113,7 +552517,9 @@ __export(cloudResources_exports, {
552113
552517
  cloudResourceInstall: () => cloudResourceInstall,
552114
552518
  cloudResourceList: () => cloudResourceList,
552115
552519
  cloudResourceRemove: () => cloudResourceRemove,
552116
- cloudResourceSync: () => cloudResourceSync
552520
+ cloudResourceSync: () => cloudResourceSync,
552521
+ findSecretShape: () => findSecretShape,
552522
+ isEnvVarName: () => isEnvVarName
552117
552523
  });
552118
552524
  import { createHash as createHash31 } from "node:crypto";
552119
552525
  import { existsSync as existsSync37, readdirSync as readdirSync15, readFileSync as readFileSync56, statSync as statSync18 } from "node:fs";
@@ -552128,9 +552534,41 @@ function resolveTargetSel(o) {
552128
552534
  );
552129
552535
  return picked.length > 1 && (err6(`Error: ${picked.join(" and ")} conflict \u2014 pass ONE target. The same command writes to whoever the target switch names:`), err6(" (none) your own personal config"), err6(" --user <u> that user's personal config (admin-managed)"), err6(" --team the active space's team standard"), err6(" --space <id> that space's team standard"), err6(" --global the instance-wide standard (instance admin)"), process.exit(1)), o.user ? { kind: "user", username: o.user } : o.global ? { kind: "team", space: "global" } : o.team || o.space ? { kind: "team", space: o.space } : { kind: "me" };
552130
552536
  }
552537
+ function isEnvVarName(s) {
552538
+ return ENV_NAME.safeParse(s).success;
552539
+ }
552540
+ function hasPemPrivateKey(s) {
552541
+ return PEM_PRIVATE_KEY_RE !== null && PEM_PRIVATE_KEY_RE.test(s);
552542
+ }
552543
+ function isSecretShapedLiteral(s) {
552544
+ return containsSecretToken(s) || hasPemPrivateKey(s);
552545
+ }
552546
+ function pathSegment(k2) {
552547
+ return k2.length > PATH_SEGMENT_MAX || isSecretShapedLiteral(k2) ? `<key, ${String(k2.length)} chars, redacted>` : k2;
552548
+ }
552549
+ function firstSecretLeafPath(v2, path28, depth, hit) {
552550
+ if (depth > SECRET_SCAN_MAX_DEPTH) return null;
552551
+ if (typeof v2 == "string") return hit(v2) ? path28 : null;
552552
+ if (Array.isArray(v2)) {
552553
+ for (let i = 0; i < v2.length; i++) {
552554
+ let found = firstSecretLeafPath(v2[i], `${path28}[${String(i)}]`, depth + 1, hit);
552555
+ if (found !== null) return found;
552556
+ }
552557
+ return null;
552558
+ }
552559
+ let rec = asRec3(v2);
552560
+ if (rec === void 0) return null;
552561
+ for (let [k2, child] of Object.entries(rec)) {
552562
+ let seg = `${path28}.${pathSegment(k2)}`;
552563
+ if (hit(k2)) return seg;
552564
+ let found = firstSecretLeafPath(child, seg, depth + 1, hit);
552565
+ if (found !== null) return found;
552566
+ }
552567
+ return null;
552568
+ }
552131
552569
  function findSecretShape(value) {
552132
- let s = JSON.stringify(value) ?? "", m2 = SECRET_SHAPE_RE.exec(s);
552133
- return m2 ? `${(m2[2] ?? m2[0]).slice(0, 8)}\u2026(redacted)` : null;
552570
+ let s = JSON.stringify(value) ?? "", composed = containsSecretToken(s), pemPath = firstSecretLeafPath(value, "$", 0, hasPemPrivateKey);
552571
+ return !composed && pemPath === null ? null : pemPath !== null ? pemPath : firstSecretLeafPath(value, "$", 0, containsSecretToken) ?? "a secret-shaped literal in the payload (redacted)";
552134
552572
  }
552135
552573
  function managedLaneError(forUser, status3, json2) {
552136
552574
  let detail = asStr4(json2.error_description);
@@ -552462,7 +552900,7 @@ async function prepareModel(m2) {
552462
552900
  let api2 = entry.api === "anthropic-messages" ? "anthropic-messages" : "openai-completions";
552463
552901
  entry.api = api2, entry.provider = api2 === "anthropic-messages" ? "anthropic" : asStr4(entry.provider) && entry.provider !== "anthropic" ? entry.provider : "gateway";
552464
552902
  let notes = [], keyEnv = asStr4(entry.apiKeyEnv);
552465
- keyEnv && !ENV_NAME_RE.test(keyEnv) && (delete entry.apiKeyEnv, strippedKeys.push("apiKeyEnv(not an env NAME)"));
552903
+ keyEnv && !isEnvVarName(keyEnv) && (delete entry.apiKeyEnv, strippedKeys.push("apiKeyEnv(not an env NAME)"));
552466
552904
  let hasInlineKey = INLINE_KEY_FIELDS.some((f) => asStr4(m2[f]));
552467
552905
  if (!asStr4(entry.apiKeyEnv) && hasInlineKey) {
552468
552906
  let { keyEnvNameForEntry: keyEnvNameForEntry2 } = await Promise.resolve().then(() => (init_modelChannels(), modelChannels_exports));
@@ -552506,7 +552944,7 @@ function prepareMcp(name, c3) {
552506
552944
  if (!command8) return { name, display: display2, entry: null, notes, skipReason: `server '${name}' has no command` };
552507
552945
  let envRefs = {}, dropped2 = [];
552508
552946
  for (let k2 of Object.keys(asRec3(c3.env) ?? {}))
552509
- ENV_NAME_RE.test(k2) ? envRefs[k2] = k2 : dropped2.push(k2);
552947
+ isEnvVarName(k2) ? envRefs[k2] = k2 : dropped2.push(k2);
552510
552948
  Object.keys(envRefs).length > 0 && notes.push(`env values stripped \u2014 cloud stores refs only; consuming machines must set: ${Object.values(envRefs).join(", ")}`), dropped2.length > 0 && notes.push(`env keys dropped (not env-NAME shaped, cannot be referenced): ${dropped2.join(", ")}`);
552511
552949
  let args = asArr3(c3.args).filter((a) => typeof a == "string");
552512
552950
  return {
@@ -553073,7 +553511,7 @@ async function cloudPublish(options) {
553073
553511
  fail5(e);
553074
553512
  }
553075
553513
  }
553076
- var out4, err6, asRec3, asArr3, asStr4, ENV_NAME_RE, DOMAIN_NAME_RE, SECRET_SHAPE_RE, personalPath, wantsTeam, TEAM_WRITE_ROLE, teamConfigPath, NOUN, ADD_VERB, REMOVE_VERB, DOMAIN, LIST_KEY, LOCAL_SOURCE, MODEL_FIELD_ALLOWLIST, INLINE_KEY_FIELDS, MODEL_ROLES, GIT_SHA_RE, byName, init_cloudResources = __esm({
553514
+ var out4, err6, asRec3, asArr3, asStr4, DOMAIN_NAME_RE, SECRET_SCAN_MAX_DEPTH, PEM_PRIVATE_KEY_RE, PATH_SEGMENT_MAX, personalPath, wantsTeam, TEAM_WRITE_ROLE, teamConfigPath, NOUN, ADD_VERB, REMOVE_VERB, DOMAIN, LIST_KEY, LOCAL_SOURCE, MODEL_FIELD_ALLOWLIST, INLINE_KEY_FIELDS, MODEL_ROLES, GIT_SHA_RE, byName, init_cloudResources = __esm({
553077
553515
  "build-src/src/cli/handlers/cloudResources.ts"() {
553078
553516
  init_types6();
553079
553517
  init_cloudAuth();
@@ -553082,7 +553520,12 @@ var out4, err6, asRec3, asArr3, asStr4, ENV_NAME_RE, DOMAIN_NAME_RE, SECRET_SHAP
553082
553520
  out4 = (line) => process.stdout.write(`${line}
553083
553521
  `), err6 = (line) => process.stderr.write(`${line}
553084
553522
  `);
553085
- asRec3 = (v2) => typeof v2 == "object" && v2 !== null && !Array.isArray(v2) ? v2 : void 0, asArr3 = (v2) => Array.isArray(v2) ? v2 : [], asStr4 = (v2) => typeof v2 == "string" && v2.length > 0 ? v2 : void 0, ENV_NAME_RE = /^[A-Z_][A-Z0-9_]*$/, DOMAIN_NAME_RE = /^[a-z0-9][a-z0-9._-]*$/i, SECRET_SHAPE_RE = /(^|["\s:=,])(sk-[A-Za-z0-9_-]{8,}|gh[opus]_[A-Za-z0-9]{8,}|github_pat_[A-Za-z0-9_]{8,}|xox[baprse]-[A-Za-z0-9-]{8,}|AKIA[0-9A-Z]{12,}|AIza[0-9A-Za-z_-]{20,}|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}|-----BEGIN[A-Z0-9 ]*PRIVATE KEY)/;
553523
+ asRec3 = (v2) => typeof v2 == "object" && v2 !== null && !Array.isArray(v2) ? v2 : void 0, asArr3 = (v2) => Array.isArray(v2) ? v2 : [], asStr4 = (v2) => typeof v2 == "string" && v2.length > 0 ? v2 : void 0;
553524
+ DOMAIN_NAME_RE = /^[a-z0-9][a-z0-9._-]*$/i, SECRET_SCAN_MAX_DEPTH = 24, PEM_PRIVATE_KEY_RE = (() => {
553525
+ let arm4 = SECRET_LITERAL_RE.source.replace(/^\^\(/, "").replace(/\)$/, "").split("|").find((a) => a.includes("PRIVATE KEY"));
553526
+ return arm4 === void 0 ? null : new RegExp(arm4, "i");
553527
+ })();
553528
+ PATH_SEGMENT_MAX = 40;
553086
553529
  personalPath = (domain2, forUser) => forUser ? `/api/v1/users/${encodeURIComponent(forUser)}/config/${domain2}` : `/api/v1/me/config/${domain2}`;
553087
553530
  wantsTeam = (o) => !!(o.team || o.space || o.global);
553088
553531
  TEAM_WRITE_ROLE = { models: "editor", mcp: "publisher", skills: "publisher", plugins: "publisher" };
@@ -563734,7 +564177,7 @@ Usage: sema --remote "your task description"`, () => gracefulShutdown(1));
563734
564177
  pendingHookMessages
563735
564178
  }, renderAndRun);
563736
564179
  }
563737
- }).version("sema 1.0.123", "-v, --version", "Output the version number"), program2.option("-w, --worktree [name]", "Create a new git worktree for this session (optionally specify a name)"), program2.option("--tmux", "Create a tmux session for the worktree (requires --worktree). Uses iTerm2 native panes when available; use --tmux=classic for traditional tmux."), canUserConfigureAdvisor() && program2.addOption(new Option("--advisor <model>", "Enable the server-side advisor tool with the specified model (alias or full ID).").hideHelp()), program2.addOption(new Option("--bg, --background", "Start the session as a background agent and return immediately (manage with `sema agents`)")), program2.command("ps").description("List background sessions").action(async () => {
564180
+ }).version("sema 1.0.124", "-v, --version", "Output the version number"), program2.option("-w, --worktree [name]", "Create a new git worktree for this session (optionally specify a name)"), program2.option("--tmux", "Create a tmux session for the worktree (requires --worktree). Uses iTerm2 native panes when available; use --tmux=classic for traditional tmux."), canUserConfigureAdvisor() && program2.addOption(new Option("--advisor <model>", "Enable the server-side advisor tool with the specified model (alias or full ID).").hideHelp()), program2.addOption(new Option("--bg, --background", "Start the session as a background agent and return immediately (manage with `sema agents`)")), program2.command("ps").description("List background sessions").action(async () => {
563738
564181
  await (await Promise.resolve().then(() => (init_bg2(), bg_exports))).psHandler([]), process.exit(process.exitCode ?? 0);
563739
564182
  }), program2.command("logs [id]").description("Print a background session's recent terminal output").action(async (id) => {
563740
564183
  await (await Promise.resolve().then(() => (init_bg2(), bg_exports))).logsHandler(id, []), process.exit(process.exitCode ?? 0);
@@ -565702,7 +566145,17 @@ function startSuspendedSubagentAskWire(opts) {
565702
566145
  surfaceTranscriptSystemNotice(text2, "warning");
565703
566146
  }), startFeed = opts.deps?.startFeed ?? startApprovalsFeed, sessionId = opts.sessionId(), tracker2 = createSuspendedAskTracker({ ...spreadSessionId(sessionId) });
565704
566147
  installSuspendedAskTracker(tracker2), noteSuspendedAskFeedInstalled(!0);
565705
- let stats3 = { snapshots: 0, surfaced: 0, retracted: 0, upgraded: 0, requeued: 0, rebuilds: 0, released: 0 }, orphanStreak = /* @__PURE__ */ new Map(), openCards = /* @__PURE__ */ new Set(), stopped = !1, onSnapshot = (snap) => {
566148
+ let stats3 = { snapshots: 0, surfaced: 0, retracted: 0, upgraded: 0, requeued: 0, rebuilds: 0, released: 0 }, orphanStreak = /* @__PURE__ */ new Map(), openCards = /* @__PURE__ */ new Set(), exhausted = /* @__PURE__ */ new Set(), stopped = !1, publishCountFrom = (snap) => {
566149
+ if (sessionId === void 0) {
566150
+ noteApprovalsAwaitingDecision(null);
566151
+ return;
566152
+ }
566153
+ try {
566154
+ noteApprovalsAwaitingDecision(countApprovalsAwaitingDecision(snap, { ...spreadSessionId(sessionId) }));
566155
+ } catch (e) {
566156
+ noteApprovalsAwaitingDecision(null), logForDebugging(`[sema][suspendedAsk] countApprovalsAwaitingDecision threw: ${String(e)}`);
566157
+ }
566158
+ }, onSnapshot = (snap) => {
565706
566159
  if (stopped) return;
565707
566160
  stats3.snapshots += 1;
565708
566161
  let now2 = opts.sessionId();
@@ -565713,11 +566166,7 @@ function startSuspendedSubagentAskWire(opts) {
565713
566166
  return;
565714
566167
  }
565715
566168
  let filter2 = spreadSessionId(sessionId);
565716
- try {
565717
- noteApprovalsAwaitingDecision(countApprovalsAwaitingDecision(snap, { ...filter2 }));
565718
- } catch (e) {
565719
- noteApprovalsAwaitingDecision(null), logForDebugging(`[sema][suspendedAsk] countApprovalsAwaitingDecision threw: ${String(e)}`);
565720
- }
566169
+ publishCountFrom(snap);
565721
566170
  let delta;
565722
566171
  try {
565723
566172
  delta = tracker2.ingest(snap);
@@ -565729,19 +566178,19 @@ function startSuspendedSubagentAskWire(opts) {
565729
566178
  let appearedNow = new Set(delta.appeared.map((r) => r.approvalId)), liveIds = /* @__PURE__ */ new Set();
565730
566179
  for (let r of suspendedSubagentAsks(snap, { ...filter2 })) {
565731
566180
  if (liveIds.add(r.approvalId), appearedNow.has(r.approvalId)) continue;
565732
- if (!(suspendedAskClaimed(r.approvalId) && !suspendedAskDecided(r.approvalId) && !suspendedAskSubmitting(r.approvalId) && !openCards.has(r.approvalId) && !liveApprovalCards.has(liveFrameCallKey(r.approvalId)))) {
566181
+ if (!(!exhausted.has(r.approvalId) && suspendedAskClaimed(r.approvalId) && !suspendedAskDecided(r.approvalId) && !suspendedAskSubmitting(r.approvalId) && !openCards.has(r.approvalId) && !liveApprovalCards.has(liveFrameCallKey(r.approvalId)))) {
565733
566182
  orphanStreak.delete(r.approvalId);
565734
566183
  continue;
565735
566184
  }
565736
566185
  let streak = (orphanStreak.get(r.approvalId) ?? 0) + 1;
565737
566186
  orphanStreak.set(r.approvalId, streak), !(streak < 2) && (orphanStreak.delete(r.approvalId), stats3.released += 1, logForDebugging(
565738
566187
  `[sema][suspendedAsk] ${r.approvalId} is still pending on the engine but nothing on this screen owns it (claimed, undecided, no live card for two snapshots) \u2014 releasing the claim so it can be surfaced again`
565739
- ), retryLater(r.approvalId, "the card that claimed it is gone and it is still pending on the engine"));
566188
+ ), retryLater(r.approvalId, "the card that claimed it is gone and it is still pending on the engine", "auto"));
565740
566189
  }
565741
566190
  for (let id of [...orphanStreak.keys()]) liveIds.has(id) || orphanStreak.delete(id);
565742
566191
  noteSuspendedAsksListed(liveIds), pruneVanishedSuspendedAsks(liveIds);
565743
566192
  for (let approvalId of delta.gone)
565744
- openCards.delete(approvalId), orphanStreak.delete(approvalId), forgetSuspendedAsk(approvalId), retract(liveFrameCallKey(approvalId), "settled-elsewhere") && (stats3.retracted += 1);
566193
+ openCards.delete(approvalId), orphanStreak.delete(approvalId), exhausted.delete(approvalId), forgetSuspendedAsk(approvalId), retract(liveFrameCallKey(approvalId), "settled-elsewhere") && (stats3.retracted += 1);
565745
566194
  for (let row2 of delta.upgraded)
565746
566195
  stats3.upgraded += 1, logForDebugging(
565747
566196
  `[sema][suspendedAsk] ${row2.approvalId} upgraded to a full frame after a blind card was already shown \u2014 leaving the shown card as-is (no in-place args refresh on this host)`
@@ -565751,11 +566200,11 @@ function startSuspendedSubagentAskWire(opts) {
565751
566200
  let lane = safeLane(opts.lane);
565752
566201
  (async () => {
565753
566202
  try {
565754
- let outcome = await surface(row2, opts.respond, void 0, lane);
566203
+ let outcome = await surface(row2, opts.respond, void 0, lane), human = takeHumanApprovalCardDecision(liveFrameCallKey(row2.approvalId));
565755
566204
  if (openCards.delete(row2.approvalId), outcome.editRefused === !0) {
565756
566205
  notify5(
565757
566206
  "that approval could not be sent with your edits: this request came from a background subagent and the engine's read face does not carry its tool input, so there is no original to edit. Nothing was decided \u2014 the card will come back so you can allow or deny the call as-is."
565758
- ), retryLater(row2.approvalId, "edits are not accepted on this card");
566207
+ ), retryLater(row2.approvalId, "edits are not accepted on this card", "user", { alreadyNotified: !0 });
565759
566208
  return;
565760
566209
  }
565761
566210
  if (outcome.retracted === !0) {
@@ -565766,41 +566215,91 @@ function startSuspendedSubagentAskWire(opts) {
565766
566215
  }
565767
566216
  if (outcome.decision === "unresolved") {
565768
566217
  let refused = outcome.respondRefusal, detail = refused === void 0 ? "the engine did not confirm it" : [refused.errorCode, refused.message].filter((x3) => typeof x3 == "string" && x3 !== "").join(" \xB7 ");
565769
- retryLater(row2.approvalId, detail === "" ? "the engine did not confirm it" : detail);
566218
+ retryLater(row2.approvalId, detail === "" ? "the engine did not confirm it" : detail, human ? "user" : "auto");
565770
566219
  return;
565771
566220
  }
565772
566221
  noteSuspendedAskDecided(row2.approvalId), orphanStreak.delete(row2.approvalId);
565773
566222
  } catch (e) {
565774
- openCards.delete(row2.approvalId), logForDebugging(`[sema][suspendedAsk] surfaceSuspendedAskAndRespond threw for ${row2.approvalId}: ${String(e)}`), retryLater(row2.approvalId, e instanceof Error ? e.message : String(e));
566223
+ takeHumanApprovalCardDecision(liveFrameCallKey(row2.approvalId)), openCards.delete(row2.approvalId), logForDebugging(`[sema][suspendedAsk] surfaceSuspendedAskAndRespond threw for ${row2.approvalId}: ${String(e)}`), retryLater(row2.approvalId, e instanceof Error ? e.message : String(e), "auto");
565775
566224
  }
565776
566225
  })();
565777
- }, retryLater = (approvalId, why) => {
565778
- if (!takeSuspendedAskRequeueBudget(approvalId, REQUEUE_MAX)) {
565779
- notify5(
565780
- `that background subagent approval could not be delivered to the engine after ${String(REQUEUE_MAX)} attempts (${why}). Nothing was decided here and the request is still waiting on the engine \u2014 run /doctor or send a message to re-check what it is waiting on.`
565781
- ), logForDebugging(`[sema][suspendedAsk] ${approvalId} exhausted the re-surface budget (${why})`);
565782
- return;
565783
- }
565784
- stats3.requeued += 1, logForDebugging(`[sema][suspendedAsk] ${approvalId} did not settle (${why}) \u2014 re-surfacing it`), requeueSuspendedAsk(approvalId);
565785
- };
565786
- installStreamApprovalOutcomeSink((note) => {
565787
- if (!stopped) {
565788
- if (note.settled) {
565789
- noteSuspendedAskDecided(note.approvalId), orphanStreak.delete(note.approvalId), openCards.delete(note.approvalId);
566226
+ }, retryLater = (approvalId, why, leg, o) => {
566227
+ if (leg === "auto") {
566228
+ if (exhausted.has(approvalId)) {
566229
+ logForDebugging(`[sema][suspendedAsk] ${approvalId} already exhausted the re-surface budget \u2014 not repeating (${why})`);
565790
566230
  return;
565791
566231
  }
565792
- if (openCards.delete(note.approvalId), orphanStreak.delete(note.approvalId), note.retracted === !0) {
565793
- requeueSuspendedAsk(note.approvalId), logForDebugging(
565794
- `[sema][suspendedAsk] ${note.approvalId} stream-leg card was retracted without a decision \u2014 claim released, re-surfaceable, no re-surface budget consumed`
565795
- );
566232
+ if (!takeSuspendedAskRequeueBudget(approvalId, REQUEUE_MAX)) {
566233
+ exhausted.add(approvalId), notify5(
566234
+ `that background subagent approval could not be delivered to the engine after ${String(REQUEUE_MAX)} attempts (${why}). Nothing was decided here and the request is still waiting on the engine \u2014 run /doctor or send a message to re-check what it is waiting on.`
566235
+ ), logForDebugging(`[sema][suspendedAsk] ${approvalId} exhausted the re-surface budget (${why})`);
565796
566236
  return;
565797
566237
  }
565798
- retryLater(note.approvalId, note.detail ?? "the engine did not confirm it");
566238
+ } else o?.alreadyNotified !== !0 && notify5(
566239
+ `that background subagent approval could not be delivered to the engine (${why}). Nothing was decided here and the request is still waiting on the engine \u2014 the card is back so you can answer it again, or run /doctor to re-check what it is waiting on.`
566240
+ );
566241
+ stats3.requeued += 1, logForDebugging(`[sema][suspendedAsk] ${approvalId} did not settle (${why}; ${leg} leg) \u2014 re-surfacing it`), requeueSuspendedAsk(approvalId);
566242
+ };
566243
+ installStreamApprovalOutcomeSink((note) => {
566244
+ if (stopped) return;
566245
+ let human = takeHumanApprovalCardDecision(liveFrameCallKey(note.approvalId));
566246
+ if (note.settled) {
566247
+ noteSuspendedAskDecided(note.approvalId), orphanStreak.delete(note.approvalId), openCards.delete(note.approvalId);
566248
+ return;
565799
566249
  }
566250
+ if (openCards.delete(note.approvalId), orphanStreak.delete(note.approvalId), note.retracted === !0) {
566251
+ requeueSuspendedAsk(note.approvalId), logForDebugging(
566252
+ `[sema][suspendedAsk] ${note.approvalId} stream-leg card was retracted without a decision \u2014 claim released, re-surfaceable, no re-surface budget consumed`
566253
+ );
566254
+ return;
566255
+ }
566256
+ retryLater(note.approvalId, note.detail ?? "the engine did not confirm it", human ? "user" : "auto");
565800
566257
  });
565801
- let feed = null;
566258
+ let feed = null, observeApprovalsList = (client3) => {
566259
+ let approvals = client3.approvals, listFn = approvals.list;
566260
+ if (typeof listFn != "function") return client3;
566261
+ let streamFn = approvals.stream, observeSeq = 0, lastObservedSeq = 0, observe2 = (body, failed, seq2) => {
566262
+ if (!stopped) {
566263
+ if (seq2 < lastObservedSeq) {
566264
+ logForDebugging(`[sema][suspendedAsk] dropping out-of-order approvals.list observation #${String(seq2)} (newest observed #${String(lastObservedSeq)})`);
566265
+ return;
566266
+ }
566267
+ lastObservedSeq = seq2;
566268
+ try {
566269
+ if (failed || readLivePendingRows(body).kind === "malformed") {
566270
+ noteApprovalsAwaitingDecision(null);
566271
+ return;
566272
+ }
566273
+ feed !== null && suspendedSubagentAwaitingCount() === null && publishCountFrom(feed.snapshot());
566274
+ } catch (e) {
566275
+ logForDebugging(`[sema][suspendedAsk] approvals.list observer threw: ${String(e)}`);
566276
+ }
566277
+ }
566278
+ };
566279
+ return {
566280
+ approvals: {
566281
+ list: (o) => {
566282
+ let seq2 = ++observeSeq, p;
566283
+ try {
566284
+ p = listFn.call(approvals, o);
566285
+ } catch (e) {
566286
+ throw observe2(void 0, !0, seq2), e;
566287
+ }
566288
+ return Promise.resolve(p).then(
566289
+ (body) => {
566290
+ observe2(body, !1, seq2);
566291
+ },
566292
+ () => {
566293
+ observe2(void 0, !0, seq2);
566294
+ }
566295
+ ), p;
566296
+ },
566297
+ ...streamFn === void 0 ? {} : { stream: (o) => streamFn.call(approvals, o) }
566298
+ }
566299
+ };
566300
+ };
565802
566301
  try {
565803
- feed = startFeed(opts.client, onSnapshot, {
566302
+ feed = startFeed(observeApprovalsList(opts.client), onSnapshot, {
565804
566303
  reconcile: {
565805
566304
  // 🔴 §61 S-2 逐字:「会话有活跃后台代理 ∧ 没有活着的宿主 run」。谓词抛 / 返回非布尔 ⇒ 包按「查」
565806
566305
  // 处置(少查一次 = 一只等人的 ask 迟迟不出现),所以这里不吞成 false。
@@ -566159,11 +566658,11 @@ function partitionSessionReap(records, departedSessionIds) {
566159
566658
  function reapSessionRecords(io, departedSessionIds) {
566160
566659
  if (departedSessionIds.length === 0) return [];
566161
566660
  if (io.mutate) {
566162
- let ids = [], m2 = io.mutate((records) => {
566661
+ let ids2 = [], m2 = io.mutate((records) => {
566163
566662
  let { kept: kept2, reaped: reaped2 } = partitionSessionReap(records, departedSessionIds);
566164
- return ids = reaped2.map((r) => r.id), reaped2.length === 0 ? null : kept2;
566663
+ return ids2 = reaped2.map((r) => r.id), reaped2.length === 0 ? null : kept2;
566165
566664
  });
566166
- return m2.ok || "reason" in m2 && m2.reason === "aborted" ? ids : [];
566665
+ return m2.ok || "reason" in m2 && m2.reason === "aborted" ? ids2 : [];
566167
566666
  }
566168
566667
  let { kept, reaped } = partitionSessionReap(io.load(), departedSessionIds);
566169
566668
  return reaped.length === 0 ? [] : (io.save(kept), reaped.map((r) => r.id));
@@ -566180,15 +566679,15 @@ function pidAlive3(pid) {
566180
566679
  }
566181
566680
  }
566182
566681
  function writeSchedulerClaim(storePath, sessionIds, pid = process.pid) {
566183
- let dir = schedulerClaimsDir(storePath), file2 = join215(dir, `${pid}.json`), ids = [...new Set(sessionIds.filter((id) => typeof id == "string" && id.length > 0))].sort();
566682
+ let dir = schedulerClaimsDir(storePath), file2 = join215(dir, `${pid}.json`), ids2 = [...new Set(sessionIds.filter((id) => typeof id == "string" && id.length > 0))].sort();
566184
566683
  try {
566185
566684
  let prev = JSON.parse(readFileSync66(file2, "utf8"));
566186
566685
  if (Array.isArray(prev.sessionIds) && prev.sessionIds.join(`
566187
- `) === ids.join(`
566686
+ `) === ids2.join(`
566188
566687
  `)) return;
566189
566688
  } catch {
566190
566689
  }
566191
- mkdirSync33(dir, { recursive: !0, mode: 448 }), writeFileSync31(file2, JSON.stringify({ pid, sessionIds: ids, writtenAt: Date.now() }), { mode: 384 });
566690
+ mkdirSync33(dir, { recursive: !0, mode: 448 }), writeFileSync31(file2, JSON.stringify({ pid, sessionIds: ids2, writtenAt: Date.now() }), { mode: 384 });
566192
566691
  }
566193
566692
  function removeSchedulerClaim(storePath, pid = process.pid) {
566194
566693
  try {
@@ -566243,11 +566742,11 @@ function sweepOrphanSessionRecords(io, storePath, opts = {}) {
566243
566742
  return { kept: kept2, reapedIds: reapedIds2 };
566244
566743
  };
566245
566744
  if (io.mutate) {
566246
- let ids = [], m2 = io.mutate((all4) => {
566745
+ let ids2 = [], m2 = io.mutate((all4) => {
566247
566746
  let t2 = partition3(all4);
566248
- return ids = t2.reapedIds, t2.reapedIds.length === 0 ? null : t2.kept;
566747
+ return ids2 = t2.reapedIds, t2.reapedIds.length === 0 ? null : t2.kept;
566249
566748
  });
566250
- return m2.ok || "reason" in m2 && m2.reason === "aborted" ? ids : [];
566749
+ return m2.ok || "reason" in m2 && m2.reason === "aborted" ? ids2 : [];
566251
566750
  }
566252
566751
  let { kept, reapedIds } = partition3(records);
566253
566752
  return reapedIds.length > 0 && io.save(kept), reapedIds;
@@ -566273,10 +566772,10 @@ function ownsScheduledRecord(r) {
566273
566772
  return r.sessionId === current6;
566274
566773
  }
566275
566774
  function currentOwnedSessionIds() {
566276
- let ids = [], live = getLiveSessionId();
566277
- live && ids.push(live);
566775
+ let ids2 = [], live = getLiveSessionId();
566776
+ live && ids2.push(live);
566278
566777
  let shell = String(getSessionId());
566279
- return ids.includes(shell) || ids.push(shell), ids;
566778
+ return ids2.includes(shell) || ids2.push(shell), ids2;
566280
566779
  }
566281
566780
  function wireSchedulerSessionLifecycle(opts = {}) {
566282
566781
  let storePath = opts.storePath ?? schedulerStorePath(), io = fileSchedulerStoreIO(storePath), onError = opts.onError ?? (() => {
@@ -571669,11 +572168,11 @@ async function launchReplProduction() {
571669
572168
  launchMode && (tpc.mode = launchMode), tpc.isBypassPermissionsModeAvailable = isBypassPermissionsModeAvailable, bypassModeLaunch = isBypassPermissionsModeAvailable;
571670
572169
  let effectiveConfig;
571671
572170
  try {
571672
- let { feature: feature3 } = await Promise.resolve().then(() => (init_bun_bundle(), bun_bundle_exports)), { getAutoModeEnabledStateIfCached: getAutoModeEnabledStateIfCached2 } = await Promise.resolve().then(() => (init_permissionSetup(), permissionSetup_exports)), factoryDefaultAutoEligible = getAutoModeEnabledStateIfCached2() !== "disabled";
571673
- effectiveConfig = resolveSemaConfig({
572171
+ let { feature: feature3 } = await Promise.resolve().then(() => (init_bun_bundle(), bun_bundle_exports)), { getAutoModeEnabledStateIfCached: getAutoModeEnabledStateIfCached2 } = await Promise.resolve().then(() => (init_permissionSetup(), permissionSetup_exports)), factoryDefaultAutoEligible = getAutoModeEnabledStateIfCached2() !== "disabled", seamOpts = {
571674
572172
  launchMode,
571675
572173
  factoryDefaultAuto: factoryDefaultAutoEligible
571676
- });
572174
+ };
572175
+ effectiveConfig = resolveSemaConfig(seamOpts);
571677
572176
  let dm = effectiveConfig.derivedMode;
571678
572177
  if (tpc.mode = dm === "bypassPermissions" && !isBypassPermissionsModeAvailable ? "default" : dm, bypassModeLaunch = tpc.mode === "bypassPermissions", tpc.mode === "auto") {
571679
572178
  let { setAutoModeActive: setAutoModeActive2 } = await Promise.resolve().then(() => (init_autoModeState(), autoModeState_exports));
@@ -571696,16 +572195,16 @@ async function launchReplProduction() {
571696
572195
  });
571697
572196
  }
571698
572197
  }
571699
- let stampMode = resolveSendSettingsMode(process.env.SEMA_SEND_SETTINGS), fullWire = toWireSettings(resolveEffective(), effectiveConfig);
572198
+ let stampMode = resolveSendSettingsMode(process.env.SEMA_SEND_SETTINGS), { assembleInteractiveWireStamp: assembleInteractiveWireStamp2 } = await Promise.resolve().then(() => (init_interactiveSettingsStamp(), interactiveSettingsStamp_exports)), wireStampAssembly = assembleInteractiveWireStamp2({ stampMode, seamOpts }), fullWire = wireStampAssembly.bootWire;
571700
572199
  try {
571701
572200
  for (let msg of describeUnenforceableRules(unenforceableSettingsRules(fullWire)))
571702
572201
  process.stderr.write(`[sema] ${msg}
571703
572202
  `), bootFailClosedNotices.push(msg);
571704
572203
  } catch {
571705
572204
  }
571706
- let { readCliToolFlagsWire: readCliToolFlagsWire2 } = await Promise.resolve().then(() => (init_settingsRulesWire(), settingsRulesWire_exports)), stampSupplier = () => buildWireSettingsStamp(stampMode, fullWire, { cliToolFlags: readCliToolFlagsWire2() }), { setSeamConfig: setSeamConfig2 } = await Promise.resolve().then(() => (init_seamQuery(), seamQuery_exports));
571707
- setSeamConfig2(stampSupplier), setWireStampProvenance({ full: fullWire, sendMode: stampMode, cliToolFlags: readCliToolFlagsWire2() });
571708
- let stamp2 = stampSupplier();
572205
+ let stampSupplier = wireStampAssembly.supplier, { setSeamConfig: setSeamConfig2 } = await Promise.resolve().then(() => (init_seamQuery(), seamQuery_exports));
572206
+ setSeamConfig2(stampSupplier);
572207
+ let stamp2 = wireStampAssembly.bootStamp;
571709
572208
  if (stamp2) {
571710
572209
  if (process.env.SEMA_DEBUG) {
571711
572210
  let p = stamp2.permissions ?? {};