@sema-agent/cli 1.0.122 → 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,9 +4354,240 @@ 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.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;
4365
+ }
4366
+ function cycleSeqOf(v2) {
4367
+ let n2 = v2?.cycleSeq;
4368
+ return typeof n2 == "number" && Number.isInteger(n2) && n2 >= 1 ? n2 : void 0;
4369
+ }
4370
+ function startedAtOf(v2) {
4371
+ let n2 = v2?.startedAt;
4372
+ return typeof n2 == "number" && Number.isFinite(n2) && n2 > 0 ? n2 : void 0;
4373
+ }
4374
+ function isStaleEngineAgentPanelEnd(end, current6) {
4375
+ let ec2 = cycleSeqOf(end), cc = cycleSeqOf(current6);
4376
+ if (ec2 !== void 0 && cc !== void 0)
4377
+ return ec2 < cc;
4378
+ let es = startedAtOf(end), cs = startedAtOf(current6);
4379
+ return es !== void 0 && cs !== void 0 ? es < cs : !1;
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
+ }
4426
+ function remember(map2, key, alias2) {
4427
+ if (map2.delete(key), map2.set(key, alias2), map2.size > MAX_IDENTITY_KEYS) {
4428
+ let oldest = map2.keys().next().value;
4429
+ oldest !== void 0 && map2.delete(oldest);
4430
+ }
4431
+ }
4432
+ function resolveEnginePanelTaskId(wireTaskId, parentToolCallId) {
4433
+ let byTranscript = fleetIdByTranscriptId.get(wireTaskId);
4434
+ if (byTranscript !== void 0)
4435
+ return remember(fleetIdByTranscriptId, wireTaskId, byTranscript), identityOf(byTranscript);
4436
+ let byParent = parentToolCallId !== void 0 ? fleetIdByParentToolCallId.get(parentToolCallId) : void 0;
4437
+ return byParent !== void 0 ? (remember(fleetIdByParentToolCallId, parentToolCallId, byParent), identityOf(byParent)) : { taskId: wireTaskId, origin: "wire" };
4438
+ }
4439
+ function identityOf(alias2) {
4440
+ return {
4441
+ taskId: alias2.fleetId,
4442
+ origin: "fleet-row",
4443
+ ...alias2.cycleSeq !== void 0 ? { cycleSeq: alias2.cycleSeq } : {},
4444
+ ...alias2.startedAt !== void 0 ? { startedAt: alias2.startedAt } : {}
4445
+ };
4446
+ }
4447
+ function rememberResolvedWire(wireTaskId, id) {
4448
+ fleetIdByTranscriptId.has(wireTaskId) || remember(fleetIdByTranscriptId, wireTaskId, {
4449
+ fleetId: id.taskId,
4450
+ ...id.cycleSeq !== void 0 ? { cycleSeq: id.cycleSeq } : {},
4451
+ ...id.startedAt !== void 0 ? { startedAt: id.startedAt } : {}
4452
+ });
4453
+ }
4454
+ function ageHeld(except) {
4455
+ for (let [wireId, held] of [...heldWireTicks])
4456
+ wireId !== except && (held.beats += 1, held.beats >= MAX_HELD_WIRE_TICK_BEATS && (heldWireTicks.delete(wireId), deliverEngineAgentPanelEvent(asIsTick(held.ev))));
4457
+ }
4458
+ function migrateResidency(wireTaskId, fleetId) {
4459
+ wireTaskId !== fleetId && residentTaskIds.has(wireTaskId) && (residentTaskIds.delete(wireTaskId), residentTaskIds.add(fleetId));
4460
+ }
4461
+ function normalizedTick(ev, fleetId) {
4462
+ let { cardBound: _cardBound, ...rest } = ev;
4463
+ return migrateResidency(ev.taskId, fleetId), { ...rest, taskId: fleetId, wireTaskId: ev.taskId, taskIdOrigin: "fleet-row" };
4464
+ }
4465
+ function asIsTick(ev) {
4466
+ let { cardBound: _cardBound, ...rest } = ev;
4467
+ return notePublishedWire(ev), { ...rest, taskIdOrigin: "wire" };
4468
+ }
4469
+ function staleWireTick(id) {
4470
+ return isStaleEngineAgentPanelEnd(id, latestCycleByFleetId.get(id.taskId));
4471
+ }
4472
+ function flushHeld(wireTaskId) {
4473
+ let held = heldWireTicks.get(wireTaskId);
4474
+ if (held === void 0)
4475
+ return;
4476
+ if (heldWireTicks.delete(wireTaskId), publishedWireIds.has(held.ev.taskId)) {
4477
+ deliverEngineAgentPanelEvent(asIsTick(held.ev));
4478
+ return;
4479
+ }
4480
+ let id = resolveEnginePanelTaskId(held.ev.taskId, held.ev.parentToolCallId);
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));
4488
+ }
4489
+ function clearEnginePanelTaskResidentByWire(wireTaskId, cycle) {
4490
+ residentTaskIds.delete(wireTaskId);
4491
+ let owner = wireIdByFleetId.get(wireTaskId);
4492
+ owner !== void 0 && !(cycle !== void 0 && isStaleEngineAgentPanelEnd(cycle, owner)) && residentTaskIds.delete(owner.wireId);
4493
+ let id = resolveEnginePanelTaskId(wireTaskId);
4494
+ id.taskId !== wireTaskId && (isStaleEngineAgentPanelEnd(id, latestCycleByFleetId.get(id.taskId)) || residentTaskIds.delete(id.taskId));
4495
+ }
4496
+ function __resetEngineAgentPanelIdentityForTests() {
4497
+ fleetIdByTranscriptId.clear(), fleetIdByParentToolCallId.clear(), heldWireTicks.clear(), latestCycleByFleetId.clear(), publishedWireIds.clear(), publishedWireByParent.clear(), wireIdByFleetId.clear();
4335
4498
  }
4336
4499
  function publishEngineAgentPanelEvent(ev) {
4500
+ switch ((ev.kind === "end" || ev.kind === "sweep") && ageHeld(ev.kind === "sweep" ? void 0 : ev.taskId), ev.kind) {
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
+ }
4508
+ let alias2 = {
4509
+ fleetId: ev.taskId,
4510
+ ...ev.cycleSeq !== void 0 ? { cycleSeq: ev.cycleSeq } : {},
4511
+ ...ev.startedAt !== void 0 ? { startedAt: ev.startedAt } : {}
4512
+ };
4513
+ if ((alias2.cycleSeq !== void 0 || alias2.startedAt !== void 0) && (latestCycleByFleetId.delete(ev.taskId), latestCycleByFleetId.set(ev.taskId, { ...alias2.cycleSeq !== void 0 ? { cycleSeq: alias2.cycleSeq } : {}, ...alias2.startedAt !== void 0 ? { startedAt: alias2.startedAt } : {} }), latestCycleByFleetId.size > MAX_IDENTITY_KEYS)) {
4514
+ let oldest = latestCycleByFleetId.keys().next().value;
4515
+ oldest !== void 0 && latestCycleByFleetId.delete(oldest);
4516
+ }
4517
+ ev.transcriptId !== void 0 && ev.transcriptId.length > 0 && remember(fleetIdByTranscriptId, ev.transcriptId, alias2), ev.parentToolCallId !== void 0 && ev.parentToolCallId.length > 0 && remember(fleetIdByParentToolCallId, ev.parentToolCallId, alias2), deliverEngineAgentPanelEvent(ev);
4518
+ for (let [wireId, held] of [...heldWireTicks])
4519
+ (wireId === ev.transcriptId || held.ev.parentToolCallId !== void 0 && held.ev.parentToolCallId === ev.parentToolCallId) && flushHeld(wireId);
4520
+ ageHeld(void 0);
4521
+ return;
4522
+ }
4523
+ case "tick": {
4524
+ if (publishedWireIds.has(ev.taskId)) {
4525
+ heldWireTicks.delete(ev.taskId), deliverEngineAgentPanelEvent(asIsTick(ev));
4526
+ return;
4527
+ }
4528
+ let id = resolveEnginePanelTaskId(ev.taskId, ev.parentToolCallId);
4529
+ if (id.origin === "fleet-row") {
4530
+ if (heldWireTicks.delete(ev.taskId), staleWireTick(id))
4531
+ return;
4532
+ rememberResolvedWire(ev.taskId, id), deliverEngineAgentPanelEvent(normalizedTick(ev, id.taskId));
4533
+ return;
4534
+ }
4535
+ if (ev.cardBound === !0) {
4536
+ deliverEngineAgentPanelEvent(asIsTick(ev));
4537
+ return;
4538
+ }
4539
+ if (heldWireTicks.has(ev.taskId)) {
4540
+ heldWireTicks.delete(ev.taskId), deliverEngineAgentPanelEvent(asIsTick(ev));
4541
+ return;
4542
+ }
4543
+ if (heldWireTicks.size >= MAX_HELD_WIRE_TICKS) {
4544
+ let oldest = heldWireTicks.keys().next().value;
4545
+ oldest !== void 0 && flushHeld(oldest);
4546
+ }
4547
+ heldWireTicks.set(ev.taskId, { ev, beats: 0 });
4548
+ return;
4549
+ }
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
+ }
4565
+ let id = resolveEnginePanelTaskId(ev.taskId);
4566
+ if (id.origin === "fleet-row" && id.taskId !== ev.taskId) {
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({
4573
+ ...ev,
4574
+ taskId: id.taskId,
4575
+ wireTaskId: ev.taskId,
4576
+ taskIdOrigin: "fleet-row",
4577
+ // end 自己不带周期身份(流内 close 臂恒不带)⇒ 借钥匙上的:复活后迟到的 end{旧 UUID} 由此带着旧代际,消费端按 isStaleEngineAgentPanelEnd 挡掉
4578
+ ...ev.cycleSeq === void 0 && id.cycleSeq !== void 0 ? { cycleSeq: id.cycleSeq } : {},
4579
+ ...ev.startedAt === void 0 && id.startedAt !== void 0 ? { startedAt: id.startedAt } : {}
4580
+ });
4581
+ return;
4582
+ }
4583
+ flushHeld(ev.taskId), deliverEngineAgentPanelEvent(ev), retireWire(ev.taskId), isStaleEngineAgentPanelEnd(ev, latestCycleByFleetId.get(ev.taskId)) || retirePanelRowRunning(ev.taskId);
4584
+ return;
4585
+ }
4586
+ default:
4587
+ deliverEngineAgentPanelEvent(ev);
4588
+ }
4589
+ }
4590
+ function deliverEngineAgentPanelEvent(ev) {
4337
4591
  if (ev.kind !== "sweep" && absenceBuffer.delete(ev.taskId), listener) {
4338
4592
  try {
4339
4593
  listener(ev);
@@ -4392,7 +4646,8 @@ function subscribeEngineAgentPanel(fn2) {
4392
4646
  };
4393
4647
  }
4394
4648
  function publishEngineAgentPanelAbsence(ev) {
4395
- if (absenceListener) {
4649
+ let owner = wireOwnerOf(ev.taskId);
4650
+ if (owner !== void 0 && (ev = { ...ev, taskId: owner, wireTaskId: ev.taskId }), absenceListener) {
4396
4651
  try {
4397
4652
  absenceListener(ev);
4398
4653
  } catch {
@@ -4421,13 +4676,15 @@ function subscribeEngineAgentPanelAbsence(fn2) {
4421
4676
  function __resetEngineAgentPanelAbsenceForTests() {
4422
4677
  absenceListener = null, absenceBuffer.clear();
4423
4678
  }
4424
- var PANEL_TOOLUSES_LANE_POLICY, residentTaskIds, MAX_BUFFER, listener, buffer, 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({
4425
4680
  "node_modules/@sema-agent/client-core/dist/engineAgentPanelStore.js"() {
4681
+ init_panelRunningHistory();
4426
4682
  PANEL_TOOLUSES_LANE_POLICY = {
4427
4683
  tick: "required-engine-always-emits",
4428
4684
  "fleet-row": "optional-tolerate-absent"
4429
4685
  }, residentTaskIds = /* @__PURE__ */ new Set();
4430
4686
  MAX_BUFFER = 200, listener = null, buffer = [];
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();
4431
4688
  MAX_ABSENCE_BUFFER = 200, absenceListener = null, absenceBuffer = /* @__PURE__ */ new Map();
4432
4689
  }
4433
4690
  });
@@ -4967,14 +5224,17 @@ function enqueueBgChildNotification(n2) {
4967
5224
  let terminal = isTaskNotificationTerminalStatus(n2.status);
4968
5225
  if (terminal && (markRunNotified(n2.taskId, cycle), cardEnqueuedRunIds.add(n2.taskId)), terminal)
4969
5226
  try {
4970
- 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({
4971
5228
  kind: "end",
4972
5229
  taskId: n2.taskId,
4973
5230
  // L-215②(0.65.0):读**单铸谓词**而不是内联两词 —— 修前这里只认 `failed`/`killed`,
4974
5231
  // 而 core [6908] 的 `blocked` 是 **agent 自报的终态**(不是等人)⇒ 一条自报走不下去的
4975
5232
  // 后台 run 在面板上被 settle 成**成功**。🔴 `suspended`/`needs_review` 仍不在表里
4976
5233
  // (那两词是「等一次人的决定」,判成终局会把一条正等着你的 run 在面板上判死)。
4977
- isError: isTerminalNotSuccess(n2.status)
5234
+ isError: isTerminalNotSuccess(n2.status),
5235
+ // 0.74.0:周期身份 —— **wire 真给了 seq 才带**。上面的 `cycle` 是去重键用的归一值(缺席归一成首周期),
5236
+ // 那是键不是事实;把它上屏等于对一条没报代际的通知声称「这是第一代」。
5237
+ ...typeof n2.seq == "number" && Number.isInteger(n2.seq) && n2.seq >= BG_FIRST_SEQ ? { cycleSeq: n2.seq } : {}
4978
5238
  });
4979
5239
  } catch {
4980
5240
  }
@@ -7115,7 +7375,7 @@ var init_toolCards = __esm({
7115
7375
 
7116
7376
  // node_modules/@sema-agent/client-core/dist/adapt/panelTasks.js
7117
7377
  function createPanelTaskLedger(ctx, cards, inst) {
7118
- let taskCardBinding = /* @__PURE__ */ new Map(), boundToolCalls = /* @__PURE__ */ new Set(), livePanelTasks = /* @__PURE__ */ new Set(), endedPanelTasks = /* @__PURE__ */ new Set(), liveBoundPanelTasks = /* @__PURE__ */ new Set(), subagentTypeById = /* @__PURE__ */ new Map(), laneOf = (taskId) => {
7378
+ let taskCardBinding = /* @__PURE__ */ new Map(), boundToolCalls = /* @__PURE__ */ new Set(), livePanelTasks = /* @__PURE__ */ new Set(), endedPanelTasks = /* @__PURE__ */ new Set(), liveBoundPanelTasks = /* @__PURE__ */ new Set(), clearResidencyBothKeys = (taskId) => clearEnginePanelTaskResidentByWire(taskId), subagentTypeById = /* @__PURE__ */ new Map(), laneOf = (taskId) => {
7119
7379
  let card = taskCardBinding.get(taskId);
7120
7380
  return card !== void 0 ? { lane: "subagent", parentToolCallId: card } : MAIN;
7121
7381
  };
@@ -7160,8 +7420,8 @@ function createPanelTaskLedger(ctx, cards, inst) {
7160
7420
  },
7161
7421
  // #6 session 常驻台账:live-bound(卡本 turn 开着)= 本 turn 生命周期,turn 末可 sweep;
7162
7422
  // inert/unbound(跨 turn bg 子代形)= 常驻,两处 sweep 都放行,终态只认通知帧。
7163
- noteResidency: (taskId) => {
7164
- liveBoundPanelTasks.has(taskId) ? clearEnginePanelTaskResident(taskId) : markEnginePanelTaskResident(taskId);
7423
+ noteResidency: (taskId, residentKey = taskId) => {
7424
+ liveBoundPanelTasks.has(taskId) ? clearEnginePanelTaskResident(residentKey) : markEnginePanelTaskResident(residentKey);
7165
7425
  },
7166
7426
  /** SubagentStart(cli fireSubagentStartHook 的臂化):类型恒记,fire 一生一次。 */
7167
7427
  *start(taskId, agentType) {
@@ -7208,7 +7468,7 @@ function createPanelTaskLedger(ctx, cards, inst) {
7208
7468
  * (清一次幂等,真终态权威性不变)。
7209
7469
  */
7210
7470
  *settleFromNotification(taskId, isError) {
7211
- clearEnginePanelTaskResident(taskId), !endedPanelTasks.has(taskId) && (endedPanelTasks.add(taskId), yield chrome({
7471
+ clearResidencyBothKeys(taskId), !endedPanelTasks.has(taskId) && (endedPanelTasks.add(taskId), yield chrome({
7212
7472
  kind: "panel_task",
7213
7473
  laneProof: MAIN,
7214
7474
  event: { kind: "end", taskId, isError }
@@ -7233,7 +7493,7 @@ function createPanelTaskLedger(ctx, cards, inst) {
7233
7493
  *settleFromTerminalTick(taskId, isError) {
7234
7494
  if (endedPanelTasks.has(taskId))
7235
7495
  return;
7236
- endedPanelTasks.add(taskId), clearEnginePanelTaskResident(taskId);
7496
+ endedPanelTasks.add(taskId), clearResidencyBothKeys(taskId);
7237
7497
  let lane = laneOf(taskId), card = taskCardBinding.get(taskId);
7238
7498
  if (card !== void 0 && (yield chrome({
7239
7499
  kind: "inline_task_stats",
@@ -7616,7 +7876,7 @@ function safeCut(buf, at) {
7616
7876
  }
7617
7877
  return n2;
7618
7878
  }
7619
- function remember(set2, key) {
7879
+ function remember2(set2, key) {
7620
7880
  if (!set2.has(key)) {
7621
7881
  if (set2.size >= MAX_REPLAY_KEYS) {
7622
7882
  let oldest = set2.values().next().value;
@@ -7626,14 +7886,14 @@ function remember(set2, key) {
7626
7886
  }
7627
7887
  }
7628
7888
  function rememberSegment(s, text2) {
7629
- remember(s.recordedSegments, text2);
7889
+ remember2(s.recordedSegments, text2);
7630
7890
  }
7631
7891
  function scheduleNotify(taskId) {
7632
7892
  pendingNotify.add(taskId), !notifyTimer && (notifyTimer = setTimeout(() => {
7633
7893
  notifyTimer = null;
7634
- let ids = [...pendingNotify];
7894
+ let ids2 = [...pendingNotify];
7635
7895
  if (pendingNotify.clear(), !!notifyListener)
7636
- for (let id of ids)
7896
+ for (let id of ids2)
7637
7897
  try {
7638
7898
  notifyListener(id);
7639
7899
  } catch {
@@ -7658,7 +7918,7 @@ function replaySeen(s, ev) {
7658
7918
  if (typeof id == "string" && id.length > 0) {
7659
7919
  if (s.seenAggregateIds.has(id))
7660
7920
  return !0;
7661
- remember(s.seenAggregateIds, id);
7921
+ remember2(s.seenAggregateIds, id);
7662
7922
  }
7663
7923
  let body = ev.text;
7664
7924
  return !!(typeof body == "string" && s.recordedSegments.has(body));
@@ -7968,6 +8228,7 @@ var assistantArm, userArm, systemArm, diagnosticsArm, steeringInjectedArm, works
7968
8228
  init_toolResult();
7969
8229
  init_workflow();
7970
8230
  init_runTerminal();
8231
+ init_engineAgentPanelStore();
7971
8232
  init_ids();
7972
8233
  init_wireShapes();
7973
8234
  assistantArm = function* (m2, { ctx, idOf, text: text2, cards, inst }) {
@@ -8377,7 +8638,8 @@ var assistantArm, userArm, systemArm, diagnosticsArm, steeringInjectedArm, works
8377
8638
  let agentType = typeof m2.name == "string" && m2.name.length > 0 ? m2.name : "subagent";
8378
8639
  yield* panel.start(taskId, agentType);
8379
8640
  }
8380
- panel.noteResidency(taskId), panel.markLive(taskId), yield chrome({
8641
+ let identity3 = resolveEnginePanelTaskId(taskId, explicitParent);
8642
+ panel.noteResidency(taskId, identity3.taskId), panel.markLive(taskId), yield chrome({
8381
8643
  kind: "panel_task",
8382
8644
  laneProof: panel.laneOf(taskId),
8383
8645
  event: {
@@ -8387,6 +8649,9 @@ var assistantArm, userArm, systemArm, diagnosticsArm, steeringInjectedArm, works
8387
8649
  ...description !== void 0 ? { description } : {},
8388
8650
  ...prompt !== void 0 ? { prompt } : {},
8389
8651
  ...currentAction !== void 0 ? { currentAction } : {},
8652
+ // 0.74.3 CC-70:身份归一的两把钥匙 —— 退路键 + 发布方提示(绑卡 = 同步委派,漏斗不用等 fleet 行)。
8653
+ ...explicitParent !== void 0 ? { parentToolCallId: explicitParent } : {},
8654
+ ...panel.isLiveBound(taskId) ? { cardBound: !0 } : {},
8390
8655
  // 🔴 这里的 `: 0` 与 `fleetAgentPanelProjection` 那句「绝不在本层 `?? 0`」**不矛盾**,
8391
8656
  // 因为不是同一条 lane 的同一种供给形(两层的分层实情写在 `engineAgentPanelStore.ts`
8392
8657
  // 的 `PANEL_TOOLUSES_LANE_POLICY` 上,两条 lane 的可选性由编译钉锁住):
@@ -9026,7 +9291,7 @@ function wireNumberKey(key, v2) {
9026
9291
  }
9027
9292
  function projectWorkflows(rows3) {
9028
9293
  return rows3.map((r) => {
9029
- let startedCount = wireStartedCount(r);
9294
+ let startedCount = wireStartedCount(r), errorCode = wireErrorCode(r);
9030
9295
  return {
9031
9296
  id: r.id,
9032
9297
  // 187 workflow label = `e.summary ?? e.description`(短 label);折成单行,空 → 187 占位符。
@@ -9038,10 +9303,15 @@ function projectWorkflows(rows3) {
9038
9303
  ...wireNumberKey("elapsedMs", wireDuration(r.elapsedMs)),
9039
9304
  ...wireNumberKey("tokens", wireCount(r.tokens)),
9040
9305
  ...wireNumberKey("failedCount", wireCount(r.failedCount)),
9041
- ...startedCount !== void 0 ? { startedCount } : {}
9306
+ ...startedCount !== void 0 ? { startedCount } : {},
9307
+ ...errorCode !== void 0 ? { errorCode } : {}
9042
9308
  };
9043
9309
  });
9044
9310
  }
9311
+ function wireErrorCode(r) {
9312
+ let v2 = r.errorCode;
9313
+ return typeof v2 == "string" && v2.length > 0 ? v2 : void 0;
9314
+ }
9045
9315
  var TERMINAL_FLEET_TASK_STATUSES, CONTROL_TOOL_VERBS, FLEET_TASK_VIEW_KEY_TUPLE, FLEET_TASK_VIEW_KEYS, FLEET_WORKFLOW_VIEW_KEY_TUPLE, FLEET_WORKFLOW_VIEW_KEYS, FLEET_TASK_ROW_WIRE_KEY_TUPLE, FLEET_TASK_ROW_WIRE_KEYS, FLEET_WORKFLOW_ROW_WIRE_KEY_TUPLE, FLEET_WORKFLOW_ROW_WIRE_KEYS, FLEET_TASK_ROW_KEYS_NOT_PROJECTED, FLEET_WORKFLOW_ROW_KEYS_NOT_PROJECTED, init_fleetProjection = __esm({
9046
9316
  "node_modules/@sema-agent/client-core/dist/fleet/fleetProjection.js"() {
9047
9317
  init_fleetTaskDesc();
@@ -9096,7 +9366,8 @@ var TERMINAL_FLEET_TASK_STATUSES, CONTROL_TOOL_VERBS, FLEET_TASK_VIEW_KEY_TUPLE,
9096
9366
  "elapsedMs",
9097
9367
  "tokens",
9098
9368
  "failedCount",
9099
- "startedCount"
9369
+ "startedCount",
9370
+ "errorCode"
9100
9371
  ], FLEET_WORKFLOW_VIEW_KEYS = FLEET_WORKFLOW_VIEW_KEY_TUPLE, FLEET_TASK_ROW_WIRE_KEY_TUPLE = [
9101
9372
  "id",
9102
9373
  "name",
@@ -9194,7 +9465,7 @@ function seenFor(sessionKey) {
9194
9465
  return m2 || (m2 = /* @__PURE__ */ new Map(), seen.set(sessionKey, m2)), m2;
9195
9466
  }
9196
9467
  function resetFleetAgentPanelProjection() {
9197
- seen.clear();
9468
+ seen.clear(), __resetPanelRunningHistoryForTests();
9198
9469
  }
9199
9470
  function resetFleetAgentPanelProjectionFor(sessionKey) {
9200
9471
  seen.delete(sessionKey);
@@ -9217,10 +9488,17 @@ function projectFleetAgentRowsFor(sessionKey, rows3, nowMs2 = Date.now()) {
9217
9488
  if (!taskId)
9218
9489
  continue;
9219
9490
  present2.add(taskId);
9220
- let status3 = row2.status ?? "running", tokens = typeof row2.tokens == "number" && Number.isInteger(row2.tokens) && row2.tokens >= 0 ? row2.tokens : void 0, toolUses = typeof row2.toolUses == "number" ? row2.toolUses : void 0, transcriptId = row2.transcriptId || void 0, startedAt = typeof row2.startedAt == "number" && row2.startedAt > 0 ? row2.startedAt : void 0, currentTool = currentToolKeyOf(row2.currentTool) !== void 0 ? row2.currentTool : void 0, currentToolKey = currentToolKeyOf(row2.currentTool), prev = seenMap.get(taskId), sameCycle = prev !== void 0 && !prev.settled && (startedAt === void 0 || prev.startedAt === void 0 || prev.startedAt === startedAt), knownTokens = tokens !== void 0 ? tokens : sameCycle ? prev?.tokens : void 0, knownStartedAt = startedAt !== void 0 ? startedAt : sameCycle ? prev?.startedAt : void 0;
9491
+ let status3 = row2.status ?? "running", tokens = typeof row2.tokens == "number" && Number.isInteger(row2.tokens) && row2.tokens >= 0 ? row2.tokens : void 0, toolUses = typeof row2.toolUses == "number" ? row2.toolUses : void 0, transcriptId = row2.transcriptId || void 0, parentToolCallId = typeof row2.parentToolCallId == "string" && row2.parentToolCallId.length > 0 ? row2.parentToolCallId : void 0, startedAt = typeof row2.startedAt == "number" && row2.startedAt > 0 ? row2.startedAt : void 0, cycleSeq = typeof row2.cycleSeq == "number" && Number.isInteger(row2.cycleSeq) && row2.cycleSeq >= 1 ? row2.cycleSeq : void 0, currentTool = currentToolKeyOf(row2.currentTool) !== void 0 ? row2.currentTool : void 0, currentToolKey = currentToolKeyOf(row2.currentTool), prev = seenMap.get(taskId), rowIdentity = { ...cycleSeq !== void 0 ? { cycleSeq } : {}, ...startedAt !== void 0 ? { startedAt } : {} }, prevIdentity = prev !== void 0 ? { ...prev.cycleSeq !== void 0 ? { cycleSeq: prev.cycleSeq } : {}, ...prev.startedAt !== void 0 ? { startedAt: prev.startedAt } : {} } : void 0;
9492
+ if (prev !== void 0 && isStaleEngineAgentPanelEnd(rowIdentity, prevIdentity))
9493
+ continue;
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:代际号变了同样是新周期(两条都报了才比;任一条没报 = 这一帧没说)
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;
9221
9496
  if (TERMINAL_FLEET_TASK_STATUSES.has(status3)) {
9222
- prev?.settled || // 最终用量也算(终态帧常是唯一带全 usage 的一帧;消费端不更新非 running ⇒ 必须赶在 end 之前发)
9223
- ((tokens !== void 0 && prev?.tokens !== tokens || toolUses !== void 0 && prev?.toolUses !== toolUses || transcriptId !== void 0 && prev?.transcriptId !== transcriptId || startedAt !== void 0 && prev?.startedAt !== startedAt) && publishEngineAgentPanelEvent({
9497
+ let newbornTerminal = prev === void 0 && panelRowNeverPublishedRunning(taskId);
9498
+ !(prev?.settled === !0 && !rowNewerCycle) && !newbornTerminal && // 0.74.0:周期身份本身推进(或首帧就带身份)也是变化 —— 消费端要先记下身份才能对 end 判陈旧。
9499
+ ((rowNewerCycle || cycleSeq !== void 0 && prev?.cycleSeq !== cycleSeq || // 含首帧(prev 缺席)就带身份的终态
9500
+ // 最终用量也算(终态帧常是唯一带全 usage 的一帧;消费端不更新非 running 行 ⇒ 必须赶在 end 之前发)
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({
9224
9502
  kind: "fleet-row",
9225
9503
  taskId,
9226
9504
  ...row2.name ? { name: row2.name } : {},
@@ -9228,20 +9506,27 @@ function projectFleetAgentRowsFor(sessionKey, rows3, nowMs2 = Date.now()) {
9228
9506
  ...knownTokens !== void 0 ? { totalTokens: knownTokens } : {},
9229
9507
  ...toolUses !== void 0 ? { toolUses } : {},
9230
9508
  ...transcriptId !== void 0 ? { transcriptId } : {},
9231
- ...knownStartedAt !== void 0 ? { startedAt: knownStartedAt } : {}
9509
+ ...parentToolCallId !== void 0 ? { parentToolCallId } : {},
9510
+ ...knownStartedAt !== void 0 ? { startedAt: knownStartedAt } : {},
9511
+ ...knownCycleSeq !== void 0 ? { cycleSeq: knownCycleSeq } : {}
9232
9512
  }), publishEngineAgentPanelEvent({
9233
9513
  kind: "end",
9234
9514
  taskId,
9235
9515
  // L-215② 族扫(0.65.0):与 `notifications.enqueueBgChildNotification` 的 `isError` 位
9236
9516
  // **同一个病形**(内联两词 ⇒ core [6908] 的 `blocked` 漏成「成功」)。两处一次改齐,
9237
9517
  // 读同一个单铸谓词;只修当格 = 下一次加词又漏一处。
9238
- isError: isTerminalNotSuccess(status3)
9518
+ isError: isTerminalNotSuccess(status3),
9519
+ // 0.74.0:这条终态属于哪个周期(在场才带)—— 消费端据此挡掉上一周期迟到的 end。
9520
+ ...knownCycleSeq !== void 0 ? { cycleSeq: knownCycleSeq } : {},
9521
+ ...knownStartedAt !== void 0 ? { startedAt: knownStartedAt } : {}
9239
9522
  })), seenMap.set(taskId, {
9240
9523
  status: status3,
9241
9524
  tokens: knownTokens,
9242
9525
  toolUses: toolUses !== void 0 ? toolUses : prev?.toolUses,
9243
9526
  transcriptId: transcriptId !== void 0 ? transcriptId : prev?.transcriptId,
9527
+ parentToolCallId: parentToolCallId !== void 0 ? parentToolCallId : prev?.parentToolCallId,
9244
9528
  startedAt: knownStartedAt,
9529
+ cycleSeq: knownCycleSeq,
9245
9530
  currentToolKey: currentToolKey !== void 0 ? currentToolKey : prev?.currentToolKey,
9246
9531
  lastSeenAt: nowMs2,
9247
9532
  settled: !0,
@@ -9252,7 +9537,7 @@ function projectFleetAgentRowsFor(sessionKey, rows3, nowMs2 = Date.now()) {
9252
9537
  continue;
9253
9538
  }
9254
9539
  (!prev || prev.settled || prev.absentReportedAtMs !== void 0 || // 行回来了:即使值未变也发一条,消费端据此撤掉 absent 标
9255
- prev.status !== status3 || prev.tokens !== knownTokens || toolUses !== void 0 && prev.toolUses !== toolUses || transcriptId !== void 0 && prev.transcriptId !== transcriptId || startedAt !== void 0 && prev.startedAt !== startedAt || 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({
9256
9541
  kind: "fleet-row",
9257
9542
  taskId,
9258
9543
  ...row2.name ? { name: row2.name } : {},
@@ -9261,14 +9546,18 @@ function projectFleetAgentRowsFor(sessionKey, rows3, nowMs2 = Date.now()) {
9261
9546
  // 🔴 缺席即不落键(消费端据「键在不在」判三态)。
9262
9547
  ...toolUses !== void 0 ? { toolUses } : {},
9263
9548
  ...transcriptId !== void 0 ? { transcriptId } : {},
9549
+ ...parentToolCallId !== void 0 ? { parentToolCallId } : {},
9264
9550
  ...knownStartedAt !== void 0 ? { startedAt: knownStartedAt } : {},
9551
+ ...knownCycleSeq !== void 0 ? { cycleSeq: knownCycleSeq } : {},
9265
9552
  ...currentTool !== void 0 ? { currentTool } : {}
9266
- }), seenMap.set(taskId, {
9553
+ })), seenMap.set(taskId, {
9267
9554
  status: status3,
9268
9555
  tokens: knownTokens,
9269
9556
  toolUses: toolUses !== void 0 ? toolUses : prev?.toolUses,
9270
9557
  transcriptId: transcriptId !== void 0 ? transcriptId : prev?.transcriptId,
9558
+ parentToolCallId: parentToolCallId !== void 0 ? parentToolCallId : prev?.parentToolCallId,
9271
9559
  startedAt: knownStartedAt,
9560
+ cycleSeq: knownCycleSeq,
9272
9561
  currentToolKey: currentToolKey !== void 0 ? currentToolKey : prev?.currentToolKey,
9273
9562
  lastSeenAt: nowMs2,
9274
9563
  settled: !1,
@@ -9295,6 +9584,7 @@ function projectFleetAgentRowsFor(sessionKey, rows3, nowMs2 = Date.now()) {
9295
9584
  var ABSENT_SETTLE_MS, SETTLED_RETENTION_MS, seen, init_fleetAgentPanelProjection = __esm({
9296
9585
  "node_modules/@sema-agent/client-core/dist/fleetAgentPanelProjection.js"() {
9297
9586
  init_engineAgentPanelStore();
9587
+ init_panelRunningHistory();
9298
9588
  init_workflow();
9299
9589
  init_fleetProjection();
9300
9590
  init_sessionSlot();
@@ -9601,6 +9891,29 @@ var installedByKey, init_engineWireTarget = __esm({
9601
9891
  }
9602
9892
  });
9603
9893
 
9894
+ // node_modules/@sema-agent/client-core/dist/engineCapsGenerationGuard.js
9895
+ function snapshotCapsGeneration(opts) {
9896
+ try {
9897
+ return opts?.generation;
9898
+ } catch {
9899
+ return null;
9900
+ }
9901
+ }
9902
+ function capsGenerationStillCurrent(baseUrl, gen) {
9903
+ if (gen === void 0)
9904
+ return !0;
9905
+ try {
9906
+ return gen === engineCapsGeneration(baseUrl);
9907
+ } catch {
9908
+ return !1;
9909
+ }
9910
+ }
9911
+ var init_engineCapsGenerationGuard = __esm({
9912
+ "node_modules/@sema-agent/client-core/dist/engineCapsGenerationGuard.js"() {
9913
+ init_engineCapsCache();
9914
+ }
9915
+ });
9916
+
9604
9917
  // node_modules/@sema-agent/client-core/dist/sqlEngineCapability.js
9605
9918
  function projectSqlEngineCapability(caps) {
9606
9919
  if (caps === null || typeof caps != "object")
@@ -9614,21 +9927,28 @@ function projectSqlEngineCapability(caps) {
9614
9927
  return { kind: "not_reported" };
9615
9928
  if (typeof sql != "object")
9616
9929
  return;
9617
- let s = sql;
9618
- if (!(typeof s.engine != "string" || s.engine === "") && !(typeof s.isolation != "string" || s.isolation === "") && !(s.txnMode !== null && (typeof s.txnMode != "string" || s.txnMode === "")))
9619
- return { kind: "present", view: { engine: s.engine, isolation: s.isolation, txnMode: s.txnMode } };
9930
+ let s = sql, engine = s.engine, isolation = s.isolation, txnMode = s.txnMode;
9931
+ if (!(typeof engine != "string" || engine === "") && !(typeof isolation != "string" || isolation === "") && !(txnMode !== null && (typeof txnMode != "string" || txnMode === "")))
9932
+ return { kind: "present", view: { engine, isolation, txnMode } };
9620
9933
  }
9621
9934
  function noteEngineCapsForSqlEngine(baseUrl, caps, opts) {
9935
+ if (typeof baseUrl != "string" || baseUrl === "")
9936
+ return;
9937
+ let gen = snapshotCapsGeneration(opts);
9938
+ if (gen === null || !capsGenerationStillCurrent(baseUrl, gen))
9939
+ return;
9940
+ let reading;
9622
9941
  try {
9623
- if (typeof baseUrl != "string" || baseUrl === "" || opts?.generation !== void 0 && opts.generation !== engineCapsGeneration(baseUrl))
9624
- return;
9625
- let reading = projectSqlEngineCapability(caps);
9942
+ reading = projectSqlEngineCapability(caps);
9943
+ } catch {
9944
+ reading = void 0;
9945
+ }
9946
+ if (capsGenerationStillCurrent(baseUrl, gen)) {
9626
9947
  if (reading === void 0) {
9627
9948
  readingByBase.delete(baseUrl);
9628
9949
  return;
9629
9950
  }
9630
9951
  readingByBase.set(baseUrl, reading);
9631
- } catch {
9632
9952
  }
9633
9953
  }
9634
9954
  function observedSqlEngine(baseUrl = engineWireTarget()?.baseUrl) {
@@ -9640,7 +9960,7 @@ function cleanSqlDetailScalar(v2) {
9640
9960
  function sqlEngineDoctorDetail(reading) {
9641
9961
  switch (reading.kind) {
9642
9962
  case "unobserved":
9643
- return "not observed \u2014 the engine reports it on /v1/capabilities; this process has not received a capabilities response from the engine yet";
9963
+ return "not observed \u2014 the engine reports it on /v1/capabilities; this process has no usable capabilities reading cached for it (none received, or the last one was unreadable)";
9644
9964
  case "not_reported":
9645
9965
  return "not reported by this engine \u2014 the capability position needs a newer engine";
9646
9966
  case "none":
@@ -9661,7 +9981,7 @@ var readingByBase, SQL_DETAIL_MAX, init_sqlEngineCapability = __esm({
9661
9981
  "node_modules/@sema-agent/client-core/dist/sqlEngineCapability.js"() {
9662
9982
  init_fleetTaskDesc();
9663
9983
  init_engineWireTarget();
9664
- init_engineCapsCache();
9984
+ init_engineCapsGenerationGuard();
9665
9985
  readingByBase = /* @__PURE__ */ new Map();
9666
9986
  SQL_DETAIL_MAX = 40;
9667
9987
  }
@@ -9680,9 +10000,9 @@ function projectWriteProtectionCapability(caps) {
9680
10000
  return { kind: "not_reported" };
9681
10001
  if (typeof wp != "object" || Array.isArray(wp))
9682
10002
  return;
9683
- let w2 = wp;
9684
- if (typeof w2.armed == "boolean" && typeof w2.replaced == "boolean" && !(typeof w2.rows != "number" || !Number.isInteger(w2.rows) || w2.rows < 0))
9685
- return { kind: "present", view: { armed: w2.armed, rows: w2.rows, replaced: w2.replaced } };
10003
+ let w2 = wp, armed3 = w2.armed, replaced = w2.replaced, rows3 = w2.rows;
10004
+ if (typeof armed3 == "boolean" && typeof replaced == "boolean" && !(typeof rows3 != "number" || !Number.isInteger(rows3) || rows3 < 0))
10005
+ return { kind: "present", view: { armed: armed3, rows: rows3, replaced } };
9686
10006
  }
9687
10007
  function projectWriteProtectionPosture(wiring) {
9688
10008
  if (wiring === null || typeof wiring != "object")
@@ -9708,16 +10028,23 @@ function projectWriteProtectionPosture(wiring) {
9708
10028
  };
9709
10029
  }
9710
10030
  function noteEngineCapsForWriteProtection(baseUrl, caps, opts) {
10031
+ if (typeof baseUrl != "string" || baseUrl === "")
10032
+ return;
10033
+ let gen = snapshotCapsGeneration(opts);
10034
+ if (gen === null || !capsGenerationStillCurrent(baseUrl, gen))
10035
+ return;
10036
+ let reading;
9711
10037
  try {
9712
- if (typeof baseUrl != "string" || baseUrl === "" || opts?.generation !== void 0 && opts.generation !== engineCapsGeneration(baseUrl))
9713
- return;
9714
- let reading = projectWriteProtectionCapability(caps);
10038
+ reading = projectWriteProtectionCapability(caps);
10039
+ } catch {
10040
+ reading = void 0;
10041
+ }
10042
+ if (capsGenerationStillCurrent(baseUrl, gen)) {
9715
10043
  if (reading === void 0) {
9716
10044
  readingByBase2.delete(baseUrl);
9717
10045
  return;
9718
10046
  }
9719
10047
  readingByBase2.set(baseUrl, reading);
9720
- } catch {
9721
10048
  }
9722
10049
  }
9723
10050
  function observedWriteProtection(baseUrl = engineWireTarget()?.baseUrl) {
@@ -9726,7 +10053,7 @@ function observedWriteProtection(baseUrl = engineWireTarget()?.baseUrl) {
9726
10053
  function writeProtectionDoctorDetail(reading) {
9727
10054
  switch (reading.kind) {
9728
10055
  case "unobserved":
9729
- return "not observed \u2014 the engine reports it on /v1/capabilities; this process has not received a capabilities response from the engine yet";
10056
+ return "not observed \u2014 the engine reports it on /v1/capabilities; this process has no usable capabilities reading cached for it (none received, or the last one was unreadable)";
9730
10057
  case "not_reported":
9731
10058
  return "not reported by this engine \u2014 the capability position needs a newer engine; this says nothing about whether a protected-name table is in effect (an absent seat is the engine shipping its own default table, not the absence of one)";
9732
10059
  case "none":
@@ -9754,7 +10081,7 @@ var readingByBase2, WP_DETAIL_MAX, init_writeProtectionCapability = __esm({
9754
10081
  "node_modules/@sema-agent/client-core/dist/writeProtectionCapability.js"() {
9755
10082
  init_fleetTaskDesc();
9756
10083
  init_engineWireTarget();
9757
- init_engineCapsCache();
10084
+ init_engineCapsGenerationGuard();
9758
10085
  readingByBase2 = /* @__PURE__ */ new Map();
9759
10086
  WP_DETAIL_MAX = 40;
9760
10087
  }
@@ -9776,16 +10103,23 @@ function projectWebSearchBackendCapability(caps) {
9776
10103
  return backend === WEB_SEARCH_BACKEND_NONE ? { kind: "none" } : { kind: "present", view: { backend } };
9777
10104
  }
9778
10105
  function noteEngineCapsForWebSearchBackend(baseUrl, caps, opts) {
10106
+ if (typeof baseUrl != "string" || baseUrl === "")
10107
+ return;
10108
+ let gen = snapshotCapsGeneration(opts);
10109
+ if (gen === null || !capsGenerationStillCurrent(baseUrl, gen))
10110
+ return;
10111
+ let reading;
9779
10112
  try {
9780
- if (typeof baseUrl != "string" || baseUrl === "" || opts?.generation !== void 0 && opts.generation !== engineCapsGeneration(baseUrl))
9781
- return;
9782
- let reading = projectWebSearchBackendCapability(caps);
10113
+ reading = projectWebSearchBackendCapability(caps);
10114
+ } catch {
10115
+ reading = void 0;
10116
+ }
10117
+ if (capsGenerationStillCurrent(baseUrl, gen)) {
9783
10118
  if (reading === void 0) {
9784
10119
  readingByBase3.delete(baseUrl);
9785
10120
  return;
9786
10121
  }
9787
10122
  readingByBase3.set(baseUrl, reading);
9788
- } catch {
9789
10123
  }
9790
10124
  }
9791
10125
  function observedWebSearchBackend(baseUrl = engineWireTarget()?.baseUrl) {
@@ -9794,7 +10128,7 @@ function observedWebSearchBackend(baseUrl = engineWireTarget()?.baseUrl) {
9794
10128
  function webSearchBackendDoctorDetail(reading) {
9795
10129
  switch (reading.kind) {
9796
10130
  case "unobserved":
9797
- return "deployment default backend not observed \u2014 the engine reports it on /v1/capabilities; this process has not received a capabilities response from the engine yet";
10131
+ return "deployment default backend not observed \u2014 the engine reports it on /v1/capabilities; this process has no usable capabilities reading cached for it (none received, or the last one was unreadable)";
9798
10132
  case "not_reported":
9799
10133
  return "deployment default backend not reported by this engine \u2014 only newer engines advertise it; this does not say whether the deployment has a search backend";
9800
10134
  case "none":
@@ -9813,7 +10147,7 @@ var WEB_SEARCH_BACKEND_NONE, readingByBase3, WS_DETAIL_MAX, DEPLOY_ENV, init_web
9813
10147
  "node_modules/@sema-agent/client-core/dist/webSearchBackendCapability.js"() {
9814
10148
  init_fleetTaskDesc();
9815
10149
  init_engineWireTarget();
9816
- init_engineCapsCache();
10150
+ init_engineCapsGenerationGuard();
9817
10151
  WEB_SEARCH_BACKEND_NONE = "none";
9818
10152
  readingByBase3 = /* @__PURE__ */ new Map();
9819
10153
  WS_DETAIL_MAX = 40, DEPLOY_ENV = "WEB_SEARCH_PROVIDER";
@@ -9836,16 +10170,23 @@ function projectExecutionLaneCapability(caps) {
9836
10170
  return { kind: "present", view: { provider, toolsOnThisHost } };
9837
10171
  }
9838
10172
  function noteEngineCapsForExecutionLane(baseUrl, caps, opts) {
10173
+ if (typeof baseUrl != "string" || baseUrl === "")
10174
+ return;
10175
+ let gen = snapshotCapsGeneration(opts);
10176
+ if (gen === null || !capsGenerationStillCurrent(baseUrl, gen))
10177
+ return;
10178
+ let reading;
9839
10179
  try {
9840
- if (typeof baseUrl != "string" || baseUrl === "" || opts?.generation !== void 0 && opts.generation !== engineCapsGeneration(baseUrl))
9841
- return;
9842
- let reading = projectExecutionLaneCapability(caps);
10180
+ reading = projectExecutionLaneCapability(caps);
10181
+ } catch {
10182
+ reading = void 0;
10183
+ }
10184
+ if (capsGenerationStillCurrent(baseUrl, gen)) {
9843
10185
  if (reading === void 0) {
9844
10186
  readingByBase4.delete(baseUrl);
9845
10187
  return;
9846
10188
  }
9847
10189
  readingByBase4.set(baseUrl, reading);
9848
- } catch {
9849
10190
  }
9850
10191
  }
9851
10192
  function observedExecutionLane(baseUrl = engineWireTarget()?.baseUrl) {
@@ -9860,7 +10201,7 @@ function toolsRunHereFromExecutionLane(reading, legacyInference) {
9860
10201
  function executionLaneDoctorDetail(reading) {
9861
10202
  switch (reading.kind) {
9862
10203
  case "unobserved":
9863
- return "execution lane not observed \u2014 the engine reports it on /v1/capabilities; this process has not received a capabilities response from the engine yet";
10204
+ return "execution lane not observed \u2014 the engine reports it on /v1/capabilities; this process has no usable capabilities reading cached for it (none received, or the last one was unreadable)";
9864
10205
  case "not_reported":
9865
10206
  return "execution lane not reported by this engine \u2014 only newer engines advertise it; this does not say where tools run, so the client keeps inferring it the way it did before";
9866
10207
  case "present": {
@@ -9879,7 +10220,7 @@ var readingByBase4, LANE_DETAIL_MAX, init_executionLaneCapability = __esm({
9879
10220
  "node_modules/@sema-agent/client-core/dist/executionLaneCapability.js"() {
9880
10221
  init_fleetTaskDesc();
9881
10222
  init_engineWireTarget();
9882
- init_engineCapsCache();
10223
+ init_engineCapsGenerationGuard();
9883
10224
  readingByBase4 = /* @__PURE__ */ new Map();
9884
10225
  LANE_DETAIL_MAX = 40;
9885
10226
  }
@@ -9898,16 +10239,23 @@ function projectApprovalsStreamLiveCapability(caps) {
9898
10239
  return { kind: "present", live: v2 };
9899
10240
  }
9900
10241
  function noteEngineCapsForApprovalsStreamLive(baseUrl, caps, opts) {
10242
+ if (typeof baseUrl != "string" || baseUrl === "")
10243
+ return;
10244
+ let gen = snapshotCapsGeneration(opts);
10245
+ if (gen === null || !capsGenerationStillCurrent(baseUrl, gen))
10246
+ return;
10247
+ let reading;
9901
10248
  try {
9902
- if (typeof baseUrl != "string" || baseUrl === "" || opts?.generation !== void 0 && opts.generation !== engineCapsGeneration(baseUrl))
9903
- return;
9904
- let reading = projectApprovalsStreamLiveCapability(caps);
10249
+ reading = projectApprovalsStreamLiveCapability(caps);
10250
+ } catch {
10251
+ reading = void 0;
10252
+ }
10253
+ if (capsGenerationStillCurrent(baseUrl, gen)) {
9905
10254
  if (reading === void 0) {
9906
10255
  readingByBase5.delete(baseUrl);
9907
10256
  return;
9908
10257
  }
9909
10258
  readingByBase5.set(baseUrl, reading);
9910
- } catch {
9911
10259
  }
9912
10260
  }
9913
10261
  function observedApprovalsStreamLive(baseUrl = engineWireTarget()?.baseUrl) {
@@ -9919,7 +10267,7 @@ function livePendingNeedsReconcile(reading) {
9919
10267
  function approvalsStreamLiveDoctorDetail(reading) {
9920
10268
  switch (reading.kind) {
9921
10269
  case "unobserved":
9922
- return "live approval push not observed \u2014 the engine reports it on /v1/capabilities; this process has not received a capabilities response yet, so suspended asks are pulled by the reconcile cadence";
10270
+ return "live approval push not observed \u2014 the engine reports it on /v1/capabilities; this process has no usable capabilities reading cached for it (none received, or the last one was unreadable), so suspended asks are pulled by the reconcile cadence";
9923
10271
  case "not_reported":
9924
10272
  return "live approval push not reported by this engine \u2014 only newer engines advertise it; this does not say whether it pushes, so suspended asks are pulled by the reconcile cadence";
9925
10273
  case "present":
@@ -9935,11 +10283,86 @@ function __resetApprovalsStreamLiveReadingsForTests() {
9935
10283
  var readingByBase5, init_approvalsStreamLiveCapability = __esm({
9936
10284
  "node_modules/@sema-agent/client-core/dist/approvalsStreamLiveCapability.js"() {
9937
10285
  init_engineWireTarget();
9938
- init_engineCapsCache();
10286
+ init_engineCapsGenerationGuard();
9939
10287
  readingByBase5 = /* @__PURE__ */ new Map();
9940
10288
  }
9941
10289
  });
9942
10290
 
10291
+ // node_modules/@sema-agent/client-core/dist/deviceExecutorManagementCapability.js
10292
+ function projectDeviceExecutorManagementCapability(caps) {
10293
+ if (caps === null || typeof caps != "object")
10294
+ return;
10295
+ let c3 = caps;
10296
+ if (!Object.hasOwn(c3, "deviceExecutor"))
10297
+ return { kind: "not_reported", why: "capability_absent" };
10298
+ let d4 = c3.deviceExecutor;
10299
+ if (d4 === void 0)
10300
+ return { kind: "not_reported", why: "capability_absent" };
10301
+ if (d4 === !1)
10302
+ return { kind: "lane_absent" };
10303
+ if (d4 === null || typeof d4 != "object" || Array.isArray(d4))
10304
+ return;
10305
+ let o = d4;
10306
+ if (!Object.hasOwn(o, "management"))
10307
+ return { kind: "not_reported", why: "management_absent" };
10308
+ let mgmt = o.management;
10309
+ if (mgmt === void 0)
10310
+ return { kind: "not_reported", why: "management_absent" };
10311
+ if (typeof mgmt == "boolean")
10312
+ return { kind: "present", management: mgmt };
10313
+ }
10314
+ function noteEngineCapsForDeviceExecutorManagement(baseUrl, caps, opts) {
10315
+ if (typeof baseUrl != "string" || baseUrl === "")
10316
+ return;
10317
+ let gen = snapshotCapsGeneration(opts);
10318
+ if (gen === null || !capsGenerationStillCurrent(baseUrl, gen))
10319
+ return;
10320
+ let reading;
10321
+ try {
10322
+ reading = projectDeviceExecutorManagementCapability(caps);
10323
+ } catch {
10324
+ reading = void 0;
10325
+ }
10326
+ if (capsGenerationStillCurrent(baseUrl, gen)) {
10327
+ if (reading === void 0) {
10328
+ readingByBase6.delete(baseUrl);
10329
+ return;
10330
+ }
10331
+ readingByBase6.set(baseUrl, reading);
10332
+ }
10333
+ }
10334
+ function observedDeviceExecutorManagement(baseUrl = engineWireTarget()?.baseUrl) {
10335
+ return typeof baseUrl != "string" || baseUrl === "" ? { kind: "unobserved" } : readingByBase6.get(baseUrl) ?? { kind: "unobserved" };
10336
+ }
10337
+ function deviceManagementVerbsAvailable(reading) {
10338
+ return reading.kind === "present" ? reading.management ? "yes" : "no" : reading.kind === "lane_absent" ? "no" : "unknown";
10339
+ }
10340
+ function deviceExecutorManagementDoctorDetail(reading) {
10341
+ switch (reading.kind) {
10342
+ case "unobserved":
10343
+ return "device management face not observed \u2014 the engine reports it on /v1/capabilities (deviceExecutor.management); this process has no usable capabilities reading cached for it (none received, or the last one was unreadable)";
10344
+ case "not_reported":
10345
+ return reading.why === "management_absent" ? "device management face not reported by this engine \u2014 the device lane is advertised but only newer engines say whether the /v1/devices management verbs exist; this does not say whether they exist, probe them directly" : "device executor capability not reported by this engine \u2014 only newer engines advertise the device lane at all; this does not say whether it exists";
10346
+ case "lane_absent":
10347
+ return "no device lane on this deployment \u2014 the /v1/devices management verbs are unavailable (capability.device_lane_required)";
10348
+ case "present":
10349
+ return reading.management ? "device management face on \u2014 the /v1/devices management verbs are available on this engine" : "device lane on but the /v1/devices management verbs are off on this deployment";
10350
+ }
10351
+ }
10352
+ function forgetDeviceExecutorManagementReading(baseUrl) {
10353
+ typeof baseUrl != "string" || baseUrl === "" || readingByBase6.delete(baseUrl);
10354
+ }
10355
+ function __resetDeviceExecutorManagementReadingsForTests() {
10356
+ readingByBase6.clear();
10357
+ }
10358
+ var readingByBase6, init_deviceExecutorManagementCapability = __esm({
10359
+ "node_modules/@sema-agent/client-core/dist/deviceExecutorManagementCapability.js"() {
10360
+ init_engineWireTarget();
10361
+ init_engineCapsGenerationGuard();
10362
+ readingByBase6 = /* @__PURE__ */ new Map();
10363
+ }
10364
+ });
10365
+
9943
10366
  // node_modules/@sema-agent/client-core/dist/mcpReconnect.js
9944
10367
  function projectStatus(raw2) {
9945
10368
  if (!isRecord(raw2) || !nonEmpty(raw2.name) || !nonEmpty(raw2.status))
@@ -10128,6 +10551,85 @@ var LEADER_RUN_STATUSES, LEADER_REJ_HEAD_DISPLAY_MAX, DETAIL_FILES_MAX, DETAIL_P
10128
10551
  }
10129
10552
  });
10130
10553
 
10554
+ // node_modules/@sema-agent/client-core/dist/runCancelContext.js
10555
+ function nonNegFinite(v2) {
10556
+ return typeof v2 == "number" && Number.isFinite(v2) && v2 >= 0 ? v2 : void 0;
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
+ }
10565
+ function readRunCancelContext(record3) {
10566
+ if (record3 === null || typeof record3 != "object")
10567
+ return;
10568
+ let holder = runResultHolder(record3);
10569
+ if (!Object.hasOwn(holder, "cancelContext") || holder.cancelContext === void 0)
10570
+ return { kind: "not_reported" };
10571
+ let c3 = holder.cancelContext;
10572
+ if (c3 === null || typeof c3 != "object" || Array.isArray(c3))
10573
+ return;
10574
+ let o = c3, kind = typeof o.lastEventKind == "string" && o.lastEventKind.length > 0 ? o.lastEventKind : void 0, age = nonNegFinite(o.lastEventAgeMs), elapsed = nonNegFinite(o.elapsedMs), brain = o.lastBrainStatus !== null && typeof o.lastBrainStatus == "object" && !Array.isArray(o.lastBrainStatus) ? o.lastBrainStatus : void 0;
10575
+ return {
10576
+ kind: "present",
10577
+ context: {
10578
+ ...kind !== void 0 ? { lastEventKind: kind } : {},
10579
+ ...age !== void 0 ? { lastEventAgeMs: age } : {},
10580
+ ...elapsed !== void 0 ? { elapsedMs: elapsed } : {},
10581
+ ...brain !== void 0 ? { lastBrainStatus: brain } : {}
10582
+ }
10583
+ };
10584
+ }
10585
+ function classifyRunAbortCause(record3) {
10586
+ if (record3 === null || typeof record3 != "object")
10587
+ return { kind: "unknown" };
10588
+ let r = record3, status3 = typeof r.status == "string" && r.status.length > 0 ? r.status : void 0, read = readRunTerminal(runResultHolder(r));
10589
+ if (read !== null && read.kind === "failed") {
10590
+ if (read.code === RUN_CANCELLED_CODE) {
10591
+ let cc = readRunCancelContext(record3);
10592
+ return { kind: "cancelled", ...cc?.kind === "present" ? { context: cc.context } : {} };
10593
+ }
10594
+ return { kind: "engine_error", ...read.code !== void 0 ? { code: read.code } : {}, ...read.message !== void 0 ? { message: read.message } : {} };
10595
+ }
10596
+ return read !== null && read.kind === "paused" ? { kind: "run_still_live", ...status3 !== void 0 ? { status: status3 } : {} } : (read === null || read.kind === "unknown") && status3 !== void 0 && LIVE_STATUSES.has(status3) ? { kind: "run_still_live", status: status3 } : { kind: "unknown", ...read !== null ? { terminal: read.kind } : {} };
10597
+ }
10598
+ var RUN_CANCELLED_CODE, LIVE_STATUSES, init_runCancelContext = __esm({
10599
+ "node_modules/@sema-agent/client-core/dist/runCancelContext.js"() {
10600
+ init_runTerminal();
10601
+ RUN_CANCELLED_CODE = "cancelled", LIVE_STATUSES = /* @__PURE__ */ new Set(["running", "queued", "suspended", "needs_review"]);
10602
+ }
10603
+ });
10604
+
10605
+ // node_modules/@sema-agent/client-core/dist/argvFlagValue.js
10606
+ function lastFlagValue(argv, name, onMissingValue = "invalidate") {
10607
+ let eq2 = `${name}=`, present2 = !1, raw2, valueMissing = !1;
10608
+ for (let i = 0; i < argv.length; i++) {
10609
+ let a = argv[i];
10610
+ if (a !== void 0) {
10611
+ if (a === "--")
10612
+ break;
10613
+ if (a === name) {
10614
+ present2 = !0;
10615
+ let nxt = argv[i + 1];
10616
+ if (nxt === void 0 || nxt.startsWith("-")) {
10617
+ if (onMissingValue === "latch-previous")
10618
+ continue;
10619
+ valueMissing = !0, raw2 = void 0;
10620
+ continue;
10621
+ }
10622
+ valueMissing = !1, raw2 = nxt, i++;
10623
+ } else a.startsWith(eq2) && (present2 = !0, valueMissing = !1, raw2 = a.slice(eq2.length));
10624
+ }
10625
+ }
10626
+ return present2 ? valueMissing || raw2 === void 0 ? { present: !0 } : { present: !0, raw: raw2 } : { present: !1 };
10627
+ }
10628
+ var init_argvFlagValue = __esm({
10629
+ "node_modules/@sema-agent/client-core/dist/argvFlagValue.js"() {
10630
+ }
10631
+ });
10632
+
10131
10633
  // node_modules/@sema-agent/client-core/dist/readFacePosture.js
10132
10634
  function projectReadFacePosture(wiring) {
10133
10635
  if (typeof wiring != "object" || wiring === null || Array.isArray(wiring) || !("readFace" in wiring))
@@ -10690,7 +11192,7 @@ function eventToSdkMessage(ev, ctx) {
10690
11192
  // 臂上**还没有座位** ⇒ 这里是防御 raw 读(同 `label` / `model` 的既有姿势)。退役条件 =
10691
11193
  // sdk 补上该位的当天,`run-compaction-boundary-projection-test.mjs` F10 行当场红逼复核。
10692
11194
  case "compacted": {
10693
- 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;
10694
11196
  return projected(stamp(ctx, {
10695
11197
  type: "system",
10696
11198
  subtype: "compact_boundary",
@@ -10702,7 +11204,8 @@ function eventToSdkMessage(ev, ctx) {
10702
11204
  trigger: typeof ev.trigger == "string" && ev.trigger.length > 0 ? ev.trigger : "auto",
10703
11205
  pre_tokens: ev.tokensBefore ?? 0,
10704
11206
  ...typeof firstKeptEntryId == "string" && firstKeptEntryId.length > 0 ? { _sema_preserved_segment: { firstKeptEntryId } } : {},
10705
- ...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 } : {}
10706
11209
  },
10707
11210
  ...Array.isArray(attachedFiles) && attachedFiles.length > 0 ? { attachedFiles } : {}
10708
11211
  }));
@@ -12684,11 +13187,11 @@ function toolNameKey(name) {
12684
13187
  function classifierDenyDisplay(toolName2, args) {
12685
13188
  let fallback = toolName2.length > 0 ? toolName2 : "tool", key = DISPLAY_ARG_KEY_BY_TOOL.get(toolNameKey(toolName2));
12686
13189
  if (key === void 0 || args === null || typeof args != "object")
12687
- return bounded(fallback);
13190
+ return bounded2(fallback);
12688
13191
  let raw2 = args[key];
12689
- 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);
12690
13193
  }
12691
- function bounded(s) {
13194
+ function bounded2(s) {
12692
13195
  if (s.length <= CLASSIFIER_DENY_DISPLAY_MAX)
12693
13196
  return s;
12694
13197
  let keep = CLASSIFIER_DENY_DISPLAY_MAX - 1, cut = s.slice(0, keep), last4 = cut.charCodeAt(cut.length - 1), next = s.charCodeAt(keep);
@@ -15406,34 +15909,6 @@ var ensured, init_scratchpadWireCaps = __esm({
15406
15909
  }
15407
15910
  });
15408
15911
 
15409
- // node_modules/@sema-agent/client-core/dist/argvFlagValue.js
15410
- function lastFlagValue(argv, name, onMissingValue = "invalidate") {
15411
- let eq2 = `${name}=`, present2 = !1, raw2, valueMissing = !1;
15412
- for (let i = 0; i < argv.length; i++) {
15413
- let a = argv[i];
15414
- if (a !== void 0) {
15415
- if (a === "--")
15416
- break;
15417
- if (a === name) {
15418
- present2 = !0;
15419
- let nxt = argv[i + 1];
15420
- if (nxt === void 0 || nxt.startsWith("-")) {
15421
- if (onMissingValue === "latch-previous")
15422
- continue;
15423
- valueMissing = !0, raw2 = void 0;
15424
- continue;
15425
- }
15426
- valueMissing = !1, raw2 = nxt, i++;
15427
- } else a.startsWith(eq2) && (present2 = !0, valueMissing = !1, raw2 = a.slice(eq2.length));
15428
- }
15429
- }
15430
- return present2 ? valueMissing || raw2 === void 0 ? { present: !0 } : { present: !0, raw: raw2 } : { present: !1 };
15431
- }
15432
- var init_argvFlagValue = __esm({
15433
- "node_modules/@sema-agent/client-core/dist/argvFlagValue.js"() {
15434
- }
15435
- });
15436
-
15437
15912
  // node_modules/@sema-agent/client-core/dist/sandboxWire.js
15438
15913
  function parseSandboxArgv(argv) {
15439
15914
  let flag = lastFlagValue(argv, "--sandbox");
@@ -16255,7 +16730,20 @@ function isElapsedBase(v2) {
16255
16730
  return typeof v2 == "number" && Number.isFinite(v2) && v2 >= 0;
16256
16731
  }
16257
16732
  function createFleetLedger(hooks2 = {}, opts = {}) {
16258
- let sessionKey = opts.sessionKey ?? DEFAULT_SESSION_KEY, nowFn = opts.nowFn ?? Date.now, taskMap = /* @__PURE__ */ new Map(), wfMap = /* @__PURE__ */ new Map(), rowMeta = /* @__PURE__ */ new Map(), retained = /* @__PURE__ */ new Map(), droppedMalformed = 0, droppedUnknownFrame = 0, droppedForeignBgNotification = 0, droppedStaleIngress = 0, connected = !1, version4 = null, scoped = null, sessionScopedMeta, bgNotifyFailClosedMeta = !1, disposed4 = !1, epochSeq = 0, liveStreamEpoch = 0, liveSnapshotEpoch = 0, streamAnchor, everIssuedStream = !1, contentAnchor, contentAnchorSet = !1, ledgerWrites = 0, debug5 = (line) => {
16733
+ let sessionKey = opts.sessionKey ?? DEFAULT_SESSION_KEY, nowFn = opts.nowFn ?? Date.now, taskMap = /* @__PURE__ */ new Map(), wfMap = /* @__PURE__ */ new Map(), rowMeta = /* @__PURE__ */ new Map(), retained = /* @__PURE__ */ new Map(), cycleWatermark = /* @__PURE__ */ new Map(), CYCLE_WATERMARK_MAX = 512;
16734
+ function raiseCycleWatermark(tail, gen) {
16735
+ if (gen === void 0 || tail.length === 0)
16736
+ return;
16737
+ let prior = cycleWatermark.get(tail);
16738
+ if (!(prior !== void 0 && prior >= gen)) {
16739
+ if (cycleWatermark.delete(tail), cycleWatermark.size >= CYCLE_WATERMARK_MAX) {
16740
+ let oldest = cycleWatermark.keys().next().value;
16741
+ oldest !== void 0 && cycleWatermark.delete(oldest);
16742
+ }
16743
+ cycleWatermark.set(tail, gen);
16744
+ }
16745
+ }
16746
+ let droppedMalformed = 0, droppedUnknownFrame = 0, droppedForeignBgNotification = 0, droppedStaleIngress = 0, connected = !1, version4 = null, scoped = null, sessionScopedMeta, bgNotifyFailClosedMeta = !1, disposed4 = !1, epochSeq = 0, liveStreamEpoch = 0, liveSnapshotEpoch = 0, streamAnchor, everIssuedStream = !1, contentAnchor, contentAnchorSet = !1, ledgerWrites = 0, debug5 = (line) => {
16259
16747
  engineWireDebugEnabled() && hostLog("debug", line);
16260
16748
  }, toBgTask = (r, retired) => {
16261
16749
  let parentId = wireParentId(r);
@@ -16315,7 +16803,7 @@ function createFleetLedger(hooks2 = {}, opts = {}) {
16315
16803
  break;
16316
16804
  }
16317
16805
  let receivedAtMs = nowFn();
16318
- taskMap.set(row2.id, row2), rowMeta.set(row2.id, { receivedAtMs }), debug5(`[fleet-row] id=${row2.id} parent=${row2.parentId ?? "-"} agentType=${row2.agentType ?? "-"} agentName=${row2.agentName ?? "-"} name=${row2.name ?? "-"} status=${row2.status ?? "-"} tokens=${row2.tokens ?? "-"} parentToolCallId=${row2.parentToolCallId ?? "-"}`);
16806
+ taskMap.set(row2.id, row2), raiseCycleWatermark(rowIdTail(row2.id), wireCycleSeq(row2)), rowMeta.set(row2.id, { receivedAtMs }), debug5(`[fleet-row] id=${row2.id} parent=${row2.parentId ?? "-"} agentType=${row2.agentType ?? "-"} agentName=${row2.agentName ?? "-"} name=${row2.name ?? "-"} status=${row2.status ?? "-"} tokens=${row2.tokens ?? "-"} parentToolCallId=${row2.parentToolCallId ?? "-"}`);
16319
16807
  let parentId = wireParentId(row2);
16320
16808
  if (parentId !== void 0) {
16321
16809
  let childTid = rowIdTail(row2.id), parentTid = rowIdTail(parentId), parentOwned = isOwnEngineRun(parentTid);
@@ -16335,9 +16823,27 @@ function createFleetLedger(hooks2 = {}, opts = {}) {
16335
16823
  }
16336
16824
  break;
16337
16825
  }
16338
- case "task_remove":
16339
- taskMap.delete(frame.id), rowMeta.delete(frame.id);
16826
+ case "task_remove": {
16827
+ let fr = frame, removedGen = typeof fr.cycleSeq == "number" && Number.isInteger(fr.cycleSeq) && fr.cycleSeq >= 1 ? fr.cycleSeq : void 0, held = taskMap.get(frame.id), heldGen = held !== void 0 ? wireCycleSeq(held) : void 0, stale = removedGen !== void 0 && heldGen !== void 0 && removedGen < heldGen;
16828
+ if (stale || (taskMap.delete(frame.id), rowMeta.delete(frame.id)), hooks2.onTaskRemoved !== void 0) {
16829
+ let reason = typeof fr.removeReason == "string" && fr.removeReason.length > 0 ? fr.removeReason : void 0;
16830
+ try {
16831
+ let out6 = hooks2.onTaskRemoved({
16832
+ id: frame.id,
16833
+ ...reason !== void 0 ? { removeReason: reason } : {},
16834
+ ...removedGen !== void 0 ? { cycleSeq: removedGen } : {},
16835
+ ...stale ? { stale: !0 } : {},
16836
+ ...held === void 0 ? { unknownRow: !0 } : {}
16837
+ });
16838
+ out6 && typeof out6.then == "function" && Promise.resolve(out6).catch((e) => {
16839
+ hostLog("debug", `[fleet-frame] onTaskRemoved hook rejected: ${String(e).slice(0, 160)}`);
16840
+ });
16841
+ } catch (e) {
16842
+ hostLog("debug", `[fleet-frame] onTaskRemoved hook threw: ${String(e).slice(0, 160)}`);
16843
+ }
16844
+ }
16340
16845
  break;
16846
+ }
16341
16847
  case "workflow":
16342
16848
  frame.row?.id ? wfMap.set(frame.row.id, frame.row) : (droppedMalformed++, debug5("[fleet-frame] MALFORMED workflow frame dropped(row \u6216 row.id \u7F3A\u5E2D)"));
16343
16849
  break;
@@ -16376,11 +16882,20 @@ function createFleetLedger(hooks2 = {}, opts = {}) {
16376
16882
  (id === n2.taskId || rowIdTail(id) === n2.taskId) && rowIds.push(id);
16377
16883
  if (TERMINAL_FLEET_TASK_STATUSES.has(n2.status)) {
16378
16884
  typeof n2.parentTaskId == "string" && n2.parentTaskId && recordBgParentRun(n2.taskId, n2.parentTaskId, ing?.session, ing?.sessionKey), typeof n2.transcriptId == "string" && n2.transcriptId.length > 0 && recordEngineTranscriptId(n2.taskId, n2.transcriptId);
16379
- let isWashGreen = (prior, next) => next === "completed" && (prior === "failed" || prior === "killed"), coerced = n2.status, nowMs2 = nowFn(), writtenIds = /* @__PURE__ */ new Set(), applied = !1, washBlocked = !1;
16885
+ let isWashGreen = (prior, next) => next === "completed" && (prior === "failed" || prior === "killed"), coerced = n2.status, nowMs2 = nowFn(), writtenIds = /* @__PURE__ */ new Set(), applied = !1, washBlocked = !1, staleBlocked = !1, notifSeq = typeof n2.seq == "number" && Number.isInteger(n2.seq) && n2.seq >= 1 ? n2.seq : void 0;
16886
+ {
16887
+ let mark = cycleWatermark.get(n2.taskId);
16888
+ notifSeq !== void 0 && mark !== void 0 && notifSeq < mark && (staleBlocked = !0, debug5(`[fleet-frame] bg_notification stale-cycle ignored(watermark=${mark} notif-seq=${notifSeq})`));
16889
+ }
16380
16890
  for (let id of rowIds) {
16381
16891
  let known = taskMap.get(id);
16382
16892
  if (!known)
16383
16893
  continue;
16894
+ let heldGen = wireCycleSeq(known);
16895
+ if (notifSeq !== void 0 && heldGen !== void 0 && notifSeq < heldGen) {
16896
+ staleBlocked = !0, debug5(`[fleet-frame] bg_notification stale-cycle ignored(row=${id} row-cycle=${heldGen} notif-seq=${notifSeq})`);
16897
+ continue;
16898
+ }
16384
16899
  let rowStatus = known.status ?? "";
16385
16900
  if (TERMINAL_FLEET_TASK_STATUSES.has(rowStatus)) {
16386
16901
  if (isWashGreen(rowStatus, n2.status)) {
@@ -16408,6 +16923,11 @@ function createFleetLedger(hooks2 = {}, opts = {}) {
16408
16923
  for (let [id, entry] of retained) {
16409
16924
  if (writtenIds.has(id) || id !== n2.taskId && rowIdTail(id) !== n2.taskId)
16410
16925
  continue;
16926
+ let retainedGen = wireCycleSeq(entry.row);
16927
+ if (notifSeq !== void 0 && retainedGen !== void 0 && notifSeq < retainedGen) {
16928
+ staleBlocked = !0, debug5(`[fleet-frame] bg_notification stale-cycle ignored(retained=${id} row-cycle=${retainedGen} notif-seq=${notifSeq})`);
16929
+ continue;
16930
+ }
16411
16931
  let prior = entry.row.status ?? "";
16412
16932
  if (prior === n2.status) {
16413
16933
  applied = !0;
@@ -16424,11 +16944,21 @@ function createFleetLedger(hooks2 = {}, opts = {}) {
16424
16944
  ...entry.retiredByNotification === !0 ? { retiredByNotification: !0 } : {}
16425
16945
  }), applied = !0;
16426
16946
  }
16427
- applied || !washBlocked && (() => {
16947
+ let factsAccepted = !staleBlocked && (applied || !washBlocked && (() => {
16428
16948
  let prior = getBgTerminalFacts(n2.taskId);
16429
- return !(prior !== void 0 && isWashGreen(prior.status, n2.status));
16430
- })() ? recordBgTerminalFacts(n2.taskId, {
16949
+ if (prior === void 0)
16950
+ return !0;
16951
+ if (notifSeq !== void 0 && prior.cycleSeq !== void 0) {
16952
+ if (notifSeq < prior.cycleSeq)
16953
+ return !1;
16954
+ if (notifSeq > prior.cycleSeq)
16955
+ return !0;
16956
+ }
16957
+ return !isWashGreen(prior.status, n2.status);
16958
+ })());
16959
+ factsAccepted && raiseCycleWatermark(n2.taskId, notifSeq), factsAccepted ? recordBgTerminalFacts(n2.taskId, {
16431
16960
  status: n2.status,
16961
+ ...notifSeq !== void 0 ? { cycleSeq: notifSeq } : {},
16432
16962
  ...typeof n2.summary == "string" ? { summary: n2.summary } : {},
16433
16963
  // 🔴 SDK 0.0.117 把 `recentSteps` 的三键 declare 成**必填** string,但那是**声称**不是保证:
16434
16964
  // 帧从 wire 上来,脏项(null / 缺键 / 非串)在类型面之外仍可能到达,而 BgTerminalFacts
@@ -17271,17 +17801,22 @@ function str4(v2) {
17271
17801
  function readDecideReceipt(result) {
17272
17802
  if (typeof result != "object" || result === null || Array.isArray(result))
17273
17803
  return;
17274
- let r = result, status3 = Object.hasOwn(r, "status") ? str4(r.status) : void 0, taskId = Object.hasOwn(r, "taskId") ? str4(r.taskId) : void 0, sessionId = Object.hasOwn(r, "sessionId") ? str4(r.sessionId) : void 0, idempotent = Object.hasOwn(r, "idempotent") && r.idempotent === !0 ? !0 : void 0, handoffTaskId = status3 === STATUS_RESUMING && taskId !== void 0 ? taskId : void 0, executionOutcome = Object.hasOwn(r, "executionOutcome") ? gateOutcomeOf({ gate: r.executionOutcome }) : void 0;
17275
- if (!(status3 === void 0 && taskId === void 0 && sessionId === void 0 && idempotent === void 0 && executionOutcome === void 0))
17804
+ let r = result, status3 = Object.hasOwn(r, "status") ? str4(r.status) : void 0, taskId = Object.hasOwn(r, "taskId") ? str4(r.taskId) : void 0, sessionId = Object.hasOwn(r, "sessionId") ? str4(r.sessionId) : void 0, idempotent = Object.hasOwn(r, "idempotent") && r.idempotent === !0 ? !0 : void 0, handoffTaskId = status3 === STATUS_RESUMING && taskId !== void 0 ? taskId : void 0, executionOutcome = Object.hasOwn(r, "executionOutcome") ? gateOutcomeOf({ gate: r.executionOutcome }) : void 0, errorCode = Object.hasOwn(r, "errorCode") ? str4(r.errorCode) : void 0, retriable = Object.hasOwn(r, "retriable") && typeof r.retriable == "boolean" ? r.retriable : void 0;
17805
+ if (!(status3 === void 0 && taskId === void 0 && sessionId === void 0 && idempotent === void 0 && executionOutcome === void 0 && errorCode === void 0 && retriable === void 0))
17276
17806
  return {
17277
17807
  ...status3 !== void 0 ? { status: status3 } : {},
17278
17808
  ...taskId !== void 0 ? { taskId } : {},
17279
17809
  ...sessionId !== void 0 ? { sessionId } : {},
17280
17810
  ...idempotent !== void 0 ? { idempotent } : {},
17281
17811
  ...handoffTaskId !== void 0 ? { handoffTaskId } : {},
17282
- ...executionOutcome !== void 0 ? { executionOutcome } : {}
17812
+ ...executionOutcome !== void 0 ? { executionOutcome } : {},
17813
+ ...errorCode !== void 0 ? { errorCode } : {},
17814
+ ...retriable !== void 0 ? { retriable } : {}
17283
17815
  };
17284
17816
  }
17817
+ function decideReceiptReopen(receipt) {
17818
+ return receipt === void 0 || receipt.status !== STATUS_FAILED ? null : resumeReopenFromError(receipt);
17819
+ }
17285
17820
  function decideAcceptedNotResolved(receipt) {
17286
17821
  return receipt?.status === STATUS_RESUMING;
17287
17822
  }
@@ -17297,11 +17832,13 @@ function decideRefusalFromError(e) {
17297
17832
  resendable: Object.hasOwn(DECIDE_RESENDABLE, code2) ? DECIDE_RESENDABLE[code2] === !0 : !1
17298
17833
  };
17299
17834
  }
17300
- var STATUS_RESUMING, DECIDE_REFUSAL_SENTENCES, DECIDE_RESENDABLE, init_decideReceipt = __esm({
17835
+ var STATUS_RESUMING, STATUS_FAILED, DECIDE_REFUSAL_SENTENCES, DECIDE_RESENDABLE, init_decideReceipt = __esm({
17301
17836
  "node_modules/@sema-agent/client-core/dist/decideReceipt.js"() {
17302
17837
  init_gateOutcome();
17838
+ init_resumeRefusalCopy();
17303
17839
  init_engineErrorCodes();
17304
17840
  STATUS_RESUMING = "resuming";
17841
+ STATUS_FAILED = "failed";
17305
17842
  DECIDE_REFUSAL_SENTENCES = Object.freeze({
17306
17843
  [DECIDE_WORKFLOW_HOST_UNKNOWN]: "no session is attached to this run to receive the decision, so re-sending the same decision cannot help; the approval is still pending and can be decided again once the run is reachable",
17307
17844
  [DECIDE_WORKFLOW_REMEMBER_UNSUPPORTED]: "this run cannot remember the decision for the session; re-send the same decision without the remember option \u2014 nothing was consumed by this refusal"
@@ -19711,6 +20248,22 @@ var PROVIDER_PRESETS, MODEL_FAMILIES, VARIANT_TAIL, presetIndexCache, init_provi
19711
20248
  }
19712
20249
  });
19713
20250
 
20251
+ // node_modules/@sema-agent/client-core/dist/hitl/suspendedReopen.js
20252
+ function suspendedReopenOf(ev) {
20253
+ if (ev === null || typeof ev != "object" || Array.isArray(ev))
20254
+ return UNSTATED;
20255
+ let o = ev;
20256
+ if (!Object.hasOwn(o, "reopened"))
20257
+ return UNSTATED;
20258
+ let v2 = o.reopened;
20259
+ return v2 === null ? NOT_REOPENED : typeof v2 == "string" && v2.length > 0 ? { kind: "reopened", code: v2 } : UNSTATED;
20260
+ }
20261
+ var UNSTATED, NOT_REOPENED, init_suspendedReopen = __esm({
20262
+ "node_modules/@sema-agent/client-core/dist/hitl/suspendedReopen.js"() {
20263
+ UNSTATED = Object.freeze({ kind: "unstated" }), NOT_REOPENED = Object.freeze({ kind: "not_reopened" });
20264
+ }
20265
+ });
20266
+
19714
20267
  // node_modules/@sema-agent/client-core/dist/hitl/hitlBridge.js
19715
20268
  function denyReasonForWire(reason, tag2) {
19716
20269
  if (typeof reason != "string")
@@ -19812,6 +20365,7 @@ var DEFAULT_DENY_REASON, MAX_DENY_REASON_CHARS, PLAN_REVIEW_MODE_AFTER_WORDS, Hi
19812
20365
  init_types();
19813
20366
  init_host();
19814
20367
  init_abortableSleep();
20368
+ init_suspendedReopen();
19815
20369
  DEFAULT_DENY_REASON = "The user rejected this tool use", MAX_DENY_REASON_CHARS = 4096;
19816
20370
  PLAN_REVIEW_MODE_AFTER_WORDS = Object.freeze(["default", "acceptEdits"]);
19817
20371
  HitlSafetyError = class extends Error {
@@ -19852,7 +20406,7 @@ var DEFAULT_DENY_REASON, MAX_DENY_REASON_CHARS, PLAN_REVIEW_MODE_AFTER_WORDS, Hi
19852
20406
  observe(ev) {
19853
20407
  switch (ev.type) {
19854
20408
  case "suspended":
19855
- ev.gate ? this.active = { gate: ev.gate, seq: eventSeq(ev) } : this.active = { gate: { kind: "human" }, seq: eventSeq(ev) };
20409
+ ev.gate ? this.active = { gate: ev.gate, seq: eventSeq(ev), reopened: suspendedReopenOf(ev) } : this.active = { gate: { kind: "human" }, seq: eventSeq(ev), reopened: suspendedReopenOf(ev) };
19856
20410
  break;
19857
20411
  case "done":
19858
20412
  case "failed":
@@ -19867,6 +20421,14 @@ var DEFAULT_DENY_REASON, MAX_DENY_REASON_CHARS, PLAN_REVIEW_MODE_AFTER_WORDS, Hi
19867
20421
  currentGate() {
19868
20422
  return this.active?.gate ?? null;
19869
20423
  }
20424
+ /**
20425
+ * 0.74.3 CC-73:当前挂起是不是一次 reopen(`suspended.reopened` 三态);没挂起 ⇒ `null`。
20426
+ * 消费方据此把「真 reopen 成功、重试会重放」那半句说出来:`reopened` 在场码 ⇒ 卡仍 pending、决定没被消费、可再决;
20427
+ * `not_reopened` / `unstated` ⇒ 普通挂起,一个字都不多说。
20428
+ */
20429
+ currentGateReopen() {
20430
+ return this.active?.reopened ?? null;
20431
+ }
19870
20432
  /**
19871
20433
  * Fetch the `PendingCheckpoint` this decide/answer is about to resolve, for the callers that do NOT
19872
20434
  * already have one in hand (see `decideTool`/`answerQuestion`'s `preResolvedPending` param — the wire
@@ -20060,6 +20622,25 @@ var DEFAULT_DENY_REASON, MAX_DENY_REASON_CHARS, PLAN_REVIEW_MODE_AFTER_WORDS, Hi
20060
20622
  }
20061
20623
  });
20062
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
+
20063
20644
  // node_modules/@sema-agent/client-core/dist/hitl/gateIdentity.js
20064
20645
  function approvalCallKey(gatedCallId, taskId) {
20065
20646
  return gatedCallId ?? taskId;
@@ -20420,6 +21001,8 @@ async function surfaceFsApprovalAndDecide(deps2, taskId, argsByCall, signal, par
20420
21001
  switch (card.kind) {
20421
21002
  case "failed":
20422
21003
  return { kind: "failed", stage: "card", gatedCallId, reason: card.reason };
21004
+ case "retracted":
21005
+ return hostLog("debug", `liveHitlAskWire: approval card retracted without a decision for ${gatedCallId ?? "(no call)"} \u2014 nothing sent`), { kind: "retracted", gatedCallId };
20423
21006
  case "aborted":
20424
21007
  return observeCancelByDeny(bridge3.decideTool({ decision: "deny", reason: "Interrupted by user" }, gatedCallId, void 0, pending4), taskId), { kind: "aborted", gatedCallId };
20425
21008
  case "allow":
@@ -20473,7 +21056,7 @@ function readReadRootCandidate(v2) {
20473
21056
  return;
20474
21057
  let o = v2;
20475
21058
  if (!(typeof o.dir != "string" || o.dir.length === 0 || o.clearsThisAsk !== !0))
20476
- return { dir: o.dir, clearsThisAsk: !0 };
21059
+ return "covers" in o ? o.covers === "exact" ? { dir: o.dir, clearsThisAsk: !0, covers: "exact" } : void 0 : { dir: o.dir, clearsThisAsk: !0 };
20477
21060
  }
20478
21061
  function isToolApprovalDelegation(v2) {
20479
21062
  if (v2 === null || typeof v2 != "object")
@@ -20824,6 +21407,8 @@ async function surfaceToolApprovalFrameAndRespond(frame, respond, streamArgs, si
20824
21407
  });
20825
21408
  if (lane?.argsUnavailable === !0 && card.kind === "allow" && card.updatedInput !== void 0)
20826
21409
  return hostLog("error", `liveToolApprovalWire: ${frame.approvalId} card returned an edited approval on an args-unavailable ask \u2014 nothing sent (the ask stays pending)`), surfaceEditRefusedOnBlindAsk(), { decision: "unresolved", editRefused: !0 };
21410
+ if (card.kind === RETRACTED_CARD_DECISION_KIND)
21411
+ return hostLog("debug", `liveToolApprovalWire: ${frame.approvalId} card retracted without a decision${card.reason ? ` (${card.reason})` : ""} \u2014 nothing sent`), { decision: "unresolved", retracted: !0 };
20827
21412
  let decision = card.kind === "allow" ? card.allowSession ? "allow_session" : "allow" : "deny";
20828
21413
  card.kind === "failed" && hostLog("debug", `liveToolApprovalWire: approval card unavailable (${card.reason}) \u2014 fail-closed deny for ${frame.approvalId}`);
20829
21414
  let note;
@@ -20863,7 +21448,7 @@ async function surfaceToolApprovalFrameAndRespond(frame, respond, streamArgs, si
20863
21448
  return hostLog("debug", `liveToolApprovalWire: respond(${decision}) failed for ${frame.approvalId} (status=${respondRefusal?.status ?? "none"} errorCode=${logSafeErrorCode(respondRefusal?.errorCode)} messageLen=${respondRefusal?.message?.length ?? 0}) \u2014 engine self-settles (TTL/abort); the refusal text is handed back on outcome.respondRefusal for the host to surface`), respondRefusal !== void 0 ? { decision: "unresolved", respondRefusal } : { decision: "unresolved" };
20864
21449
  }
20865
21450
  }
20866
- var cardPortByKey, cardPortMissesByKey, TOOL_APPROVAL_FRAME_KEYS_MIRROR, RESPOND_DECISIONS, USELESS_REFUSAL_TEXTS, MACHINE_CODE_SHAPE, FS_WRITE_GATE_ASK_PATTERN, MAX_RULE_OFFERS_TOLERATED, MAX_RULE_OFFER_BATCH_MEMBERS_TOLERATED, MAX_RULE_OFFER_UNCOVERED_DETAIL_TOLERATED, MAX_RESPOND_NOTE_CHARS, init_toolApprovalWire = __esm({
21451
+ var RETRACTED_CARD_DECISION_KIND, cardPortByKey, cardPortMissesByKey, TOOL_APPROVAL_FRAME_KEYS_MIRROR, RESPOND_DECISIONS, USELESS_REFUSAL_TEXTS, MACHINE_CODE_SHAPE, FS_WRITE_GATE_ASK_PATTERN, MAX_RULE_OFFERS_TOLERATED, MAX_RULE_OFFER_BATCH_MEMBERS_TOLERATED, MAX_RULE_OFFER_UNCOVERED_DETAIL_TOLERATED, MAX_RESPOND_NOTE_CHARS, init_toolApprovalWire = __esm({
20867
21452
  "node_modules/@sema-agent/client-core/dist/hitl/toolApprovalWire.js"() {
20868
21453
  init_hitlBridge();
20869
21454
  init_askParkRowRouting();
@@ -20874,7 +21459,7 @@ var cardPortByKey, cardPortMissesByKey, TOOL_APPROVAL_FRAME_KEYS_MIRROR, RESPOND
20874
21459
  init_gateIdentity();
20875
21460
  init_gateVocabulary();
20876
21461
  init_decideReceipt();
20877
- cardPortByKey = createSessionSlot(), cardPortMissesByKey = /* @__PURE__ */ new Map();
21462
+ RETRACTED_CARD_DECISION_KIND = "retracted", cardPortByKey = createSessionSlot(), cardPortMissesByKey = /* @__PURE__ */ new Map();
20878
21463
  TOOL_APPROVAL_FRAME_KEYS_MIRROR = [
20879
21464
  "type",
20880
21465
  "approvalId",
@@ -21063,7 +21648,16 @@ async function routeToolApprovalFrame(ev, ctx) {
21063
21648
  }
21064
21649
  let fromSubagent = isFromSubagent(ev);
21065
21650
  hostLog("debug", `liveHitlAskWire: tool_approval frame ${ev.approvalId} tool=${String(ev.toolName)}${fromSubagent ? ` from-subagent=${String(ev.sourceTaskId ?? ev.sourceAgentName ?? "explicit")}` : ""}`);
21066
- let gatedCallId = fromSubagent ? void 0 : led.lastPendingFsCall(), { decision } = await surfaceToolApprovalFrameAndRespond(ev, deps2.respondToolApproval, argsOfGatedStart(led, gatedCallId), ctx.signal, deps2.approvalLane);
21651
+ let gatedCallId = fromSubagent ? void 0 : led.lastPendingFsCall(), outcome = await surfaceToolApprovalFrameAndRespond(ev, deps2.respondToolApproval, argsOfGatedStart(led, gatedCallId), ctx.signal, deps2.approvalLane), { decision } = outcome;
21652
+ if (deps2.onToolApprovalOutcome !== void 0)
21653
+ try {
21654
+ let out6 = deps2.onToolApprovalOutcome(ev, outcome);
21655
+ out6 && typeof out6.then == "function" && Promise.resolve(out6).catch((e) => {
21656
+ hostLog("debug", `liveHitlAskWire: onToolApprovalOutcome rejected: ${String(e).slice(0, 160)}`);
21657
+ });
21658
+ } catch (e) {
21659
+ hostLog("debug", `liveHitlAskWire: onToolApprovalOutcome threw: ${String(e).slice(0, 160)}`);
21660
+ }
21067
21661
  return decision === "deny" && !fromSubagent && (gatedCallId !== void 0 ? led.markDenied(gatedCallId) : led.armDenyStamp()), { kind: "skip" };
21068
21662
  }
21069
21663
  function routeToolStart(ev, callId, led) {
@@ -21577,14 +22171,15 @@ async function resolvePark(park, ctx) {
21577
22171
  outcome = { kind: "failed", stage: "orchestration", reason: stalledReason };
21578
22172
  else {
21579
22173
  let closing = await surfaceParkGate(park, ctx, park.gatedCallId, witness);
21580
- outcome = closing.kind === "decided" || closing.kind === "aborted" ? closing : { kind: "failed", stage: "orchestration", reason: `${stalledReason}; closing re-read: ${closing.reason}` };
22174
+ outcome = closing.kind === "decided" || closing.kind === "aborted" || closing.kind === "retracted" ? closing : { kind: "failed", stage: "orchestration", reason: `${stalledReason}; closing re-read: ${closing.reason}` };
21581
22175
  }
21582
22176
  } else
21583
22177
  park.gate === "fs" && (candidateGatedCallId = led.lastFsOrShellGatedCallId()), outcome = await surfaceParkGate(park, ctx, park.gatedCallId, witness);
21584
22178
  let alreadyDecidedById = outcome.kind === "failed" && candidateGatedCallId !== void 0 && led.takeDecided(candidateGatedCallId);
21585
22179
  if (!closingCardTried && outcome.kind === "failed" && (isAlreadyResolvedFailure(outcome) || alreadyDecidedById)) {
21586
22180
  let firstReason = outcome.reason, streakKey = alreadyResolvedStreakKey(!isAlreadyResolvedFailure(outcome) && alreadyDecidedById), reasonToken = alreadyResolvedReasonToken(outcome.reason), rescan = isFetchStepNoPending(outcome) && stalledRounds <= MAX_GATE_HOPS ? await surfaceParkGate(park, ctx, park.gatedCallId, witness) : void 0;
21587
- if (rescan !== void 0 && (rescan.kind === "decided" || rescan.kind === "aborted" || rescan.kind === "failed" && rescan.retryExhausted === !0))
22181
+ if (rescan !== void 0 && (rescan.kind === "decided" || rescan.kind === "aborted" || rescan.kind === "retracted" || // 0.74.1(CC-67):宿主撤卡也是「人那一侧有了处置」,采信,不再重探
22182
+ rescan.kind === "failed" && rescan.retryExhausted === !0))
21588
22183
  hostLog("debug", `liveHitlAskWire: gate reported already-resolved (${firstReason}) but a fresh approvals re-read for run ${taskId} surfaced a decidable row under the current coordinates \u2014 re-presented it (rescan: ${rescan.kind}) instead of re-attaching on the stale park identity`), outcome = rescan;
21589
22184
  else {
21590
22185
  let streak = led.noteAlreadyResolvedGate(streakKey);
@@ -21616,8 +22211,11 @@ async function resolvePark(park, ctx) {
21616
22211
  reason: `the decide call failed on transport ${streak} times in a row while the run stayed parked (${outcome.reason})`
21617
22212
  };
21618
22213
  }
21619
- if (outcome.kind !== "decided")
21620
- return hostLog("debug", `liveHitlAskWire: gate not decided (${outcome.kind}${"reason" in outcome ? `: ${outcome.reason}` : ""}) \u2014 fail-soft to suspended terminal`), { kind: "failsoft", events: failsoftEvents(park, ctx, outcome.kind === "aborted", outcome.kind === "failed" ? outcome.reason : void 0) };
22214
+ if (outcome.kind !== "decided") {
22215
+ hostLog("debug", `liveHitlAskWire: gate not decided (${outcome.kind}${"reason" in outcome ? `: ${outcome.reason}` : ""}) \u2014 fail-soft to suspended terminal`);
22216
+ let failedReason = outcome.kind === "failed" ? outcome.reason : outcome.kind === "retracted" ? "the approval card was retracted by the host without a decision (nothing was sent; the run stays parked and remains decidable elsewhere)" : void 0;
22217
+ return { kind: "failsoft", events: failsoftEvents(park, ctx, outcome.kind === "aborted", failedReason) };
22218
+ }
21621
22219
  led.dropHeldForDecidedPark(outcome.gatedCallId, park.gatedCallId), outcome.gatedCallId && (led.markDecided(outcome.gatedCallId), "answered" in outcome && outcome.answered && led.rememberAnswer(outcome.gatedCallId, outcome.answered));
21622
22220
  let handoffTaskId = "receipt" in outcome && outcome.receipt?.handoffTaskId !== void 0 && outcome.receipt.handoffTaskId !== taskId ? outcome.receipt.handoffTaskId : void 0, seq2 = led.lastSeq();
21623
22221
  return hostLog("debug", handoffTaskId !== void 0 ? `liveHitlAskWire: gate decided (call ${outcome.gatedCallId ?? "?"}) \u2014 the decide was ACCEPTED for delivery (status "resuming") and the engine handed the continuation to run ${handoffTaskId}; attaching runs.events(${handoffTaskId}) from the start (durable seq is per-run, so ${seq2 ?? "the previous seq"} does not apply there)` : `liveHitlAskWire: gate decided (call ${outcome.gatedCallId ?? "?"}) \u2014 attaching runs.events(${taskId})${seq2 ? ` from seq ${seq2}` : ""}`), {
@@ -24745,6 +25343,8 @@ __export(dist_exports, {
24745
25343
  ADAPTER_DIVERGENCES: () => ADAPTER_DIVERGENCES,
24746
25344
  AGENT_MEMORY_WORDS: () => AGENT_MEMORY_WORDS,
24747
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,
24748
25348
  ASK_ORIGIN_WORDS: () => ASK_ORIGIN_WORDS,
24749
25349
  ASK_PARK_GATE_KINDS: () => ASK_PARK_GATE_KINDS,
24750
25350
  ASK_PARK_ROW_POLL_MS: () => ASK_PARK_ROW_POLL_MS,
@@ -24886,6 +25486,7 @@ __export(dist_exports, {
24886
25486
  MAX_AGENT_TOOLS: () => MAX_AGENT_TOOLS,
24887
25487
  MAX_AGENT_TOOL_NAME_CHARS: () => MAX_AGENT_TOOL_NAME_CHARS,
24888
25488
  MAX_GATE_HOPS: () => MAX_GATE_HOPS,
25489
+ MAX_HELD_WIRE_TICK_BEATS: () => MAX_HELD_WIRE_TICK_BEATS,
24889
25490
  MAX_HOOK_NOTICE_TEXT_CHARS: () => MAX_HOOK_NOTICE_TEXT_CHARS,
24890
25491
  MAX_TASK_AGENTS: () => MAX_TASK_AGENTS,
24891
25492
  MAX_TOKENS_MAX: () => MAX_TOKENS_MAX,
@@ -24953,6 +25554,7 @@ __export(dist_exports, {
24953
25554
  RESUME_USAGE_WINDOW_EXHAUSTED: () => RESUME_USAGE_WINDOW_EXHAUSTED,
24954
25555
  RETAIN_BACKGROUND_ENV: () => RETAIN_BACKGROUND_ENV,
24955
25556
  RETIRED_PERMISSION_RULE_ISSUE_CODES: () => RETIRED_PERMISSION_RULE_ISSUE_CODES,
25557
+ RETRACTED_CARD_DECISION_KIND: () => RETRACTED_CARD_DECISION_KIND,
24956
25558
  REVIEW_PARK_GATE_KINDS: () => REVIEW_PARK_GATE_KINDS,
24957
25559
  REWIND_ERROR_CODE_PREFIXES: () => REWIND_ERROR_CODE_PREFIXES,
24958
25560
  RULE_NOT_SENT_REJECTED_WARN_TEXT: () => RULE_NOT_SENT_REJECTED_WARN_TEXT,
@@ -24964,6 +25566,7 @@ __export(dist_exports, {
24964
25566
  RULE_STORE_UNREADABLE_KINDS: () => RULE_STORE_UNREADABLE_KINDS,
24965
25567
  RUNNING_STATES: () => RUNNING_STATES,
24966
25568
  RUN_BLOCKED_MESSAGE_PREFIX: () => RUN_BLOCKED_MESSAGE_PREFIX,
25569
+ RUN_CANCELLED_CODE: () => RUN_CANCELLED_CODE,
24967
25570
  RUN_LEVEL_STOP_ERROR_CODES: () => RUN_LEVEL_STOP_ERROR_CODES,
24968
25571
  RUN_STOPPED_MESSAGE_PREFIX: () => RUN_STOPPED_MESSAGE_PREFIX,
24969
25572
  RUN_TERMINAL_NOT_SUCCESS_STATUSES: () => RUN_TERMINAL_NOT_SUCCESS_STATUSES,
@@ -25055,7 +25658,9 @@ __export(dist_exports, {
25055
25658
  __feedWorkflowActivityFrameForTests: () => __feedWorkflowActivityFrameForTests,
25056
25659
  __resetApprovalsStreamLiveReadingsForTests: () => __resetApprovalsStreamLiveReadingsForTests,
25057
25660
  __resetBgOwnerAbsenceForTests: () => __resetBgOwnerAbsenceForTests,
25661
+ __resetDeviceExecutorManagementReadingsForTests: () => __resetDeviceExecutorManagementReadingsForTests,
25058
25662
  __resetEngineAgentPanelAbsenceForTests: () => __resetEngineAgentPanelAbsenceForTests,
25663
+ __resetEngineAgentPanelIdentityForTests: () => __resetEngineAgentPanelIdentityForTests,
25059
25664
  __resetEngineCapsCacheForTests: () => __resetEngineCapsCacheForTests,
25060
25665
  __resetEngineCompactArmForTests: () => __resetEngineCompactArmForTests,
25061
25666
  __resetEngineDelegatedPromptForTests: () => __resetEngineDelegatedPromptForTests,
@@ -25114,6 +25719,7 @@ __export(dist_exports, {
25114
25719
  approvalCardPortFor: () => approvalCardPortFor,
25115
25720
  approvalCardPortMisses: () => approvalCardPortMisses,
25116
25721
  approvalCardPortMissesFor: () => approvalCardPortMissesFor,
25722
+ approvalOutcomeNoteOf: () => approvalOutcomeNoteOf,
25117
25723
  approvalsStreamLiveDoctorDetail: () => approvalsStreamLiveDoctorDetail,
25118
25724
  armDetachCancel: () => armDetachCancel,
25119
25725
  armPlanReviewApproval: () => armPlanReviewApproval,
@@ -25162,6 +25768,7 @@ __export(dist_exports, {
25162
25768
  classifyMemoryStatusFailure: () => classifyMemoryStatusFailure,
25163
25769
  classifyPeerNotification: () => classifyPeerNotification,
25164
25770
  classifyRulesFailure: () => classifyRulesFailure,
25771
+ classifyRunAbortCause: () => classifyRunAbortCause,
25165
25772
  classifySelfOrchestrationRefusal: () => classifySelfOrchestrationRefusal,
25166
25773
  classifySkippedReason: () => classifySkippedReason,
25167
25774
  classifySubagentResumeFailure: () => classifySubagentResumeFailure,
@@ -25172,6 +25779,7 @@ __export(dist_exports, {
25172
25779
  clearArmedGate: () => clearArmedGate,
25173
25780
  clearBgTerminalFacts: () => clearBgTerminalFacts,
25174
25781
  clearEnginePanelTaskResident: () => clearEnginePanelTaskResident,
25782
+ clearEnginePanelTaskResidentByWire: () => clearEnginePanelTaskResidentByWire,
25175
25783
  clearRunningChoiceOffer: () => clearRunningChoiceOffer,
25176
25784
  clearSubagentContent: () => clearSubagentContent,
25177
25785
  clientContextField: () => clientContextField,
@@ -25206,6 +25814,7 @@ __export(dist_exports, {
25206
25814
  createWireToCcAdapter: () => createWireToCcAdapter,
25207
25815
  decideAcceptedNotResolved: () => decideAcceptedNotResolved,
25208
25816
  decidePlanReview: () => decidePlanReview,
25817
+ decideReceiptReopen: () => decideReceiptReopen,
25209
25818
  decideRefusalFromError: () => decideRefusalFromError,
25210
25819
  decisionNoteAuditLine: () => decisionNoteAuditLine,
25211
25820
  defaultMaxTokensFor: () => defaultMaxTokensFor,
@@ -25222,6 +25831,8 @@ __export(dist_exports, {
25222
25831
  detachedTaskId: () => detachedTaskId,
25223
25832
  detectEngineBgShellReceipt: () => detectEngineBgShellReceipt,
25224
25833
  deviceAuthProviderFor: () => deviceAuthProviderFor,
25834
+ deviceExecutorManagementDoctorDetail: () => deviceExecutorManagementDoctorDetail,
25835
+ deviceManagementVerbsAvailable: () => deviceManagementVerbsAvailable,
25225
25836
  diagnoseSseIdleTear: () => diagnoseSseIdleTear,
25226
25837
  discussionWorkflowName: () => discussionWorkflowName,
25227
25838
  doneToSdkResult: () => doneToSdkResult,
@@ -25291,6 +25902,7 @@ __export(dist_exports, {
25291
25902
  fmtCtxOut: () => fmtCtxOut,
25292
25903
  fmtTokens: () => fmtTokens,
25293
25904
  forgetApprovalsStreamLiveReading: () => forgetApprovalsStreamLiveReading,
25905
+ forgetDeviceExecutorManagementReading: () => forgetDeviceExecutorManagementReading,
25294
25906
  forgetExecutionLaneReading: () => forgetExecutionLaneReading,
25295
25907
  forgetSqlEngineReading: () => forgetSqlEngineReading,
25296
25908
  forgetWebSearchBackendReading: () => forgetWebSearchBackendReading,
@@ -25403,6 +26015,7 @@ __export(dist_exports, {
25403
26015
  isLoopbackWireUrl: () => isLoopbackWireUrl,
25404
26016
  isModelOutputErrorRowText: () => isModelOutputErrorRowText,
25405
26017
  isModelOutputErrorText: () => isModelOutputErrorText,
26018
+ isNewEngineAgentPanelCycle: () => isNewEngineAgentPanelCycle,
25406
26019
  isOutcomeUnknownRowText: () => isOutcomeUnknownRowText,
25407
26020
  isOwnEngineRun: () => isOwnEngineRun,
25408
26021
  isOwnWorkflowRun: () => isOwnWorkflowRun,
@@ -25418,6 +26031,7 @@ __export(dist_exports, {
25418
26031
  isSeatModelCatalog: () => isSeatModelCatalog,
25419
26032
  isSendMessageAck: () => isSendMessageAck,
25420
26033
  isSseIdleError: () => isSseIdleError,
26034
+ isStaleEngineAgentPanelEnd: () => isStaleEngineAgentPanelEnd,
25421
26035
  isSubFlowSegmentEnd: () => isSubFlowSegmentEnd,
25422
26036
  isSupportedCatalogSchemaVersion: () => isSupportedCatalogSchemaVersion,
25423
26037
  isTaskNotificationObjective: () => isTaskNotificationObjective,
@@ -25435,6 +26049,7 @@ __export(dist_exports, {
25435
26049
  isWorkflowCompletionCardEnqueued: () => isWorkflowCompletionCardEnqueued,
25436
26050
  isWorkflowParkRefusalCode: () => isWorkflowParkRefusalCode,
25437
26051
  kickEngineCapsProbe: () => kickEngineCapsProbe,
26052
+ lastFlagValue: () => lastFlagValue,
25438
26053
  leaderConflictDetail: () => leaderConflictDetail,
25439
26054
  limitsForPrint: () => limitsForPrint,
25440
26055
  listAllPersistedRules: () => listAllPersistedRules,
@@ -25478,6 +26093,7 @@ __export(dist_exports, {
25478
26093
  normalizeWirePrincipal: () => normalizeWirePrincipal,
25479
26094
  noteBgOwnerAbsence: () => noteBgOwnerAbsence,
25480
26095
  noteEngineCapsForApprovalsStreamLive: () => noteEngineCapsForApprovalsStreamLive,
26096
+ noteEngineCapsForDeviceExecutorManagement: () => noteEngineCapsForDeviceExecutorManagement,
25481
26097
  noteEngineCapsForExecutionLane: () => noteEngineCapsForExecutionLane,
25482
26098
  noteEngineCapsForSqlEngine: () => noteEngineCapsForSqlEngine,
25483
26099
  noteEngineCapsForWebSearchBackend: () => noteEngineCapsForWebSearchBackend,
@@ -25492,6 +26108,7 @@ __export(dist_exports, {
25492
26108
  notificationQueuePortMisses: () => notificationQueuePortMisses,
25493
26109
  observeCancelByDeny: () => observeCancelByDeny,
25494
26110
  observedApprovalsStreamLive: () => observedApprovalsStreamLive,
26111
+ observedDeviceExecutorManagement: () => observedDeviceExecutorManagement,
25495
26112
  observedExecutionLane: () => observedExecutionLane,
25496
26113
  observedSqlEngine: () => observedSqlEngine,
25497
26114
  observedWebSearchBackend: () => observedWebSearchBackend,
@@ -25558,6 +26175,7 @@ __export(dist_exports, {
25558
26175
  projectBackgroundView: () => projectBackgroundView,
25559
26176
  projectCrashConverged: () => projectCrashConverged,
25560
26177
  projectDescription: () => projectDescription,
26178
+ projectDeviceExecutorManagementCapability: () => projectDeviceExecutorManagementCapability,
25561
26179
  projectDiagnosticsFrame: () => projectDiagnosticsFrame,
25562
26180
  projectEffectiveBody: () => projectEffectiveBody,
25563
26181
  projectExecutionLaneCapability: () => projectExecutionLaneCapability,
@@ -25621,6 +26239,7 @@ __export(dist_exports, {
25621
26239
  readRuleOfferSupply: () => readRuleOfferSupply,
25622
26240
  readRuleOffers: () => readRuleOffers,
25623
26241
  readRulePersistOutcome: () => readRulePersistOutcome,
26242
+ readRunCancelContext: () => readRunCancelContext,
25624
26243
  readRunCostFacts: () => readRunCostFacts,
25625
26244
  readRunTerminal: () => readRunTerminal,
25626
26245
  readSessionMemoryStatus: () => readSessionMemoryStatus,
@@ -25664,6 +26283,7 @@ __export(dist_exports, {
25664
26283
  resetWorkflowActivityLedgers: () => resetWorkflowActivityLedgers,
25665
26284
  resolveAutonomousLoopPrompt: () => resolveAutonomousLoopPrompt,
25666
26285
  resolveCatalogSources: () => resolveCatalogSources,
26286
+ resolveEnginePanelTaskId: () => resolveEnginePanelTaskId,
25667
26287
  resolveEntryVision: () => resolveEntryVision,
25668
26288
  resolveHeadlessDetach: () => resolveHeadlessDetach,
25669
26289
  resolveHeadlessFinalVerify: () => resolveHeadlessFinalVerify,
@@ -25769,6 +26389,7 @@ __export(dist_exports, {
25769
26389
  surfaceRuleArmRejected: () => surfaceRuleArmRejected,
25770
26390
  surfaceSuspendedAskAndRespond: () => surfaceSuspendedAskAndRespond,
25771
26391
  surfaceToolApprovalFrameAndRespond: () => surfaceToolApprovalFrameAndRespond,
26392
+ suspendedReopenOf: () => suspendedReopenOf,
25772
26393
  suspendedSubagentAsks: () => suspendedSubagentAsks,
25773
26394
  tailEngineSubagent: () => tailEngineSubagent,
25774
26395
  taskAgentsField: () => taskAgentsField,
@@ -25860,9 +26481,12 @@ var init_dist = __esm({
25860
26481
  init_webSearchBackendCapability();
25861
26482
  init_executionLaneCapability();
25862
26483
  init_approvalsStreamLiveCapability();
26484
+ init_deviceExecutorManagementCapability();
25863
26485
  init_mcpReconnect();
25864
26486
  init_leaderConflict();
25865
26487
  init_runTerminal();
26488
+ init_runCancelContext();
26489
+ init_argvFlagValue();
25866
26490
  init_readFacePosture();
25867
26491
  init_mcpPanel();
25868
26492
  init_effectiveFacts();
@@ -25954,6 +26578,8 @@ var init_dist = __esm({
25954
26578
  init_liveInitToolFace();
25955
26579
  init_providerPresets2();
25956
26580
  init_hitlBridge();
26581
+ init_suspendedReopen();
26582
+ init_approvalOutcomeNote();
25957
26583
  init_frameRouter();
25958
26584
  init_frameRouter();
25959
26585
  init_hitlHostSurface();
@@ -26120,12 +26746,13 @@ function publishEngineContextUsage(frame) {
26120
26746
  }, lastFrameSessionId = currentSessionIdOrNull3());
26121
26747
  }
26122
26748
  function noteEngineCompaction(record3) {
26123
- 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;
26124
26750
  lastCompaction = {
26125
26751
  atMs: record3.atMs ?? Date.now(),
26126
26752
  ...preTokens !== void 0 ? { preTokens } : {},
26127
26753
  ...postTokens !== void 0 ? { postTokens } : {},
26128
26754
  ...triggerTokensBefore !== void 0 ? { triggerTokensBefore } : {},
26755
+ ...freedTokens !== void 0 ? { freedTokens } : {},
26129
26756
  ...trigger !== void 0 ? { trigger } : {}
26130
26757
  }, lastCompactionSessionId = currentSessionIdOrNull3();
26131
26758
  }
@@ -27116,9 +27743,9 @@ function getSessionCronTasks() {
27116
27743
  function addSessionCronTask(task) {
27117
27744
  STATE.sessionCronTasks.push(task);
27118
27745
  }
27119
- function removeSessionCronTasks(ids) {
27120
- if (ids.length === 0) return 0;
27121
- 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;
27122
27749
  return removed === 0 ? 0 : (STATE.sessionCronTasks = remaining, removed);
27123
27750
  }
27124
27751
  function setSessionTrustAccepted(accepted) {
@@ -39442,8 +40069,8 @@ function emoji() {
39442
40069
  return new RegExp(_emoji, "u");
39443
40070
  }
39444
40071
  function timeSource(args) {
39445
- let hhmm = "(?:[01]\\d|2[0-3]):[0-5]\\d";
39446
- 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+)?)?`;
39447
40074
  }
39448
40075
  function time(args) {
39449
40076
  return new RegExp(`^${timeSource(args)}$`);
@@ -40654,12 +41281,12 @@ var $ZodType, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, $ZodU
40654
41281
  return `shape[${k2}]._zod.run({ value: input[${k2}], issues: [] }, ctx)`;
40655
41282
  };
40656
41283
  doc.write("const input = payload.value;");
40657
- let ids = /* @__PURE__ */ Object.create(null), counter = 0;
41284
+ let ids2 = /* @__PURE__ */ Object.create(null), counter = 0;
40658
41285
  for (let key of normalized.keys)
40659
- ids[key] = `key_${counter++}`;
41286
+ ids2[key] = `key_${counter++}`;
40660
41287
  doc.write("const newResult = {};");
40661
41288
  for (let key of normalized.keys) {
40662
- 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";
40663
41290
  doc.write(`const ${id} = ${parseStr(key)};`), isOptionalIn && isOptionalOut ? doc.write(`
40664
41291
  if (${id}.issues.length) {
40665
41292
  if (${k2} in input) {
@@ -69967,13 +70594,51 @@ function displaySafeFreeText(text2) {
69967
70594
  return out6 += text2.slice(cursor), out6.replace(SCHEMELESS_USERINFO, `${REDACTED_USERINFO}@$1`);
69968
70595
  }
69969
70596
  function redactSecretWords(text2) {
69970
- return text2.replace(SECRET_SCHEME_WORD, swapSecretValue).replace(SECRET_LABELLED_WORD, swapSecretValue);
70597
+ return redactByLabel(redactByLabel(text2, SECRET_SCHEME_WORD), SECRET_LABELLED_WORD);
70598
+ }
70599
+ function scanSecretValue(text2, from) {
70600
+ let i = from, slashes = 0;
70601
+ for (; i < text2.length && text2[i] === "\\" && slashes < 4; )
70602
+ i++, slashes++;
70603
+ let q2 = text2[i];
70604
+ if (q2 === '"' || q2 === "'") {
70605
+ let open19 = i + 1;
70606
+ if (slashes > 0) {
70607
+ let close = text2.indexOf("\\" + q2, open19);
70608
+ return close === -1 || close - open19 > VALUE_SCAN_CAP ? null : close > open19 ? { start: open19, end: close } : null;
70609
+ }
70610
+ let j4 = open19;
70611
+ for (; j4 < text2.length && j4 - open19 <= VALUE_SCAN_CAP; ) {
70612
+ if (text2[j4] === "\\") {
70613
+ j4 += 2;
70614
+ continue;
70615
+ }
70616
+ if (text2[j4] === q2) return j4 > open19 ? { start: open19, end: j4 } : null;
70617
+ j4++;
70618
+ }
70619
+ return null;
70620
+ }
70621
+ let j3 = i;
70622
+ for (; j3 < text2.length && j3 - i < VALUE_SCAN_CAP && !isBareValueStop(text2[j3]); ) j3++;
70623
+ return j3 > i ? { start: i, end: j3 } : null;
69971
70624
  }
69972
- function swapSecretValue(whole, label, value) {
70625
+ function isDiagnosticValue(value) {
70626
+ if (value.startsWith("\xABredacted") || /^[a-z][a-z0-9+.-]{1,15}:\/\//i.test(value)) return !0;
69973
70627
  let bare = value.replace(/[.,;:!?)\]}'"]{0,8}$/, "").toLowerCase();
69974
- return DIAGNOSTIC_VALUE_WORDS.has(bare) ? whole : `${label} ${REDACTED_SECRET}`;
70628
+ return bare === "" || DIAGNOSTIC_VALUE_WORDS.has(bare);
70629
+ }
70630
+ function redactByLabel(text2, re) {
70631
+ let out6 = "", last4 = 0;
70632
+ re.lastIndex = 0;
70633
+ for (let m2 = re.exec(text2); m2 !== null; m2 = re.exec(text2)) {
70634
+ let v2 = scanSecretValue(text2, m2.index + m2[0].length);
70635
+ if (v2 === null) continue;
70636
+ let value = text2.slice(v2.start, v2.end);
70637
+ out6 += text2.slice(last4, v2.start) + (isDiagnosticValue(value) ? value : REDACTED_SECRET), last4 = v2.end, re.lastIndex = v2.end;
70638
+ }
70639
+ return out6 + text2.slice(last4);
69975
70640
  }
69976
- var DISPLAY_REDACTION_MARKER_RE, REDACTED_USERINFO, REDACTED_QUERY, REDACTED_FRAGMENT, TOKEN_STOP, TRAILING_PUNCTUATION, VALUE_BOUNDARY_TAIL, isWhitespaceOrControl, isSchemeChar, isAlpha, SCHEMELESS_USERINFO, REDACTED_SECRET, DIAGNOSTIC_VALUE_WORDS, SECRET_SCHEME_WORD, SECRET_LABELLED_WORD, init_displaySafeUrl = __esm({
70641
+ var DISPLAY_REDACTION_MARKER_RE, REDACTED_USERINFO, REDACTED_QUERY, REDACTED_FRAGMENT, TOKEN_STOP, TRAILING_PUNCTUATION, VALUE_BOUNDARY_TAIL, isWhitespaceOrControl, isSchemeChar, isAlpha, SCHEMELESS_USERINFO, REDACTED_SECRET, DIAGNOSTIC_VALUE_WORDS, VALUE_SCAN_CAP, BARE_VALUE_STOP_CHARS, isBareValueStop, SECRET_SCHEME_WORD, SECRET_LABELLED_WORD, init_displaySafeUrl = __esm({
69977
70642
  "build-src/src/sema/displaySafeUrl.ts"() {
69978
70643
  DISPLAY_REDACTION_MARKER_RE = /^«redacted(?::[a-z-]{1,16}){0,2}»$/, REDACTED_USERINFO = "\xABredacted:userinfo\xBB", REDACTED_QUERY = "\xABredacted:query\xBB", REDACTED_FRAGMENT = "\xABredacted:fragment\xBB";
69979
70644
  TOKEN_STOP = /* @__PURE__ */ new Set(['"', "<", ">", "`", "|", "\\", "^", "{", "}"]), TRAILING_PUNCTUATION = /* @__PURE__ */ new Set([".", ",", ";", ":", "!", "?", "'"]), VALUE_BOUNDARY_TAIL = /[?#&=;]$/, isWhitespaceOrControl = (ch2) => {
@@ -70009,9 +70674,57 @@ var DISPLAY_REDACTION_MARKER_RE, REDACTED_USERINFO, REDACTED_QUERY, REDACTED_FRA
70009
70674
  "revoked",
70010
70675
  "disabled",
70011
70676
  "unavailable",
70012
- "incorrect"
70013
- ]);
70014
- SECRET_SCHEME_WORD = /(?:\b|(?<=\\[A-Za-z"']))(bearer|basic)[\s:=\uFF1A\uFF1D]{1,8}(?:\\{0,4}["']\s{0,4})?([A-Za-z0-9._~+/=%-]{8,})/gi, SECRET_LABELLED_WORD = /(?:\b|(?<=\\[A-Za-z"']))((?:access[-_ ]?|refresh[-_ ]?|id[-_ ]?|client[-_ ]?|api[-_ ]?|x[-_]api[-_ ]?|session[-_ ]?|auth[-_ ]?)?(?:token|key|secret|password|authorization|credential)s?)(?:\\{0,4}["']|\\{1,4})?\s{0,4}[:=\uFF1A\uFF1D]\s{0,4}(?:\\{0,4}["']|\\{1,4})?\s{0,4}([A-Za-z0-9._~+/=%-]{8,})/gi;
70677
+ "incorrect",
70678
+ "not",
70679
+ "no",
70680
+ "set",
70681
+ "unset",
70682
+ "blank",
70683
+ "value",
70684
+ "values",
70685
+ "of",
70686
+ "the",
70687
+ "a",
70688
+ "an",
70689
+ "is",
70690
+ "was",
70691
+ "are",
70692
+ "for",
70693
+ "to",
70694
+ "in",
70695
+ "on",
70696
+ "and",
70697
+ "or",
70698
+ "from",
70699
+ "with",
70700
+ "at",
70701
+ "by",
70702
+ "this",
70703
+ "that",
70704
+ "it",
70705
+ "be",
70706
+ "must",
70707
+ "should",
70708
+ "can",
70709
+ "cannot",
70710
+ "true",
70711
+ "false",
70712
+ "yes",
70713
+ "ok",
70714
+ "n/a",
70715
+ "na",
70716
+ // 认证方案词:`Authorization: Bearer <tok>` 里 `Bearer` 是标签的一部分,真值由 ① 那条正则接着洗。
70717
+ "bearer",
70718
+ "basic",
70719
+ "digest",
70720
+ "hmac",
70721
+ "oauth",
70722
+ "oauth2",
70723
+ "jwt",
70724
+ "apikey",
70725
+ "api-key"
70726
+ ]), VALUE_SCAN_CAP = 512, BARE_VALUE_STOP_CHARS = /* @__PURE__ */ new Set([",", ";", '"', "'", "\\", "(", ")", "[", "]", "{", "}", "<", ">"]), isBareValueStop = (ch2) => ch2 <= " " || BARE_VALUE_STOP_CHARS.has(ch2);
70727
+ SECRET_SCHEME_WORD = /(?:\b|(?<=\\[A-Za-z"']))(bearer|basic)[\s:=\uFF1A\uFF1D]{1,8}/gi, SECRET_LABELLED_WORD = /(?:\b|(?<=\\[A-Za-z"']))((?:access[-_ ]?|refresh[-_ ]?|id[-_ ]?|client[-_ ]?|api[-_ ]?|x[-_]api[-_ ]?|session[-_ ]?|auth[-_ ]?)?(?:token|key|secret|password|authorization|credential)s?)(?:\\{0,4}["'])?\s{0,4}[:=\uFF1A\uFF1D]\s{0,4}/gi;
70015
70728
  }
70016
70729
  });
70017
70730
 
@@ -77188,7 +77901,7 @@ __export(modelRoutingEnvPrecedence_exports, {
77188
77901
  modelRoutingEnvNote: () => modelRoutingEnvNote
77189
77902
  });
77190
77903
  function classifyModelRoutingEnv(env6, entryBaseUrl) {
77191
- 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);
77192
77905
  if (rawUrl === void 0 || provider === void 0) return { kind: "not-applicable" };
77193
77906
  let envEndpoint = normalizeEndpoint(rawUrl);
77194
77907
  if (envEndpoint === "") return { kind: "not-applicable" };
@@ -77210,12 +77923,12 @@ function modelRoutingEnvClause(env6, hop) {
77210
77923
  let v2 = classifyModelRoutingEnv(env6);
77211
77924
  return v2.kind !== "gateway-wins" ? null : providerNotDecidingClause(v2.provider);
77212
77925
  }
77213
- var ANTHROPIC_ROUTE_PROVIDERS, GATEWAY_ROUTE_PROVIDERS, nonEmpty4, init_modelRoutingEnvPrecedence = __esm({
77926
+ var ANTHROPIC_ROUTE_PROVIDERS, GATEWAY_ROUTE_PROVIDERS, nonEmpty5, init_modelRoutingEnvPrecedence = __esm({
77214
77927
  "build-src/src/sema/modelRoutingEnvPrecedence.ts"() {
77215
77928
  init_untrustedDisplayText();
77216
77929
  init_displaySafeUrl();
77217
77930
  init_servedEndpointEnv();
77218
- 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;
77219
77932
  }
77220
77933
  });
77221
77934
 
@@ -77350,9 +78063,9 @@ function classifyAnthropicEnvRouting(env6, opts) {
77350
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";
77351
78064
  if (own2) {
77352
78065
  if (catalogPresent) return { kind: "ignored", why: CATALOG_WHY };
77353
- 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);
77354
78067
  if (explicitProvider === "anthropic") return { kind: "honored", via: "explicit-anthropic-provider" };
77355
- let inferBaseUrl = baseUrl, inferCred = nonEmpty5(env6.ANTHROPIC_API_KEY) ?? authToken;
78068
+ let inferBaseUrl = baseUrl, inferCred = nonEmpty6(env6.ANTHROPIC_API_KEY) ?? authToken;
77356
78069
  if (explicitProvider === void 0 && inferBaseUrl && inferCred)
77357
78070
  return { kind: "honored", via: "engine-inferred-anthropic" };
77358
78071
  if (explicitProvider !== void 0) {
@@ -87951,7 +88664,10 @@ var USER_ROLES, NO_ENTRIES_DROPPED, OPEN_WORLD_KNOWN_KEYS, init_config_fns = __e
87951
88664
  init_types6();
87952
88665
  USER_ROLES = ["viewer", "editor", "publisher", "admin"];
87953
88666
  NO_ENTRIES_DROPPED = Object.freeze({}), OPEN_WORLD_KNOWN_KEYS = {
87954
- limits: { "": Object.keys(LimitsConfig.shape), infraCostRates: Object.keys(InfraCostRates.shape) }
88667
+ limits: [
88668
+ [[], Object.keys(LimitsConfig.shape)],
88669
+ [["infraCostRates"], Object.keys(InfraCostRates.shape)]
88670
+ ]
87955
88671
  };
87956
88672
  }
87957
88673
  });
@@ -88780,9 +89496,10 @@ var init_migrate = __esm({
88780
89496
  }
88781
89497
  });
88782
89498
 
88783
- // node_modules/@sema-agent/settings-schema/dist/api/wire.js
88784
- var DEVICE_GRANT_TYPE, REFRESH_TOKEN_TTL_SECONDS, OAUTH_ERROR_CODES, DEVICE_AUTH_STATUSES, init_wire = __esm({
88785
- "node_modules/@sema-agent/settings-schema/dist/api/wire.js"() {
89499
+ // node_modules/@sema-agent/settings-schema/dist/api/auth.js
89500
+ var DEVICE_GRANT_TYPE, REFRESH_TOKEN_TTL_SECONDS, OAUTH_ERROR_CODES, DEVICE_AUTH_STATUSES, OAuthErrorResponse, DeviceCodeRequest, DeviceCodeResponse, DeviceTokenRequest, TokenGrantResponse, TokenRefreshRequest, LogoutRequest, LogoutResponse, DeviceApproveLookupResponse, DeviceApproveRequest, DeviceApproveResponse, init_auth = __esm({
89501
+ "node_modules/@sema-agent/settings-schema/dist/api/auth.js"() {
89502
+ init_zod();
88786
89503
  DEVICE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code", REFRESH_TOKEN_TTL_SECONDS = 720 * 60 * 60, OAUTH_ERROR_CODES = [
88787
89504
  /** device/token: the user has not approved (or denied) the handshake yet — keep polling. */
88788
89505
  "authorization_pending",
@@ -88801,17 +89518,7 @@ var DEVICE_GRANT_TYPE, REFRESH_TOKEN_TTL_SECONDS, OAUTH_ERROR_CODES, DEVICE_AUTH
88801
89518
  "invalid_grant",
88802
89519
  /** SSO not configured on the registry (HTTP 503) — a deployment problem, not a client one. */
88803
89520
  "server_error"
88804
- ], DEVICE_AUTH_STATUSES = ["pending", "approved", "denied"];
88805
- }
88806
- });
88807
-
88808
- // node_modules/@sema-agent/settings-schema/dist/api/auth.js
88809
- var OAuthErrorResponse, DeviceCodeRequest, DeviceCodeResponse, DeviceTokenRequest, TokenGrantResponse, TokenRefreshRequest, LogoutRequest, LogoutResponse, DeviceApproveLookupResponse, DeviceApproveRequest, DeviceApproveResponse, init_auth = __esm({
88810
- "node_modules/@sema-agent/settings-schema/dist/api/auth.js"() {
88811
- init_zod();
88812
- init_wire();
88813
- init_wire();
88814
- OAuthErrorResponse = external_exports2.object({
89521
+ ], DEVICE_AUTH_STATUSES = ["pending", "approved", "denied"], OAuthErrorResponse = external_exports2.object({
88815
89522
  error: external_exports2.enum(OAUTH_ERROR_CODES),
88816
89523
  error_description: external_exports2.string().optional()
88817
89524
  }).passthrough(), DeviceCodeRequest = external_exports2.object({
@@ -88913,8 +89620,6 @@ var GLOBAL_SCOPE, RESERVED_SCOPE_IDS, SCOPE_ID_REGEX, ScopeId, ScopeRole, Scope,
88913
89620
  init_zod();
88914
89621
  init_config_fns();
88915
89622
  init_auth();
88916
- init_wire();
88917
- init_wire();
88918
89623
  GLOBAL_SCOPE = "global", RESERVED_SCOPE_IDS = [GLOBAL_SCOPE], SCOPE_ID_REGEX = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
88919
89624
  ScopeId = external_exports2.string().regex(SCOPE_ID_REGEX, "scope id must be a slug: [a-z0-9-], 1-64 chars, no edge dash"), ScopeRole = external_exports2.enum(USER_ROLES), Scope = external_exports2.object({
88920
89625
  id: ScopeId,
@@ -89863,10 +90568,10 @@ function patchPresent(intended, onDisk) {
89863
90568
  return intended === onDisk;
89864
90569
  }
89865
90570
  function keyEntriesOnDisk(pool, err8) {
89866
- let ids = err8.missingKeyEntries ?? [];
89867
- if (ids.length === 0) return !0;
90571
+ let ids2 = err8.missingKeyEntries ?? [];
90572
+ if (ids2.length === 0) return !0;
89868
90573
  let env6 = readSettingsEnv();
89869
- return ids.every((id) => {
90574
+ return ids2.every((id) => {
89870
90575
  let e = pool.find((p) => p.id === id);
89871
90576
  return !e?.apiKey || env6[keyEnvNameForEntry(id)] === e.apiKey;
89872
90577
  });
@@ -90047,13 +90752,13 @@ function mergeRenameErrors(stage1, stage2) {
90047
90752
  function poolWriteErrorNotice(error51, verb = "Saved") {
90048
90753
  let e = error51;
90049
90754
  if (!e.keyWriteOnly) return `Pool write failed: ${error51.message}`;
90050
- let ids = e.missingKeyEntries ?? [];
90051
- if (ids.length === 0)
90755
+ let ids2 = e.missingKeyEntries ?? [];
90756
+ if (ids2.length === 0)
90052
90757
  return `${verb}. A settings write failed (${error51.message}) \u2014 no API key was lost.`;
90053
- if (ids.length === 1)
90054
- return `${verb}, but the API key for "${ids[0]}" was not stored (${error51.message}). Open it in the Hub and set the key again.`;
90055
- let shown = ids.slice(0, 3).join(", ");
90056
- 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.`;
90057
90762
  }
90058
90763
  function poolSaveFailureNotice(error51, renamedTo, failVerb) {
90059
90764
  let e = error51;
@@ -90363,10 +91068,10 @@ function readSemaAutoModeOverride(env6 = process.env, configHome = resolveConfig
90363
91068
  let enabled = !0;
90364
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)
90365
91070
  try {
90366
- 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();
90367
91072
  for (let e of pool)
90368
- e.id && ids.add(e.id), e.modelId && ids.add(e.modelId);
90369
- 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]);
90370
91075
  } catch {
90371
91076
  }
90372
91077
  if (!enabled && allowModels === void 0) return;
@@ -125350,6 +126055,29 @@ var init_types8 = __esm({
125350
126055
  }
125351
126056
  });
125352
126057
 
126058
+ // build-src/src/sema/apiErrorMessageWash.ts
126059
+ function washApiErrorMessage(m2) {
126060
+ if (typeof m2 != "object" || m2 === null) return m2;
126061
+ let rec = m2;
126062
+ if (rec.isApiErrorMessage !== !0) return m2;
126063
+ let envelope = rec.message;
126064
+ if (typeof envelope != "object" || envelope === null) return m2;
126065
+ let content = envelope.content;
126066
+ if (!Array.isArray(content)) return m2;
126067
+ let changed = !1, washed = content.map((block2) => {
126068
+ let b3 = block2;
126069
+ if (typeof b3 != "object" || b3 === null || b3.type !== "text" || typeof b3.text != "string") return block2;
126070
+ let next = displaySafeFreeText(b3.text);
126071
+ return next === b3.text ? block2 : (changed = !0, { ...b3, text: next });
126072
+ });
126073
+ return changed ? { ...rec, message: { ...envelope, content: washed } } : m2;
126074
+ }
126075
+ var init_apiErrorMessageWash = __esm({
126076
+ "build-src/src/sema/apiErrorMessageWash.ts"() {
126077
+ init_displaySafeUrl();
126078
+ }
126079
+ });
126080
+
125353
126081
  // build-src/src/sema/appStateRef.ts
125354
126082
  var appStateRef_exports = {};
125355
126083
  __export(appStateRef_exports, {
@@ -125906,6 +126634,7 @@ function watchEngineContextFrames(events3) {
125906
126634
  preTokens: c3.tokensBefore,
125907
126635
  postTokens: c3.tokensAfter,
125908
126636
  triggerTokensBefore: c3.triggerTokensBefore,
126637
+ freedTokens: c3.freedTokens,
125909
126638
  trigger: c3.trigger
125910
126639
  })
125911
126640
  ).catch(() => {
@@ -125951,8 +126680,8 @@ function rewriteActiveRunBusyRow(msgs, seen2, billTurnCosts = !0, runToken) {
125951
126680
  }
125952
126681
  function passThroughWithBusyRewrite(msgs, seen2) {
125953
126682
  return (async function* () {
125954
- for await (let m2 of msgs) {
125955
- let busy = seen2.busy;
126683
+ for await (let raw2 of msgs) {
126684
+ let m2 = washApiErrorMessage(raw2), busy = seen2.busy;
125956
126685
  if (busy && typeof m2 == "object" && m2 !== null && "isApiErrorMessage" in m2 && m2.isApiErrorMessage === !0) {
125957
126686
  let envelope = "message" in m2 ? m2.message : void 0;
125958
126687
  if (typeof envelope == "object" && envelope !== null) {
@@ -126057,6 +126786,7 @@ var runTokenSeq, mintRunToken, reportedDroppedTypes2, DROPPED_TYPE_MEMO_CAP2, in
126057
126786
  "build-src/src/seam/adapter/runStream.ts"() {
126058
126787
  init_dist();
126059
126788
  init_untrustedDisplayText();
126789
+ init_apiErrorMessageWash();
126060
126790
  init_planReviewModeAfterOffer();
126061
126791
  init_turnUsageTranscriptStamp();
126062
126792
  init_activeRunSelfHeal2();
@@ -140263,6 +140993,94 @@ var PROBE_FACTS_OFF, PROBE_FACTS_ON, PROBE_VECTORS, init_epoch = __esm({
140263
140993
  }
140264
140994
  });
140265
140995
 
140996
+ // node_modules/@sema-agent/core/dist/tools/fs/read-deny.js
140997
+ function resolveReadDenyBuiltins(config4) {
140998
+ let activeTiers;
140999
+ if (config4?.tiers === void 0)
141000
+ activeTiers = new Set(READ_DENY_DEFAULT_TIERS);
141001
+ else {
141002
+ if (!Array.isArray(config4.tiers))
141003
+ throw new Error(`readDenyBuiltinTiers: expected an array of tier names, got ${JSON.stringify(config4.tiers)}.`);
141004
+ for (let t2 of config4.tiers)
141005
+ if (typeof t2 != "string" || !READ_DENY_BUILTIN_TIERS.includes(t2))
141006
+ throw new Error(`readDenyBuiltinTiers: unknown tier ${JSON.stringify(t2)} \u2014 known tiers: ${READ_DENY_BUILTIN_TIERS.join(", ")}.`);
141007
+ activeTiers = new Set(config4.tiers);
141008
+ }
141009
+ let excluded;
141010
+ if (config4?.exclude === void 0)
141011
+ excluded = /* @__PURE__ */ new Set();
141012
+ else {
141013
+ if (!Array.isArray(config4.exclude))
141014
+ throw new Error(`readDenyBuiltinExclude: expected an array of built-in row names (canonical pattern texts), got ${JSON.stringify(config4.exclude)}.`);
141015
+ for (let name of config4.exclude)
141016
+ if (typeof name != "string" || !READ_FACE_BUILTIN_DENY_TABLE.some((r) => r.pattern === name))
141017
+ throw new Error(`readDenyBuiltinExclude: ${JSON.stringify(name)} names no built-in row \u2014 row names are the canonical pattern texts of READ_FACE_BUILTIN_DENY_TABLE (e.g. ".ssh", ".config/gcloud").`);
141018
+ excluded = new Set(config4.exclude);
141019
+ }
141020
+ return READ_FACE_BUILTIN_DENY_TABLE.filter((r) => activeTiers.has(r.tier) && !excluded.has(r.pattern));
141021
+ }
141022
+ var READ_DENY_BUILTIN_TIERS, READ_FACE_BUILTIN_DENY_TABLE, READ_DENY_DEFAULT_TIERS, READ_FACE_DEFAULT_DENY_ENTRIES, init_read_deny = __esm({
141023
+ "node_modules/@sema-agent/core/dist/tools/fs/read-deny.js"() {
141024
+ READ_DENY_BUILTIN_TIERS = ["credentials", "shell-history", "browser", "wallet", "agent-config"], READ_FACE_BUILTIN_DENY_TABLE = [
141025
+ { pattern: ".ssh", tier: "credentials" },
141026
+ { pattern: "id_rsa*", tier: "credentials" },
141027
+ { pattern: "id_ed25519*", tier: "credentials" },
141028
+ { pattern: "id_ecdsa*", tier: "credentials" },
141029
+ { pattern: ".gnupg", tier: "credentials" },
141030
+ { pattern: ".aws", tier: "credentials" },
141031
+ { pattern: ".config/gcloud", tier: "credentials" },
141032
+ { pattern: ".azure", tier: "credentials" },
141033
+ { pattern: ".kube", tier: "credentials" },
141034
+ { pattern: ".netrc", tier: "credentials" },
141035
+ { pattern: "_netrc", tier: "credentials" },
141036
+ { pattern: ".git-credentials", tier: "credentials" },
141037
+ { pattern: ".docker/config.json", tier: "credentials" },
141038
+ { pattern: ".config/gh", tier: "credentials" },
141039
+ { pattern: ".npmrc", tier: "credentials" },
141040
+ { pattern: ".pypirc", tier: "credentials" },
141041
+ { pattern: ".local/share/keyrings", tier: "credentials" },
141042
+ { pattern: "Library/Keychains", tier: "credentials" },
141043
+ { pattern: ".credentials.json", tier: "credentials" },
141044
+ { pattern: ".codex/auth.json", tier: "credentials" },
141045
+ { pattern: ".config/github-copilot", tier: "credentials" },
141046
+ { pattern: ".gemini/oauth_creds.json", tier: "credentials" },
141047
+ { pattern: ".bash_history", tier: "shell-history" },
141048
+ { pattern: ".zsh_history", tier: "shell-history" },
141049
+ { pattern: "Library/Application Support/Google/Chrome", tier: "browser" },
141050
+ { pattern: "Library/Application Support/Firefox", tier: "browser" },
141051
+ { pattern: "Library/Safari", tier: "browser" },
141052
+ { pattern: ".config/google-chrome", tier: "browser" },
141053
+ { pattern: ".config/chromium", tier: "browser" },
141054
+ { pattern: ".mozilla/firefox", tier: "browser" },
141055
+ { pattern: "AppData/Local/Google/Chrome/User Data", tier: "browser" },
141056
+ { pattern: "AppData/Local/Microsoft/Edge/User Data", tier: "browser" },
141057
+ { pattern: "AppData/Roaming/Mozilla/Firefox", tier: "browser" },
141058
+ { pattern: ".bitcoin", tier: "wallet" },
141059
+ { pattern: ".ethereum", tier: "wallet" },
141060
+ { pattern: ".electrum", tier: "wallet" },
141061
+ { pattern: "Library/Application Support/Exodus", tier: "wallet" },
141062
+ { pattern: "Library/Application Support/Ledger Live", tier: "wallet" },
141063
+ { pattern: "wallet.dat", tier: "wallet" },
141064
+ { pattern: ".sema/settings.json", tier: "agent-config" },
141065
+ { pattern: ".sema/settings.local.json", tier: "agent-config" },
141066
+ { pattern: ".sema.*", tier: "agent-config" },
141067
+ { pattern: ".claude/settings.json", tier: "agent-config" },
141068
+ { pattern: ".claude/settings.local.json", tier: "agent-config" },
141069
+ { pattern: ".claude.*", tier: "agent-config" },
141070
+ { pattern: ".mcp.json", tier: "agent-config" },
141071
+ { pattern: ".ai-agent/.env", tier: "agent-config" },
141072
+ { pattern: ".sema/engine-data/.env", tier: "agent-config" },
141073
+ { pattern: ".codex/config.toml", tier: "agent-config" },
141074
+ { pattern: ".cursor/mcp.json", tier: "agent-config" },
141075
+ { pattern: ".continue/config.json", tier: "agent-config" },
141076
+ { pattern: ".continue/config.yaml", tier: "agent-config" },
141077
+ { pattern: ".aider.conf.yml", tier: "agent-config" },
141078
+ { pattern: ".gemini/settings.json", tier: "agent-config" }
141079
+ ], READ_DENY_DEFAULT_TIERS = [];
141080
+ READ_FACE_DEFAULT_DENY_ENTRIES = resolveReadDenyBuiltins().map((r) => r.pattern);
141081
+ }
141082
+ });
141083
+
140266
141084
  // node_modules/@sema-agent/core/dist/core/tool-face.js
140267
141085
  var TOOL_FAMILIES, TOOL_MOUNT_TAGS, TOOL_APPROVAL_CARDS, TOOL_PATH_BASES, TOOL_PATH_ABSENCES, TOOL_WIRE_NAME_MAX_CHARS, TOOL_CONTRACT_MAX_CHARS, TOOL_CARD_ID_MAX_CHARS, TOOL_KEY_MAX_CHARS, TOOL_KEYS_MAX, RENDER_HINT_MAX_CHARS, RENDER_HINT_ACTIVITY_MAX_CHARS, RENDER_HINT_MAX_LIST, MOUNT_TAG_IN_HANDS_BAND, HANDS_BAND_TAGS, init_tool_face = __esm({
140268
141086
  "node_modules/@sema-agent/core/dist/core/tool-face.js"() {
@@ -140679,7 +141497,7 @@ var FULL_SHELL_CONTRACT_ID, READONLY_SHELL_CONTRACT_ID, TASK_CREATE_TOOL_NAME, T
140679
141497
  { id: "task-stop-hands", name: "TaskStop", source: "builtin", definedIn: "src/tools/fs/fs-bash.ts", mountedBy: ["hands"], cards: [], face: { family: "delegate", effect: "write", contract: TASK_STOP_CONTRACT } },
140680
141498
  { id: "task-output", name: "TaskOutput", source: "builtin", definedIn: "src/core/task-registry.ts", mountedBy: ["delegation"], cards: ["task-output"], face: { family: "delegate", effect: "read", contract: TASK_OUTPUT_CONTRACT } },
140681
141499
  { id: "task-stop", name: "TaskStop", source: "builtin", definedIn: "src/core/task-registry.ts", mountedBy: ["delegation"], cards: ["task-stop"], face: { family: "delegate", effect: "write", contract: TASK_STOP_CONTRACT } },
140682
- { id: "monitor", name: "Monitor", source: "builtin", definedIn: "src/tools/monitor.ts", mountedBy: ["backgroundTasks"], cards: ["monitor-start"], face: { family: "other", effect: "write", contract: c("core.monitor@1"), offloadThresholdChars: 1e4 } },
141500
+ { id: "monitor", name: "Monitor", source: "builtin", definedIn: "src/tools/monitor.ts", mountedBy: ["backgroundTasks"], cards: ["monitor-start", "readonly_out_of_root"], face: { family: "other", effect: "write", contract: c("core.monitor@1"), offloadThresholdChars: 1e4 } },
140683
141501
  { id: "send-message", name: "SendMessage", source: "builtin", definedIn: "src/agents/send-message-tool.ts", mountedBy: ["delegation", "hostInternals", "peerLane"], cards: ["send-message"], face: { family: "protocol", effect: "write", contract: c("core.send_message@1") } },
140684
141502
  { id: "agent-transcript", name: "AgentTranscript", source: "builtin", definedIn: "src/agents/agent-transcript-tool.ts", mountedBy: ["delegation"], cards: ["agent-transcript"], face: { family: "delegate", effect: "read", contract: c("core.agent_transcript@1") } },
140685
141503
  { id: "list-agents", name: "ListAgents", source: "builtin", definedIn: "src/agents/list-agents-tool.ts", mountedBy: ["peerLane"], cards: ["list-agents"], face: { family: "protocol", effect: "read", aliases: ["ListPeers"], contract: c("core.list_agents@1") } },
@@ -140894,6 +141712,7 @@ function identityAnchorOf(identity3) {
140894
141712
  }
140895
141713
  var WIN_RESERVED_RE, asciiBytes, BINARY_MAGIC_SIGNATURES, init_safety = __esm({
140896
141714
  "node_modules/@sema-agent/core/dist/tools/fs/safety.js"() {
141715
+ init_read_deny();
140897
141716
  init_surrogate_safe_slice();
140898
141717
  init_tool_registry();
140899
141718
  init_gate_bounded_await();
@@ -141143,6 +141962,7 @@ var init_tools = __esm({
141143
141962
  "node_modules/@sema-agent/core/dist/core/tools.js"() {
141144
141963
  init_value2();
141145
141964
  init_tool_errors();
141965
+ init_thrown_value();
141146
141966
  init_tool_catalog();
141147
141967
  }
141148
141968
  });
@@ -151928,6 +152748,7 @@ function summarizeWorkflowRun(run2) {
151928
152748
  ...run2.name !== void 0 ? { name: run2.name } : {},
151929
152749
  ...run2.description !== void 0 ? { description: run2.description } : {},
151930
152750
  status: run2.status,
152751
+ ...run2.errorCode !== void 0 ? { errorCode: run2.errorCode } : {},
151931
152752
  ...run2.agentFailures !== void 0 ? { agentFailures: run2.agentFailures } : {},
151932
152753
  ...run2.budgetOvershoot !== void 0 ? { budgetOvershoot: { ...run2.budgetOvershoot } } : {},
151933
152754
  ...run2.timeoutInterruption !== void 0 ? { timeoutInterruption: { ...run2.timeoutInterruption } } : {},
@@ -153371,7 +154192,7 @@ async function deliverToRunningAgentLane(core, id, access7, notification, opts)
153371
154192
  return { ok: !1, reason: "not_found" };
153372
154193
  if (handle2.status !== "running")
153373
154194
  return { ok: !1, reason: "not_running" };
153374
- let bounded2 = (p, fallback, onTimeout) => new Promise((resolve59) => {
154195
+ let bounded3 = (p, fallback, onTimeout) => new Promise((resolve59) => {
153375
154196
  let t2 = setTimeout(() => {
153376
154197
  try {
153377
154198
  onTimeout?.();
@@ -153389,12 +154210,12 @@ async function deliverToRunningAgentLane(core, id, access7, notification, opts)
153389
154210
  if (handle2.channelState !== "attaching")
153390
154211
  return { ok: !1, reason: "no_channel" };
153391
154212
  let q2 = handle2.preAttachQueue ??= [];
153392
- 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) => {
153393
154214
  q2.push([notification, opts, resolve59]);
153394
154215
  }), { ok: !0, disposition: "pending" });
153395
154216
  }
153396
154217
  let detachOnTimeout;
153397
- return await bounded2(new Promise((resolve59) => {
154218
+ return await bounded3(new Promise((resolve59) => {
153398
154219
  let inflight4 = handle2.inFlightDirect ??= /* @__PURE__ */ new Set(), settleOnce = (r) => {
153399
154220
  inflight4.has(settleOnce) && (inflight4.delete(settleOnce), resolve59(r));
153400
154221
  };
@@ -155071,7 +155892,10 @@ var SUBSTITUTION_PLACEHOLDER, UNREADABLE_EXPANSION_TEXT, UNDELIMITED_SUBSTITUTIO
155071
155892
  });
155072
155893
 
155073
155894
  // node_modules/@sema-agent/core/dist/tools/fs/bash-program-position.js
155074
- var NOT_AUTO_ALLOWED, NO_DECLARED_OPTIONS, launcherRow, LAUNCHER_TABLE, COMMAND_LAUNCHERS, SHELL_SCAN_DECLINES, init_bash_program_position = __esm({
155895
+ function seatDeclineEvidence(table) {
155896
+ return new Set(SHELL_SCAN_DECLINES.filter((decline) => table[decline] === !0));
155897
+ }
155898
+ var NOT_AUTO_ALLOWED, NO_DECLARED_OPTIONS, launcherRow, LAUNCHER_TABLE, COMMAND_LAUNCHERS, SHELL_SCAN_DECLINES, BOUNDARY_SEAT_READS_DECLINE, CLASSIFY_SEAT_READS_DECLINE, init_bash_program_position = __esm({
155075
155899
  "node_modules/@sema-agent/core/dist/tools/fs/bash-program-position.js"() {
155076
155900
  NOT_AUTO_ALLOWED = "\u2014 not auto-allowed", NO_DECLARED_OPTIONS = { optionArity: /* @__PURE__ */ new Map() }, launcherRow = (pairs, extra = {}) => ({ optionArity: new Map(pairs), ...extra }), LAUNCHER_TABLE = /* @__PURE__ */ new Map([
155077
155901
  ["env", launcherRow([["-i", 0], ["-0", 0], ["-v", 0], ["--ignore-environment", 0], ["--null", 0], ["--debug", 0], ["-u", 1], ["--unset", 1]], { assignmentOperands: !0 })],
@@ -155136,7 +155960,13 @@ var NOT_AUTO_ALLOWED, NO_DECLARED_OPTIONS, launcherRow, LAUNCHER_TABLE, COMMAND_
155136
155960
  ["valgrind", NO_DECLARED_OPTIONS],
155137
155961
  ["firejail", { optionArity: /* @__PURE__ */ new Map(), whenNoProgram: "shell" }],
155138
155962
  ["bwrap", NO_DECLARED_OPTIONS]
155139
- ]), COMMAND_LAUNCHERS = new Set(LAUNCHER_TABLE.keys()), SHELL_SCAN_DECLINES = ["unreadable_program_position", "stream_fed_operands"];
155963
+ ]), COMMAND_LAUNCHERS = new Set(LAUNCHER_TABLE.keys()), SHELL_SCAN_DECLINES = ["unreadable_program_position", "stream_fed_operands"], BOUNDARY_SEAT_READS_DECLINE = {
155964
+ unreadable_program_position: !0,
155965
+ stream_fed_operands: !0
155966
+ }, CLASSIFY_SEAT_READS_DECLINE = {
155967
+ unreadable_program_position: !1,
155968
+ stream_fed_operands: !1
155969
+ };
155140
155970
  }
155141
155971
  });
155142
155972
 
@@ -155147,9 +155977,13 @@ function hasBareShellOperator(s, quotedOperatorsAreText) {
155147
155977
  let mask = quoteMask(s);
155148
155978
  if (!mask.balanced)
155149
155979
  return SHELL_OPERATORS.test(s);
155150
- for (let i = 0; i < s.length; i++)
155151
- if (!mask.quoted[i] && SHELL_OPERATORS.test(s[i]))
155980
+ for (let i = 0; i < s.length; i++) {
155981
+ let ch2 = s[i];
155982
+ if (!SHELL_OPERATORS.test(ch2))
155983
+ continue;
155984
+ if (!(SHELL_EXPANDS_IN_DOUBLE_QUOTES.test(ch2) ? mask.openedBy[i] === "'" : mask.quoted[i]))
155152
155985
  return !0;
155986
+ }
155153
155987
  return !1;
155154
155988
  }
155155
155989
  function parseLeadingCommandName(command8, options) {
@@ -155211,12 +156045,14 @@ function splitShellCompoundSegments(source, options) {
155211
156045
  let segments = lexed.segments.map((s) => s.text), connectors = lexed.segments.map((s) => s.connector);
155212
156046
  return { segments, pipeFed: connectors.map((k2) => k2 === "|"), connectors };
155213
156047
  }
155214
- var SHELL_OPERATORS, SHELL_SEGMENT_QUOTE_BLIND_REJECT, SHELL_EXPANSION_CHARS, SHELL_REDIRECTION_OPERATORS, SHELL_CONNECTOR_CHARS, BLANK_INLINE, PERL_INLINE, RUBY_INLINE, PYTHON_INLINE, NODE_INLINE, PHP_INLINE, LUA_INLINE, TCL_INLINE, EXPECT_INLINE, AWK_INLINE, JQ_INLINE, BC_INLINE, DC_INLINE, SQLITE_INLINE, PSQL_INLINE, OSASCRIPT_INLINE, RSCRIPT_INLINE, JULIA_INLINE, GHCI_INLINE, GROOVY_INLINE, BUN_INLINE, init_bash_readonly_classifier = __esm({
156048
+ var SHELL_OPERATORS, SHELL_EXPANDS_IN_DOUBLE_QUOTES, SHELL_SEGMENT_QUOTE_BLIND_REJECT, SHELL_EXPANSION_CHARS, SHELL_REDIRECTION_OPERATORS, SHELL_CONNECTOR_CHARS, BLANK_INLINE, PERL_INLINE, RUBY_INLINE, PYTHON_INLINE, NODE_INLINE, PHP_INLINE, LUA_INLINE, TCL_INLINE, EXPECT_INLINE, AWK_INLINE, JQ_INLINE, BC_INLINE, DC_INLINE, SQLITE_INLINE, PSQL_INLINE, OSASCRIPT_INLINE, RSCRIPT_INLINE, JULIA_INLINE, GHCI_INLINE, GROOVY_INLINE, BUN_INLINE, init_bash_readonly_classifier = __esm({
155215
156049
  "node_modules/@sema-agent/core/dist/tools/fs/bash-readonly-classifier.js"() {
156050
+ init_read_deny();
155216
156051
  init_safety();
155217
156052
  init_bash_lexer();
155218
156053
  init_bash_program_position();
155219
156054
  SHELL_OPERATORS = /[;&|<>$()`\n\r\\]/;
156055
+ SHELL_EXPANDS_IN_DOUBLE_QUOTES = /[$`]/;
155220
156056
  SHELL_SEGMENT_QUOTE_BLIND_REJECT = /[<>()`\n\r\\]/, SHELL_EXPANSION_CHARS = /[$]/;
155221
156057
  SHELL_REDIRECTION_OPERATORS = /[<>]/, SHELL_CONNECTOR_CHARS = /[|&;]/;
155222
156058
  BLANK_INLINE = {
@@ -155411,7 +156247,7 @@ var init_gh_rate_limit = __esm({
155411
156247
  });
155412
156248
 
155413
156249
  // node_modules/@sema-agent/core/dist/tools/fs/fs-bash.js
155414
- var BOUNDARY_SEAT_DECLINE_EVIDENCE, TOOL_PROGRESS_BOUND, READONLY_FACE_ESCAPE_PROSE, init_fs_bash = __esm({
156250
+ var BOUNDARY_SEAT_DECLINE_EVIDENCE, CLASSIFY_SEAT_DECLINE_EVIDENCE, TOOL_PROGRESS_BOUND, READONLY_FACE_ESCAPE_PROSE, FULL_SHELL_FACE_ESCAPE_PROSE, MONITOR_ESCAPE_PROSE, init_fs_bash = __esm({
155415
156251
  "node_modules/@sema-agent/core/dist/tools/fs/fs-bash.js"() {
155416
156252
  init_build3();
155417
156253
  init_tools();
@@ -155421,6 +156257,7 @@ var BOUNDARY_SEAT_DECLINE_EVIDENCE, TOOL_PROGRESS_BOUND, READONLY_FACE_ESCAPE_PR
155421
156257
  init_task_tool_shape();
155422
156258
  init_background_shell();
155423
156259
  init_untrusted_text();
156260
+ init_surrogate_safe_slice();
155424
156261
  init_mcp();
155425
156262
  init_safety();
155426
156263
  init_remote_env();
@@ -155429,102 +156266,21 @@ var BOUNDARY_SEAT_DECLINE_EVIDENCE, TOOL_PROGRESS_BOUND, READONLY_FACE_ESCAPE_PR
155429
156266
  init_untrusted_text();
155430
156267
  init_bash_readonly_classifier();
155431
156268
  init_bash_program_position();
156269
+ init_read_deny();
155432
156270
  init_tool_catalog_entries();
155433
156271
  init_thrown_value();
155434
156272
  init_tool_catalog_entries();
155435
- BOUNDARY_SEAT_DECLINE_EVIDENCE = new Set(SHELL_SCAN_DECLINES), TOOL_PROGRESS_BOUND = Object.freeze({ intervalMs: 1e3, tailLines: 20, tailMaxBytes: 16 * 1024 }), READONLY_FACE_ESCAPE_PROSE = {
156273
+ BOUNDARY_SEAT_DECLINE_EVIDENCE = seatDeclineEvidence(BOUNDARY_SEAT_READS_DECLINE), CLASSIFY_SEAT_DECLINE_EVIDENCE = seatDeclineEvidence(CLASSIFY_SEAT_READS_DECLINE), TOOL_PROGRESS_BOUND = Object.freeze({ intervalMs: 1e3, tailLines: 20, tailMaxBytes: 16 * 1024 }), READONLY_FACE_ESCAPE_PROSE = {
156274
+ tool: "Bash",
155436
156275
  subject: "a path this command reads",
155437
156276
  verdictPhrase: ` ${NOT_AUTO_ALLOWED}`,
155438
156277
  note: BASH_READONLY_CONFINEMENT_NOTE
155439
- };
155440
- }
155441
- });
155442
-
155443
- // node_modules/@sema-agent/core/dist/tools/fs/read-deny.js
155444
- function resolveReadDenyBuiltins(config4) {
155445
- let activeTiers;
155446
- if (config4?.tiers === void 0)
155447
- activeTiers = new Set(READ_DENY_DEFAULT_TIERS);
155448
- else {
155449
- if (!Array.isArray(config4.tiers))
155450
- throw new Error(`readDenyBuiltinTiers: expected an array of tier names, got ${JSON.stringify(config4.tiers)}.`);
155451
- for (let t2 of config4.tiers)
155452
- if (typeof t2 != "string" || !READ_DENY_BUILTIN_TIERS.includes(t2))
155453
- throw new Error(`readDenyBuiltinTiers: unknown tier ${JSON.stringify(t2)} \u2014 known tiers: ${READ_DENY_BUILTIN_TIERS.join(", ")}.`);
155454
- activeTiers = new Set(config4.tiers);
155455
- }
155456
- let excluded;
155457
- if (config4?.exclude === void 0)
155458
- excluded = /* @__PURE__ */ new Set();
155459
- else {
155460
- if (!Array.isArray(config4.exclude))
155461
- throw new Error(`readDenyBuiltinExclude: expected an array of built-in row names (canonical pattern texts), got ${JSON.stringify(config4.exclude)}.`);
155462
- for (let name of config4.exclude)
155463
- if (typeof name != "string" || !READ_FACE_BUILTIN_DENY_TABLE.some((r) => r.pattern === name))
155464
- throw new Error(`readDenyBuiltinExclude: ${JSON.stringify(name)} names no built-in row \u2014 row names are the canonical pattern texts of READ_FACE_BUILTIN_DENY_TABLE (e.g. ".ssh", ".config/gcloud").`);
155465
- excluded = new Set(config4.exclude);
155466
- }
155467
- return READ_FACE_BUILTIN_DENY_TABLE.filter((r) => activeTiers.has(r.tier) && !excluded.has(r.pattern));
155468
- }
155469
- var READ_DENY_BUILTIN_TIERS, READ_FACE_BUILTIN_DENY_TABLE, READ_DENY_DEFAULT_TIERS, READ_FACE_DEFAULT_DENY_ENTRIES, init_read_deny = __esm({
155470
- "node_modules/@sema-agent/core/dist/tools/fs/read-deny.js"() {
155471
- READ_DENY_BUILTIN_TIERS = ["credentials", "shell-history", "browser", "wallet", "agent-config"], READ_FACE_BUILTIN_DENY_TABLE = [
155472
- { pattern: ".ssh", tier: "credentials" },
155473
- { pattern: "id_rsa*", tier: "credentials" },
155474
- { pattern: "id_ed25519*", tier: "credentials" },
155475
- { pattern: "id_ecdsa*", tier: "credentials" },
155476
- { pattern: ".gnupg", tier: "credentials" },
155477
- { pattern: ".aws", tier: "credentials" },
155478
- { pattern: ".config/gcloud", tier: "credentials" },
155479
- { pattern: ".azure", tier: "credentials" },
155480
- { pattern: ".kube", tier: "credentials" },
155481
- { pattern: ".netrc", tier: "credentials" },
155482
- { pattern: "_netrc", tier: "credentials" },
155483
- { pattern: ".git-credentials", tier: "credentials" },
155484
- { pattern: ".docker/config.json", tier: "credentials" },
155485
- { pattern: ".config/gh", tier: "credentials" },
155486
- { pattern: ".npmrc", tier: "credentials" },
155487
- { pattern: ".pypirc", tier: "credentials" },
155488
- { pattern: ".local/share/keyrings", tier: "credentials" },
155489
- { pattern: "Library/Keychains", tier: "credentials" },
155490
- { pattern: ".credentials.json", tier: "credentials" },
155491
- { pattern: ".codex/auth.json", tier: "credentials" },
155492
- { pattern: ".config/github-copilot", tier: "credentials" },
155493
- { pattern: ".gemini/oauth_creds.json", tier: "credentials" },
155494
- { pattern: ".bash_history", tier: "shell-history" },
155495
- { pattern: ".zsh_history", tier: "shell-history" },
155496
- { pattern: "Library/Application Support/Google/Chrome", tier: "browser" },
155497
- { pattern: "Library/Application Support/Firefox", tier: "browser" },
155498
- { pattern: "Library/Safari", tier: "browser" },
155499
- { pattern: ".config/google-chrome", tier: "browser" },
155500
- { pattern: ".config/chromium", tier: "browser" },
155501
- { pattern: ".mozilla/firefox", tier: "browser" },
155502
- { pattern: "AppData/Local/Google/Chrome/User Data", tier: "browser" },
155503
- { pattern: "AppData/Local/Microsoft/Edge/User Data", tier: "browser" },
155504
- { pattern: "AppData/Roaming/Mozilla/Firefox", tier: "browser" },
155505
- { pattern: ".bitcoin", tier: "wallet" },
155506
- { pattern: ".ethereum", tier: "wallet" },
155507
- { pattern: ".electrum", tier: "wallet" },
155508
- { pattern: "Library/Application Support/Exodus", tier: "wallet" },
155509
- { pattern: "Library/Application Support/Ledger Live", tier: "wallet" },
155510
- { pattern: "wallet.dat", tier: "wallet" },
155511
- { pattern: ".sema/settings.json", tier: "agent-config" },
155512
- { pattern: ".sema/settings.local.json", tier: "agent-config" },
155513
- { pattern: ".sema.*", tier: "agent-config" },
155514
- { pattern: ".claude/settings.json", tier: "agent-config" },
155515
- { pattern: ".claude/settings.local.json", tier: "agent-config" },
155516
- { pattern: ".claude.*", tier: "agent-config" },
155517
- { pattern: ".mcp.json", tier: "agent-config" },
155518
- { pattern: ".ai-agent/.env", tier: "agent-config" },
155519
- { pattern: ".sema/engine-data/.env", tier: "agent-config" },
155520
- { pattern: ".codex/config.toml", tier: "agent-config" },
155521
- { pattern: ".cursor/mcp.json", tier: "agent-config" },
155522
- { pattern: ".continue/config.json", tier: "agent-config" },
155523
- { pattern: ".continue/config.yaml", tier: "agent-config" },
155524
- { pattern: ".aider.conf.yml", tier: "agent-config" },
155525
- { pattern: ".gemini/settings.json", tier: "agent-config" }
155526
- ], READ_DENY_DEFAULT_TIERS = [];
155527
- READ_FACE_DEFAULT_DENY_ENTRIES = resolveReadDenyBuiltins().map((r) => r.pattern);
156278
+ }, FULL_SHELL_FACE_ESCAPE_PROSE = {
156279
+ tool: "Bash",
156280
+ subject: "a path this command names",
156281
+ verdictPhrase: "",
156282
+ note: "The read boundary judged this command's written spelling before the call was approved, and execution is past the approval step \u2014 a target reached only through symlink resolution is refused here rather than escalated."
156283
+ }, MONITOR_ESCAPE_PROSE = { ...FULL_SHELL_FACE_ESCAPE_PROSE, tool: "Monitor" };
155528
156284
  }
155529
156285
  });
155530
156286
 
@@ -155910,7 +156666,7 @@ function ruleLaneShapeOf(command8, reading) {
155910
156666
  names2.push(void 0);
155911
156667
  continue;
155912
156668
  }
155913
- let floor = parseLeadingCommandName(segment2, { ...RULE_LANE_FLOOR, quotedOperatorsAreText: reading.quotedOperatorsAreText });
156669
+ let floor = parseLeadingCommandName(segment2, RULE_LANE_FLOOR);
155914
156670
  if ("reject" in floor)
155915
156671
  return {
155916
156672
  reject: split.segments.length > 1 ? `the segment "${escapeForDisclosure(segment2.trim())}" is not a single simple command (${floor.reject})` : floor.reject
@@ -156044,7 +156800,7 @@ function admitsUnder(rule, command8, reading) {
156044
156800
  if (rule.match === "exact")
156045
156801
  return folded === rule.command;
156046
156802
  let bodyShape = ruleLaneShapeOf(rule.command, reading);
156047
- return "reject" in bodyShape || shape.segments.length !== bodyShape.segments.length ? !1 : folded === rule.command || folded.startsWith(rule.command + " ");
156803
+ return "reject" in bodyShape || foldSpacing(rule.command) === void 0 || shape.segments.length !== bodyShape.segments.length ? !1 : folded === rule.command || folded.startsWith(rule.command + " ");
156048
156804
  }
156049
156805
  function ruleBreadthWarningsOf(rule) {
156050
156806
  if (rule.match !== "prefix" && rule.match !== "wildcard")
@@ -156242,7 +156998,10 @@ var RULE_BEHAVIORS, RULE_BEHAVIOR_SET, RULE_BEHAVIOR_PRECEDENCE, RULE_BEHAVIORS_
156242
156998
  "gh search prs",
156243
156999
  "gh search code"
156244
157000
  ], LEXICON_BODIES = SUGGESTION_LEXICON.map((b3) => b3.split(" ")), SCREENED_HEAD_NAMES = new Set([...BARE_INTERPRETER_NAMES].map((n2) => n2.toLowerCase()));
156245
- RULE_LANE_FLOOR = { pathPrefixedNameIsText: !0 }, MATCH_READING = { terminator: "keep", quotedOperatorsAreText: !1, redirection: "reject" };
157001
+ RULE_LANE_FLOOR = {
157002
+ pathPrefixedNameIsText: !0,
157003
+ quotedOperatorsAreText: !0
157004
+ }, MATCH_READING = { terminator: "keep", redirection: "reject" };
156246
157005
  CONTROL_CHARS_RE = /[\u0000-\u0008\u000A-\u001F\u007F-\u009F\p{Cf}\u2028\u2029]/u, CONTROL_CHARS_GLOBAL_RE = new RegExp(CONTROL_CHARS_RE.source, "gu"), DISCLOSED_RULE_TEXT_MAX_CHARS = 120;
156247
157006
  DISPLAY_STRIP_FORMAT_RE = new RegExp("\\p{Cf}", "gu");
156248
157007
  PATH_RULE_BASE_LABEL = {
@@ -156655,6 +157414,7 @@ var MAX_PENDING_STEER_CHARS, PENDING_STEER_QUEUE_BYTE_BUDGET_BYTES, MAX_PENDING_
156655
157414
  init_permission_rule_model();
156656
157415
  init_untrusted_egress();
156657
157416
  init_ask_question();
157417
+ init_untrusted_text();
156658
157418
  MAX_PENDING_STEER_CHARS = 16e3, PENDING_STEER_QUEUE_BYTE_BUDGET_BYTES = 48e3, MAX_PENDING_STEER_ENTRIES = Math.floor(PENDING_STEER_QUEUE_BYTE_BUDGET_BYTES / MAX_PENDING_STEER_CHARS), CheckpointError = class extends Error {
156659
157419
  code;
156660
157420
  detail;
@@ -158224,10 +158984,19 @@ var init_task_outcome = __esm({
158224
158984
  }
158225
158985
  });
158226
158986
 
158987
+ // node_modules/@sema-agent/core/dist/brain/errors.js
158988
+ var BRAIN_ERROR_CODES, CODE_ALTERNATION, CODE_RE, CODE_PREFIX_RE, init_errors10 = __esm({
158989
+ "node_modules/@sema-agent/core/dist/brain/errors.js"() {
158990
+ init_thrown_value();
158991
+ BRAIN_ERROR_CODES = ["auth", "rate_limit", "invalid_request", "server", "network", "http", "stream_torn", "refusal", "length_empty"], CODE_ALTERNATION = BRAIN_ERROR_CODES.join("|"), CODE_RE = new RegExp(`^\\[(${CODE_ALTERNATION})\\]`), CODE_PREFIX_RE = new RegExp(`^\\[(?:${CODE_ALTERNATION})\\]\\s*`);
158992
+ }
158993
+ });
158994
+
158227
158995
  // node_modules/@sema-agent/core/dist/brain/route-adjudicator.js
158228
158996
  var init_route_adjudicator = __esm({
158229
158997
  "node_modules/@sema-agent/core/dist/brain/route-adjudicator.js"() {
158230
158998
  init_request_params();
158999
+ init_errors10();
158231
159000
  }
158232
159001
  });
158233
159002
 
@@ -158247,14 +159016,6 @@ var SWAPPABLE_DEP_SEATS, SWAPPABLE_DEP_SEAT_SET, init_swappable_deps = __esm({
158247
159016
  }
158248
159017
  });
158249
159018
 
158250
- // node_modules/@sema-agent/core/dist/brain/errors.js
158251
- var BRAIN_ERROR_CODES, CODE_ALTERNATION, CODE_RE, CODE_PREFIX_RE, init_errors10 = __esm({
158252
- "node_modules/@sema-agent/core/dist/brain/errors.js"() {
158253
- init_thrown_value();
158254
- BRAIN_ERROR_CODES = ["auth", "rate_limit", "invalid_request", "server", "network", "http", "stream_torn", "refusal", "length_empty"], CODE_ALTERNATION = BRAIN_ERROR_CODES.join("|"), CODE_RE = new RegExp(`^\\[(${CODE_ALTERNATION})\\]`), CODE_PREFIX_RE = new RegExp(`^\\[(?:${CODE_ALTERNATION})\\]\\s*`);
158255
- }
158256
- });
158257
-
158258
159019
  // node_modules/@sema-agent/core/dist/brain/circuit-breaker.js
158259
159020
  var init_circuit_breaker = __esm({
158260
159021
  "node_modules/@sema-agent/core/dist/brain/circuit-breaker.js"() {
@@ -160636,6 +161397,7 @@ var MONITOR_DESCRIPTION, init_monitor = __esm({
160636
161397
  init_background_shell();
160637
161398
  init_task_registry();
160638
161399
  init_tool_catalog_entries();
161400
+ init_fs_bash();
160639
161401
  init_thrown_value();
160640
161402
  MONITOR_DESCRIPTION = `Run a shell command in the background and watch its stdout as a stream of events.
160641
161403
 
@@ -163830,11 +164592,13 @@ var ERROR_BODY_BYTE_CAP, init_stream_engine = __esm({
163830
164592
  init_stream_shared();
163831
164593
  init_context_overflow();
163832
164594
  init_errors10();
164595
+ init_route_adjudicator();
163833
164596
  init_input_too_long();
163834
164597
  init_retry();
163835
164598
  init_status_sink();
163836
164599
  init_timeout();
163837
164600
  init_thrown_value();
164601
+ init_untrusted_egress();
163838
164602
  ERROR_BODY_BYTE_CAP = 64 * 1024;
163839
164603
  }
163840
164604
  });
@@ -183878,13 +184642,13 @@ var caPath, builtinRootBodies, init_tlsTrust = __esm({
183878
184642
  function nearestListed(body, modelId) {
183879
184643
  let data = body?.data;
183880
184644
  if (!Array.isArray(data)) return;
183881
- let ids = data.map((m2) => m2?.id).filter((x3) => typeof x3 == "string");
183882
- if (ids.includes(modelId)) return;
184645
+ let ids2 = data.map((m2) => m2?.id).filter((x3) => typeof x3 == "string");
184646
+ if (ids2.includes(modelId)) return;
183883
184647
  let norm3 = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, ""), target = norm3(modelId);
183884
184648
  for (let len of [6, 5, 4]) {
183885
184649
  let stem = target.slice(0, len);
183886
184650
  if (stem.length < len) continue;
183887
- let hit = ids.find((i) => norm3(i).startsWith(stem));
184651
+ let hit = ids2.find((i) => norm3(i).startsWith(stem));
183888
184652
  if (hit) return hit;
183889
184653
  }
183890
184654
  }
@@ -221978,7 +222742,7 @@ async function resolveDependencyClosure(rootId, lookup, alreadyEnabled, allowedC
221978
222742
  return err8 || { ok: !0, closure };
221979
222743
  }
221980
222744
  async function expandClosureFromManifestDeps(opts) {
221981
- let ids = [], skipped = [], seen2 = /* @__PURE__ */ new Set();
222745
+ let ids2 = [], skipped = [], seen2 = /* @__PURE__ */ new Set();
221982
222746
  for (let rawDep of opts.manifestDeps ?? []) {
221983
222747
  let dep = qualifyDependency(rawDep, opts.declaringId);
221984
222748
  if (seen2.has(dep) || opts.closureSet.has(dep) || opts.alreadyEnabled.has(dep)) continue;
@@ -222006,9 +222770,9 @@ async function expandClosureFromManifestDeps(opts) {
222006
222770
  });
222007
222771
  continue;
222008
222772
  }
222009
- seen2.add(dep), ids.push(dep);
222773
+ seen2.add(dep), ids2.push(dep);
222010
222774
  }
222011
- return { ok: !0, ids, skipped };
222775
+ return { ok: !0, ids: ids2, skipped };
222012
222776
  }
222013
222777
  function formatSkippedManifestDependency(s) {
222014
222778
  let depMkt = parsePluginIdentifier(s.dependency).marketplace;
@@ -224120,12 +224884,12 @@ function estimateMessageTokens(messages) {
224120
224884
  return Math.ceil(totalTokens * (4 / 3));
224121
224885
  }
224122
224886
  function collectCompactableToolIds(messages) {
224123
- let ids = [];
224887
+ let ids2 = [];
224124
224888
  for (let message of messages)
224125
224889
  if (message.type === "assistant" && Array.isArray(message.message.content))
224126
224890
  for (let block2 of message.message.content)
224127
- block2.type === "tool_use" && COMPACTABLE_TOOLS2.has(block2.name) && ids.push(block2.id);
224128
- return ids;
224891
+ block2.type === "tool_use" && COMPACTABLE_TOOLS2.has(block2.name) && ids2.push(block2.id);
224892
+ return ids2;
224129
224893
  }
224130
224894
  function isMainThreadSource(querySource) {
224131
224895
  return !querySource || querySource.startsWith("repl_main_thread");
@@ -231498,7 +232262,7 @@ function stripUnderlineAnsi(content) {
231498
232262
  }
231499
232263
  var import_compiler_runtime22, React15, import_jsx_runtime26, MAX_JSON_FORMAT_LENGTH, URL_IN_JSON, init_OutputLine = __esm({
231500
232264
  "build-src/src/components/shell/OutputLine.tsx"() {
231501
- 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);
231502
232266
  init_useTerminalSize();
231503
232267
  init_ink2();
231504
232268
  init_hyperlink();
@@ -231507,7 +232271,7 @@ var import_compiler_runtime22, React15, import_jsx_runtime26, MAX_JSON_FORMAT_LE
231507
232271
  init_MessageResponse();
231508
232272
  init_messageActions();
231509
232273
  init_ExpandShellOutputContext();
231510
- import_jsx_runtime26 = __toESM(require_jsx_runtime());
232274
+ import_jsx_runtime26 = __toESM(require_jsx_runtime(), 1);
231511
232275
  MAX_JSON_FORMAT_LENGTH = 1e4;
231512
232276
  URL_IN_JSON = /https?:\/\/[^\s"'<>\\]+/g;
231513
232277
  }
@@ -251285,7 +252049,7 @@ function ruleStoreUnreadableNote(kind) {
251285
252049
  function readRootCandidateNote(v2) {
251286
252050
  if (v2 === void 0) return;
251287
252051
  let dir = elideUntrustedPath(v2.dir, 512);
251288
- return `candidate read root ${dir} \u2014 if it is a directory, adding it as a session read directory (/add-dir ${dir}) clears this ask`;
252052
+ return v2.covers === "exact" ? `candidate read root ${dir} \u2014 the engine named this exact path, not a directory. This host can only add directories as session read directories, and widening to the enclosing directory would grant more than this ask needs, so there is no one-step way to clear it here: answer this card instead.` : `candidate read root ${dir} \u2014 adding it as a session read directory (/add-dir ${dir}) clears this ask`;
251289
252053
  }
251290
252054
  function askFrameNoteParts(req2, _autoModeRaw) {
251291
252055
  let denial = denialLimitFallbackNote(req2.denialLimitFallback), origin2 = askOriginNote(req2.origin), ruleStore = ruleStoreUnreadableNote(req2.ruleStoreUnreadable), absence = ruleOffersAbsenceNote(req2.ruleOffersAbsence), readRoot = readRootCandidateNote(req2.readRootCandidate);
@@ -251378,17 +252142,28 @@ function markApprovalCardGateRow(toolCallId, row2, streamEpoch) {
251378
252142
  let handle2 = liveApprovalCards.get(born.callKey);
251379
252143
  return handle2 === void 0 ? !1 : handle2.windowClosed(row2 === "parked" ? "parked-frame" : "auto-denied");
251380
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
+ }
251381
252155
  function surfaceToolEndAutoDenied(ev, streamEpoch) {
251382
252156
  let r = resolveToolEndAutoDenied(ev, streamEpoch);
251383
252157
  if (r.kind !== "late") return r.kind;
251384
252158
  let [content, level] = r.row === "parked" ? [approvalMovedToDurableQueueLateRow(r.toolName), "info"] : [approvalAutoDeniedRow(r.toolName), "warning"];
251385
252159
  return surfaceLateDecideOutcome(content, level) ? "late" : "late-unsurfaced";
251386
252160
  }
251387
- 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({
251388
252162
  "build-src/src/sema/liveApprovalCardHandles.ts"() {
251389
252163
  init_askParkExpiry();
251390
252164
  init_liveSessionStore();
251391
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();
251392
252167
  }
251393
252168
  });
251394
252169
 
@@ -251904,10 +252679,17 @@ function planReviewEchoBackoffMs(attempt) {
251904
252679
  let i = Math.min(Math.floor(attempt), PLAN_REVIEW_ECHO_BACKOFF_LADDER.length - 1);
251905
252680
  return PLAN_REVIEW_ECHO_BACKOFF_LADDER[i];
251906
252681
  }
251907
- var openWindows, PLAN_REVIEW_ECHO_BACKOFF_LADDER, PLAN_REVIEW_ECHO_MAX_RETRIES, init_planReviewDecisionWindow = __esm({
252682
+ function planReviewEchoDeferral(attempt, deferredSoFarMs) {
252683
+ let spent = Number.isFinite(deferredSoFarMs) && deferredSoFarMs > 0 ? deferredSoFarMs : 0;
252684
+ return spent >= PLAN_REVIEW_ECHO_TOTAL_CAP_MS ? { kind: "fallback" } : { kind: "defer", waitMs: Math.min(planReviewEchoBackoffMs(attempt), PLAN_REVIEW_ECHO_TOTAL_CAP_MS - spent) };
252685
+ }
252686
+ function shouldSuppressPlanReviewReopen(taskId) {
252687
+ return typeof taskId == "string" && taskId !== "" && openWindows.has(taskId);
252688
+ }
252689
+ var openWindows, PLAN_REVIEW_ECHO_BACKOFF_LADDER, PLAN_REVIEW_ECHO_TOTAL_CAP_MS, PLAN_REVIEW_ECHO_MAX_RETRIES, init_planReviewDecisionWindow = __esm({
251908
252690
  "build-src/src/sema/planReviewDecisionWindow.ts"() {
251909
252691
  openWindows = /* @__PURE__ */ new Set();
251910
- PLAN_REVIEW_ECHO_BACKOFF_LADDER = [400, 800, 1600, 3200], PLAN_REVIEW_ECHO_MAX_RETRIES = PLAN_REVIEW_ECHO_BACKOFF_LADDER.length;
252692
+ PLAN_REVIEW_ECHO_BACKOFF_LADDER = [400, 800, 1600, 3200, 6400], PLAN_REVIEW_ECHO_TOTAL_CAP_MS = 6e4, PLAN_REVIEW_ECHO_MAX_RETRIES = PLAN_REVIEW_ECHO_BACKOFF_LADDER.length;
251911
252693
  }
251912
252694
  });
251913
252695
 
@@ -307626,7 +308408,7 @@ function FileEditToolUseRejectedMessage(t0) {
307626
308408
  }
307627
308409
  var import_compiler_runtime38, import_jsx_runtime45, MAX_LINES_TO_RENDER, init_FileEditToolUseRejectedMessage = __esm({
307628
308410
  "build-src/src/components/FileEditToolUseRejectedMessage.tsx"() {
307629
- import_compiler_runtime38 = __toESM(require_compiler_runtime());
308411
+ import_compiler_runtime38 = __toESM(require_compiler_runtime(), 1);
307630
308412
  init_useTerminalSize();
307631
308413
  init_cwd();
307632
308414
  init_ink2();
@@ -307634,7 +308416,7 @@ var import_compiler_runtime38, import_jsx_runtime45, MAX_LINES_TO_RENDER, init_F
307634
308416
  init_MessageResponse();
307635
308417
  init_StructuredDiffList();
307636
308418
  init_stringUtils();
307637
- import_jsx_runtime45 = __toESM(require_jsx_runtime()), MAX_LINES_TO_RENDER = 10;
308419
+ import_jsx_runtime45 = __toESM(require_jsx_runtime(), 1), MAX_LINES_TO_RENDER = 10;
307638
308420
  }
307639
308421
  });
307640
308422
 
@@ -329009,15 +329791,15 @@ async function bashToolHasPermission(input, context3, getCommandSubcommandPrefix
329009
329791
  if (permissionResult.behavior === "ask" || permissionResult.behavior === "passthrough") {
329010
329792
  let updates = "suggestions" in permissionResult ? permissionResult.suggestions : void 0, rules = extractRules(updates);
329011
329793
  for (let rule of rules) {
329012
- let ruleKey = permissionRuleValueToString(rule);
329013
- collectedRules.set(ruleKey, rule);
329794
+ let ruleKey2 = permissionRuleValueToString(rule);
329795
+ collectedRules.set(ruleKey2, rule);
329014
329796
  }
329015
329797
  if (permissionResult.behavior === "ask" && rules.length === 0 && permissionResult.decisionReason?.type !== "rule")
329016
329798
  for (let rule of extractRules(
329017
329799
  suggestionForExactCommand3(subcommand)
329018
329800
  )) {
329019
- let ruleKey = permissionRuleValueToString(rule);
329020
- collectedRules.set(ruleKey, rule);
329801
+ let ruleKey2 = permissionRuleValueToString(rule);
329802
+ collectedRules.set(ruleKey2, rule);
329021
329803
  }
329022
329804
  }
329023
329805
  let decisionReason = {
@@ -329950,10 +330732,10 @@ async function addCronTask(cron, prompt, recurring, durable, agentId) {
329950
330732
  await writeCronTasks([...current6, task], root2);
329951
330733
  }), id) : (addSessionCronTask({ ...task, ...agentId ? { agentId } : {} }), id);
329952
330734
  }
329953
- async function removeCronTasks(ids, dir) {
329954
- 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)
329955
330737
  return;
329956
- let idSet = new Set(ids);
330738
+ let idSet = new Set(ids2);
329957
330739
  await withCronFileLock(dir, async (current6, root2) => {
329958
330740
  let remaining = current6.filter((t2) => !idSet.has(t2.id));
329959
330741
  remaining.length !== current6.length && await writeCronTasks(remaining, root2);
@@ -331479,10 +332261,10 @@ function getToolUseIdsFromMessage(msg) {
331479
332261
  }).filter(Boolean) : [];
331480
332262
  }
331481
332263
  function getToolUseIdsFromCollapsedGroup(message) {
331482
- let ids = [];
332264
+ let ids2 = [];
331483
332265
  for (let msg of message.messages)
331484
- ids.push(...getToolUseIdsFromMessage(msg));
331485
- return ids;
332266
+ ids2.push(...getToolUseIdsFromMessage(msg));
332267
+ return ids2;
331486
332268
  }
331487
332269
  function hasAnyToolInProgress(message, inProgressToolUseIDs) {
331488
332270
  return getToolUseIdsFromCollapsedGroup(message).some(
@@ -357967,10 +358749,12 @@ __export(suspendedAskPort_exports, {
357967
358749
  claimStreamApproval: () => claimStreamApproval,
357968
358750
  forgetSuspendedAsk: () => forgetSuspendedAsk,
357969
358751
  installLiveToolApprovalResponder: () => installLiveToolApprovalResponder,
358752
+ installStreamApprovalOutcomeSink: () => installStreamApprovalOutcomeSink,
357970
358753
  installSuspendedAskTracker: () => installSuspendedAskTracker,
357971
358754
  liveToolApprovalResponder: () => liveToolApprovalResponder,
357972
358755
  noteApprovalsAwaitingDecision: () => noteApprovalsAwaitingDecision,
357973
358756
  noteSeamClientInstalled: () => noteSeamClientInstalled,
358757
+ noteStreamApprovalOutcome: () => noteStreamApprovalOutcome,
357974
358758
  noteSuspendedAskDecided: () => noteSuspendedAskDecided,
357975
358759
  noteSuspendedAskFeedInstalled: () => noteSuspendedAskFeedInstalled,
357976
358760
  noteSuspendedAskSubmitted: () => noteSuspendedAskSubmitted,
@@ -358078,8 +358862,8 @@ function takeSuspendedAskRequeueBudget(approvalId, max2) {
358078
358862
  function forgetSuspendedAsk(approvalId) {
358079
358863
  claimed.delete(approvalId), decided.delete(approvalId), requeueUsed.delete(approvalId), submitting.delete(approvalId), seenInSnapshot.delete(approvalId);
358080
358864
  }
358081
- function noteSuspendedAsksListed(ids) {
358082
- for (let id of ids) boundedAdd(seenInSnapshot, id);
358865
+ function noteSuspendedAsksListed(ids2) {
358866
+ for (let id of ids2) boundedAdd(seenInSnapshot, id);
358083
358867
  }
358084
358868
  function pruneVanishedSuspendedAsks(liveIds) {
358085
358869
  let n2 = 0;
@@ -358110,8 +358894,19 @@ function requeueSuspendedAsk(approvalId) {
358110
358894
  } catch {
358111
358895
  }
358112
358896
  }
358897
+ function installStreamApprovalOutcomeSink(fn2) {
358898
+ outcomeSink = fn2;
358899
+ }
358900
+ function noteStreamApprovalOutcome(note) {
358901
+ let sink2 = outcomeSink;
358902
+ if (sink2 !== null)
358903
+ try {
358904
+ sink2(note);
358905
+ } catch {
358906
+ }
358907
+ }
358113
358908
  function _resetSuspendedAskPortForTest() {
358114
- tracker = null, responder = null, claimed.clear(), decided.clear(), requeueUsed.clear(), submitting.clear(), seenInSnapshot.clear(), ledgerOverflowed = !1, installed3 = !1, count3 = null, listeners10.clear(), clientListeners.clear();
358909
+ tracker = null, responder = null, outcomeSink = null, claimed.clear(), decided.clear(), requeueUsed.clear(), submitting.clear(), seenInSnapshot.clear(), ledgerOverflowed = !1, installed3 = !1, count3 = null, listeners10.clear(), clientListeners.clear();
358115
358910
  }
358116
358911
  function emit5() {
358117
358912
  for (let l3 of [...listeners10])
@@ -358120,13 +358915,14 @@ function emit5() {
358120
358915
  } catch {
358121
358916
  }
358122
358917
  }
358123
- var responder, clientListeners, tracker, claimed, decided, requeueUsed, submitting, seenInSnapshot, CLAIM_LEDGER_MAX, ledgerOverflowed, installed3, count3, listeners10, init_suspendedAskPort = __esm({
358918
+ var responder, clientListeners, tracker, claimed, decided, requeueUsed, submitting, seenInSnapshot, CLAIM_LEDGER_MAX, ledgerOverflowed, installed3, count3, listeners10, outcomeSink, init_suspendedAskPort = __esm({
358124
358919
  "build-src/src/sema/suspendedAskPort.ts"() {
358125
358920
  responder = null;
358126
358921
  clientListeners = /* @__PURE__ */ new Set();
358127
358922
  tracker = null, claimed = /* @__PURE__ */ new Set(), decided = /* @__PURE__ */ new Set(), requeueUsed = /* @__PURE__ */ new Map(), submitting = /* @__PURE__ */ new Set(), seenInSnapshot = /* @__PURE__ */ new Set(), CLAIM_LEDGER_MAX = 4096;
358128
358923
  ledgerOverflowed = !1;
358129
358924
  installed3 = !1, count3 = null, listeners10 = /* @__PURE__ */ new Set();
358925
+ outcomeSink = null;
358130
358926
  }
358131
358927
  });
358132
358928
 
@@ -358701,11 +359497,11 @@ function RejectedPlanMessage(t0) {
358701
359497
  }
358702
359498
  var import_compiler_runtime106, import_jsx_runtime133, init_RejectedPlanMessage = __esm({
358703
359499
  "build-src/src/components/messages/UserToolResultMessage/RejectedPlanMessage.tsx"() {
358704
- import_compiler_runtime106 = __toESM(require_compiler_runtime());
359500
+ import_compiler_runtime106 = __toESM(require_compiler_runtime(), 1);
358705
359501
  init_Markdown();
358706
359502
  init_MessageResponse();
358707
359503
  init_ink2();
358708
- import_jsx_runtime133 = __toESM(require_jsx_runtime());
359504
+ import_jsx_runtime133 = __toESM(require_jsx_runtime(), 1);
358709
359505
  }
358710
359506
  });
358711
359507
 
@@ -383618,12 +384414,12 @@ function resolveStopTargetByName(query2, appState) {
383618
384414
  tasks3
383619
384415
  ), namedExact = resolveNamedAgent((n2) => n2 === query2, appState);
383620
384416
  if (teammateExact.status !== "not_found" && namedExact) {
383621
- let ids = teammateExact.status === "found" ? [
384417
+ let ids2 = teammateExact.status === "found" ? [
383622
384418
  teammateExact.task.identity?.agentId ?? teammateExact.taskId
383623
384419
  ] : teammateExact.candidates;
383624
384420
  return {
383625
384421
  status: "ambiguous",
383626
- message: teammateVsNamedAgentMessage(query2, ids, namedExact.taskId)
384422
+ message: teammateVsNamedAgentMessage(query2, ids2, namedExact.taskId)
383627
384423
  };
383628
384424
  }
383629
384425
  if (teammateExact.status === "ambiguous")
@@ -383644,12 +384440,12 @@ function resolveStopTargetByName(query2, appState) {
383644
384440
  tasks3
383645
384441
  ), namedNorm = resolveNamedAgent((n2) => normalizeAgentName2(n2) === norm3, appState);
383646
384442
  if (teammateNorm.status !== "not_found" && namedNorm) {
383647
- let ids = teammateNorm.status === "found" ? [
384443
+ let ids2 = teammateNorm.status === "found" ? [
383648
384444
  teammateNorm.task.identity?.agentId ?? teammateNorm.taskId
383649
384445
  ] : teammateNorm.candidates;
383650
384446
  return {
383651
384447
  status: "ambiguous",
383652
- message: teammateVsNamedAgentMessage(query2, ids, namedNorm.taskId)
384448
+ message: teammateVsNamedAgentMessage(query2, ids2, namedNorm.taskId)
383653
384449
  };
383654
384450
  }
383655
384451
  return teammateNorm.status === "ambiguous" ? {
@@ -393931,6 +394727,48 @@ var SUBAGENT_OBSERVATION_EXEMPT_NAMES, WORKFLOW_ACCEPTED_EXEMPT_NAMES, latchedSe
393931
394727
  }
393932
394728
  });
393933
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
+
393934
394772
  // build-src/src/sema/hooksWireCaps.ts
393935
394773
  var hooksWireCaps_exports = {};
393936
394774
  __export(hooksWireCaps_exports, {
@@ -395049,6 +395887,79 @@ var HOOK_NOTICE_WARN_KEY, HOOK_NOTICE_WARN_TIMEOUT_MS, HOOK_FAILURE_WARN_KEY, ho
395049
395887
  }
395050
395888
  });
395051
395889
 
395890
+ // build-src/src/sema/engineAgentAbsence.ts
395891
+ function isAbsentRow(task) {
395892
+ return typeof task != "object" || task === null ? !1 : task._semaAbsence !== void 0;
395893
+ }
395894
+ function readRowAbsence(task) {
395895
+ if (!(typeof task != "object" || task === null))
395896
+ return task._semaAbsence;
395897
+ }
395898
+ function markEngineAgentRowAbsent(task, ev) {
395899
+ return task.status !== "running" || task._semaAbsence !== void 0 ? task : {
395900
+ ...task,
395901
+ _semaAbsence: { lastSeenAtMs: ev.lastSeenAtMs, absentForMs: ev.absentForMs },
395902
+ endTime: task.endTime ?? ev.lastSeenAtMs
395903
+ };
395904
+ }
395905
+ function clearEngineAgentRowAbsence(task) {
395906
+ return task._semaAbsence === void 0 ? task : { ...task, _semaAbsence: void 0, endTime: void 0 };
395907
+ }
395908
+ function engineAgentAbsenceExpired(task, now2 = Date.now(), ttlMs2 = 18e5) {
395909
+ let absence = readRowAbsence(task);
395910
+ return absence === void 0 ? !1 : now2 - absence.lastSeenAtMs >= ttlMs2;
395911
+ }
395912
+ function engineAgentAbsenceDroppedLine(label, ttlMs2 = 18e5, removeReason) {
395913
+ let minutes = Math.round(ttlMs2 / 6e4), why = typeof removeReason == "string" && removeReason !== "" ? ` \xB7 the engine removed it from the fleet list (${removeReason}); that is not an outcome \u2014 read the run to settle it` : " \xB7 outcome unknown";
395914
+ return `${label} was dropped from the task panel after ${minutes} min without an engine report${why}`;
395915
+ }
395916
+ function noteEngineAgentRowRemoved(taskId, removeReason) {
395917
+ if (taskId.length !== 0 && !(typeof removeReason != "string" || removeReason === ""))
395918
+ for (removedRowReasons.set(taskId, removeReason); removedRowReasons.size > REMOVED_ROW_REASON_LEDGER_MAX; ) {
395919
+ let oldest = removedRowReasons.keys().next();
395920
+ if (oldest.done === !0) break;
395921
+ removedRowReasons.delete(oldest.value);
395922
+ }
395923
+ }
395924
+ function takeEngineAgentRowRemoveReason(taskId) {
395925
+ let reason = removedRowReasons.get(taskId);
395926
+ return reason === void 0 ? null : (removedRowReasons.delete(taskId), reason);
395927
+ }
395928
+ function engineAgentTerminalAfterDropLine(label, status3, hasReport) {
395929
+ return `${label} reported ${status3} after it was dropped from the task panel${hasReport ? " \xB7 its final report arrived too late to keep in the panel" : ""}`;
395930
+ }
395931
+ function noteEngineAgentRowReclaimed(taskId, label) {
395932
+ if (taskId.length !== 0)
395933
+ for (reclaimedRows.set(taskId, label.length > 0 ? label : taskId); reclaimedRows.size > RECLAIMED_ROW_LEDGER_MAX; ) {
395934
+ let oldest = reclaimedRows.keys().next();
395935
+ if (oldest.done === !0) break;
395936
+ reclaimedRows.delete(oldest.value);
395937
+ }
395938
+ }
395939
+ function takeEngineAgentReclaimedRow(taskId) {
395940
+ let label = reclaimedRows.get(taskId);
395941
+ return label === void 0 ? null : (reclaimedRows.delete(taskId), label);
395942
+ }
395943
+ function reapExpiredEngineAgentAbsences(tasks3, ownedRowIds, now2 = Date.now(), ttlMs2 = 18e5) {
395944
+ let out6 = [];
395945
+ for (let [id, task] of Object.entries(tasks3))
395946
+ ownedRowIds.has(id) && engineAgentAbsenceExpired(task, now2, ttlMs2) && (typeof task == "object" && task !== null && task.retain === !0 || out6.push(id));
395947
+ return out6;
395948
+ }
395949
+ function expiredButRetainedEngineAgentAbsences(tasks3, ownedRowIds, now2 = Date.now(), ttlMs2 = 18e5) {
395950
+ let out6 = [];
395951
+ for (let [id, task] of Object.entries(tasks3))
395952
+ ownedRowIds.has(id) && engineAgentAbsenceExpired(task, now2, ttlMs2) && typeof task == "object" && task !== null && task.retain === !0 && out6.push(id);
395953
+ return out6;
395954
+ }
395955
+ var ENGINE_AGENT_ABSENT_ROW_TEXT, REMOVED_ROW_REASON_LEDGER_MAX, removedRowReasons, RECLAIMED_ROW_LEDGER_MAX, reclaimedRows, init_engineAgentAbsence = __esm({
395956
+ "build-src/src/sema/engineAgentAbsence.ts"() {
395957
+ ENGINE_AGENT_ABSENT_ROW_TEXT = "engine no longer reports this agent \xB7 outcome unknown";
395958
+ REMOVED_ROW_REASON_LEDGER_MAX = 256, removedRowReasons = /* @__PURE__ */ new Map();
395959
+ RECLAIMED_ROW_LEDGER_MAX = 256, reclaimedRows = /* @__PURE__ */ new Map();
395960
+ }
395961
+ });
395962
+
395052
395963
  // build-src/src/sema/fleetClient.ts
395053
395964
  var fleetClient_exports = {};
395054
395965
  __export(fleetClient_exports, {
@@ -395106,7 +396017,17 @@ function createLiveFleetSource(config4, now2 = Date.now()) {
395106
396017
  // 按档留痕 —— 处置边界与论证见 fleetDurableTerminalOverlay.ts 的 `evidenceTier` 头注
395107
396018
  // (要点:本模块是进程内**呈现**面,不落库/不跨会话搬运/翻行另有一道正交归属门,
395108
396019
  // 故不属包文档划的「有副作用的归属动作」射程)。`rowIds` 本端暂无消费面,显式具名弃用。
395109
- onBgNotificationAccepted: (n2, _rowIds, evidence) => observeFleetBgNotification(n2, evidence)
396020
+ onBgNotificationAccepted: (n2, _rowIds, evidence) => observeFleetBgNotification(n2, evidence),
396021
+ // ── CC-65(client-core 0.74.0):`task_remove` 帧的**离场读口** ─────────────────────────
396022
+ // 🔴 离场**不是终局证据**(包头注逐字:结算的属主在 durable 侧)⇒ 这一端一个状态都不改、
396023
+ // 一行都不 settle,只把引擎给的**真因**记进缺席台账 —— 「为什么这一行不再上报」此前只能
396024
+ // 落到 TTL 回收那句「outcome unknown」,而引擎其实说过。
396025
+ // 🔴 两形不入账(包给的判别位,壳零自铸):`stale` = 退的是前一代、行根本没被删;
396026
+ // `unknownRow` = 账本里本来就没这一行(晚连接者收到的退场帧)。把这两形记进去就是拿
396027
+ // 别的事实去解释这一行的缺席。
396028
+ onTaskRemoved: (removal) => {
396029
+ removal.stale === !0 || removal.unknownRow === !0 || noteEngineAgentRowRemoved(removal.id, removal.removeReason);
396030
+ }
395110
396031
  }), lastError = null, disposed4 = !1, client3 = new AgentClient({
395111
396032
  baseUrl: config4.baseUrl,
395112
396033
  authToken: config4.authToken,
@@ -395232,6 +396153,7 @@ var ROW_FILTER, workflowRowObserver, init_fleetClient = __esm({
395232
396153
  init_fleetDurableTerminalOverlay();
395233
396154
  init_footerRowBelt();
395234
396155
  init_hookNoticeStore();
396156
+ init_engineAgentAbsence();
395235
396157
  init_dist();
395236
396158
  ROW_FILTER = (rows3) => filterFooterTaskRows(rows3), workflowRowObserver = null;
395237
396159
  Promise.resolve().then(() => (init_state(), state_exports)).then((m2) => {
@@ -399425,6 +400347,7 @@ async function* query(params) {
399425
400347
  }
399426
400348
  noteEngineTurnStart();
399427
400349
  let setInProgress = params.toolUseContext?.setInProgressToolUseIDs, engineOpenToolIds = /* @__PURE__ */ new Set(), foregroundRunRegistered = null, semaQuotaDeniedThisTurn = !1, listenedRuns = /* @__PURE__ */ new Set();
400350
+ noteRunStreamStarted();
399428
400351
  try {
399429
400352
  let sessionId = req2.sessionId ?? mockClientIds.sessionId;
399430
400353
  try {
@@ -399482,7 +400405,7 @@ async function* query(params) {
399482
400405
  }
399483
400406
  }
399484
400407
  }
399485
- }, bgTearResends = 0, drainingRetries = 0, planReviewEchoRetries = 0, resumeAtRetried = !1, busySignal = null, readBusySignal = () => busySignal, runningChoiceOffered = !1, runningChoiceSilentWaitTaskId = null, engineFrameSeen = !1, boundRunId, retryStream = !0, interruptedResendDone = !1, pendingInterruptedSettledRow = null, pendingAttachRunId, pendingFollowRow = null;
400408
+ }, bgTearResends = 0, drainingRetries = 0, planReviewEchoRetries = 0, planReviewEchoDeferredMs = 0, resumeAtRetried = !1, busySignal = null, readBusySignal = () => busySignal, runningChoiceOffered = !1, runningChoiceSilentWaitTaskId = null, engineFrameSeen = !1, boundRunId, retryStream = !0, interruptedResendDone = !1, pendingInterruptedSettledRow = null, pendingAttachRunId, pendingFollowRow = null;
399486
400409
  for (; retryStream; ) {
399487
400410
  retryStream = !1, engineFrameSeen = !1, busySignal = null, boundRunId = void 0;
399488
400411
  let attachRunId = pendingAttachRunId;
@@ -399607,18 +400530,18 @@ async function* query(params) {
399607
400530
  activeTaskStatus: detectedBusy.activeTaskStatus,
399608
400531
  pendingGateKind: detectedBusy.pendingGate?.kind ?? null
399609
400532
  };
399610
- if (submissionOrigin === "injected" && isMainLaneQuerySource(params.querySource) && !signal?.aborted && isStalePlanReviewEcho(planReviewEcho))
399611
- if (planReviewEchoRetries < PLAN_REVIEW_ECHO_MAX_RETRIES) {
399612
- let waitMs = planReviewEchoBackoffMs(planReviewEchoRetries);
399613
- planReviewEchoRetries++, logForDebugging(
399614
- `[sema][seamQuery] plan-review echo window on run ${String(detectedBusy.activeTaskId)} \u2014 deferring this injected submission ${String(planReviewEchoRetries)}/${String(PLAN_REVIEW_ECHO_MAX_RETRIES)} by ${String(waitMs)}ms instead of racing the decision (L-405)`
399615
- ), await new Promise((res) => setTimeout(res, waitMs)), signal?.aborted || (retryStream = !0);
400533
+ if (submissionOrigin === "injected" && isMainLaneQuerySource(params.querySource) && !signal?.aborted && isStalePlanReviewEcho(planReviewEcho)) {
400534
+ let deferral = planReviewEchoDeferral(planReviewEchoRetries, planReviewEchoDeferredMs);
400535
+ if (deferral.kind === "defer") {
400536
+ planReviewEchoRetries++, planReviewEchoDeferredMs += deferral.waitMs, logForDebugging(
400537
+ `[sema][seamQuery] plan-review echo window on run ${String(detectedBusy.activeTaskId)} \u2014 deferring this injected submission (attempt ${String(planReviewEchoRetries)}, ${String(deferral.waitMs)}ms, ${String(planReviewEchoDeferredMs)}/${String(PLAN_REVIEW_ECHO_TOTAL_CAP_MS)}ms spent)`
400538
+ ), await new Promise((res) => setTimeout(res, deferral.waitMs)), signal?.aborted || (retryStream = !0);
399616
400539
  continue;
399617
400540
  } else
399618
400541
  logForDebugging(
399619
- `[sema][seamQuery] plan-review echo window on run ${String(detectedBusy.activeTaskId)} did not clear within ${String(PLAN_REVIEW_ECHO_MAX_RETRIES)} deferrals \u2014 falling through to the existing self-heal leg (L-405)`
400542
+ `[sema][seamQuery] plan-review echo window on run ${String(detectedBusy.activeTaskId)} did not clear within ${String(PLAN_REVIEW_ECHO_TOTAL_CAP_MS)}ms \u2014 falling back to the self-heal lane with plan-review reopen suppressed`
399620
400543
  );
399621
- else leftPlanReviewGate(planReviewEcho) && clearPlanReviewDecisionWindow(detectedBusy.activeTaskId);
400544
+ } else leftPlanReviewGate(planReviewEcho) && clearPlanReviewDecisionWindow(detectedBusy.activeTaskId);
399622
400545
  let outcome = await attemptActiveRunSelfHeal2(detectedBusy, durableRunVerbs(client), {
399623
400546
  // `hasPendingDecision`(车L 12,原「故意不接」记账销案):真读面 = REPL
399624
400547
  // toolUseConfirmQueue 的模块级长度镜像(leaderPermissionBridge,队列变更 effect
@@ -399642,7 +400565,9 @@ async function* query(params) {
399642
400565
  // `plan-review:<taskId>`,而 REPL overlay 钩子带一个会话级 seenQuestionIds 去重集,
399643
400566
  // 同 id 再发一次会被**静默丢掉** —— 那样「已重新打开审批卡」就成了假话。
399644
400567
  // planReviewReopen 每次铸新身份,决断通路仍是同一个 decidePlanReview wire。
399645
- reopenPlanReview: reopenPlanReviewCard2,
400568
+ // L-422 守卫:本端刚交过决断且窗没关 ⇒ 拒开(reopened:false),绝不把已决断的门再问一遍;
400569
+ // 窗关(引擎已离开那道门 / 换代 / 清窗)才走真重开口。
400570
+ reopenPlanReview: (tid) => shouldSuppressPlanReviewReopen(tid) ? (logForDebugging(`[sema][seamQuery] plan-review reopen for run ${tid} suppressed \u2014 a decision from this shell is still being applied by the engine`), { reopened: !1 }) : reopenPlanReviewCard2(tid),
399646
400571
  // ask park 的重开口(#155):待决行经 approvals.list 取。结构判定装配 —— client 真有
399647
400572
  // approvals 面(live SDK)才装;mock 车道缺席 ⇒ dep 不装 ⇒ ask-reopen-failed 诚实臂。
399648
400573
  // MED-6(复审):装配门与包 HitlClientLike 的四动词同宽——只校 list 会让「有 list
@@ -399831,7 +400756,7 @@ ${notifSupplement}` : baseErrorContent
399831
400756
  }
399832
400757
  return void 0;
399833
400758
  } finally {
399834
- if (publishEngineAgentPanelEvent({ kind: "sweep" }), semaAutoResumeStore && !semaQuotaDeniedThisTurn && isMainLaneQuerySource(params.querySource) && !isBackgroundJournalSuppressed())
400759
+ if (noteRunStreamSettled(), publishEngineAgentPanelEvent({ kind: "sweep" }), semaAutoResumeStore && !semaQuotaDeniedThisTurn && isMainLaneQuerySource(params.querySource) && !isBackgroundJournalSuppressed())
399835
400760
  try {
399836
400761
  semaAutoResumeStore.noteUsageLimitAutoResumeTurnCompleted();
399837
400762
  } catch {
@@ -400267,6 +401192,7 @@ var transcriptUsageDriveSeq, BG_TEAR_MAX_RESENDS, BG_RECOVERY_WAIT_MS, DRAINING_
400267
401192
  init_dist();
400268
401193
  init_deferSessionExemption();
400269
401194
  init_debug();
401195
+ init_midTurnRuleNotice();
400270
401196
  init_hooksWireCaps2();
400271
401197
  init_dist();
400272
401198
  init_intl();
@@ -401145,66 +402071,6 @@ var init_sanitizeToolResultContent = __esm({
401145
402071
  }
401146
402072
  });
401147
402073
 
401148
- // build-src/src/sema/engineAgentAbsence.ts
401149
- function isAbsentRow(task) {
401150
- return typeof task != "object" || task === null ? !1 : task._semaAbsence !== void 0;
401151
- }
401152
- function readRowAbsence(task) {
401153
- if (!(typeof task != "object" || task === null))
401154
- return task._semaAbsence;
401155
- }
401156
- function markEngineAgentRowAbsent(task, ev) {
401157
- return task.status !== "running" || task._semaAbsence !== void 0 ? task : {
401158
- ...task,
401159
- _semaAbsence: { lastSeenAtMs: ev.lastSeenAtMs, absentForMs: ev.absentForMs },
401160
- endTime: task.endTime ?? ev.lastSeenAtMs
401161
- };
401162
- }
401163
- function clearEngineAgentRowAbsence(task) {
401164
- return task._semaAbsence === void 0 ? task : { ...task, _semaAbsence: void 0, endTime: void 0 };
401165
- }
401166
- function engineAgentAbsenceExpired(task, now2 = Date.now(), ttlMs2 = 18e5) {
401167
- let absence = readRowAbsence(task);
401168
- return absence === void 0 ? !1 : now2 - absence.lastSeenAtMs >= ttlMs2;
401169
- }
401170
- function engineAgentAbsenceDroppedLine(label, ttlMs2 = 18e5) {
401171
- let minutes = Math.round(ttlMs2 / 6e4);
401172
- return `${label} was dropped from the task panel after ${minutes} min without an engine report \xB7 outcome unknown`;
401173
- }
401174
- function engineAgentTerminalAfterDropLine(label, status3, hasReport) {
401175
- return `${label} reported ${status3} after it was dropped from the task panel${hasReport ? " \xB7 its final report arrived too late to keep in the panel" : ""}`;
401176
- }
401177
- function noteEngineAgentRowReclaimed(taskId, label) {
401178
- if (taskId.length !== 0)
401179
- for (reclaimedRows.set(taskId, label.length > 0 ? label : taskId); reclaimedRows.size > RECLAIMED_ROW_LEDGER_MAX; ) {
401180
- let oldest = reclaimedRows.keys().next();
401181
- if (oldest.done === !0) break;
401182
- reclaimedRows.delete(oldest.value);
401183
- }
401184
- }
401185
- function takeEngineAgentReclaimedRow(taskId) {
401186
- let label = reclaimedRows.get(taskId);
401187
- return label === void 0 ? null : (reclaimedRows.delete(taskId), label);
401188
- }
401189
- function reapExpiredEngineAgentAbsences(tasks3, ownedRowIds, now2 = Date.now(), ttlMs2 = 18e5) {
401190
- let out6 = [];
401191
- for (let [id, task] of Object.entries(tasks3))
401192
- ownedRowIds.has(id) && engineAgentAbsenceExpired(task, now2, ttlMs2) && (typeof task == "object" && task !== null && task.retain === !0 || out6.push(id));
401193
- return out6;
401194
- }
401195
- function expiredButRetainedEngineAgentAbsences(tasks3, ownedRowIds, now2 = Date.now(), ttlMs2 = 18e5) {
401196
- let out6 = [];
401197
- for (let [id, task] of Object.entries(tasks3))
401198
- ownedRowIds.has(id) && engineAgentAbsenceExpired(task, now2, ttlMs2) && typeof task == "object" && task !== null && task.retain === !0 && out6.push(id);
401199
- return out6;
401200
- }
401201
- var ENGINE_AGENT_ABSENT_ROW_TEXT, RECLAIMED_ROW_LEDGER_MAX, reclaimedRows, init_engineAgentAbsence = __esm({
401202
- "build-src/src/sema/engineAgentAbsence.ts"() {
401203
- ENGINE_AGENT_ABSENT_ROW_TEXT = "engine no longer reports this agent \xB7 outcome unknown";
401204
- RECLAIMED_ROW_LEDGER_MAX = 256, reclaimedRows = /* @__PURE__ */ new Map();
401205
- }
401206
- });
401207
-
401208
402074
  // build/stubs/internalLogging.ts
401209
402075
  async function logPermissionContextForAnts(_toolPermissionContext, _moment) {
401210
402076
  }
@@ -402582,10 +403448,10 @@ function getToolResultIds(message) {
402582
403448
  let content = message.message.content;
402583
403449
  if (!Array.isArray(content))
402584
403450
  return [];
402585
- let ids = [];
403451
+ let ids2 = [];
402586
403452
  for (let block2 of content)
402587
- block2.type === "tool_result" && ids.push(block2.tool_use_id);
402588
- return ids;
403453
+ block2.type === "tool_result" && ids2.push(block2.tool_use_id);
403454
+ return ids2;
402589
403455
  }
402590
403456
  function hasToolUseWithIds(message, toolUseIds) {
402591
403457
  if (message.type !== "assistant")
@@ -405439,8 +406305,8 @@ function isValidImagePaste(c3) {
405439
406305
  function getImagePasteIds(pastedContents) {
405440
406306
  if (!pastedContents)
405441
406307
  return;
405442
- let ids = Object.values(pastedContents).filter(isValidImagePaste).map((c3) => c3.id);
405443
- 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;
405444
406310
  }
405445
406311
  var init_textInputTypes = __esm({
405446
406312
  "build-src/src/types/textInputTypes.ts"() {
@@ -424400,7 +425266,7 @@ function applyPermissionUpdate(context3, update2) {
424400
425266
  );
424401
425267
  logForDebugging(
424402
425268
  `Applying permission update: Adding ${update2.rules.length} ${update2.behavior} rule(s) to destination '${update2.destination}': ${jsonStringify(ruleStrings)}`
424403
- );
425269
+ ), update2.behavior !== "allow" && noteRestrictionRulesAdded(update2.behavior, ruleStrings);
424404
425270
  let ruleKind = update2.behavior === "allow" ? "alwaysAllowRules" : update2.behavior === "deny" ? "alwaysDenyRules" : "alwaysAskRules";
424405
425271
  return {
424406
425272
  ...context3,
@@ -424637,6 +425503,7 @@ var init_PermissionUpdate = __esm({
424637
425503
  init_filesystem();
424638
425504
  init_permissionRuleParser();
424639
425505
  init_permissionsLoader();
425506
+ init_midTurnRuleNotice();
424640
425507
  }
424641
425508
  });
424642
425509
 
@@ -426139,11 +427006,11 @@ function AddDirError(t0) {
426139
427006
  ] }), $3[7] = t3, $3[8] = t4, $3[9] = t5) : t5 = $3[9], t5;
426140
427007
  }
426141
427008
  async function call5(onDone, context3, args) {
426142
- let directoryPath = (args ?? "").trim(), appState = context3.getAppState(), handleAddDirectory = async (path28, remember2 = !1) => {
427009
+ let directoryPath = (args ?? "").trim(), appState = context3.getAppState(), handleAddDirectory = async (path28, remember3 = !1) => {
426143
427010
  let permissionUpdate = {
426144
427011
  type: "addDirectories",
426145
427012
  directories: [path28],
426146
- destination: remember2 ? "localSettings" : "session"
427013
+ destination: remember3 ? "localSettings" : "session"
426147
427014
  }, latestAppState = context3.getAppState(), updatedContext = applyPermissionUpdate(latestAppState.toolPermissionContext, permissionUpdate);
426148
427015
  context3.setAppState((prev) => ({
426149
427016
  ...prev,
@@ -426152,7 +427019,7 @@ async function call5(onDone, context3, args) {
426152
427019
  let currentDirs = getAdditionalDirectoriesForClaudeMd();
426153
427020
  currentDirs.includes(path28) || setAdditionalDirectoriesForClaudeMd([...currentDirs, path28]), SandboxManager2.refreshConfig(), broadcastRootsListChanged();
426154
427021
  let message;
426155
- if (remember2) {
427022
+ if (remember3) {
426156
427023
  let persistError = null;
426157
427024
  try {
426158
427025
  persistError = persistPermissionUpdate(permissionUpdate).error;
@@ -429410,23 +430277,20 @@ var sema_brand_default, init_sema_brand = __esm({
429410
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"
429411
430278
  },
429412
430279
  whatsNew: {
429413
- version: "1.0.122",
430280
+ version: "1.0.124",
429414
430281
  notes: [
429415
- "Bundled engine 7.87.3 (core 7.23.2), client runtime 0.73.5 and client SDK 9.7.1; the settings schema stays 2.1.0. /doctor and the engine line report 7.87.3.",
429416
- "Credentials in an endpoint URL no longer reach the screen, the transcript or the log files. When the engine's own error text or a notice carries the URL it dialled, sema masks the user name, any query values and any fragment before rendering, on every surface: -p text, json and stream-json output, the interactive error row and notice, the /model failure receipt, sema doctor, the session transcript and the error log. Host, port, path and query key names are kept because those are what you need to fix the setting; a successful answer is never touched.",
429417
- "When both MODEL_GATEWAY_BASEURL and an explicit MODEL_PROVIDER are set and the gateway serves the hop, the line that says so now appears for every kind of model-lane failure (network, request construction, timeout, not only HTTP status codes) and in all three -p output formats. The startup warning and the /status row use the same wording, so the shell no longer says two different things about which setting routes the request. If the engine refuses to start because MODEL_PROVIDER is not one of the accepted values, the shell shows the engine's own refusal line with its machine-readable code, the offending value and the accepted values instead of guessing that the port is in use.",
429418
- "Background subagents that hit an approval gate now raise their card in the session instead of stalling silently. The footer says how many subagent approvals are waiting on you and shows a dash when the engine does not report it. On engines that do not carry the subagent call's arguments the card says so and no longer offers edit-then-approve.",
429419
- "Approving a plan no longer makes a second plan-review card appear afterwards.",
429420
- "Background task panel: a task parked at a pending approval keeps its row through compaction and the row says it is waiting for an approval. Numbers the engine did not report show as a dash instead of 0 (duration, progress), and the usage and queue badges are simply omitted. The workflow size warning no longer vanishes when the total is unknown; it says the size was not reported. When a background agent starts a new cycle its usage and tool counters reset instead of carrying the previous cycle's numbers, and the workflow details header omits the agent count when the details could not be fetched.",
429421
- "Cancel and submit failures are explained by the engine's own code: a cancel refused because the gate was already decided is worded differently from one where the cancel flag did not attach and can simply be resent, and a submit refused by the deployment's usage window says how long to wait when the engine gives a window and states no number when it does not.",
429422
- "Interrupted turns now tell you when the engine you were talking to was replaced by another process, not just when the whole instance changed. Cancelling a turn records which engine run it belonged to, so a later resume can ask the engine what happened to it.",
429423
- "Plugins: installing a plugin whose own plugin.json lists dependencies now installs them too, including plugins that come from a git or npm source. A dependency that cannot be installed automatically is named in the install output instead of being silent. Plugin options that declare a default value work without opening the configuration dialog first; the declared default is used until you set your own.",
429424
- "sema mcp list and sema mcp get now say why a connection failed (HTTP status text, the remote's own message, endpoint not found, connection refused) instead of a bare Failed to connect; credentials inside that text are masked and, when no reason is available, the row says so. mcp get adds an Issue line under Status for a failing server.",
429425
- "/context adds a note when the numbers shrank by less than the display's precision, and the read-directory hint on approval cards no longer promises that /add-dir will clear the question when the candidate is a single file."
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."
429426
430290
  ]
429427
430291
  },
429428
- productVersion: "1.0.122",
429429
- announcement: "sema 1.0.122 \u2014 engine 7.87.3 pickup (core 7.23.2), client runtime 0.73.5, client SDK 9.7.1. Credentials in endpoint URLs are masked on every surface; background subagents raise their approval card instead of stalling; approving a plan no longer brings a second card; the task panel shows a dash for numbers the engine did not report; plugins install their manifest dependencies and honour declared option defaults; mcp list and mcp get say why a connection 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.",
429430
430294
  version: "1.0.91"
429431
430295
  };
429432
430296
  }
@@ -434992,6 +435856,9 @@ function modelBadge(model) {
434992
435856
  function autocompactSourceOf(data) {
434993
435857
  return data.autocompactSource ?? "auto";
434994
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
+ }
434995
435862
  function localStamp(atMs) {
434996
435863
  let d4 = new Date(atMs), p2 = (n2) => String(n2).padStart(2, "0");
434997
435864
  return `${p2(d4.getMonth() + 1)}-${p2(d4.getDate())} ${p2(d4.getHours())}:${p2(d4.getMinutes())}:${p2(d4.getSeconds())}`;
@@ -434999,12 +435866,12 @@ function localStamp(atMs) {
434999
435866
  function lastCompactionLine(data) {
435000
435867
  let rec = data._sema_lastCompaction;
435001
435868
  if (rec === void 0 || !Number.isFinite(rec.atMs)) return null;
435002
- let at = localStamp(rec.atMs);
435869
+ let at = localStamp(rec.atMs), freed = freedTail(rec.freedTokens);
435003
435870
  if (rec.triggerTokensBefore !== void 0 && rec.postTokens !== void 0) {
435004
- 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)";
435005
- 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;
435006
435873
  }
435007
- 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;
435008
435875
  }
435009
435876
  function autocompactBufferSourceLine(data, bufferRowPresent) {
435010
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";
@@ -456705,23 +457572,20 @@ var require_sema_brand = __commonJS({
456705
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"
456706
457573
  },
456707
457574
  whatsNew: {
456708
- version: "1.0.122",
457575
+ version: "1.0.124",
456709
457576
  notes: [
456710
- "Bundled engine 7.87.3 (core 7.23.2), client runtime 0.73.5 and client SDK 9.7.1; the settings schema stays 2.1.0. /doctor and the engine line report 7.87.3.",
456711
- "Credentials in an endpoint URL no longer reach the screen, the transcript or the log files. When the engine's own error text or a notice carries the URL it dialled, sema masks the user name, any query values and any fragment before rendering, on every surface: -p text, json and stream-json output, the interactive error row and notice, the /model failure receipt, sema doctor, the session transcript and the error log. Host, port, path and query key names are kept because those are what you need to fix the setting; a successful answer is never touched.",
456712
- "When both MODEL_GATEWAY_BASEURL and an explicit MODEL_PROVIDER are set and the gateway serves the hop, the line that says so now appears for every kind of model-lane failure (network, request construction, timeout, not only HTTP status codes) and in all three -p output formats. The startup warning and the /status row use the same wording, so the shell no longer says two different things about which setting routes the request. If the engine refuses to start because MODEL_PROVIDER is not one of the accepted values, the shell shows the engine's own refusal line with its machine-readable code, the offending value and the accepted values instead of guessing that the port is in use.",
456713
- "Background subagents that hit an approval gate now raise their card in the session instead of stalling silently. The footer says how many subagent approvals are waiting on you and shows a dash when the engine does not report it. On engines that do not carry the subagent call's arguments the card says so and no longer offers edit-then-approve.",
456714
- "Approving a plan no longer makes a second plan-review card appear afterwards.",
456715
- "Background task panel: a task parked at a pending approval keeps its row through compaction and the row says it is waiting for an approval. Numbers the engine did not report show as a dash instead of 0 (duration, progress), and the usage and queue badges are simply omitted. The workflow size warning no longer vanishes when the total is unknown; it says the size was not reported. When a background agent starts a new cycle its usage and tool counters reset instead of carrying the previous cycle's numbers, and the workflow details header omits the agent count when the details could not be fetched.",
456716
- "Cancel and submit failures are explained by the engine's own code: a cancel refused because the gate was already decided is worded differently from one where the cancel flag did not attach and can simply be resent, and a submit refused by the deployment's usage window says how long to wait when the engine gives a window and states no number when it does not.",
456717
- "Interrupted turns now tell you when the engine you were talking to was replaced by another process, not just when the whole instance changed. Cancelling a turn records which engine run it belonged to, so a later resume can ask the engine what happened to it.",
456718
- "Plugins: installing a plugin whose own plugin.json lists dependencies now installs them too, including plugins that come from a git or npm source. A dependency that cannot be installed automatically is named in the install output instead of being silent. Plugin options that declare a default value work without opening the configuration dialog first; the declared default is used until you set your own.",
456719
- "sema mcp list and sema mcp get now say why a connection failed (HTTP status text, the remote's own message, endpoint not found, connection refused) instead of a bare Failed to connect; credentials inside that text are masked and, when no reason is available, the row says so. mcp get adds an Issue line under Status for a failing server.",
456720
- "/context adds a note when the numbers shrank by less than the display's precision, and the read-directory hint on approval cards no longer promises that /add-dir will clear the question when the candidate is a single file."
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."
456721
457585
  ]
456722
457586
  },
456723
- productVersion: "1.0.122",
456724
- announcement: "sema 1.0.122 \u2014 engine 7.87.3 pickup (core 7.23.2), client runtime 0.73.5, client SDK 9.7.1. Credentials in endpoint URLs are masked on every surface; background subagents raise their approval card instead of stalling; approving a plan no longer brings a second card; the task panel shows a dash for numbers the engine did not report; plugins install their manifest dependencies and honour declared option defaults; mcp list and mcp get say why a connection 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.",
456725
457589
  version: "1.0.91"
456726
457590
  };
456727
457591
  }
@@ -467267,15 +468131,15 @@ function PermissionRuleList(t0) {
467267
468131
  }
467268
468132
  return 0;
467269
468133
  }), lowerQuery = query2.toLowerCase();
467270
- for (let ruleKey of sortedRuleKeys) {
467271
- let rule_2 = rulesByKey.get(ruleKey);
468134
+ for (let ruleKey2 of sortedRuleKeys) {
468135
+ let rule_2 = rulesByKey.get(ruleKey2);
467272
468136
  if (rule_2) {
467273
468137
  let ruleString = permissionRuleValueToString(rule_2.ruleValue);
467274
468138
  if (query2 && !ruleString.toLowerCase().includes(lowerQuery))
467275
468139
  continue;
467276
468140
  options.push({
467277
468141
  label: ruleString,
467278
- value: ruleKey
468142
+ value: ruleKey2
467279
468143
  });
467280
468144
  }
467281
468145
  }
@@ -467420,19 +468284,19 @@ function PermissionRuleList(t0) {
467420
468284
  }
467421
468285
  if (isAddingWorkspaceDirectory) {
467422
468286
  let t222;
467423
- $3[56] !== setAppState || $3[57] !== toolPermissionContext ? (t222 = (path_0, remember2) => {
468287
+ $3[56] !== setAppState || $3[57] !== toolPermissionContext ? (t222 = (path_0, remember3) => {
467424
468288
  let permissionUpdate = {
467425
468289
  type: "addDirectories",
467426
468290
  directories: [path_0],
467427
- destination: remember2 ? "localSettings" : "session"
468291
+ destination: remember3 ? "localSettings" : "session"
467428
468292
  }, updatedContext = applyPermissionUpdate(toolPermissionContext, permissionUpdate);
467429
468293
  setAppState((prev_4) => ({
467430
468294
  ...prev_4,
467431
468295
  toolPermissionContext: updatedContext
467432
468296
  }));
467433
468297
  let persistError = null;
467434
- remember2 && (persistError = persistPermissionUpdate(permissionUpdate).error);
467435
- let savedSuffix = persistError ? sessionOnlyPersistSuffix("localSettings", persistError) : remember2 ? " and saved to local settings" : " for this session";
468298
+ remember3 && (persistError = persistPermissionUpdate(permissionUpdate).error);
468299
+ let savedSuffix = persistError ? sessionOnlyPersistSuffix("localSettings", persistError) : remember3 ? " and saved to local settings" : " for this session";
467436
468300
  setChanges((prev_5) => [...prev_5, `Added directory ${source_default.bold(path_0)} to workspace${savedSuffix}`]), setIsAddingWorkspaceDirectory(!1);
467437
468301
  }, $3[56] = setAppState, $3[57] = toolPermissionContext, $3[58] = t222) : t222 = $3[58];
467438
468302
  let t232;
@@ -470067,15 +470931,15 @@ function PluginList({
470067
470931
  }) {
470068
470932
  let errors2 = useAppState((s) => s.plugins.errors), enabledPlugins = useAppState((s) => s.plugins.enabled), disabledPlugins = useAppState((s) => s.plugins.disabled);
470069
470933
  return (0, import_react190.useEffect)(() => {
470070
- let v2 = loadInstalledPluginsV2(), ids = Object.keys(v2.plugins).sort();
470071
- if (ids.length === 0) {
470934
+ let v2 = loadInstalledPluginsV2(), ids2 = Object.keys(v2.plugins).sort();
470935
+ if (ids2.length === 0) {
470072
470936
  onComplete(
470073
470937
  "No plugins installed. Use `/plugin install` to install a plugin."
470074
470938
  );
470075
470939
  return;
470076
470940
  }
470077
470941
  let enabledScopes = getPluginEditableScopes(), loadedEnabledSources = new Set(enabledPlugins.map((p) => p.source)), lines = ["Installed plugins:"], shown = 0;
470078
- for (let id of ids) {
470942
+ for (let id of ids2) {
470079
470943
  let name = id.split("@")[0] ?? id, isEnabled3 = enabledScopes.has(id);
470080
470944
  if (filter2 !== void 0 && filter2 === "enabled" !== isEnabled3) continue;
470081
470945
  let hasError = errors2.some(
@@ -479740,12 +480604,12 @@ function isLoggableMessage(m2) {
479740
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;
479741
480605
  }
479742
480606
  function collectReplIds(messages) {
479743
- let ids = /* @__PURE__ */ new Set();
480607
+ let ids2 = /* @__PURE__ */ new Set();
479744
480608
  for (let m2 of messages)
479745
480609
  if (m2.type === "assistant" && Array.isArray(m2.message.content))
479746
480610
  for (let b3 of m2.message.content)
479747
- b3.type === "tool_use" && b3.name === REPL_TOOL_NAME && ids.add(b3.id);
479748
- return ids;
480611
+ b3.type === "tool_use" && b3.name === REPL_TOOL_NAME && ids2.add(b3.id);
480612
+ return ids2;
479749
480613
  }
479750
480614
  function transformMessagesForExternalTranscript(messages, replIds) {
479751
480615
  return messages.flatMap((m2) => {
@@ -483166,8 +484030,8 @@ function resolveEffective() {
483166
484030
  return resolveEffectiveSettings(consume88Layers());
483167
484031
  }
483168
484032
  function resolveSemaConfigWithEffective(opts) {
483169
- let eff = resolveEffectiveSettings(consume88Layers());
483170
- 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) };
483171
484035
  }
483172
484036
  var init_settings5 = __esm({
483173
484037
  "build-src/src/sema/settings/index.ts"() {
@@ -484019,6 +484883,8 @@ function askRetractionRow(cause, toolName2) {
484019
484883
  return `${what} was withdrawn by the engine, so this card was taken down. Nothing was decided on your behalf here.`;
484020
484884
  case "unanswered-after-window":
484021
484885
  return `${what} was still unanswered well after the engine's approval window closed, so this card was taken down to let this turn finish. Nothing was decided on your behalf here. If the engine parked that step it is still waiting in its durable queue \u2014 send a message and sema will re-check what it is waiting on.`;
484886
+ case "host-decision-port-gone":
484887
+ return `${what} was taken down because this session no longer has a way to answer it \u2014 the engine connection or session it belonged to was replaced. Nothing was decided on your behalf here. If the engine is still waiting on that step, send a message and sema will re-check what it is waiting on.`;
484022
484888
  case "durable-reaped":
484023
484889
  return `${what} sat in the engine's durable queue past its deadline, so this card was taken down. The engine reaps rows that pass their deadline; nothing was decided on your behalf here. If the step is still needed, ask for it again.`;
484024
484890
  default:
@@ -484179,7 +485045,7 @@ function shellApprovalCardPort(req2) {
484179
485045
  let tool = lookup.kind === "tool" ? lookup.tool : genericGateTool(req2.toolName), { callKey, signal } = req2, askDeadlineMs = readAskDeadlineMs(req2) ?? readParkRowDeadline(req2.callKey);
484180
485046
  return new Promise((resolve59) => {
484181
485047
  let selectedPersistRule, selectedPersistRuleBatchOfferIndex, selectedPersistRuleEdited, windowClosedAtMs, lateApproveConfirmedOnce = !1, lateApproveConfirmShown = !1, stagedPermissionUpdates = [], lateDecideWatchdogTimer, settled2 = !1, saidWindowClosed = !1, bornEpoch = getLiveSessionEpoch(), settle3 = (o) => {
484182
- 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));
484183
485049
  }, removeFromQueue = () => {
484184
485050
  try {
484185
485051
  setQueue((queue3) => queue3.filter((item) => item.toolUseID !== callKey));
@@ -484264,7 +485130,7 @@ function shellApprovalCardPort(req2) {
484264
485130
  } catch (e) {
484265
485131
  logForDebugging(`liveToolApprovalWire: could not surface the retraction row: ${String(e)}`);
484266
485132
  }
484267
- settle3({ kind: "aborted" });
485133
+ settle3({ kind: RETRACTED_CARD_DECISION_KIND, reason: cause });
484268
485134
  }
484269
485135
  }, backstopWindowMs = 0, armBackstopOnce = () => {
484270
485136
  settled2 || askBackstopTimer !== void 0 || isParkRowCard(callKey) || (askBackstopTimer = setTimeout(() => {
@@ -484426,7 +485292,7 @@ function shellApprovalCardPort(req2) {
484426
485292
  onUserInteraction() {
484427
485293
  },
484428
485294
  onAbort() {
484429
- settle3({ kind: "aborted" });
485295
+ noteHumanApprovalCardDecision(callKey), settle3({ kind: "aborted" });
484430
485296
  },
484431
485297
  onAllow(updatedInput, permissionUpdates) {
484432
485298
  settleMaybeLate(buildAllowDecision(updatedInput, permissionUpdates), "approve");
@@ -484466,7 +485332,7 @@ function shellApprovalCardPort(req2) {
484466
485332
  onUserInteraction() {
484467
485333
  },
484468
485334
  onAbort() {
484469
- settle3({ kind: "aborted" });
485335
+ noteHumanApprovalCardDecision(callKey), settle3({ kind: "aborted" });
484470
485336
  },
484471
485337
  onAllow(updatedInput, permissionUpdates) {
484472
485338
  lateApproveConfirmedOnce = !0;
@@ -485066,6 +485932,10 @@ async function* consumeStreamApprovalFrames(events3, deps2, opts = {}) {
485066
485932
  logging(`stream-approval ask=${askId} card aborted \u2014 no decision sent`);
485067
485933
  return;
485068
485934
  }
485935
+ if (decision.kind === RETRACTED_CARD_DECISION_KIND) {
485936
+ logging(`stream-approval ask=${askId} card retracted \u2014 no decision sent`);
485937
+ return;
485938
+ }
485069
485939
  if (decision.kind === "failed") {
485070
485940
  logging(`stream-approval ask=${askId} card unavailable (${decision.reason}) \u2014 no decision sent`);
485071
485941
  return;
@@ -485562,6 +486432,8 @@ __export(agentsWire_exports, {
485562
486432
  ADAPTER_DIVERGENCES: () => ADAPTER_DIVERGENCES,
485563
486433
  AGENT_MEMORY_WORDS: () => AGENT_MEMORY_WORDS,
485564
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,
485565
486437
  ASK_ORIGIN_WORDS: () => ASK_ORIGIN_WORDS,
485566
486438
  ASK_PARK_GATE_KINDS: () => ASK_PARK_GATE_KINDS,
485567
486439
  ASK_PARK_ROW_POLL_MS: () => ASK_PARK_ROW_POLL_MS,
@@ -485703,6 +486575,7 @@ __export(agentsWire_exports, {
485703
486575
  MAX_AGENT_TOOLS: () => MAX_AGENT_TOOLS,
485704
486576
  MAX_AGENT_TOOL_NAME_CHARS: () => MAX_AGENT_TOOL_NAME_CHARS,
485705
486577
  MAX_GATE_HOPS: () => MAX_GATE_HOPS,
486578
+ MAX_HELD_WIRE_TICK_BEATS: () => MAX_HELD_WIRE_TICK_BEATS,
485706
486579
  MAX_HOOK_NOTICE_TEXT_CHARS: () => MAX_HOOK_NOTICE_TEXT_CHARS,
485707
486580
  MAX_TASK_AGENTS: () => MAX_TASK_AGENTS,
485708
486581
  MAX_TOKENS_MAX: () => MAX_TOKENS_MAX,
@@ -485770,6 +486643,7 @@ __export(agentsWire_exports, {
485770
486643
  RESUME_USAGE_WINDOW_EXHAUSTED: () => RESUME_USAGE_WINDOW_EXHAUSTED,
485771
486644
  RETAIN_BACKGROUND_ENV: () => RETAIN_BACKGROUND_ENV,
485772
486645
  RETIRED_PERMISSION_RULE_ISSUE_CODES: () => RETIRED_PERMISSION_RULE_ISSUE_CODES,
486646
+ RETRACTED_CARD_DECISION_KIND: () => RETRACTED_CARD_DECISION_KIND,
485773
486647
  REVIEW_PARK_GATE_KINDS: () => REVIEW_PARK_GATE_KINDS,
485774
486648
  REWIND_ERROR_CODE_PREFIXES: () => REWIND_ERROR_CODE_PREFIXES,
485775
486649
  RULE_NOT_SENT_REJECTED_WARN_TEXT: () => RULE_NOT_SENT_REJECTED_WARN_TEXT,
@@ -485781,6 +486655,7 @@ __export(agentsWire_exports, {
485781
486655
  RULE_STORE_UNREADABLE_KINDS: () => RULE_STORE_UNREADABLE_KINDS,
485782
486656
  RUNNING_STATES: () => RUNNING_STATES,
485783
486657
  RUN_BLOCKED_MESSAGE_PREFIX: () => RUN_BLOCKED_MESSAGE_PREFIX,
486658
+ RUN_CANCELLED_CODE: () => RUN_CANCELLED_CODE,
485784
486659
  RUN_LEVEL_STOP_ERROR_CODES: () => RUN_LEVEL_STOP_ERROR_CODES,
485785
486660
  RUN_STOPPED_MESSAGE_PREFIX: () => RUN_STOPPED_MESSAGE_PREFIX,
485786
486661
  RUN_TERMINAL_NOT_SUCCESS_STATUSES: () => RUN_TERMINAL_NOT_SUCCESS_STATUSES,
@@ -485872,7 +486747,9 @@ __export(agentsWire_exports, {
485872
486747
  __feedWorkflowActivityFrameForTests: () => __feedWorkflowActivityFrameForTests,
485873
486748
  __resetApprovalsStreamLiveReadingsForTests: () => __resetApprovalsStreamLiveReadingsForTests,
485874
486749
  __resetBgOwnerAbsenceForTests: () => __resetBgOwnerAbsenceForTests,
486750
+ __resetDeviceExecutorManagementReadingsForTests: () => __resetDeviceExecutorManagementReadingsForTests,
485875
486751
  __resetEngineAgentPanelAbsenceForTests: () => __resetEngineAgentPanelAbsenceForTests,
486752
+ __resetEngineAgentPanelIdentityForTests: () => __resetEngineAgentPanelIdentityForTests,
485876
486753
  __resetEngineCapsCacheForTests: () => __resetEngineCapsCacheForTests,
485877
486754
  __resetEngineCompactArmForTests: () => __resetEngineCompactArmForTests,
485878
486755
  __resetEngineDelegatedPromptForTests: () => __resetEngineDelegatedPromptForTests,
@@ -485931,6 +486808,7 @@ __export(agentsWire_exports, {
485931
486808
  approvalCardPortFor: () => approvalCardPortFor,
485932
486809
  approvalCardPortMisses: () => approvalCardPortMisses,
485933
486810
  approvalCardPortMissesFor: () => approvalCardPortMissesFor,
486811
+ approvalOutcomeNoteOf: () => approvalOutcomeNoteOf,
485934
486812
  approvalsStreamLiveDoctorDetail: () => approvalsStreamLiveDoctorDetail,
485935
486813
  armDetachCancel: () => armDetachCancel,
485936
486814
  armPlanReviewApproval: () => armPlanReviewApproval,
@@ -485980,6 +486858,7 @@ __export(agentsWire_exports, {
485980
486858
  classifyMemoryStatusFailure: () => classifyMemoryStatusFailure,
485981
486859
  classifyPeerNotification: () => classifyPeerNotification,
485982
486860
  classifyRulesFailure: () => classifyRulesFailure,
486861
+ classifyRunAbortCause: () => classifyRunAbortCause,
485983
486862
  classifySelfOrchestrationRefusal: () => classifySelfOrchestrationRefusal,
485984
486863
  classifySkippedReason: () => classifySkippedReason,
485985
486864
  classifySubagentResumeFailure: () => classifySubagentResumeFailure,
@@ -485990,6 +486869,7 @@ __export(agentsWire_exports, {
485990
486869
  clearArmedGate: () => clearArmedGate,
485991
486870
  clearBgTerminalFacts: () => clearBgTerminalFacts,
485992
486871
  clearEnginePanelTaskResident: () => clearEnginePanelTaskResident,
486872
+ clearEnginePanelTaskResidentByWire: () => clearEnginePanelTaskResidentByWire,
485993
486873
  clearRunningChoiceOffer: () => clearRunningChoiceOffer,
485994
486874
  clearSubagentContent: () => clearSubagentContent,
485995
486875
  clientContextField: () => clientContextField,
@@ -486024,6 +486904,7 @@ __export(agentsWire_exports, {
486024
486904
  createWireToCcAdapter: () => createWireToCcAdapter,
486025
486905
  decideAcceptedNotResolved: () => decideAcceptedNotResolved,
486026
486906
  decidePlanReview: () => decidePlanReview,
486907
+ decideReceiptReopen: () => decideReceiptReopen,
486027
486908
  decideRefusalFromError: () => decideRefusalFromError,
486028
486909
  decisionNoteAuditLine: () => decisionNoteAuditLine,
486029
486910
  defaultMaxTokensFor: () => defaultMaxTokensFor,
@@ -486040,6 +486921,8 @@ __export(agentsWire_exports, {
486040
486921
  detachedTaskId: () => detachedTaskId,
486041
486922
  detectEngineBgShellReceipt: () => detectEngineBgShellReceipt,
486042
486923
  deviceAuthProviderFor: () => deviceAuthProviderFor,
486924
+ deviceExecutorManagementDoctorDetail: () => deviceExecutorManagementDoctorDetail,
486925
+ deviceManagementVerbsAvailable: () => deviceManagementVerbsAvailable,
486043
486926
  diagnoseSseIdleTear: () => diagnoseSseIdleTear,
486044
486927
  discussionWorkflowName: () => discussionWorkflowName,
486045
486928
  doneToSdkResult: () => doneToSdkResult,
@@ -486109,6 +486992,7 @@ __export(agentsWire_exports, {
486109
486992
  fmtCtxOut: () => fmtCtxOut,
486110
486993
  fmtTokens: () => fmtTokens,
486111
486994
  forgetApprovalsStreamLiveReading: () => forgetApprovalsStreamLiveReading,
486995
+ forgetDeviceExecutorManagementReading: () => forgetDeviceExecutorManagementReading,
486112
486996
  forgetExecutionLaneReading: () => forgetExecutionLaneReading,
486113
486997
  forgetSqlEngineReading: () => forgetSqlEngineReading,
486114
486998
  forgetWebSearchBackendReading: () => forgetWebSearchBackendReading,
@@ -486221,6 +487105,7 @@ __export(agentsWire_exports, {
486221
487105
  isLoopbackWireUrl: () => isLoopbackWireUrl,
486222
487106
  isModelOutputErrorRowText: () => isModelOutputErrorRowText,
486223
487107
  isModelOutputErrorText: () => isModelOutputErrorText,
487108
+ isNewEngineAgentPanelCycle: () => isNewEngineAgentPanelCycle,
486224
487109
  isOutcomeUnknownRowText: () => isOutcomeUnknownRowText,
486225
487110
  isOwnEngineRun: () => isOwnEngineRun,
486226
487111
  isOwnWorkflowRun: () => isOwnWorkflowRun,
@@ -486236,6 +487121,7 @@ __export(agentsWire_exports, {
486236
487121
  isSeatModelCatalog: () => isSeatModelCatalog,
486237
487122
  isSendMessageAck: () => isSendMessageAck,
486238
487123
  isSseIdleError: () => isSseIdleError,
487124
+ isStaleEngineAgentPanelEnd: () => isStaleEngineAgentPanelEnd,
486239
487125
  isSubFlowSegmentEnd: () => isSubFlowSegmentEnd,
486240
487126
  isSupportedCatalogSchemaVersion: () => isSupportedCatalogSchemaVersion,
486241
487127
  isTaskNotificationObjective: () => isTaskNotificationObjective,
@@ -486253,6 +487139,7 @@ __export(agentsWire_exports, {
486253
487139
  isWorkflowCompletionCardEnqueued: () => isWorkflowCompletionCardEnqueued,
486254
487140
  isWorkflowParkRefusalCode: () => isWorkflowParkRefusalCode,
486255
487141
  kickEngineCapsProbe: () => kickEngineCapsProbe,
487142
+ lastFlagValue: () => lastFlagValue,
486256
487143
  leaderConflictDetail: () => leaderConflictDetail,
486257
487144
  limitsForPrint: () => limitsForPrint,
486258
487145
  listAllPersistedRules: () => listAllPersistedRules,
@@ -486296,6 +487183,7 @@ __export(agentsWire_exports, {
486296
487183
  normalizeWirePrincipal: () => normalizeWirePrincipal,
486297
487184
  noteBgOwnerAbsence: () => noteBgOwnerAbsence,
486298
487185
  noteEngineCapsForApprovalsStreamLive: () => noteEngineCapsForApprovalsStreamLive,
487186
+ noteEngineCapsForDeviceExecutorManagement: () => noteEngineCapsForDeviceExecutorManagement,
486299
487187
  noteEngineCapsForExecutionLane: () => noteEngineCapsForExecutionLane,
486300
487188
  noteEngineCapsForSqlEngine: () => noteEngineCapsForSqlEngine,
486301
487189
  noteEngineCapsForWebSearchBackend: () => noteEngineCapsForWebSearchBackend,
@@ -486310,6 +487198,7 @@ __export(agentsWire_exports, {
486310
487198
  notificationQueuePortMisses: () => notificationQueuePortMisses,
486311
487199
  observeCancelByDeny: () => observeCancelByDeny,
486312
487200
  observedApprovalsStreamLive: () => observedApprovalsStreamLive,
487201
+ observedDeviceExecutorManagement: () => observedDeviceExecutorManagement,
486313
487202
  observedExecutionLane: () => observedExecutionLane,
486314
487203
  observedSqlEngine: () => observedSqlEngine,
486315
487204
  observedWebSearchBackend: () => observedWebSearchBackend,
@@ -486377,6 +487266,7 @@ __export(agentsWire_exports, {
486377
487266
  projectBackgroundView: () => projectBackgroundView,
486378
487267
  projectCrashConverged: () => projectCrashConverged,
486379
487268
  projectDescription: () => projectDescription,
487269
+ projectDeviceExecutorManagementCapability: () => projectDeviceExecutorManagementCapability,
486380
487270
  projectDiagnosticsFrame: () => projectDiagnosticsFrame,
486381
487271
  projectEffectiveBody: () => projectEffectiveBody,
486382
487272
  projectExecutionLaneCapability: () => projectExecutionLaneCapability,
@@ -486440,6 +487330,7 @@ __export(agentsWire_exports, {
486440
487330
  readRuleOfferSupply: () => readRuleOfferSupply,
486441
487331
  readRuleOffers: () => readRuleOffers,
486442
487332
  readRulePersistOutcome: () => readRulePersistOutcome,
487333
+ readRunCancelContext: () => readRunCancelContext,
486443
487334
  readRunCostFacts: () => readRunCostFacts,
486444
487335
  readRunTerminal: () => readRunTerminal,
486445
487336
  readSessionMemoryStatus: () => readSessionMemoryStatus,
@@ -486483,6 +487374,7 @@ __export(agentsWire_exports, {
486483
487374
  resetWorkflowActivityLedgers: () => resetWorkflowActivityLedgers,
486484
487375
  resolveAutonomousLoopPrompt: () => resolveAutonomousLoopPrompt,
486485
487376
  resolveCatalogSources: () => resolveCatalogSources,
487377
+ resolveEnginePanelTaskId: () => resolveEnginePanelTaskId,
486486
487378
  resolveEntryVision: () => resolveEntryVision,
486487
487379
  resolveHeadlessDetach: () => resolveHeadlessDetach,
486488
487380
  resolveHeadlessFinalVerify: () => resolveHeadlessFinalVerify,
@@ -486588,6 +487480,7 @@ __export(agentsWire_exports, {
486588
487480
  surfaceRuleArmRejected: () => surfaceRuleArmRejected,
486589
487481
  surfaceSuspendedAskAndRespond: () => surfaceSuspendedAskAndRespond,
486590
487482
  surfaceToolApprovalFrameAndRespond: () => surfaceToolApprovalFrameAndRespond,
487483
+ suspendedReopenOf: () => suspendedReopenOf,
486591
487484
  suspendedSubagentAsks: () => suspendedSubagentAsks,
486592
487485
  tailEngineSubagent: () => tailEngineSubagent,
486593
487486
  taskAgentsField: () => taskAgentsField,
@@ -486829,6 +487722,13 @@ var init_approvalsStreamLiveCapability2 = __esm({
486829
487722
  }
486830
487723
  });
486831
487724
 
487725
+ // build-src/src/sema/deviceExecutorManagementCapability.ts
487726
+ var init_deviceExecutorManagementCapability2 = __esm({
487727
+ "build-src/src/sema/deviceExecutorManagementCapability.ts"() {
487728
+ init_dist();
487729
+ }
487730
+ });
487731
+
486832
487732
  // build-src/src/sema/engineCapsArm.ts
486833
487733
  function beginCapsTeeEpoch(baseUrl) {
486834
487734
  let next = (capsTeeEpochByBase.get(baseUrl) ?? 0) + 1;
@@ -486856,7 +487756,7 @@ function armEngineCapsProbes(input) {
486856
487756
  });
486857
487757
  } : capsProbe;
486858
487758
  if (afterEngineRespawn) {
486859
- resetCapsDiscoveryState(baseUrl), invalidateSelfKnowledgeCap(baseUrl), forgetSqlEngineReading(baseUrl), forgetWriteProtectionReading(baseUrl), forgetWebSearchBackendReading(baseUrl), forgetExecutionLaneReading(baseUrl), forgetApprovalsStreamLiveReading(baseUrl), forgetWiringManifestReading(), forgetClassifierRoundObservation(), forgetEffectiveTurnFacts(), kickAppendSystemPromptCapProbe(baseUrl, appendCapProbe), invalidateEngineCaps(baseUrl, guardedCapsProbe);
487759
+ resetCapsDiscoveryState(baseUrl), invalidateSelfKnowledgeCap(baseUrl), forgetSqlEngineReading(baseUrl), forgetWriteProtectionReading(baseUrl), forgetWebSearchBackendReading(baseUrl), forgetExecutionLaneReading(baseUrl), forgetApprovalsStreamLiveReading(baseUrl), forgetDeviceExecutorManagementReading(baseUrl), forgetWiringManifestReading(), forgetClassifierRoundObservation(), forgetEffectiveTurnFacts(), kickAppendSystemPromptCapProbe(baseUrl, appendCapProbe), invalidateEngineCaps(baseUrl, guardedCapsProbe);
486860
487760
  return;
486861
487761
  }
486862
487762
  kickAppendSystemPromptCapProbe(baseUrl, appendCapProbe), kickEngineCapsProbe(baseUrl, guardedCapsProbe);
@@ -486873,6 +487773,7 @@ var capsTeeEpochByBase, init_engineCapsArm = __esm({
486873
487773
  init_webSearchBackendCapability2();
486874
487774
  init_executionLaneCapability2();
486875
487775
  init_approvalsStreamLiveCapability2();
487776
+ init_deviceExecutorManagementCapability2();
486876
487777
  init_wiringManifestStore();
486877
487778
  init_classifierRoundObservation();
486878
487779
  init_effectiveTurnFactsStore();
@@ -487028,8 +487929,8 @@ function readDisclosureLedger(scope) {
487028
487929
  try {
487029
487930
  let { readFileSync: readFileSync69 } = __require("node:fs"), raw2 = JSON.parse(readFileSync69(path28, "utf8"));
487030
487931
  if (typeof raw2 != "object" || raw2 === null) return EMPTY_LEDGER;
487031
- let ids = raw2.ids;
487032
- 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;
487033
487934
  } catch {
487034
487935
  return EMPTY_LEDGER;
487035
487936
  }
@@ -487038,8 +487939,8 @@ function writeDisclosureLedger(scope, next) {
487038
487939
  let path28 = ledgerPath(scope);
487039
487940
  if (path28 !== null)
487040
487941
  try {
487041
- 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`;
487042
- 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);
487043
487944
  } catch {
487044
487945
  }
487045
487946
  }
@@ -487460,7 +488361,7 @@ function createLiveConversationClient(config4) {
487460
488361
  capsTee: (caps, generation2) => {
487461
488362
  noteEngineCapsForMcpGate(config4.baseUrl, caps), noteEngineCapsForSessionBackground(config4.baseUrl, caps), noteEngineCapsForProjectContext(config4.baseUrl, caps), readCrashConvergedOnce(client3, config4.baseUrl, { principal: config4.principal }), noteEngineCapsForWorkflowsGate(config4.baseUrl, caps, {
487462
488363
  ...typeof config4.principal == "string" ? { principal: config4.principal } : {}
487463
- }), noteEngineCapsForSqlEngine(config4.baseUrl, caps, { generation: generation2 }), noteEngineCapsForWriteProtection(config4.baseUrl, caps, { generation: generation2 }), noteEngineCapsForWebSearchBackend(config4.baseUrl, caps, { generation: generation2 }), noteEngineCapsForExecutionLane(config4.baseUrl, caps, { generation: generation2 }), noteEngineCapsForApprovalsStreamLive(config4.baseUrl, caps, { generation: generation2 });
488364
+ }), noteEngineCapsForSqlEngine(config4.baseUrl, caps, { generation: generation2 }), noteEngineCapsForWriteProtection(config4.baseUrl, caps, { generation: generation2 }), noteEngineCapsForWebSearchBackend(config4.baseUrl, caps, { generation: generation2 }), noteEngineCapsForExecutionLane(config4.baseUrl, caps, { generation: generation2 }), noteEngineCapsForApprovalsStreamLive(config4.baseUrl, caps, { generation: generation2 }), noteEngineCapsForDeviceExecutorManagement(config4.baseUrl, caps, { generation: generation2 });
487464
488365
  },
487465
488366
  afterEngineRespawn: config4.afterEngineRespawn === !0
487466
488367
  }), prepareTaskAgentsWire({
@@ -487568,6 +488469,25 @@ function createLiveConversationClient(config4) {
487568
488469
  // 但显式 false 让「这条腿判过了」在 diff 与 census 上可见,不与「忘了传」同形)。
487569
488470
  windowIsCurrent
487570
488471
  };
488472
+ },
488473
+ // ── CC-68(client-core 0.74.1):流内帧腿的**结局回交** ───────────────────────────────
488474
+ // 包每次 `tool_approval` 帧经卡口决断后恰调一次(撤卡也回交)。壳这一端**只转交**,一条
488475
+ // 判定都不铸:「落没落定」由包答(`decision === 'unresolved'`),放不放认领 / 重不重出卡
488476
+ // 由悬挂 ask 装配件的既有有界预算腿答。
488477
+ // 🔴 为什么非它不可:帧腿在**出卡之前**就永久认领了这只 ask,而它那一发 respond 失败时壳
488478
+ // 这一侧此前看不到 —— 只能靠「连续两张快照都看到已认领∧没决断∧台账无活卡」这条间接
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。
488489
+ onToolApprovalOutcome: (frame, outcome) => {
488490
+ noteStreamApprovalOutcome(approvalOutcomeNoteOf(frame, outcome));
487571
488491
  }
487572
488492
  };
487573
488493
  }, approvalStreamDeps = {
@@ -487831,6 +488751,7 @@ var ENGINE_TO_CC_TOOL, SUGGESTIONS_TAIL_MAX_ATTEMPTS, SUGGESTIONS_TAIL_RETRY_MS,
487831
488751
  init_engineToolDetach();
487832
488752
  init_dist();
487833
488753
  init_dist();
488754
+ init_dist();
487834
488755
  init_engineSessionParam2();
487835
488756
  init_engineCompactWire2();
487836
488757
  init_liveSessionStore();
@@ -487864,6 +488785,7 @@ var ENGINE_TO_CC_TOOL, SUGGESTIONS_TAIL_MAX_ATTEMPTS, SUGGESTIONS_TAIL_RETRY_MS,
487864
488785
  init_webSearchBackendCapability2();
487865
488786
  init_executionLaneCapability2();
487866
488787
  init_approvalsStreamLiveCapability2();
488788
+ init_deviceExecutorManagementCapability2();
487867
488789
  init_suspendedAskPort();
487868
488790
  init_liveApprovalCardHandles();
487869
488791
  init_debugLine();
@@ -490710,7 +491632,7 @@ function workflowParts(wf) {
490710
491632
  { text: wf.doneCount !== void 0 && wf.totalCount !== void 0 ? `${wf.doneCount}/${wf.totalCount} agents done${failedSeg}` : `${ABSENT_NUMBER_TEXT} agents done${failedSeg}` },
490711
491633
  { text: wf.elapsedMs !== void 0 ? fmtDur2(Math.max(0, wf.elapsedMs)) : ABSENT_NUMBER_TEXT }
490712
491634
  ];
490713
- wf.tokens !== void 0 && wf.tokens > 0 && segments.push({ text: `${ARROW_DOWN} ${fmtTokens3(wf.tokens)} tokens` });
491635
+ wf.tokens !== void 0 && wf.tokens > 0 && segments.push({ text: `${ARROW_DOWN} ${fmtTokens3(wf.tokens)} tokens` }), typeof wf.errorCode == "string" && wf.errorCode !== "" && segments.push({ text: cleanUntrustedForDisplay(wf.errorCode, 48), warn: !0 });
490714
491636
  let bulletColor = isTerminal2(wf.status) ? statusColor(wf.status) : wf.failedCount !== void 0 && wf.failedCount > 0 ? "error" : void 0;
490715
491637
  return {
490716
491638
  name: wf.name,
@@ -491177,6 +492099,7 @@ var React127, import_react205, import_jsx_runtime364, F_POINTER2, F_CIRCLE, G_VI
491177
492099
  init_format2();
491178
492100
  init_AppState();
491179
492101
  init_appStateRef();
492102
+ init_untrustedDisplayText();
491180
492103
  init_engineAgentView();
491181
492104
  init_subagentStatusLine();
491182
492105
  init_workflowSizeWarning2();
@@ -501214,7 +502137,17 @@ var RENDERED_UUID_PREFIX_LEN, init_rewindArm = __esm({
501214
502137
 
501215
502138
  // build-src/src/sema/fleetRowCycleProjection.ts
501216
502139
  function launchAnchorChanged2(existing, ev) {
501217
- return 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
+ );
501218
502151
  }
501219
502152
  function progressAfterFleetRowFrame(existing, ev) {
501220
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;
@@ -501223,6 +502156,7 @@ function progressAfterFleetRowFrame(existing, ev) {
501223
502156
  }
501224
502157
  var init_fleetRowCycleProjection = __esm({
501225
502158
  "build-src/src/sema/fleetRowCycleProjection.ts"() {
502159
+ init_dist();
501226
502160
  }
501227
502161
  });
501228
502162
 
@@ -501307,21 +502241,31 @@ var import_compiler_runtime244, React132, import_jsx_runtime375, init_Coordinato
501307
502241
  function useCoordinatorTaskCount() {
501308
502242
  return fleetFooterTaskCount(useFleetFooterRows());
501309
502243
  }
502244
+ function noteFleetRowCycleIdentity(taskId, next) {
502245
+ if (fleetRowCycleIdentities.delete(taskId), fleetRowCycleIdentities.set(taskId, next), !(fleetRowCycleIdentities.size <= FLEET_ROW_CYCLE_LEDGER_MAX))
502246
+ for (let key of [...fleetRowCycleIdentities.keys()]) {
502247
+ if (fleetRowCycleIdentities.size <= FLEET_ROW_CYCLE_LEDGER_MAX) break;
502248
+ key === taskId || engineOwnedRowIds.has(key) || fleetRowCycleIdentities.delete(key);
502249
+ }
502250
+ }
501310
502251
  function useEngineAgentPanelBridge(setAppState) {
501311
502252
  let ownedRows = engineOwnedRowIds, reapAbsentRows = React133.useCallback(() => {
501312
502253
  let reaped = [];
501313
502254
  setAppState((prev) => {
501314
- let ids = reapExpiredEngineAgentAbsences(prev.tasks ?? {}, ownedRows);
501315
- if (ids.length === 0) return prev;
502255
+ let ids2 = reapExpiredEngineAgentAbsences(prev.tasks ?? {}, ownedRows);
502256
+ if (ids2.length === 0) return prev;
501316
502257
  let nextTasks = { ...prev.tasks };
501317
- for (let id of ids) {
502258
+ for (let id of ids2) {
501318
502259
  let row2 = nextTasks[id];
501319
502260
  reaped.push({ id, label: row2?.description ?? id }), delete nextTasks[id];
501320
502261
  }
501321
502262
  return { ...prev, tasks: nextTasks };
501322
502263
  });
501323
502264
  for (let r of reaped) {
501324
- noteEngineAgentRowReclaimed(r.id, r.label), ownedRows.delete(r.id), fleetOwnedRowIds.delete(r.id), tickLaneRowIds.delete(r.id), queueTranscriptSystemNotice(engineAgentAbsenceDroppedLine(r.label), "info");
502265
+ noteEngineAgentRowReclaimed(r.id, r.label), ownedRows.delete(r.id), fleetOwnedRowIds.delete(r.id), fleetRowCycleIdentities.delete(r.id), tickLaneRowIds.delete(r.id), queueTranscriptSystemNotice(
502266
+ engineAgentAbsenceDroppedLine(r.label, 18e5, takeEngineAgentRowRemoveReason(r.id)),
502267
+ "info"
502268
+ );
501325
502269
  let pending4 = absenceReapTimers.get(r.id);
501326
502270
  pending4 !== void 0 && (clearTimeout(pending4), absenceReapTimers.delete(r.id));
501327
502271
  }
@@ -501417,7 +502361,19 @@ function useEngineAgentPanelBridge(setAppState) {
501417
502361
  return { ...prev, tasks: { ...prev.tasks, [ev.taskId]: row2 } };
501418
502362
  }), seedEngineAgentTranscript(setAppState, ev.taskId);
501419
502363
  else if (ev.kind === "fleet-row") {
501420
- if (tickLaneRowIds.has(ev.taskId)) {
502364
+ let priorCycle = fleetRowCycleIdentities.get(ev.taskId);
502365
+ (ev.cycleSeq !== void 0 || ev.startedAt !== void 0) && noteFleetRowCycleIdentity(ev.taskId, {
502366
+ ...ev.cycleSeq !== void 0 ? { cycleSeq: ev.cycleSeq } : {},
502367
+ ...ev.startedAt !== void 0 ? { startedAt: ev.startedAt } : {}
502368
+ });
502369
+ let withPriorCycle = (existing) => priorCycle?.cycleSeq === void 0 ? existing : { ...existing, cycleSeq: priorCycle.cycleSeq };
502370
+ if (launchAnchorChanged2(
502371
+ {
502372
+ ...priorCycle?.startedAt !== void 0 ? { startTime: priorCycle.startedAt, startTimeFromWire: !0 } : {},
502373
+ ...priorCycle?.cycleSeq !== void 0 ? { cycleSeq: priorCycle.cycleSeq } : {}
502374
+ },
502375
+ ev
502376
+ ) && tickLaneRowIds.delete(ev.taskId), tickLaneRowIds.has(ev.taskId)) {
501421
502377
  updateTaskState(ev.taskId, setAppState, clearEngineAgentRowAbsence);
501422
502378
  return;
501423
502379
  }
@@ -501427,13 +502383,13 @@ function useEngineAgentPanelBridge(setAppState) {
501427
502383
  let existing = prev.tasks[ev.taskId];
501428
502384
  if (existing) {
501429
502385
  if (!isLocalAgentTask2(existing)) return prev;
501430
- let revived = launchAnchorChanged2(existing, ev);
501431
- if (!revived && (existing.status !== "running" || !fleetOwnedRowIds.has(ev.taskId)))
502386
+ let revived = launchAnchorChanged2(withPriorCycle(existing), ev);
502387
+ if (revived && fleetOwnedRowIds.add(ev.taskId), !revived && (existing.status !== "running" || !fleetOwnedRowIds.has(ev.taskId)))
501432
502388
  return prev;
501433
502389
  let absenceCleared = isAbsentRow(existing), tokensChanged = ev.totalTokens !== void 0 && existing.progress?.tokenCount !== ev.totalTokens, toolUsesChanged = ev.toolUses !== void 0 && existing.progress?.toolUseCount !== ev.toolUses, startChanged = ev.startedAt !== void 0 && existing.startTime !== ev.startedAt;
501434
502390
  if (!tokensChanged && !toolUsesChanged && !startChanged && !absenceCleared && !revived)
501435
502391
  return prev;
501436
- let mergedProgress = progressAfterFleetRowFrame(existing, ev), next = {
502392
+ let mergedProgress = progressAfterFleetRowFrame(withPriorCycle(existing), ev), next = {
501437
502393
  ...existing,
501438
502394
  // 回来了 ⇒ 清缺席位 + 撤停表(endTime 是 absent 臂为了停表落的猜测值,不是终局钟;
501439
502395
  // 行还在跑,留着它 elapsed 就永远冻在缺席那一刻)。
@@ -501447,11 +502403,25 @@ function useEngineAgentPanelBridge(setAppState) {
501447
502403
  // 删掉 fleetOwnedRowIds,活着的任务显示完成还可能被回收。那比「数字是旧的」严重一个量级。
501448
502404
  // ② [medium] 清 `result` 拦不住上一周期**在飞**的终报回填(`engineAgentView` 的异步回写
501449
502405
  // 只核行类型与「有没有 report」,不核周期)—— 清了也会被旧响应重新写回来。
501450
- // ⇒ 两条的根治都要上游给终态事件一个**周期身份**(已记进车 P 回执的上游缺口段)。
501451
- // 在那之前,壳这一层只做证得出来的那一件:把**说了假话的那两个数**拿掉。
501452
- // ⚠️ 留下的残留(如实记,已进 KNOWN-LIMITS):复活后的行在 grace 窗内仍显示上一轮的终态词,
501453
- // 数字已清;`evictAfter` 到期回收之后,下一帧走新行分支建一条干净的行 —— 窗有界(30 s)。
501454
- ...revived ? { progress: void 0, _semaAbsence: void 0 } : {},
502406
+ // ⇒ 两条的根治都要上游给终态事件一个**周期身份**。
502407
+ //
502408
+ // ── 🔴 1.0.123:那个根治到货了(client-core 0.74.0 CC-66)───────────────────────
502409
+ // `fleet-row` `end` 都带 `cycleSeq` / `startedAt`,单源判据 `isStaleEngineAgentPanelEnd`
502410
+ // 在 end 臂把「上一周期迟到的那只」挡掉(见下方 end 分支)⇒ 的理由不成立了。
502411
+ // ⇒ 复活**把状态整只翻回 running**:清终态词 / 撤停表(endTime)/ 撤回收期限(evictAfter)/
502412
+ // 撤上一轮的终报(result),数字照旧整段清。只清数字不翻状态的那一版会让复活后的行在
502413
+ // grace 窗里挂着上一轮的终态词(旧 KNOWN-LIMITS 条目,本版随之删除)。
502414
+ // 🔴 ② 那条残余(上一周期**在飞**的终报异步回填)不在本件射程内:它走的是
502415
+ // `engineAgentView` 的异步回写、不经这条 `end` 臂 —— 记在回执的上游缺口段,不在这里
502416
+ // 靠猜去挡(挡错了会把**本轮**的真终报丢掉)。
502417
+ ...revived ? {
502418
+ progress: void 0,
502419
+ _semaAbsence: void 0,
502420
+ status: "running",
502421
+ endTime: void 0,
502422
+ evictAfter: void 0,
502423
+ result: void 0
502424
+ } : {},
501455
502425
  ...startChanged ? { startTime: ev.startedAt, startTimeFromWire: !0 } : {},
501456
502426
  // 🔴 三态 + 换周期(server 1.278.0 / L-401):
501457
502427
  // · 同周期、有键 ⇒ 赋真值(**累计口径**,绝不 `+=`;真 0 也照写 0);
@@ -501513,6 +502483,16 @@ function useEngineAgentPanelBridge(setAppState) {
501513
502483
  );
501514
502484
  }
501515
502485
  } else if (ev.kind === "end") {
502486
+ let endCycle = {
502487
+ ...ev.cycleSeq !== void 0 ? { cycleSeq: ev.cycleSeq } : {},
502488
+ ...ev.startedAt !== void 0 ? { startedAt: ev.startedAt } : {}
502489
+ };
502490
+ if (isStaleEngineAgentPanelEnd(endCycle, fleetRowCycleIdentities.get(ev.taskId))) {
502491
+ logForDebugging(
502492
+ `[sema][enginePanel] ignoring a stale end for ${ev.taskId} \u2014 it belongs to an earlier cycle than the row's current one (not settling, not writing the report, not dropping ownership)`
502493
+ );
502494
+ return;
502495
+ }
501516
502496
  let droppedLabel = takeEngineAgentReclaimedRow(ev.taskId);
501517
502497
  if (droppedLabel !== null && queueTranscriptSystemNotice(
501518
502498
  engineAgentTerminalAfterDropLine(
@@ -501614,7 +502594,7 @@ function useEngineBgShellPanelBridge(setAppState) {
501614
502594
  [setAppState]
501615
502595
  );
501616
502596
  }
501617
- var React133, import_jsx_runtime376, fleetOwnedRowIds, tickLaneRowIds, absenceReapTimers, RETAINED_ABSENCE_RECHECK_MS, init_chrome_agentprogress = __esm({
502597
+ var React133, import_jsx_runtime376, fleetOwnedRowIds, tickLaneRowIds, absenceReapTimers, fleetRowCycleIdentities, FLEET_ROW_CYCLE_LEDGER_MAX, RETAINED_ABSENCE_RECHECK_MS, init_chrome_agentprogress = __esm({
501618
502598
  "build-src/src/sema/overrides/chrome-agentprogress.tsx"() {
501619
502599
  React133 = __toESM(require_react(), 1);
501620
502600
  init_figures();
@@ -501645,7 +502625,8 @@ var React133, import_jsx_runtime376, fleetOwnedRowIds, tickLaneRowIds, absenceRe
501645
502625
  init_engineSubagentTail2();
501646
502626
  init_CoordinatorAgentStatus();
501647
502627
  import_jsx_runtime376 = __toESM(require_jsx_runtime(), 1);
501648
- fleetOwnedRowIds = /* @__PURE__ */ new Set(), tickLaneRowIds = /* @__PURE__ */ new Set(), absenceReapTimers = /* @__PURE__ */ new Map(), RETAINED_ABSENCE_RECHECK_MS = 6e4;
502628
+ fleetOwnedRowIds = /* @__PURE__ */ new Set(), tickLaneRowIds = /* @__PURE__ */ new Set(), absenceReapTimers = /* @__PURE__ */ new Map(), fleetRowCycleIdentities = /* @__PURE__ */ new Map(), FLEET_ROW_CYCLE_LEDGER_MAX = 512;
502629
+ RETAINED_ABSENCE_RECHECK_MS = 6e4;
501649
502630
  }
501650
502631
  });
501651
502632
 
@@ -502462,7 +503443,7 @@ function readRestartInflightLine() {
502462
503443
  workflows,
502463
503444
  leaderStreaming,
502464
503445
  otherSessionsSharing: sharing
502465
- }), 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]);
502466
503447
  if (unknown2.length === 0) return { line, key };
502467
503448
  let caveat = `\u26A0 could not read ${unknown2.join(" / ")} \u2014 this list may be incomplete`;
502468
503449
  return { line: line === null ? caveat : `${line}
@@ -538591,6 +539572,168 @@ var DEFAULT_DEBUG_LINES_READ, TAIL_READ_BYTES, init_debug3 = __esm({
538591
539572
  }
538592
539573
  });
538593
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
+
538594
539737
  // build-src/src/commands/doctor/permissionsPostureRow.ts
538595
539738
  function formatApprovalWindow(ms) {
538596
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`;
@@ -538605,7 +539748,7 @@ function modeSegment(r) {
538605
539748
  function permissionsPostureDetail(r) {
538606
539749
  let parts = [];
538607
539750
  return parts.push(modeSegment(r)), parts.push(
538608
- r.wireRules === null ? `permission rules ${NOT_OBSERVED}` : describeWireRules(r.wireRules)
539751
+ (r.wireRules === null ? `permission rules ${NOT_OBSERVED}` : describeWireRules(r.wireRules)) + describeSettingsStampStale(r.wireStampStale)
538609
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(
538610
539753
  `approval window ${formatApprovalWindow(r.approvalWindowMs)}${r.approvalWindowSource === "env" ? " (env STREAM_ASK_WINDOW_MS, passed through to engines this shell starts)" : ""}`
538611
539754
  ), parts.push(
@@ -538619,6 +539762,7 @@ function permissionsPostureDetail(r) {
538619
539762
  var NOT_OBSERVED, init_permissionsPostureRow = __esm({
538620
539763
  "build-src/src/commands/doctor/permissionsPostureRow.ts"() {
538621
539764
  init_settingsRulesWire();
539765
+ init_interactiveSettingsStamp();
538622
539766
  NOT_OBSERVED = "not observed";
538623
539767
  }
538624
539768
  });
@@ -538973,9 +540117,16 @@ async function readLivePermissionsPosture(engineTarget) {
538973
540117
  } catch {
538974
540118
  classifier = null;
538975
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
+ }
538976
540127
  let wireRules = null;
538977
540128
  try {
538978
- 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();
538979
540130
  if (frozen !== void 0)
538980
540131
  wireRules = wireRuleSurface2(frozen.full, {
538981
540132
  sendMode: frozen.sendMode,
@@ -538989,7 +540140,7 @@ async function readLivePermissionsPosture(engineTarget) {
538989
540140
  {
538990
540141
  // 🔴 总开关也是这一段的输入:`SEMA_SEND_SETTINGS=off` 时规则整份不发,读面若不看它
538991
540142
  // 就会报一个不存在的安全姿态。env 视图与播种同律取。
538992
- sendMode: resolveSendSettingsMode2(envView.SEMA_SEND_SETTINGS)
540143
+ sendMode: resolveSendSettingsMode3(envView.SEMA_SEND_SETTINGS)
538993
540144
  }
538994
540145
  );
538995
540146
  }
@@ -539040,6 +540191,7 @@ async function readLivePermissionsPosture(engineTarget) {
539040
540191
  readDenyTiers,
539041
540192
  selfSpawnLane,
539042
540193
  wireRules,
540194
+ wireStampStale,
539043
540195
  writeProtection,
539044
540196
  readFace,
539045
540197
  readFaceDisagreement: readFaceDisagreement2,
@@ -550687,7 +551839,7 @@ async function ensurePrintModeEngine() {
550687
551839
  async function printLaneWireSettings(knobs) {
550688
551840
  if (knobs.mockScenario) return;
550689
551841
  let { resolveSemaConfigWithEffective: resolveSemaConfigWithEffective2 } = await Promise.resolve().then(() => (init_settings5(), settings_exports4)), {
550690
- resolveSendSettingsMode: resolveSendSettingsMode2,
551842
+ resolveSendSettingsMode: resolveSendSettingsMode3,
550691
551843
  buildWireSettingsStamp: buildWireSettingsStamp2,
550692
551844
  toWireSettings: toWireSettings2,
550693
551845
  unenforceableSettingsRules: unenforceableSettingsRules2,
@@ -550699,7 +551851,7 @@ async function printLaneWireSettings(knobs) {
550699
551851
  } = await Promise.resolve().then(() => (init_settingsRulesWire(), settingsRulesWire_exports)), { effective, config: config4 } = resolveSemaConfigWithEffective2(), fullWire = toWireSettings2(effective, config4);
550700
551852
  for (let msg of describeUnenforceableRules2(unenforceableSettingsRules2(fullWire))) emitPrintLaneRuleNotice(msg);
550701
551853
  emitPrintLaneRuleNotice(describeHeadlessAskContentRules2(askContentRulesDeniedHeadless2(fullWire)));
550702
- let stampMode = resolveSendSettingsMode2(knobs.sendSettings), cliToolFlags = readCliToolFlagsWire2();
551854
+ let stampMode = resolveSendSettingsMode3(knobs.sendSettings), cliToolFlags = readCliToolFlagsWire2();
550703
551855
  return setWireStampProvenance2({ full: fullWire, sendMode: stampMode, cliToolFlags }), buildWireSettingsStamp2(stampMode, fullWire, {
550704
551856
  // L-66①:`--tools` / `--disallowedTools` 的壳本地快照。**求值点必须在这里**(晚绑定供给器内),
550705
551857
  // 不能在前置步就读:前置步跑在 `import('../main.js')` 之前,那时 commander 还没解析 argv,
@@ -550965,8 +552117,8 @@ function syncEntriesToTranscriptLines(entries, ctx) {
550965
552117
  leafUuid: lines.length > 0 ? lines[lines.length - 1].uuid : ctx.startingParentUuid ?? null
550966
552118
  };
550967
552119
  }
550968
- function selectEntriesByIds(entries, ids) {
550969
- let want = new Set(ids);
552120
+ function selectEntriesByIds(entries, ids2) {
552121
+ let want = new Set(ids2);
550970
552122
  return entries.filter((e) => want.has(e.id));
550971
552123
  }
550972
552124
  function lastLineUuid(jsonlBody) {
@@ -551365,7 +552517,9 @@ __export(cloudResources_exports, {
551365
552517
  cloudResourceInstall: () => cloudResourceInstall,
551366
552518
  cloudResourceList: () => cloudResourceList,
551367
552519
  cloudResourceRemove: () => cloudResourceRemove,
551368
- cloudResourceSync: () => cloudResourceSync
552520
+ cloudResourceSync: () => cloudResourceSync,
552521
+ findSecretShape: () => findSecretShape,
552522
+ isEnvVarName: () => isEnvVarName
551369
552523
  });
551370
552524
  import { createHash as createHash31 } from "node:crypto";
551371
552525
  import { existsSync as existsSync37, readdirSync as readdirSync15, readFileSync as readFileSync56, statSync as statSync18 } from "node:fs";
@@ -551380,9 +552534,41 @@ function resolveTargetSel(o) {
551380
552534
  );
551381
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" };
551382
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
+ }
551383
552569
  function findSecretShape(value) {
551384
- let s = JSON.stringify(value) ?? "", m2 = SECRET_SHAPE_RE.exec(s);
551385
- 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)";
551386
552572
  }
551387
552573
  function managedLaneError(forUser, status3, json2) {
551388
552574
  let detail = asStr4(json2.error_description);
@@ -551714,7 +552900,7 @@ async function prepareModel(m2) {
551714
552900
  let api2 = entry.api === "anthropic-messages" ? "anthropic-messages" : "openai-completions";
551715
552901
  entry.api = api2, entry.provider = api2 === "anthropic-messages" ? "anthropic" : asStr4(entry.provider) && entry.provider !== "anthropic" ? entry.provider : "gateway";
551716
552902
  let notes = [], keyEnv = asStr4(entry.apiKeyEnv);
551717
- 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)"));
551718
552904
  let hasInlineKey = INLINE_KEY_FIELDS.some((f) => asStr4(m2[f]));
551719
552905
  if (!asStr4(entry.apiKeyEnv) && hasInlineKey) {
551720
552906
  let { keyEnvNameForEntry: keyEnvNameForEntry2 } = await Promise.resolve().then(() => (init_modelChannels(), modelChannels_exports));
@@ -551758,7 +552944,7 @@ function prepareMcp(name, c3) {
551758
552944
  if (!command8) return { name, display: display2, entry: null, notes, skipReason: `server '${name}' has no command` };
551759
552945
  let envRefs = {}, dropped2 = [];
551760
552946
  for (let k2 of Object.keys(asRec3(c3.env) ?? {}))
551761
- ENV_NAME_RE.test(k2) ? envRefs[k2] = k2 : dropped2.push(k2);
552947
+ isEnvVarName(k2) ? envRefs[k2] = k2 : dropped2.push(k2);
551762
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(", ")}`);
551763
552949
  let args = asArr3(c3.args).filter((a) => typeof a == "string");
551764
552950
  return {
@@ -552325,7 +553511,7 @@ async function cloudPublish(options) {
552325
553511
  fail5(e);
552326
553512
  }
552327
553513
  }
552328
- 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({
552329
553515
  "build-src/src/cli/handlers/cloudResources.ts"() {
552330
553516
  init_types6();
552331
553517
  init_cloudAuth();
@@ -552334,7 +553520,12 @@ var out4, err6, asRec3, asArr3, asStr4, ENV_NAME_RE, DOMAIN_NAME_RE, SECRET_SHAP
552334
553520
  out4 = (line) => process.stdout.write(`${line}
552335
553521
  `), err6 = (line) => process.stderr.write(`${line}
552336
553522
  `);
552337
- 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;
552338
553529
  personalPath = (domain2, forUser) => forUser ? `/api/v1/users/${encodeURIComponent(forUser)}/config/${domain2}` : `/api/v1/me/config/${domain2}`;
552339
553530
  wantsTeam = (o) => !!(o.team || o.space || o.global);
552340
553531
  TEAM_WRITE_ROLE = { models: "editor", mcp: "publisher", skills: "publisher", plugins: "publisher" };
@@ -562986,7 +564177,7 @@ Usage: sema --remote "your task description"`, () => gracefulShutdown(1));
562986
564177
  pendingHookMessages
562987
564178
  }, renderAndRun);
562988
564179
  }
562989
- }).version("sema 1.0.122", "-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 () => {
562990
564181
  await (await Promise.resolve().then(() => (init_bg2(), bg_exports))).psHandler([]), process.exit(process.exitCode ?? 0);
562991
564182
  }), program2.command("logs [id]").description("Print a background session's recent terminal output").action(async (id) => {
562992
564183
  await (await Promise.resolve().then(() => (init_bg2(), bg_exports))).logsHandler(id, []), process.exit(process.exitCode ?? 0);
@@ -564950,11 +566141,21 @@ __export(suspendedSubagentAskWire_exports, {
564950
566141
  startSuspendedSubagentAskWire: () => startSuspendedSubagentAskWire
564951
566142
  });
564952
566143
  function startSuspendedSubagentAskWire(opts) {
564953
- let surface = opts.deps?.surface ?? surfaceSuspendedAskAndRespond, retract = opts.deps?.retract ?? ((callKey) => retractApprovalCard(callKey, "settled-elsewhere")), notify5 = opts.deps?.notify ?? ((text2) => {
566144
+ let surface = opts.deps?.surface ?? surfaceSuspendedAskAndRespond, retract = opts.deps?.retract ?? ((callKey, cause) => retractApprovalCard(callKey, cause)), notify5 = opts.deps?.notify ?? ((text2) => {
564954
566145
  surfaceTranscriptSystemNotice(text2, "warning");
564955
566146
  }), startFeed = opts.deps?.startFeed ?? startApprovalsFeed, sessionId = opts.sessionId(), tracker2 = createSuspendedAskTracker({ ...spreadSessionId(sessionId) });
564956
566147
  installSuspendedAskTracker(tracker2), noteSuspendedAskFeedInstalled(!0);
564957
- 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) => {
564958
566159
  if (stopped) return;
564959
566160
  stats3.snapshots += 1;
564960
566161
  let now2 = opts.sessionId();
@@ -564965,11 +566166,7 @@ function startSuspendedSubagentAskWire(opts) {
564965
566166
  return;
564966
566167
  }
564967
566168
  let filter2 = spreadSessionId(sessionId);
564968
- try {
564969
- noteApprovalsAwaitingDecision(countApprovalsAwaitingDecision(snap, { ...filter2 }));
564970
- } catch (e) {
564971
- noteApprovalsAwaitingDecision(null), logForDebugging(`[sema][suspendedAsk] countApprovalsAwaitingDecision threw: ${String(e)}`);
564972
- }
566169
+ publishCountFrom(snap);
564973
566170
  let delta;
564974
566171
  try {
564975
566172
  delta = tracker2.ingest(snap);
@@ -564981,19 +566178,19 @@ function startSuspendedSubagentAskWire(opts) {
564981
566178
  let appearedNow = new Set(delta.appeared.map((r) => r.approvalId)), liveIds = /* @__PURE__ */ new Set();
564982
566179
  for (let r of suspendedSubagentAsks(snap, { ...filter2 })) {
564983
566180
  if (liveIds.add(r.approvalId), appearedNow.has(r.approvalId)) continue;
564984
- 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)))) {
564985
566182
  orphanStreak.delete(r.approvalId);
564986
566183
  continue;
564987
566184
  }
564988
566185
  let streak = (orphanStreak.get(r.approvalId) ?? 0) + 1;
564989
566186
  orphanStreak.set(r.approvalId, streak), !(streak < 2) && (orphanStreak.delete(r.approvalId), stats3.released += 1, logForDebugging(
564990
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`
564991
- ), 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"));
564992
566189
  }
564993
566190
  for (let id of [...orphanStreak.keys()]) liveIds.has(id) || orphanStreak.delete(id);
564994
566191
  noteSuspendedAsksListed(liveIds), pruneVanishedSuspendedAsks(liveIds);
564995
566192
  for (let approvalId of delta.gone)
564996
- openCards.delete(approvalId), orphanStreak.delete(approvalId), forgetSuspendedAsk(approvalId), retract(liveFrameCallKey(approvalId)) && (stats3.retracted += 1);
566193
+ openCards.delete(approvalId), orphanStreak.delete(approvalId), exhausted.delete(approvalId), forgetSuspendedAsk(approvalId), retract(liveFrameCallKey(approvalId), "settled-elsewhere") && (stats3.retracted += 1);
564997
566194
  for (let row2 of delta.upgraded)
564998
566195
  stats3.upgraded += 1, logForDebugging(
564999
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)`
@@ -565003,34 +566200,106 @@ function startSuspendedSubagentAskWire(opts) {
565003
566200
  let lane = safeLane(opts.lane);
565004
566201
  (async () => {
565005
566202
  try {
565006
- 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));
565007
566204
  if (openCards.delete(row2.approvalId), outcome.editRefused === !0) {
565008
566205
  notify5(
565009
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."
565010
- ), retryLater(row2.approvalId, "edits are not accepted on this card");
566207
+ ), retryLater(row2.approvalId, "edits are not accepted on this card", "user", { alreadyNotified: !0 });
566208
+ return;
566209
+ }
566210
+ if (outcome.retracted === !0) {
566211
+ requeueSuspendedAsk(row2.approvalId), orphanStreak.delete(row2.approvalId), logForDebugging(
566212
+ `[sema][suspendedAsk] ${row2.approvalId} card was retracted without a decision (this host let go of it) \u2014 claim released, re-surfaceable, no re-surface budget consumed`
566213
+ );
565011
566214
  return;
565012
566215
  }
565013
566216
  if (outcome.decision === "unresolved") {
565014
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 ");
565015
- 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");
565016
566219
  return;
565017
566220
  }
565018
566221
  noteSuspendedAskDecided(row2.approvalId), orphanStreak.delete(row2.approvalId);
565019
566222
  } catch (e) {
565020
- 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");
565021
566224
  }
565022
566225
  })();
565023
- }, retryLater = (approvalId, why) => {
565024
- if (!takeSuspendedAskRequeueBudget(approvalId, REQUEUE_MAX)) {
565025
- notify5(
565026
- `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.`
565027
- ), logForDebugging(`[sema][suspendedAsk] ${approvalId} exhausted the re-surface budget (${why})`);
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})`);
566230
+ return;
566231
+ }
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})`);
566236
+ return;
566237
+ }
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);
565028
566248
  return;
565029
566249
  }
565030
- stats3.requeued += 1, logForDebugging(`[sema][suspendedAsk] ${approvalId} did not settle (${why}) \u2014 re-surfacing it`), requeueSuspendedAsk(approvalId);
565031
- }, feed = null;
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");
566257
+ });
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
+ };
565032
566301
  try {
565033
- feed = startFeed(opts.client, onSnapshot, {
566302
+ feed = startFeed(observeApprovalsList(opts.client), onSnapshot, {
565034
566303
  reconcile: {
565035
566304
  // 🔴 §61 S-2 逐字:「会话有活跃后台代理 ∧ 没有活着的宿主 run」。谓词抛 / 返回非布尔 ⇒ 包按「查」
565036
566305
  // 处置(少查一次 = 一只等人的 ask 迟迟不出现),所以这里不吞成 false。
@@ -565049,8 +566318,11 @@ function startSuspendedSubagentAskWire(opts) {
565049
566318
  } catch {
565050
566319
  }
565051
566320
  openCards.size > 0 && logForDebugging(
565052
- `[sema][suspendedAsk] teardown with ${String(openCards.size)} card(s) still on screen \u2014 leaving them up on purpose (retracting them would post a deny the user never chose)`
565053
- ), openCards.clear(), installSuspendedAskTracker(null), noteSuspendedAskFeedInstalled(!1);
566321
+ `[sema][suspendedAsk] teardown with ${String(openCards.size)} card(s) still on screen \u2014 retracting them (this host no longer has a decision port for them; CC-67 retraction sends nothing)`
566322
+ );
566323
+ for (let approvalId of [...openCards])
566324
+ retract(liveFrameCallKey(approvalId), "host-decision-port-gone") && (stats3.retracted += 1);
566325
+ openCards.clear(), installStreamApprovalOutcomeSink(null), installSuspendedAskTracker(null), noteSuspendedAskFeedInstalled(!1);
565054
566326
  }
565055
566327
  },
565056
566328
  stats: () => ({ ...stats3 })
@@ -565386,11 +566658,11 @@ function partitionSessionReap(records, departedSessionIds) {
565386
566658
  function reapSessionRecords(io, departedSessionIds) {
565387
566659
  if (departedSessionIds.length === 0) return [];
565388
566660
  if (io.mutate) {
565389
- let ids = [], m2 = io.mutate((records) => {
566661
+ let ids2 = [], m2 = io.mutate((records) => {
565390
566662
  let { kept: kept2, reaped: reaped2 } = partitionSessionReap(records, departedSessionIds);
565391
- 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;
565392
566664
  });
565393
- return m2.ok || "reason" in m2 && m2.reason === "aborted" ? ids : [];
566665
+ return m2.ok || "reason" in m2 && m2.reason === "aborted" ? ids2 : [];
565394
566666
  }
565395
566667
  let { kept, reaped } = partitionSessionReap(io.load(), departedSessionIds);
565396
566668
  return reaped.length === 0 ? [] : (io.save(kept), reaped.map((r) => r.id));
@@ -565407,15 +566679,15 @@ function pidAlive3(pid) {
565407
566679
  }
565408
566680
  }
565409
566681
  function writeSchedulerClaim(storePath, sessionIds, pid = process.pid) {
565410
- 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();
565411
566683
  try {
565412
566684
  let prev = JSON.parse(readFileSync66(file2, "utf8"));
565413
566685
  if (Array.isArray(prev.sessionIds) && prev.sessionIds.join(`
565414
- `) === ids.join(`
566686
+ `) === ids2.join(`
565415
566687
  `)) return;
565416
566688
  } catch {
565417
566689
  }
565418
- 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 });
565419
566691
  }
565420
566692
  function removeSchedulerClaim(storePath, pid = process.pid) {
565421
566693
  try {
@@ -565470,11 +566742,11 @@ function sweepOrphanSessionRecords(io, storePath, opts = {}) {
565470
566742
  return { kept: kept2, reapedIds: reapedIds2 };
565471
566743
  };
565472
566744
  if (io.mutate) {
565473
- let ids = [], m2 = io.mutate((all4) => {
566745
+ let ids2 = [], m2 = io.mutate((all4) => {
565474
566746
  let t2 = partition3(all4);
565475
- return ids = t2.reapedIds, t2.reapedIds.length === 0 ? null : t2.kept;
566747
+ return ids2 = t2.reapedIds, t2.reapedIds.length === 0 ? null : t2.kept;
565476
566748
  });
565477
- return m2.ok || "reason" in m2 && m2.reason === "aborted" ? ids : [];
566749
+ return m2.ok || "reason" in m2 && m2.reason === "aborted" ? ids2 : [];
565478
566750
  }
565479
566751
  let { kept, reapedIds } = partition3(records);
565480
566752
  return reapedIds.length > 0 && io.save(kept), reapedIds;
@@ -565500,10 +566772,10 @@ function ownsScheduledRecord(r) {
565500
566772
  return r.sessionId === current6;
565501
566773
  }
565502
566774
  function currentOwnedSessionIds() {
565503
- let ids = [], live = getLiveSessionId();
565504
- live && ids.push(live);
566775
+ let ids2 = [], live = getLiveSessionId();
566776
+ live && ids2.push(live);
565505
566777
  let shell = String(getSessionId());
565506
- return ids.includes(shell) || ids.push(shell), ids;
566778
+ return ids2.includes(shell) || ids2.push(shell), ids2;
565507
566779
  }
565508
566780
  function wireSchedulerSessionLifecycle(opts = {}) {
565509
566781
  let storePath = opts.storePath ?? schedulerStorePath(), io = fileSchedulerStoreIO(storePath), onError = opts.onError ?? (() => {
@@ -570896,11 +572168,11 @@ async function launchReplProduction() {
570896
572168
  launchMode && (tpc.mode = launchMode), tpc.isBypassPermissionsModeAvailable = isBypassPermissionsModeAvailable, bypassModeLaunch = isBypassPermissionsModeAvailable;
570897
572169
  let effectiveConfig;
570898
572170
  try {
570899
- 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";
570900
- 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 = {
570901
572172
  launchMode,
570902
572173
  factoryDefaultAuto: factoryDefaultAutoEligible
570903
- });
572174
+ };
572175
+ effectiveConfig = resolveSemaConfig(seamOpts);
570904
572176
  let dm = effectiveConfig.derivedMode;
570905
572177
  if (tpc.mode = dm === "bypassPermissions" && !isBypassPermissionsModeAvailable ? "default" : dm, bypassModeLaunch = tpc.mode === "bypassPermissions", tpc.mode === "auto") {
570906
572178
  let { setAutoModeActive: setAutoModeActive2 } = await Promise.resolve().then(() => (init_autoModeState(), autoModeState_exports));
@@ -570923,16 +572195,16 @@ async function launchReplProduction() {
570923
572195
  });
570924
572196
  }
570925
572197
  }
570926
- 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;
570927
572199
  try {
570928
572200
  for (let msg of describeUnenforceableRules(unenforceableSettingsRules(fullWire)))
570929
572201
  process.stderr.write(`[sema] ${msg}
570930
572202
  `), bootFailClosedNotices.push(msg);
570931
572203
  } catch {
570932
572204
  }
570933
- 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));
570934
- setSeamConfig2(stampSupplier), setWireStampProvenance({ full: fullWire, sendMode: stampMode, cliToolFlags: readCliToolFlagsWire2() });
570935
- 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;
570936
572208
  if (stamp2) {
570937
572209
  if (process.env.SEMA_DEBUG) {
570938
572210
  let p = stamp2.permissions ?? {};