@linxin666/dsh-client-ui-task-board 0.4.18 → 0.4.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +2 -2
  3. package/README.zh.md +2 -2
  4. package/lib/client.js +179 -60
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +492 -74
  7. package/lib/types/client/board/TaskForm.d.ts +3 -1
  8. package/lib/types/client/index.d.ts +7 -1
  9. package/lib/types/client/native-panel.d.ts +1 -1
  10. package/lib/types/client/seats.d.ts +36 -2
  11. package/lib/types/client/settings-form.d.ts +2 -0
  12. package/lib/types/core/controller.d.ts +1 -1
  13. package/lib/types/core/extension.d.ts +135 -1
  14. package/lib/types/core/session-reuse.d.ts +46 -13
  15. package/lib/types/core/tasks.d.ts +2 -2
  16. package/lib/types/host/agent-tools.d.ts +7 -2
  17. package/lib/types/host/extension-registry.d.ts +30 -1
  18. package/lib/types/host-ledger.d.ts +86 -1
  19. package/lib/types/host-routes.d.ts +7 -1
  20. package/lib/types/host-runner.d.ts +20 -1
  21. package/lib/types/host-service.d.ts +59 -14
  22. package/lib/types/protocol.d.ts +9 -1
  23. package/package.json +26 -26
  24. package/src/client/board/ExecutionLog.tsx +9 -2
  25. package/src/client/board/NewTaskModal.tsx +88 -3
  26. package/src/client/board/TaskDetail.tsx +18 -11
  27. package/src/client/board/TaskForm.tsx +13 -2
  28. package/src/client/board.module.css +67 -1
  29. package/src/client/index.ts +3 -0
  30. package/src/client/locales.ts +7 -6
  31. package/src/client/native-panel.tsx +2 -1
  32. package/src/client/seats.tsx +32 -4
  33. package/src/client/service.ts +3 -0
  34. package/src/client/settings-form.ts +21 -2
  35. package/src/core/controller.ts +9 -3
  36. package/src/core/extension.ts +138 -1
  37. package/src/core/session-reuse.ts +58 -21
  38. package/src/core/tasks.ts +2 -2
  39. package/src/host/agent-tools.ts +8 -2
  40. package/src/host/extension-registry.ts +121 -2
  41. package/src/host-ledger.ts +252 -18
  42. package/src/host-routes.ts +30 -3
  43. package/src/host-runner.ts +44 -5
  44. package/src/host-service.ts +180 -37
  45. package/src/index.ts +28 -2
  46. package/src/protocol.ts +9 -1
package/lib/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import z from "@deepseek-ai/schemastery";
2
- import { accessSync, chmodSync, closeSync, constants, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { accessSync, chmodSync, closeSync, constants, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
3
3
  import { dirname, isAbsolute, join, win32 } from "node:path";
4
4
  import { homedir } from "node:os";
5
5
  import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
@@ -199,39 +199,47 @@ function sessionPollMs(seconds) {
199
199
  //#endregion
200
200
  //#region src/core/session-reuse.ts
201
201
  /**
202
+ * The session the newest settled execution ran in, or undefined when no
203
+ * execution carries one.
204
+ *
205
+ * The launch path calls the reuse rule after `startExecution` appended this
206
+ * run's own open record, so the array tail is always an unsettled row at that
207
+ * point and the scan has to skip it (issue #1587).
208
+ * @param task - the task whose history is read.
209
+ * @returns the newest settled session id, if any.
210
+ */
211
+ function newestSettledSessionId(task) {
212
+ for (let index = task.executions.length - 1; index >= 0; index -= 1) {
213
+ const candidate = task.executions[index];
214
+ if (candidate !== void 0 && candidate.sessionId !== void 0 && candidate.endedAt !== void 0) return candidate.sessionId;
215
+ }
216
+ }
217
+ /**
202
218
  * Pick the session a new execution of this task may continue in, or undefined
203
219
  * to mint a fresh conversation. Reuse requires ALL of:
204
- * - the task opted in (`reuseSession === true`);
205
- * - the task's newest SETTLED execution carries a session id (issue #1587: the
206
- * launch path calls this after `startExecution` appended this run's own open
207
- * record, so reading the array tail always found an unsettled row and reuse
208
- * never happened);
209
- * - the roster is known and that session is present and idle.
220
+ * - the task opted in (`reuseSession === true`) unless the caller forces it;
221
+ * - the task's newest settled execution carries a session id (issue #1587);
222
+ * - the roster is known and that session is present and idle;
223
+ * - that session is not archived, when the deployment reports an archive set
224
+ * (issue #2068).
210
225
  *
211
226
  * An unknown roster (session/list unavailable) never reuses: minting a fresh
212
227
  * conversation is always safe, prompting into a session we cannot see is not.
228
+ * An archived session is refused for the same reason — the Host will not run a
229
+ * turn in it, so continuing there can only fail the run that tried.
213
230
  * @param task - the task about to run.
214
231
  * @param idleSessionIds - ids the last roster saw as present and not running;
215
232
  * undefined when that roster is unknown.
216
- * @param options.force - continue the settled session regardless of the card's
217
- * own `reuseSession` opt-in. A rework is exactly that case: the reviewer read
218
- * the previous run's session and sent it back. Every condition above still
219
- * applies — the force waives the opt-in, never the evidence.
233
+ * @param options - force and the archive set; see {@link ReuseOptions}.
220
234
  * @returns the session id to continue in, or undefined for a fresh session.
221
235
  */
222
236
  function reusableSessionId(task, idleSessionIds, options = {}) {
223
237
  if (options.force !== true && task.reuseSession !== true) return void 0;
224
238
  if (idleSessionIds === void 0) return void 0;
225
- let last;
226
- for (let index = task.executions.length - 1; index >= 0; index -= 1) {
227
- const candidate = task.executions[index];
228
- if (candidate.sessionId !== void 0 && candidate.endedAt !== void 0) {
229
- last = candidate;
230
- break;
231
- }
232
- }
233
- if (last === void 0 || last.sessionId === void 0) return void 0;
234
- return idleSessionIds.has(last.sessionId) ? last.sessionId : void 0;
239
+ const newest = newestSettledSessionId(task);
240
+ if (newest === void 0) return void 0;
241
+ if (options.archivedSessionIds?.has(newest) === true) return void 0;
242
+ return idleSessionIds.has(newest) ? newest : void 0;
235
243
  }
236
244
  //#endregion
237
245
  //#region src/host/launch-admission.ts
@@ -3544,8 +3552,25 @@ const LEGACY_START_TOLERANCE_MS = 2e3;
3544
3552
  * live owner; only one that has been unreadable for longer than any write can
3545
3553
  * take is treated as an unclean-shutdown leftover (issue #1528: a 0-byte lock
3546
3554
  * kept the Host half from mounting until it was deleted by hand).
3555
+ *
3556
+ * The same window bounds the identity-unprobeable takeover below: it is two
3557
+ * heartbeat intervals, so an owner that keeps beating is never mistaken for a
3558
+ * leftover (issue #2061).
3547
3559
  */
3548
3560
  const UNREADABLE_LOCK_GRACE_MS = 6e4;
3561
+ /**
3562
+ * How often the lock owner refreshes its lock file's mtime (issue #2061). The
3563
+ * record itself never changes, only the timestamp moves, so a later start can
3564
+ * tell a live owner from a hard-kill leftover even when the platform identity
3565
+ * probe reads nothing (a protected process, a WMI/CIM timeout). Two missed
3566
+ * beats age the lock past UNREADABLE_LOCK_GRACE_MS and make it reclaimable; a
3567
+ * beating owner stays protected.
3568
+ */
3569
+ const LOCK_HEARTBEAT_MS = 3e4;
3570
+ const defaultLockProcessProbe = {
3571
+ isAlive: processIsAlive,
3572
+ startTimeMs: processStartTimeMs
3573
+ };
3549
3574
  /** Whether the recorded start time proves the recorded PID is another process. */
3550
3575
  function startTimeMismatch(recorded, actual, exact) {
3551
3576
  return exact ? recorded !== actual : Math.abs(recorded - actual) > LEGACY_START_TOLERANCE_MS;
@@ -3633,6 +3658,10 @@ var HostTaskLedger = class {
3633
3658
  requestCache = /* @__PURE__ */ new Map();
3634
3659
  lockToken = crypto.randomUUID();
3635
3660
  lockFd;
3661
+ lockHeartbeat;
3662
+ processProbe;
3663
+ /** Warning sink; defaults to console.warn, tests inject a collector. */
3664
+ warn;
3636
3665
  file;
3637
3666
  lockFile;
3638
3667
  /** Small sidecar for the 30 s scheduler heartbeat (lastTickAt only). */
@@ -3663,6 +3692,16 @@ var HostTaskLedger = class {
3663
3692
  spendBudget;
3664
3693
  /** Today's measured spend in tokens, or undefined when nothing can be measured. */
3665
3694
  spendUsed;
3695
+ /**
3696
+ * The board's launch gate, or undefined when no consumer is attached.
3697
+ *
3698
+ * The ledger is where every run is opened — the run actions, a due schedule,
3699
+ * the run tool, a rework all arrive here — so this is the one point a run can
3700
+ * be handed to someone else before an execution record exists. Installed by
3701
+ * the Host service after construction, because the gate belongs to the
3702
+ * extension registry that is built around this ledger.
3703
+ */
3704
+ launchGate;
3666
3705
  constructor(dir = join(dshHome(), "task-board"), now = Date.now, options = {}) {
3667
3706
  this.now = now;
3668
3707
  const baseline = options.sessionDefaultPermission;
@@ -3671,12 +3710,18 @@ var HostTaskLedger = class {
3671
3710
  this.cardDefaults = options.cardDefaults ?? (() => ({}));
3672
3711
  this.spendBudget = options.spendBudgetTokens ?? (() => 0);
3673
3712
  this.spendUsed = options.spendUsedToday ?? ((now) => usedTokensToday(now));
3713
+ this.launchGate = options.launchGate;
3714
+ this.processProbe = options.processProbe ?? defaultLockProcessProbe;
3715
+ this.warn = options.warn ?? ((message) => {
3716
+ console.warn(message);
3717
+ });
3674
3718
  mkdirSync(dir, { recursive: true });
3675
3719
  this.file = join(dir, "ledger-v2.json");
3676
3720
  this.lockFile = join(dir, "ledger-v2.lock");
3677
3721
  this.schedulerFile = join(dir, "scheduler-v2.json");
3678
3722
  this.cleanStaleTemporaryFiles(dir);
3679
3723
  this.lockFd = this.acquireLock();
3724
+ this.startLockHeartbeat();
3680
3725
  try {
3681
3726
  this.document = this.load(dir);
3682
3727
  for (const request of this.document.recentRequests) this.requestCache.set(request.requestId, { fingerprint: request.fingerprint });
@@ -3704,6 +3749,18 @@ var HostTaskLedger = class {
3704
3749
  this.depthLimit = next;
3705
3750
  this.notify();
3706
3751
  }
3752
+ /**
3753
+ * Install the launch gate, or remove it with undefined.
3754
+ *
3755
+ * The Host service owns it: the board's extension registry is built around
3756
+ * this ledger, so the gate is attached once that registry exists. A ledger
3757
+ * with no gate — every ledger a test drives on its own — opens every run
3758
+ * itself, exactly as it did before the seam existed.
3759
+ * @param gate - the gate to consult before a run opens, or undefined.
3760
+ */
3761
+ setLaunchGate(gate) {
3762
+ this.launchGate = gate;
3763
+ }
3707
3764
  /** Remove leftover *.tmp-* files from previous crashes or interrupted writes. */
3708
3765
  cleanStaleTemporaryFiles(dir) {
3709
3766
  try {
@@ -3815,7 +3872,39 @@ var HostTaskLedger = class {
3815
3872
  this.listeners.delete(listener);
3816
3873
  };
3817
3874
  }
3875
+ /**
3876
+ * Refresh the lock's mtime so a later start can distinguish a live owner from
3877
+ * a hard-kill leftover without reading the process identity (issue #2061).
3878
+ * Best-effort: a failed beat only ages the lock, and a record that no longer
3879
+ * carries this owner's token stops the heartbeat instead of beating for
3880
+ * whoever holds the lock now.
3881
+ */
3882
+ renewLock() {
3883
+ if (this.lockFd === void 0) return;
3884
+ try {
3885
+ if (JSON.parse(readFileSync(this.lockFile, "utf8")).token !== this.lockToken) {
3886
+ this.warn(`[task-board] lost the ledger lock to another owner; this instance stops renewing ${this.lockFile}`);
3887
+ this.stopLockHeartbeat();
3888
+ return;
3889
+ }
3890
+ const seconds = this.now() / 1e3;
3891
+ utimesSync(this.lockFile, seconds, seconds);
3892
+ } catch {}
3893
+ }
3894
+ startLockHeartbeat() {
3895
+ const timer = setInterval(() => {
3896
+ this.renewLock();
3897
+ }, LOCK_HEARTBEAT_MS);
3898
+ timer.unref?.();
3899
+ this.lockHeartbeat = timer;
3900
+ }
3901
+ stopLockHeartbeat() {
3902
+ if (this.lockHeartbeat === void 0) return;
3903
+ clearInterval(this.lockHeartbeat);
3904
+ this.lockHeartbeat = void 0;
3905
+ }
3818
3906
  dispose() {
3907
+ this.stopLockHeartbeat();
3819
3908
  const fd = this.lockFd;
3820
3909
  if (fd === void 0) return;
3821
3910
  this.lockFd = void 0;
@@ -3824,7 +3913,7 @@ var HostTaskLedger = class {
3824
3913
  if (JSON.parse(readFileSync(this.lockFile, "utf8")).token === this.lockToken) unlinkSync(this.lockFile);
3825
3914
  } catch {}
3826
3915
  }
3827
- applyRequest(requestId, action, initiator) {
3916
+ applyRequest(requestId, action, initiator, trigger) {
3828
3917
  const fingerprint = createHash("sha256").update(JSON.stringify(action)).digest("hex");
3829
3918
  const cached = this.requestCache.get(requestId);
3830
3919
  if (cached !== void 0) {
@@ -3835,7 +3924,7 @@ var HostTaskLedger = class {
3835
3924
  while (this.requestCache.size > MAX_REQUEST_CACHE) this.requestCache.delete(this.requestCache.keys().next().value);
3836
3925
  this.syncRecentRequests();
3837
3926
  try {
3838
- return this.apply(action, initiator);
3927
+ return this.apply(action, initiator, trigger);
3839
3928
  } catch (error) {
3840
3929
  this.requestCache.delete(requestId);
3841
3930
  this.syncRecentRequests();
@@ -3843,6 +3932,25 @@ var HostTaskLedger = class {
3843
3932
  }
3844
3933
  }
3845
3934
  /**
3935
+ * Open the run one due occurrence produced, with the occurrence's own progress
3936
+ * written in the same commit.
3937
+ *
3938
+ * The occurrence is spent either way: a launch gate that hands the run to a
3939
+ * provider still consumed this trigger, so the rule's budget advances here
3940
+ * exactly as it does for a run the Host opens itself. A call that opened
3941
+ * nothing commits the progress it recorded on its own, because the fire path
3942
+ * has no other commit behind it.
3943
+ * @param task - the card whose rule fired.
3944
+ * @param triggeredAt - the instant the occurrence came due.
3945
+ * @param progress - the rule's advance, recorded atomically with the launch.
3946
+ * @returns the executions the occurrence opened.
3947
+ */
3948
+ scheduledRun(task, triggeredAt, progress) {
3949
+ const started = this.startRun(task, triggeredAt, void 0, false, progress, void 0, "schedule");
3950
+ if (!started.committed) this.commit();
3951
+ return started.runs;
3952
+ }
3953
+ /**
3846
3954
  * Open the one run a due schedule triggers: an empty array means nothing ran
3847
3955
  * (already running, a card whose elevated permission is still unconfirmed, a
3848
3956
  * one-shot whose instant was missed, or an exhausted budget), and the rule's
@@ -3873,7 +3981,7 @@ var HostTaskLedger = class {
3873
3981
  this.skipOccurrence(taskId, "permission", triggeredAt);
3874
3982
  return [];
3875
3983
  }
3876
- if (hasOpenExecution(task)) {
3984
+ if (hasOpenExecution(task) || task.status === "running") {
3877
3985
  this.skipOccurrence(taskId, "busy", triggeredAt);
3878
3986
  return [];
3879
3987
  }
@@ -3883,7 +3991,7 @@ var HostTaskLedger = class {
3883
3991
  this.skipOccurrence(taskId, "limit", triggeredAt);
3884
3992
  return [];
3885
3993
  }
3886
- if (schedule.mode === "once") return this.startRun(task, triggeredAt, void 0, false, {
3994
+ if (schedule.mode === "once") return this.scheduledRun(task, triggeredAt, {
3887
3995
  consumed: 1,
3888
3996
  lastTriggeredAt: triggeredAt,
3889
3997
  endedReason: "fired"
@@ -3899,7 +4007,7 @@ var HostTaskLedger = class {
3899
4007
  const consumed = schedule.runCount + 1;
3900
4008
  const budget = scheduleRunBudget(schedule);
3901
4009
  const spent = budget !== void 0 && consumed >= budget;
3902
- return this.startRun(task, triggeredAt, void 0, false, {
4010
+ return this.scheduledRun(task, triggeredAt, {
3903
4011
  consumed: 1,
3904
4012
  nextRunAt: spent ? void 0 : next,
3905
4013
  lastTriggeredAt: triggeredAt,
@@ -4153,9 +4261,11 @@ var HostTaskLedger = class {
4153
4261
  else this.document.tasks = [...this.document.tasks, task];
4154
4262
  this.commit();
4155
4263
  }
4156
- apply(action, initiator) {
4264
+ apply(action, initiator, trigger) {
4157
4265
  const now = this.now();
4158
4266
  let runs;
4267
+ /** Whether the run path already committed this action's write. */
4268
+ let startCommitted = false;
4159
4269
  switch (action.kind) {
4160
4270
  case "import": {
4161
4271
  const sources = new Set(this.document.scheduler.importedSources ?? []);
@@ -4316,12 +4426,14 @@ var HostTaskLedger = class {
4316
4426
  const rework = action.kind === "rework" ? this.reworkInput(task, action.instructions) : void 0;
4317
4427
  const refusal = this.bindingRefusal(task);
4318
4428
  if (refusal !== void 0) throw new Error(bindingRefusalMessage(refusal, this.sessionDefaultPermission, "run"));
4319
- runs = this.startRun(task, now, initiator, action.kind !== "run", void 0, rework);
4429
+ const started = this.startRun(task, now, initiator, action.kind !== "run", void 0, rework, action.kind === "run" ? trigger ?? "manual" : action.kind === "rerun" ? "rerun" : "manual");
4430
+ runs = started.runs;
4431
+ startCommitted = started.committed;
4320
4432
  break;
4321
4433
  }
4322
4434
  default: throw new Error(`unknown task board action kind: ${String(action.kind)}`);
4323
4435
  }
4324
- if (runs === void 0 || runs.length === 0) this.commit();
4436
+ if (runs === void 0 || !startCommitted) this.commit();
4325
4437
  return {
4326
4438
  state: this.state(),
4327
4439
  ...runs === void 0 ? {} : { runs }
@@ -4395,6 +4507,15 @@ var HostTaskLedger = class {
4395
4507
  * subagents inside this session), and the group id is what later lets the
4396
4508
  * settlement fold a HISTORICAL multi-member group it opened before this
4397
4509
  * behavior changed.
4510
+ *
4511
+ * This is also the launch gate: every entry that opens a run — the run and
4512
+ * rerun actions, a due schedule, the run tool, a rework — arrives here, which
4513
+ * makes it the only point where a provider can take a run over before an
4514
+ * execution record exists and before any session can be created. A gate that
4515
+ * answers `external` writes the running column instead of an execution and
4516
+ * nothing else: no session, no run record, no settlement. A gate that answers
4517
+ * `local` runs the card exactly as it would have, carrying the preamble the
4518
+ * provider asked for to the prompt.
4398
4519
  * @param root - the task the user ran.
4399
4520
  * @param now - clock instant (ms epoch).
4400
4521
  * @param initiator - the DSH session that asked for the run (audit only).
@@ -4404,22 +4525,45 @@ var HostTaskLedger = class {
4404
4525
  * atomic commit that opened the execution.
4405
4526
  * @param rework - the reviewer's instructions, when this run redoes previous
4406
4527
  * work; recorded on the execution it opens.
4528
+ * @param trigger - which entry asked for this run, handed to the gate.
4407
4529
  */
4408
- startRun(root, now, initiator, rerun = false, progress, rework) {
4530
+ startRun(root, now, initiator, rerun = false, progress, rework, trigger = "manual") {
4409
4531
  const before = this.document.tasks;
4410
4532
  const [participant] = cascadeTargets(before, root.id);
4411
- if (participant === void 0 || participant.archivedAt !== void 0) return [];
4412
- if (hasOpenExecution(participant)) return [];
4533
+ if (participant === void 0 || participant.archivedAt !== void 0) return {
4534
+ runs: [],
4535
+ committed: false
4536
+ };
4537
+ if (hasOpenExecution(participant)) return {
4538
+ runs: [],
4539
+ committed: false
4540
+ };
4541
+ const decision = this.launchGate?.(participant, { trigger });
4542
+ if (decision?.kind === "external") {
4543
+ let handed = before.map((task) => task.id === participant.id ? withStatus(participant, "running", now) : task);
4544
+ if (progress !== void 0) handed = applyScheduleProgress(handed, root.id, progress, now);
4545
+ this.document.tasks = [...handed];
4546
+ this.commit();
4547
+ return {
4548
+ runs: [],
4549
+ committed: true
4550
+ };
4551
+ }
4413
4552
  const groupId = crypto.randomUUID();
4414
4553
  const opened = startExecution(rerun ? withStatus(participant, "todo", now) : participant, now, crypto.randomUUID(), initiator, groupId, rework);
4415
4554
  let tasks = before.map((task) => task.id === participant.id ? opened.task : task);
4416
4555
  if (progress !== void 0) tasks = applyScheduleProgress(tasks, root.id, progress, now);
4417
4556
  this.document.tasks = [...tasks];
4418
4557
  this.commit();
4419
- return [{
4420
- task: resolveExecutionTargets(opened.task, before, this.maxSubtaskDepth),
4421
- execution: opened.execution
4422
- }];
4558
+ const preamble = decision?.kind === "local" ? decision.promptPreamble : void 0;
4559
+ return {
4560
+ runs: [{
4561
+ task: resolveExecutionTargets(opened.task, before, this.maxSubtaskDepth),
4562
+ execution: opened.execution,
4563
+ ...preamble === void 0 ? {} : { promptPreamble: preamble }
4564
+ }],
4565
+ committed: true
4566
+ };
4423
4567
  }
4424
4568
  /**
4425
4569
  * Finalize every stored run-group parent that is ready, walking from `taskId`
@@ -4815,6 +4959,29 @@ var HostTaskLedger = class {
4815
4959
  notify() {
4816
4960
  for (const listener of [...this.listeners]) listener();
4817
4961
  }
4962
+ /**
4963
+ * Move an unidentifiable, heartbeat-aged lock aside instead of deleting it:
4964
+ * the record is the only evidence of which process held the ledger, and the
4965
+ * takeover is a judgment call an operator may need to audit (issue #2061).
4966
+ * A refused rename falls back to removal, because the takeover itself must
4967
+ * not depend on the filesystem allowing the rename.
4968
+ */
4969
+ quarantineOrphanLock(pid, age) {
4970
+ const orphan = `${this.lockFile}.orphan-${this.now()}`;
4971
+ let kept = true;
4972
+ try {
4973
+ renameSync(this.lockFile, orphan);
4974
+ } catch {
4975
+ kept = false;
4976
+ try {
4977
+ unlinkSync(this.lockFile);
4978
+ } catch (unlinkError) {
4979
+ if (unlinkError.code !== "ENOENT") throw unlinkError;
4980
+ }
4981
+ }
4982
+ const seconds = Number.isFinite(age) ? `${Math.round(age / 1e3)}s` : "an unreadable age";
4983
+ this.warn(`[task-board] reclaimed the ledger lock of process ${pid}: its identity could not be probed and its heartbeat is ${seconds} old${kept ? `; the record was kept as ${orphan}` : ""}`);
4984
+ }
4818
4985
  acquireLock() {
4819
4986
  for (let attempt = 0; attempt < 2; attempt += 1) try {
4820
4987
  const fd = openSync(this.lockFile, "wx", 384);
@@ -4856,18 +5023,28 @@ var HostTaskLedger = class {
4856
5023
  }
4857
5024
  continue;
4858
5025
  }
4859
- if (pid !== void 0 && processIsAlive(pid)) {
4860
- const actualStartedAt = pid === process.pid ? ownProcessStartTimeMs() : processStartTimeMs(pid);
4861
- if (!(actualStartedAt !== void 0 && (ownerStartedAt !== void 0 ? startTimeMismatch(ownerStartedAt, actualStartedAt, ownerExact) : (() => {
5026
+ if (pid !== void 0 && this.processProbe.isAlive(pid)) {
5027
+ const actualStartedAt = pid === process.pid ? ownProcessStartTimeMs() : this.processProbe.startTimeMs(pid);
5028
+ const staleReuse = actualStartedAt !== void 0 && (ownerStartedAt !== void 0 ? startTimeMismatch(ownerStartedAt, actualStartedAt, ownerExact) : (() => {
4862
5029
  try {
4863
5030
  return statSync(this.lockFile).mtimeMs < actualStartedAt;
4864
5031
  } catch {
4865
5032
  return true;
4866
5033
  }
4867
- })()))) {
5034
+ })());
5035
+ const lockAge = (() => {
5036
+ try {
5037
+ return this.now() - statSync(this.lockFile).mtimeMs;
5038
+ } catch {
5039
+ return Number.POSITIVE_INFINITY;
5040
+ }
5041
+ })();
5042
+ const staleHeartbeat = actualStartedAt === void 0 && lockAge >= UNREADABLE_LOCK_GRACE_MS;
5043
+ if (!staleReuse && !staleHeartbeat) {
4868
5044
  const hint = ownerStartedAt !== void 0 && actualStartedAt !== void 0 && !startTimeMismatch(ownerStartedAt, actualStartedAt, ownerExact) ? "" : `; if this PID was reused after a crash and no other DSH host is running, remove ${this.lockFile} manually and retry`;
4869
5045
  throw new Error(`task-board ledger is already owned by process ${pid}${hint}`, { cause: error });
4870
5046
  }
5047
+ if (staleHeartbeat && !staleReuse) this.quarantineOrphanLock(pid, lockAge);
4871
5048
  }
4872
5049
  try {
4873
5050
  unlinkSync(this.lockFile);
@@ -5560,6 +5737,7 @@ function promptText(task, context = {}) {
5560
5737
  const handover = task.handover;
5561
5738
  const handoverPreamble = handover === void 0 || handover.references.length === 0 ? void 0 : `交接包引用(来自任务看板续接卡片,冻结于 ${new Date(handover.bundledAt).toISOString()}):\n${handover.references.map((reference) => `- ${reference}`).join("\n")}`;
5562
5739
  const preambles = [
5740
+ launchPromptPreamble(context),
5563
5741
  tagPromptPreamble(task),
5564
5742
  context.files === void 0 ? void 0 : attachmentPromptPreamble(context.files),
5565
5743
  handoverPreamble,
@@ -5575,6 +5753,21 @@ function promptText(task, context = {}) {
5575
5753
  return preamble === void 0 ? declaration : `${preamble}\n\n${declaration}`;
5576
5754
  }
5577
5755
  /**
5756
+ * Build the launch-gate section of the execution prompt.
5757
+ *
5758
+ * A provider that answered `local` keeps the board's own execution and only
5759
+ * adds context for it, so its text is a preamble like the tag prompts: same
5760
+ * injection path, same placement rules, and the same delimiter neutralization —
5761
+ * a preamble a provider composed from card text can therefore not counterfeit
5762
+ * the freeze wrap either. A blank preamble yields undefined and the prompt is
5763
+ * exactly what an unintercepted run produces.
5764
+ */
5765
+ function launchPromptPreamble(context) {
5766
+ const preamble = context.launchPreamble?.trim();
5767
+ if (preamble === void 0 || preamble === "") return void 0;
5768
+ return escapeProvenanceDelimiter(preamble);
5769
+ }
5770
+ /**
5578
5771
  * Build the tag section of the execution prompt (issue #1521). Only tags with
5579
5772
  * a non-blank `promptPrefix` contribute; a task whose tags are all bare names
5580
5773
  * (or which has no tags at all) yields undefined and the prompt is byte-for-byte
@@ -6526,6 +6719,42 @@ function extensionText(value, what) {
6526
6719
  return text;
6527
6720
  }
6528
6721
  /**
6722
+ * Read one handler answer as a launch decision.
6723
+ *
6724
+ * A handler is provider code reached synchronously from the launch path, so its
6725
+ * return value is judged here instead of trusted: anything the board cannot act
6726
+ * on is reported and treated as "not mine", exactly like a throw. A local
6727
+ * decision with a blank preamble is normalized to no preamble, so a provider
6728
+ * that answers local to take no visible part changes nothing at all.
6729
+ * @param answer - what the handler returned.
6730
+ * @param warn - sink for a refusal the provider can read.
6731
+ * @returns the decision to act on, or undefined.
6732
+ */
6733
+ function launchDecision(answer, warn) {
6734
+ if (answer === void 0) return void 0;
6735
+ if (typeof answer !== "object" || answer === null) {
6736
+ warn("returned a non-object decision");
6737
+ return;
6738
+ }
6739
+ const kind = answer.kind;
6740
+ if (kind === "external") return { kind: "external" };
6741
+ if (kind !== "local") {
6742
+ warn("returned an unknown decision kind");
6743
+ return;
6744
+ }
6745
+ const preamble = answer.promptPreamble;
6746
+ if (preamble === void 0) return { kind: "local" };
6747
+ if (typeof preamble !== "string") {
6748
+ warn("returned a non-string promptPreamble");
6749
+ return;
6750
+ }
6751
+ const trimmed = preamble.trim();
6752
+ return trimmed === "" ? { kind: "local" } : {
6753
+ kind: "local",
6754
+ promptPreamble: trimmed
6755
+ };
6756
+ }
6757
+ /**
6529
6758
  * The session a follow-up message goes to, or the refusal that says why there
6530
6759
  * is none. The open execution owns the answer while one is running: delivering
6531
6760
  * into the previous conversation instead would answer a question the current
@@ -6557,6 +6786,8 @@ var TaskBoardExtensionRegistry = class {
6557
6786
  uuid;
6558
6787
  logger;
6559
6788
  toolResolver;
6789
+ onPublished;
6790
+ publishedVersionCounter = 0;
6560
6791
  /** Board master switch (enabled config); providers start only while it is on. */
6561
6792
  boardEnabled = true;
6562
6793
  disposed = false;
@@ -6569,6 +6800,11 @@ var TaskBoardExtensionRegistry = class {
6569
6800
  this.uuid = options.uuid ?? (() => crypto.randomUUID());
6570
6801
  this.logger = options.logger ?? DEFAULT_LOGGER;
6571
6802
  this.toolResolver = options.toolRegistry;
6803
+ this.onPublished = options.onPublished;
6804
+ }
6805
+ /** Monotonic revision of the published extension summaries map. */
6806
+ get publishedRevision() {
6807
+ return this.publishedVersionCounter;
6572
6808
  }
6573
6809
  /**
6574
6810
  * Pin (or replace) the deployment's tool registry. A registry that appears
@@ -6617,7 +6853,8 @@ var TaskBoardExtensionRegistry = class {
6617
6853
  extension,
6618
6854
  active: false,
6619
6855
  subscriptions: emptySubscriptions(),
6620
- tools: []
6856
+ tools: [],
6857
+ launchHandlers: /* @__PURE__ */ new Set()
6621
6858
  };
6622
6859
  this.entries.set(extension.id, entry);
6623
6860
  this.reconcile(entry);
@@ -6644,6 +6881,40 @@ var TaskBoardExtensionRegistry = class {
6644
6881
  if (typeof handler !== "function") throw new TaskBoardExtensionError("unsupported-action", `extension "${request.extensionId}" handles no actions`);
6645
6882
  return await handler.call(entry.extension, request);
6646
6883
  }
6884
+ /**
6885
+ * The board's single launch gate: ask every running provider whether this run
6886
+ * is theirs.
6887
+ *
6888
+ * Consulted by the ledger at the one point every trigger passes — before a
6889
+ * session exists and before an execution record is written — so the order
6890
+ * here is the only ordering a provider can observe: registration order, first
6891
+ * decision wins. A handler that throws is isolated and treated as "not mine",
6892
+ * exactly as if it had answered undefined, because a provider's bug must cost
6893
+ * its own interception and never the launch. Without a registered handler
6894
+ * this answers nothing at all and the launch path is untouched.
6895
+ * @param task - the card about to run.
6896
+ * @param context - which entry asked for this run.
6897
+ * @returns the first decision a running provider made, or undefined.
6898
+ */
6899
+ interceptLaunch(task, context) {
6900
+ if (this.disposed) return void 0;
6901
+ for (const entry of this.entries.values()) {
6902
+ if (!entry.active) continue;
6903
+ for (const handler of [...entry.launchHandlers]) {
6904
+ let answer;
6905
+ try {
6906
+ answer = handler(task, context);
6907
+ } catch (error) {
6908
+ this.logger.error(`[dsh-task-board] extension "${entry.extension.id}" launch handler failed; the launch proceeds unhandled`, error);
6909
+ continue;
6910
+ }
6911
+ const decision = launchDecision(answer, (message) => {
6912
+ this.logger.warn(`[dsh-task-board] extension "${entry.extension.id}" launch handler ${message}; the launch proceeds unhandled`);
6913
+ });
6914
+ if (decision !== void 0) return decision;
6915
+ }
6916
+ }
6917
+ }
6647
6918
  /** Published summaries of currently running providers, keyed by extension id. */
6648
6919
  published() {
6649
6920
  const result = {};
@@ -6701,6 +6972,7 @@ var TaskBoardExtensionRegistry = class {
6701
6972
  this.syncTools(entry);
6702
6973
  }
6703
6974
  stopEntry(entry) {
6975
+ const hadPublished = entry.published !== void 0;
6704
6976
  if (entry.active) {
6705
6977
  entry.active = false;
6706
6978
  for (const kind of Object.keys(entry.subscriptions)) entry.subscriptions[kind].clear();
@@ -6710,8 +6982,14 @@ var TaskBoardExtensionRegistry = class {
6710
6982
  this.logger.error(`[dsh-task-board] extension "${entry.extension.id}" stop() failed`, error);
6711
6983
  }
6712
6984
  }
6985
+ entry.published = void 0;
6713
6986
  this.disposeTools(entry);
6714
6987
  entry.tools.length = 0;
6988
+ entry.launchHandlers.clear();
6989
+ if (hadPublished) {
6990
+ this.publishedVersionCounter += 1;
6991
+ if (!this.disposed) this.onPublished?.();
6992
+ }
6715
6993
  }
6716
6994
  /** (Re)register every buffered tool against the current tool registry. */
6717
6995
  syncTools(entry) {
@@ -6776,6 +7054,10 @@ var TaskBoardExtensionRegistry = class {
6776
7054
  sessions: { followUp: async (taskId, text) => {
6777
7055
  await this.followUp(entry, taskId, text);
6778
7056
  } },
7057
+ launch: { intercept: (handler) => {
7058
+ assertActive("intercept a launch");
7059
+ return this.addLaunchHandler(entry, handler);
7060
+ } },
6779
7061
  integration: {
6780
7062
  read: (taskId) => {
6781
7063
  assertActive("read");
@@ -6935,6 +7217,20 @@ var TaskBoardExtensionRegistry = class {
6935
7217
  this.assertActive(entry, "publish a summary");
6936
7218
  if (!isTaskBoardExtensionPayload(summary)) throw new TaskBoardExtensionError("invalid-payload", "published summary must be a pure JSON object within the size limit");
6937
7219
  entry.published = summary;
7220
+ this.publishedVersionCounter += 1;
7221
+ this.onPublished?.();
7222
+ }
7223
+ /**
7224
+ * Hold one launch handler for a running provider. The handler is dropped when
7225
+ * the provider stops or is unregistered, so the disposer only has to cover the
7226
+ * provider's own early withdrawal.
7227
+ */
7228
+ addLaunchHandler(entry, handler) {
7229
+ if (typeof handler !== "function") throw new TaskBoardExtensionError("invalid-handler", "a launch handler must be a function");
7230
+ entry.launchHandlers.add(handler);
7231
+ return () => {
7232
+ entry.launchHandlers.delete(handler);
7233
+ };
6938
7234
  }
6939
7235
  registerTool(entry, definition) {
6940
7236
  const tool = { definition };
@@ -6986,11 +7282,21 @@ const UNREADABLE_SETTLE_POLLS = 24;
6986
7282
  const ABANDONED_LAUNCH_REASON = "host stopped before this execution started";
6987
7283
  /**
6988
7284
  * Why a rework could not launch: it redoes work in the card's own
6989
- * conversation, so a session the Host cannot continue means there is nothing to
6990
- * send the reviewer's instructions into. Starting a fresh conversation instead
6991
- * would hand those instructions to an agent that never saw the work.
7285
+ * conversation, so a session the Host cannot confirm as reachable means there is
7286
+ * nothing to send the reviewer's instructions into. Starting a fresh
7287
+ * conversation instead would hand those instructions to an agent that never saw
7288
+ * the work. "Could not be confirmed" also covers an unreadable roster, which is
7289
+ * neither "idle" nor "gone".
6992
7290
  */
6993
- const REWORK_SESSION_REASON = "rework: the card's previous execution session is not present and idle in the host session roster, so there is no conversation to send the rework instructions into";
7291
+ const REWORK_SESSION_REASON = "rework: the card's previous execution session could not be confirmed as present and idle in the host session roster, so there is no conversation to send the rework instructions into";
7292
+ /**
7293
+ * Why a rework could not launch into an archived conversation (issue #2068).
7294
+ * The session still exists, so the generic reason would misdirect: the operator
7295
+ * has to unarchive that conversation before the rework can be sent into it.
7296
+ * @param sessionId - the archived conversation the rework addressed.
7297
+ * @returns the refusal the operator reads on the card.
7298
+ */
7299
+ const reworkArchivedReason = (sessionId) => "rework: the card's previous execution session " + sessionId + " is archived, so the Host will not run a turn in it; unarchive that session and start the rework again";
6994
7300
  /**
6995
7301
  * Actions that can change the instant the schedule timer is armed at. Only
6996
7302
  * these re-arm the native timer; an unrelated card edit leaves the pending fire
@@ -7184,8 +7490,13 @@ var TaskBoardHostService = class {
7184
7490
  instructions
7185
7491
  }, initiator);
7186
7492
  },
7187
- now: this.now
7493
+ now: this.now,
7494
+ onPublished: () => {
7495
+ this.emit();
7496
+ },
7497
+ ...options.extensionLogger === void 0 ? {} : { logger: options.extensionLogger }
7188
7498
  });
7499
+ this.ledger.setLaunchGate((task, context) => this.extensions.interceptLaunch(task, context));
7189
7500
  installStreamErrorGuards();
7190
7501
  this.ledger.subscribe(() => {
7191
7502
  this.syncPowerReasons();
@@ -7270,7 +7581,8 @@ var TaskBoardHostService = class {
7270
7581
  maxSubtaskDepth: this.ledger.maxSubtaskDepth,
7271
7582
  ...cardDefaults === void 0 ? {} : { cardDefaults },
7272
7583
  ...this.attachmentStore() === void 0 ? {} : { attachmentLimits: publishedAttachmentLimits(this.attachmentStore()) },
7273
- ...Object.keys(published).length === 0 ? {} : { extensions: published }
7584
+ ...Object.keys(published).length === 0 ? {} : { extensions: published },
7585
+ extensionsRevision: this.extensions.publishedRevision
7274
7586
  });
7275
7587
  }
7276
7588
  /**
@@ -7293,6 +7605,7 @@ var TaskBoardHostService = class {
7293
7605
  const { revision, scheduler } = this.ledger.summary();
7294
7606
  return {
7295
7607
  revision,
7608
+ extensionsRevision: this.extensions.publishedRevision,
7296
7609
  scheduler,
7297
7610
  power: this.power.snapshot()
7298
7611
  };
@@ -7365,23 +7678,23 @@ var TaskBoardHostService = class {
7365
7678
  if (store === void 0) throw new Error("this deployment serves no attachment storage");
7366
7679
  await verifyAttachments(store, attachments);
7367
7680
  }
7368
- apply(requestId, action, initiator) {
7681
+ apply(requestId, action, initiator, trigger) {
7369
7682
  if (!this.active) throw new Error("task board is disabled");
7370
7683
  const kind = action?.kind;
7371
7684
  if (typeof kind !== "string" || !Object.hasOwn(ACTION_KINDS, kind)) throw new Error(`unknown task board action kind: ${String(kind)}`);
7372
7685
  if (action.kind === "extension-action") return this.handleExtensionAction(action);
7373
- return projectSnapshotForWire(this.applyBoardAction(requestId, action, initiator));
7686
+ return projectSnapshotForWire(this.applyBoardAction(requestId, action, initiator, false, trigger));
7374
7687
  }
7375
7688
  /**
7376
7689
  * Apply one board-owned action with every gate intact. Provider capability
7377
7690
  * calls and the same-origin wire both land here, so the two surfaces can
7378
7691
  * never disagree about a card.
7379
7692
  */
7380
- applyBoardAction(requestId, action, initiator, attachmentVerified = false) {
7693
+ applyBoardAction(requestId, action, initiator, attachmentVerified = false, trigger) {
7381
7694
  if (!attachmentVerified && attachmentsOfAction(action) !== void 0) throw new Error("attachments must be applied through the verified attachment action route");
7382
7695
  const before = this.statusMap();
7383
7696
  if (action.kind === "run" || action.kind === "rerun" || action.kind === "rework") this.assertSpendCap();
7384
- const result = this.ledger.applyRequest(requestId, this.withInheritedWorkspace(action, initiator), initiator);
7697
+ const result = this.ledger.applyRequest(requestId, this.withInheritedWorkspace(action, initiator), initiator, trigger);
7385
7698
  if (result.runs !== void 0) this.dispatchRuns(result.runs);
7386
7699
  if (SCHEDULE_WRITE_ACTIONS.has(action.kind)) this.refreshSchedule();
7387
7700
  this.emitStatusChanges(before, initiator);
@@ -7414,12 +7727,16 @@ var TaskBoardHostService = class {
7414
7727
  }
7415
7728
  /** Route one provider action and answer the resulting board snapshot. */
7416
7729
  async handleExtensionAction(action) {
7417
- await this.extensions.handleAction({
7730
+ const answer = await this.extensions.handleAction({
7418
7731
  extensionId: action.extensionId,
7419
7732
  action: action.action,
7420
7733
  ...action.taskId === void 0 ? {} : { taskId: action.taskId },
7421
7734
  ...action.payload === void 0 ? {} : { payload: action.payload }
7422
7735
  });
7736
+ if (typeof answer === "object" && answer !== null && answer.ok === false) {
7737
+ const reason = answer.error;
7738
+ throw new Error(typeof reason === "string" && reason.trim() !== "" ? reason : `extension "${action.extensionId}" refused action "${action.action}"`);
7739
+ }
7423
7740
  return this.snapshot();
7424
7741
  }
7425
7742
  /** Current task id -> status map, for change detection around a mutation. */
@@ -7466,6 +7783,7 @@ var TaskBoardHostService = class {
7466
7783
  reuseSessionId = await this.reworkSessionFor(opened.task);
7467
7784
  }
7468
7785
  const contextParts = {
7786
+ ...opened.promptPreamble === void 0 ? {} : { launchPreamble: opened.promptPreamble },
7469
7787
  ...descendants.length === 0 ? {} : { descendants: descendants.map((descendant) => ({
7470
7788
  id: descendant.id,
7471
7789
  title: descendant.title,
@@ -7569,30 +7887,90 @@ var TaskBoardHostService = class {
7569
7887
  /**
7570
7888
  * The session a run may continue in, for a card that opted into reuse
7571
7889
  * (issue #1419). Reuse requires positive evidence that the previous session
7572
- * is present and idle, and that evidence must be read for THIS launch: an
7573
- * idle board no longer polls, so a roster cached from an earlier pass could
7574
- * be hours old — either refusing a session that has been idle all along, or
7575
- * prompting into one that started running since. A card that did not opt in
7576
- * reads no roster at all, and a read that fails mints a fresh conversation
7577
- * exactly as an unknown roster always did.
7890
+ * is present, idle, and not archived, and that evidence must be read for THIS
7891
+ * launch: an idle board no longer polls, so a roster cached from an earlier
7892
+ * pass could be hours old — either refusing a session that has been idle all
7893
+ * along, or prompting into one that started running since. A card that did not
7894
+ * opt in reads no roster at all, and a read that fails mints a fresh
7895
+ * conversation exactly as an unknown roster always did.
7578
7896
  * @param task - the task about to run.
7579
- * @param force - continue the settled session regardless of the card's own
7580
- * opt-in (a rework), which the reuse rule accepts without waiving any of its
7581
- * evidence conditions.
7582
7897
  * @returns the session id to continue in, or undefined for a fresh session.
7583
7898
  */
7584
- async reuseSessionFor(task, force) {
7585
- if (task.reuseSession !== true && force !== true) return void 0;
7899
+ async reuseSessionFor(task) {
7900
+ if (task.reuseSession !== true) return void 0;
7901
+ const decision = await this.reuseDecision(task, false);
7902
+ if (decision.sessionId !== void 0) return decision.sessionId;
7903
+ if (decision.archivedSessionId !== void 0) safeConsoleWarn(`[dsh-task-board] session reuse skipped for task ${task.id}: session ${decision.archivedSessionId} is archived, starting a fresh conversation`);
7904
+ }
7905
+ /**
7906
+ * One reuse decision for this launch: the session to continue in, or nothing
7907
+ * plus the reason nothing was chosen, so each caller can report it.
7908
+ *
7909
+ * Reuse never targets a session in the Workspace registry's archive set
7910
+ * (issue #2068). The Host's archived-session gate rejects the first step of a
7911
+ * turn in an archived session before any model request is issued, so the
7912
+ * run would settle as the opaque failure `agent turn ended without
7913
+ * completing: blocked` — the fate of every scheduled run of a card whose
7914
+ * conversation the user archived while cleaning the sidebar. Starting a fresh
7915
+ * conversation is the only safe answer: archiving is a live user decision,
7916
+ * and the board must not unarchive a conversation behind the user's back to
7917
+ * keep reusing it.
7918
+ * @param task - the task about to run.
7919
+ * @param force - reuse without the card's own opt-in (a rework).
7920
+ * @returns the reuse decision for this launch.
7921
+ */
7922
+ async reuseDecision(task, force) {
7586
7923
  let running;
7587
7924
  try {
7588
7925
  running = await this.runner.listRunning();
7589
7926
  } catch (error) {
7590
7927
  this.notePollFailure();
7591
- safeConsoleError("[dsh-task-board] session roster read for session reuse failed; starting a fresh session", error);
7928
+ safeConsoleError("[dsh-task-board] the session reuse probe failed; reuse is skipped for this launch", error);
7929
+ return {};
7930
+ }
7931
+ if (!running.known) return {};
7932
+ const archived = this.archivedSessionIds();
7933
+ const sessionId = reusableSessionId(task, new Set(running.items.filter((item) => !item.running).map((item) => item.sessionId)), {
7934
+ ...force ? { force: true } : {},
7935
+ ...archived === void 0 ? {} : { archivedSessionIds: archived }
7936
+ });
7937
+ if (sessionId !== void 0) return { sessionId };
7938
+ const archivedSessionId = this.archivedReuseTarget(task, archived);
7939
+ return archivedSessionId === void 0 ? {} : { archivedSessionId };
7940
+ }
7941
+ /**
7942
+ * The archived conversation the reuse rule refused, when it refused one.
7943
+ *
7944
+ * Reuse skipping an archived conversation is otherwise invisible: the board
7945
+ * simply opens a new one, and only the caller knows which outcome it produced.
7946
+ * @param task - the task about to run.
7947
+ * @param archived - the archive set read for this launch, when reported.
7948
+ * @returns the newest settled session id when it is archived, else undefined.
7949
+ */
7950
+ archivedReuseTarget(task, archived) {
7951
+ if (archived === void 0) return void 0;
7952
+ const newest = newestSettledSessionId(task);
7953
+ return newest !== void 0 && archived.has(newest) ? newest : void 0;
7954
+ }
7955
+ /**
7956
+ * The Workspace registry's archive set, or undefined when this deployment's
7957
+ * registry face cannot report one. An unreportable set is unknown evidence,
7958
+ * never proof that nothing is archived: the rule then keeps its pre-archive
7959
+ * behavior instead of inventing a refusal, because a registry face without
7960
+ * the getter serves no archive action for the board to defend against.
7961
+ *
7962
+ * Read per launch rather than cached: archiving is a live user action, and an
7963
+ * idle board no longer polls, so a set kept from an earlier pass could already
7964
+ * claim a session that the user archived a moment ago.
7965
+ * @returns the archived session ids, or undefined when unreportable.
7966
+ */
7967
+ archivedSessionIds() {
7968
+ try {
7969
+ const archived = this.workspaceRegistry?.archivedSessionIds;
7970
+ return archived === void 0 ? void 0 : new Set(archived);
7971
+ } catch {
7592
7972
  return;
7593
7973
  }
7594
- if (!running.known) return void 0;
7595
- return reusableSessionId(task, new Set(running.items.filter((item) => !item.running).map((item) => item.sessionId)), force === true ? { force: true } : {});
7596
7974
  }
7597
7975
  /**
7598
7976
  * The session a rework continues, or the refusal that says why it cannot.
@@ -7607,9 +7985,9 @@ var TaskBoardHostService = class {
7607
7985
  * @returns the session id this rework continues in.
7608
7986
  */
7609
7987
  async reworkSessionFor(task) {
7610
- const sessionId = await this.reuseSessionFor(task, true);
7611
- if (sessionId === void 0) throw new Error(REWORK_SESSION_REASON);
7612
- return sessionId;
7988
+ const decision = await this.reuseDecision(task, true);
7989
+ if (decision.sessionId !== void 0) return decision.sessionId;
7990
+ throw new Error(decision.archivedSessionId === void 0 ? REWORK_SESSION_REASON : reworkArchivedReason(decision.archivedSessionId));
7613
7991
  }
7614
7992
  /** Reuse the session list this poll already fetched: one list RPC per tick, not 1 + E. */
7615
7993
  async reconcileExecutions(sessions, executions) {
@@ -7875,6 +8253,15 @@ function safeConsoleError(message, ...args) {
7875
8253
  console.error(message, ...args);
7876
8254
  } catch {}
7877
8255
  }
8256
+ /**
8257
+ * Defensively log to console.warn, for a diagnostic that must never turn a
8258
+ * launch decision into a failed run when the stderr write itself fails.
8259
+ */
8260
+ function safeConsoleWarn(message, ...args) {
8261
+ try {
8262
+ console.warn(message, ...args);
8263
+ } catch {}
8264
+ }
7878
8265
  //#endregion
7879
8266
  //#region src/host/llm-dispatch.ts
7880
8267
  /**
@@ -8358,7 +8745,7 @@ function buildRunTool(host) {
8358
8745
  const snapshot = await host.apply(crypto.randomUUID(), {
8359
8746
  kind: args.rerun === true ? "rerun" : "run",
8360
8747
  taskId: args.taskId
8361
- }, callingSessionId(exec));
8748
+ }, callingSessionId(exec), "tool");
8362
8749
  const beforeById = new Map(before.tasks.map((task) => [task.id, task]));
8363
8750
  const started = snapshot.tasks.flatMap((task) => {
8364
8751
  return openedExecutions(beforeById.get(task.id)?.executions ?? [], task.executions).map((execution) => ({
@@ -9279,7 +9666,12 @@ function matchesToken(candidate, expected) {
9279
9666
  */
9280
9667
  function isTrustedTaskBoardRequest(req, access) {
9281
9668
  const connection = access.connection?.();
9282
- if (connection !== void 0 && connection.requestRejection(req) === void 0) return true;
9669
+ if (connection !== void 0) try {
9670
+ if (typeof connection.admit === "function") {
9671
+ const admission = connection.admit(req);
9672
+ if (admission.rejection === void 0 && "peer" in admission && admission.peer !== void 0) return true;
9673
+ } else if (typeof connection.requestRejection === "function" && connection.requestRejection(req) === void 0) return true;
9674
+ } catch {}
9283
9675
  if (!browserSameOriginMarker(req)) return false;
9284
9676
  if (isLoopbackRequest(req)) return true;
9285
9677
  if (access.trustForwardedProxy() && req.headers["sec-fetch-site"] !== "cross-site" && isForwardedLoopbackRequest(req)) return true;
@@ -9605,7 +9997,10 @@ function makeTaskBoardRoutes(service, access = {}, options = {}) {
9605
9997
  }
9606
9998
  }
9607
9999
  }
9608
- ];
10000
+ ].map((route) => ({
10001
+ ...route,
10002
+ auth: "anonymous"
10003
+ }));
9609
10004
  }
9610
10005
  //#endregion
9611
10006
  //#region src/mount-once.ts
@@ -9888,7 +10283,8 @@ const DEFAULT_TRUST_FORWARDED_PROXY = false;
9888
10283
  function resolveConnectionTrust(ctx) {
9889
10284
  try {
9890
10285
  const connection = ctx.get("connection");
9891
- return connection !== void 0 && typeof connection.requestRejection === "function" ? connection : void 0;
10286
+ if (connection === void 0 || connection === null) return void 0;
10287
+ return typeof connection.admit === "function" || typeof connection.requestRejection === "function" ? connection : void 0;
9892
10288
  } catch {
9893
10289
  return;
9894
10290
  }
@@ -10192,12 +10588,34 @@ function applyImpl(ctx, config) {
10192
10588
  disposeTools = void 0;
10193
10589
  };
10194
10590
  });
10591
+ /**
10592
+ * The connection service captured in a scope that injects BOTH `connection`
10593
+ * and `connection.authentication`. Post-#8266 hosts answer the peer-auth
10594
+ * fence through `connection.admit(request)`, and that method reads
10595
+ * `connection.authentication` through the CALLING context: a bare
10596
+ * `ctx.get('connection')` from this row throws "cannot get property
10597
+ * \"connection.authentication\" without inject", which escaped every route
10598
+ * handler as a bare 400. The scope keeps the row's own inject list unchanged
10599
+ * (the service stays optional: a deployment without it keeps the loopback
10600
+ * fence), and a cohort whose connection has no authentication sub-service
10601
+ * simply never activates this scope, leaving the `requestRejection` bridge.
10602
+ */
10603
+ let admittedConnection;
10604
+ const scopedInjectConnection = ctx.inject;
10605
+ if (typeof scopedInjectConnection === "function") scopedInjectConnection.call(ctx, ["connection", "connection.authentication"], (scoped) => {
10606
+ scoped.effect(() => {
10607
+ admittedConnection = resolveConnectionTrust(scoped);
10608
+ return () => {
10609
+ admittedConnection = void 0;
10610
+ };
10611
+ }, "task-board: connection trust");
10612
+ });
10195
10613
  ctx.effect(() => {
10196
10614
  const disposers = [];
10197
10615
  try {
10198
10616
  const routes = makeTaskBoardRoutes(host, {
10199
10617
  ...resolveProxyAccess(config),
10200
- connection: () => resolveConnectionTrust(ctx)
10618
+ connection: () => admittedConnection ?? resolveConnectionTrust(ctx)
10201
10619
  }, {
10202
10620
  attachments: () => resolveAttachmentStore(ctx),
10203
10621
  parseTask: async (request, signal) => {