@linxin666/dsh-client-ui-task-board 0.4.6 → 0.4.8

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 (73) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +15 -6
  3. package/README.zh.md +15 -6
  4. package/lib/client.js +1634 -822
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +1072 -125
  7. package/lib/types/client/CardDefaultPresetField.d.ts +35 -0
  8. package/lib/types/client/PluginSettingsCard.d.ts +39 -0
  9. package/lib/types/client/TaskBoardSettingsCard.d.ts +56 -0
  10. package/lib/types/client/board/ReasoningEffortField.d.ts +25 -0
  11. package/lib/types/client/board/model-options.d.ts +67 -0
  12. package/lib/types/client/board/preset-label.d.ts +21 -0
  13. package/lib/types/client/board/preset-roster.d.ts +45 -0
  14. package/lib/types/client/board/team-run-promotion.d.ts +26 -0
  15. package/lib/types/client/locales.d.ts +18 -0
  16. package/lib/types/client/telemetry.d.ts +14 -2
  17. package/lib/types/core/card-defaults.d.ts +78 -0
  18. package/lib/types/core/controller.d.ts +32 -7
  19. package/lib/types/core/execution-summary.d.ts +52 -0
  20. package/lib/types/core/extension.d.ts +34 -0
  21. package/lib/types/core/launch-width.d.ts +31 -0
  22. package/lib/types/core/reasoning-effort.d.ts +57 -0
  23. package/lib/types/core/spend-budget.d.ts +28 -0
  24. package/lib/types/core/subtask.d.ts +30 -8
  25. package/lib/types/core/tasks.d.ts +51 -1
  26. package/lib/types/core/use-cases/task-create.d.ts +10 -5
  27. package/lib/types/core/use-cases/task-update.d.ts +1 -1
  28. package/lib/types/host/launch-admission.d.ts +72 -0
  29. package/lib/types/host-ledger.d.ts +33 -6
  30. package/lib/types/host-runner.d.ts +83 -5
  31. package/lib/types/host-service.d.ts +116 -2
  32. package/lib/types/host-spend.d.ts +52 -0
  33. package/lib/types/index.d.ts +98 -0
  34. package/lib/types/loopback.d.ts +20 -1
  35. package/lib/types/protocol.d.ts +13 -0
  36. package/package.json +28 -28
  37. package/src/client/CardDefaultPresetField.tsx +101 -0
  38. package/src/client/PluginSettingsCard.tsx +63 -3
  39. package/src/client/TaskBoardSettingsCard.tsx +251 -16
  40. package/src/client/board/LinkSubtaskModal.tsx +8 -0
  41. package/src/client/board/NewTaskModal.tsx +86 -40
  42. package/src/client/board/ReasoningEffortField.tsx +50 -0
  43. package/src/client/board/TaskDetail.tsx +42 -6
  44. package/src/client/board/model-options.ts +178 -0
  45. package/src/client/board/preset-label.ts +32 -0
  46. package/src/client/board/preset-roster.ts +58 -0
  47. package/src/client/board/team-run-promotion.ts +39 -0
  48. package/src/client/index.ts +98 -94
  49. package/src/client/locales.ts +38 -2
  50. package/src/client/settings-card.module.css +70 -1
  51. package/src/client/settings-entry-form.ts +0 -1
  52. package/src/client/telemetry.ts +47 -2
  53. package/src/core/card-defaults.ts +132 -0
  54. package/src/core/controller.ts +44 -9
  55. package/src/core/execution-summary.ts +96 -0
  56. package/src/core/extension.ts +34 -0
  57. package/src/core/launch-width.ts +38 -0
  58. package/src/core/reasoning-effort.ts +92 -0
  59. package/src/core/spend-budget.ts +35 -0
  60. package/src/core/store.ts +9 -0
  61. package/src/core/subtask.ts +48 -13
  62. package/src/core/tasks.ts +63 -1
  63. package/src/core/use-cases/task-create.ts +27 -16
  64. package/src/core/use-cases/task-update.ts +6 -1
  65. package/src/host/agent-tools.ts +21 -8
  66. package/src/host/launch-admission.ts +140 -0
  67. package/src/host-ledger.ts +80 -10
  68. package/src/host-runner.ts +199 -25
  69. package/src/host-service.ts +340 -27
  70. package/src/host-spend.ts +105 -0
  71. package/src/index.ts +182 -2
  72. package/src/loopback.ts +25 -1
  73. package/src/protocol.ts +28 -4
package/lib/index.js CHANGED
@@ -1,13 +1,183 @@
1
1
  import z from "@deepseek-ai/schemastery";
2
- import { spawn, spawnSync } from "node:child_process";
3
- import { createHash, timingSafeEqual } from "node:crypto";
4
2
  import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
5
3
  import { dirname, isAbsolute, join, win32 } from "node:path";
6
4
  import { homedir } from "node:os";
7
5
  import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
6
+ import { spawn, spawnSync } from "node:child_process";
7
+ import { createHash, timingSafeEqual } from "node:crypto";
8
+ import { Context } from "@deepseek-ai/cordis";
8
9
  import { ReasoningEffortId, createUserMessage } from "@deepseek-ai/dsh-llm";
9
10
  import { defineTool } from "@deepseek-ai/dsh-tools";
10
11
  /**
12
+ * Clamp a configured width into the supported range. A value the schema would
13
+ * refuse (non-finite, below the floor, above the ceiling) still leaves the
14
+ * board launching: an out-of-range setting never stalls a run.
15
+ * @param width - configured width, or undefined for the default.
16
+ * @returns the effective width.
17
+ */
18
+ function normalizeRunLaunchWidth(width) {
19
+ if (width === void 0 || !Number.isFinite(width)) return 3;
20
+ return Math.min(Math.max(Math.trunc(width), 1), 16);
21
+ }
22
+ //#endregion
23
+ //#region src/core/spend-budget.ts
24
+ /**
25
+ * Whether a day's measured spend already reached the cap.
26
+ * @param usedTokens - tokens the day's spend measurement reported.
27
+ * @param cap - the configured cap, 0 for "no gate".
28
+ * @returns true when a run must be refused.
29
+ */
30
+ function spendCapReached(usedTokens, cap) {
31
+ return cap > 0 && usedTokens >= cap;
32
+ }
33
+ /**
34
+ * The refusal text both gates report: the thrown message a client sees as
35
+ * board-refused, and the scheduler error a due occurrence records.
36
+ * @param usedTokens - tokens the day's spend measurement reported.
37
+ * @param cap - the configured cap.
38
+ * @returns the refusal message.
39
+ */
40
+ function spendCapMessage(usedTokens, cap) {
41
+ return `spend cap reached: ${usedTokens} tokens of ${cap} today; raise the cap in the task board settings`;
42
+ }
43
+ //#endregion
44
+ //#region src/dsh-home.ts
45
+ /**
46
+ * DSH_HOME resolution shared by the plugin family's Host halves: the
47
+ * environment override wins, the platform home fallback follows. Mirrors
48
+ * what dsh-pet and dsh-liangshen each used to implement locally.
49
+ */
50
+ /** Expand a leading ~ (or ~user) in a path, platform-style. */
51
+ function expandHome(path, home = homedir()) {
52
+ const j = home.startsWith("/") ? join$1 : join;
53
+ if (path === "~") return home;
54
+ if (path.startsWith("~/") || path.startsWith("~\\")) return j(home, path.slice(2));
55
+ return path;
56
+ }
57
+ /**
58
+ * Resolve the DSH home directory.
59
+ * @param env - process environment to read DSH_HOME from.
60
+ * @param home - platform home directory fallback (test seam).
61
+ * @returns the absolute DSH home path.
62
+ */
63
+ function resolveDshHome(env = process.env, home = homedir()) {
64
+ const isPosix = home.startsWith("/");
65
+ const j = isPosix ? join$1 : join;
66
+ const isAbs = isPosix ? isAbsolute$1 : isAbsolute;
67
+ const raw = env.DSH_HOME;
68
+ if (raw !== void 0 && raw.trim() !== "") {
69
+ const expanded = expandHome(raw.trim(), home);
70
+ return isAbs(expanded) ? expanded : j(process.cwd(), expanded);
71
+ }
72
+ return j(home, ".dsh");
73
+ }
74
+ /** Resolve the DSH home directory from the live environment. */
75
+ function dshHome() {
76
+ return resolveDshHome();
77
+ }
78
+ //#endregion
79
+ //#region src/host-spend.ts
80
+ /**
81
+ * Today's measured spend, read from the usage ledger this deployment keeps at
82
+ * `$DSH_HOME/dsh-usage/usage-ledger.json`.
83
+ *
84
+ * The measure is the family usage ledger rather than a counter this plugin
85
+ * accumulates from `session/event`, for two reasons. The ledger is durable, so
86
+ * a cap cannot be reset by restarting the Host (the Loader remounts a row on
87
+ * any config change, and a spend counter that lived only in memory would forget
88
+ * the day). And a second fold of the same events inside the board would have to
89
+ * persist its own totals to be worth anything, which means a second writer of
90
+ * spend state in one process.
91
+ *
92
+ * What that costs: the file belongs to the dsh-usage plugin, so a deployment
93
+ * that does not mount it keeps no ledger and the cap cannot measure anything.
94
+ * That case is reported once per process and the gate then refuses nothing —
95
+ * wedging the board because a sibling plugin is absent would be worse than a
96
+ * cap that says it cannot see. The 3 s flush debounce of that plugin is the
97
+ * other cost: the reading trails the busiest moments by at most one debounce.
98
+ * @module @linxin666/dsh-task-board/host-spend
99
+ */
100
+ /**
101
+ * The token fields one ledger bucket totals. Billed input is uncached input
102
+ * plus both cache buckets; output already includes reasoning, so reasoning is
103
+ * deliberately not added again — the sum is the one the usage panel shows.
104
+ */
105
+ const TOKEN_FIELDS = [
106
+ "inputTokens",
107
+ "outputTokens",
108
+ "cacheReadTokens",
109
+ "cacheWriteTokens"
110
+ ];
111
+ /** Reported at most once per process: an unmeasurable cap is a startup fact, not a per-run one. */
112
+ let reportedUnmeasurable = false;
113
+ /**
114
+ * Local-date key (`YYYY-MM-DD`) of an instant, the bucketing the usage ledger
115
+ * itself uses: the cap and the usage panel therefore roll over at the same
116
+ * local midnight.
117
+ * @param ms - clock instant (ms epoch).
118
+ * @returns the day key.
119
+ */
120
+ function spendDateKey(ms) {
121
+ const date = new Date(ms);
122
+ const month = String(date.getMonth() + 1).padStart(2, "0");
123
+ const day = String(date.getDate()).padStart(2, "0");
124
+ return `${date.getFullYear()}-${month}-${day}`;
125
+ }
126
+ /**
127
+ * Total tokens one ledger day recorded, across every provider and model of that
128
+ * day. Anything that is not a finite token count contributes 0, so a ledger
129
+ * written by another version degrades to a smaller reading instead of NaN.
130
+ * @param day - one day bucket as the ledger stores it, when it is one.
131
+ * @returns the day's token total.
132
+ */
133
+ function ledgerDayTokens(day) {
134
+ if (typeof day !== "object" || day === null) return 0;
135
+ let total = 0;
136
+ for (const models of Object.values(day)) {
137
+ if (typeof models !== "object" || models === null) continue;
138
+ for (const bucket of Object.values(models)) {
139
+ if (typeof bucket !== "object" || bucket === null) continue;
140
+ for (const field of TOKEN_FIELDS) {
141
+ const value = bucket[field];
142
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) total += value;
143
+ }
144
+ }
145
+ }
146
+ return total;
147
+ }
148
+ /**
149
+ * Path of the usage ledger for this DSH home.
150
+ * @returns the absolute ledger path.
151
+ */
152
+ function spendLedgerPath() {
153
+ return join(dshHome(), "dsh-usage", "usage-ledger.json");
154
+ }
155
+ /**
156
+ * Tokens already spent today, or undefined when no measurement is available.
157
+ *
158
+ * Undefined is "cannot see", not "spent nothing": the caller fails open and
159
+ * reports it, because a spend cap that cannot read its own source must never
160
+ * decide that no work may run.
161
+ * @param now - clock instant (ms epoch).
162
+ * @param path - ledger path (test seam).
163
+ * @returns today's token total, or undefined when the ledger is unreadable.
164
+ */
165
+ function usedTokensToday(now = Date.now(), path = spendLedgerPath()) {
166
+ try {
167
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
168
+ const days = typeof parsed === "object" && parsed !== null ? parsed.days : void 0;
169
+ if (typeof days !== "object" || days === null) return void 0;
170
+ return ledgerDayTokens(days[spendDateKey(now)]);
171
+ } catch (error) {
172
+ if (!reportedUnmeasurable) {
173
+ reportedUnmeasurable = true;
174
+ const detail = error instanceof Error ? error.message : String(error);
175
+ console.warn(`[dsh-task-board] spend cap cannot be measured from ${path}: ${detail}; runs are not gated until that ledger is readable`);
176
+ }
177
+ return;
178
+ }
179
+ }
180
+ /**
11
181
  * Clamp a configured cadence into the supported range. A value the schema
12
182
  * would refuse (non-finite, below the floor, above the ceiling) still leaves
13
183
  * the board polling: an out-of-range setting never disables the timer.
@@ -59,40 +229,91 @@ function reusableSessionId(task, idleSessionIds) {
59
229
  return idleSessionIds.has(last.sessionId) ? last.sessionId : void 0;
60
230
  }
61
231
  //#endregion
62
- //#region src/dsh-home.ts
63
- /**
64
- * DSH_HOME resolution shared by the plugin family's Host halves: the
65
- * environment override wins, the platform home fallback follows. Mirrors
66
- * what dsh-pet and dsh-liangshen each used to implement locally.
67
- */
68
- /** Expand a leading ~ (or ~user) in a path, platform-style. */
69
- function expandHome(path, home = homedir()) {
70
- const j = home.startsWith("/") ? join$1 : join;
71
- if (path === "~") return home;
72
- if (path.startsWith("~/") || path.startsWith("~\\")) return j(home, path.slice(2));
73
- return path;
74
- }
75
- /**
76
- * Resolve the DSH home directory.
77
- * @param env - process environment to read DSH_HOME from.
78
- * @param home - platform home directory fallback (test seam).
79
- * @returns the absolute DSH home path.
80
- */
81
- function resolveDshHome(env = process.env, home = homedir()) {
82
- const isPosix = home.startsWith("/");
83
- const j = isPosix ? join$1 : join;
84
- const isAbs = isPosix ? isAbsolute$1 : isAbsolute;
85
- const raw = env.DSH_HOME;
86
- if (raw !== void 0 && raw.trim() !== "") {
87
- const expanded = expandHome(raw.trim(), home);
88
- return isAbs(expanded) ? expanded : j(process.cwd(), expanded);
232
+ //#region src/host/launch-admission.ts
233
+ var LaunchAdmissionQueue = class {
234
+ width;
235
+ /** Waiting launches per run group, in arrival order. */
236
+ waiting = /* @__PURE__ */ new Map();
237
+ /** Run groups in round-robin order. */
238
+ rotation = [];
239
+ /** Slot holders of the launches in flight, one per admitted launch. */
240
+ inFlight = /* @__PURE__ */ new Set();
241
+ /** Highest number of launches in flight at once; observability and tests. */
242
+ peakInFlight = 0;
243
+ /**
244
+ * @param width - live admission width (already normalized by the caller).
245
+ */
246
+ constructor(width) {
247
+ this.width = width;
248
+ }
249
+ /** Launches the queue has not admitted yet. */
250
+ get pendingCount() {
251
+ let total = 0;
252
+ for (const queue of this.waiting.values()) total += queue.length;
253
+ return total;
254
+ }
255
+ /** Launches currently holding a slot. */
256
+ get inFlightCount() {
257
+ return this.inFlight.size;
258
+ }
259
+ /** Admit one launch, immediately if a slot is free. */
260
+ enqueue(launch) {
261
+ const queue = this.waiting.get(launch.groupId);
262
+ if (queue === void 0) {
263
+ this.waiting.set(launch.groupId, [launch]);
264
+ this.rotation.push(launch.groupId);
265
+ } else queue.push(launch);
266
+ this.pump();
89
267
  }
90
- return j(home, ".dsh");
91
- }
92
- /** Resolve the DSH home directory from the live environment. */
93
- function dshHome() {
94
- return resolveDshHome();
95
- }
268
+ /**
269
+ * Abandon every waiting launch: the queue is being torn down, so an entry
270
+ * that never started can never start. Launches already in flight are left
271
+ * alone — their session may already exist, and the callers that own them
272
+ * settle them through the normal path.
273
+ * @returns the abandoned launches, in abandonment order.
274
+ */
275
+ drain() {
276
+ const abandoned = [];
277
+ for (const groupId of this.rotation) for (const launch of this.waiting.get(groupId) ?? []) abandoned.push(launch);
278
+ this.rotation = [];
279
+ this.waiting.clear();
280
+ for (const launch of abandoned) launch.abandon();
281
+ return abandoned;
282
+ }
283
+ pump() {
284
+ while (this.inFlight.size < this.width()) {
285
+ const launch = this.takeNext();
286
+ if (launch === void 0) return;
287
+ this.admit(launch);
288
+ }
289
+ }
290
+ /** The next launch by round-robin across groups and FIFO inside one. */
291
+ takeNext() {
292
+ while (this.rotation.length > 0) {
293
+ const groupId = this.rotation.shift();
294
+ if (groupId === void 0) return void 0;
295
+ const queue = this.waiting.get(groupId);
296
+ if (queue === void 0 || queue.length === 0) {
297
+ this.waiting.delete(groupId);
298
+ continue;
299
+ }
300
+ const launch = queue.shift();
301
+ if (launch === void 0) continue;
302
+ if (queue.length === 0) this.waiting.delete(groupId);
303
+ else this.rotation.push(groupId);
304
+ return launch;
305
+ }
306
+ }
307
+ admit(launch) {
308
+ const release = () => {
309
+ this.inFlight.delete(release);
310
+ this.pump();
311
+ };
312
+ this.inFlight.add(release);
313
+ if (this.inFlight.size > this.peakInFlight) this.peakInFlight = this.inFlight.size;
314
+ Promise.resolve().then(() => launch.start()).catch(() => {}).then(release);
315
+ }
316
+ };
96
317
  //#endregion
97
318
  //#region src/core/schedule.ts
98
319
  /** Inclusive ranges per field, in cron order. */
@@ -444,6 +665,14 @@ function normalizeTaskIntegrations(value) {
444
665
  }
445
666
  return Object.keys(result).length === 0 ? void 0 : result;
446
667
  }
668
+ //#endregion
669
+ //#region src/core/tasks.ts
670
+ /**
671
+ * Upper bound of one recorded summary, in characters. The ledger stores a
672
+ * conclusion, not a transcript: a reader that needs the whole message follows
673
+ * {@link ExecutionSummary.seq} into the session history.
674
+ */
675
+ const EXECUTION_SUMMARY_LIMIT = 4e3;
447
676
  /**
448
677
  * Trim an execution list to at most {@link EXECUTION_HISTORY_LIMIT} records,
449
678
  * most recent last. A running (unsettled) execution is never trimmed: the
@@ -659,6 +888,7 @@ function createTask(input, now, id) {
659
888
  mode: normalizeTargetId(input.mode),
660
889
  permission: isTaskPermission(input.permission) ? input.permission : void 0,
661
890
  model: normalizeTargetId(input.model),
891
+ reasoningEffort: normalizeTargetId(input.reasoningEffort),
662
892
  reuseSession: input.reuseSession === true ? true : void 0,
663
893
  teamRun: input.teamRun === true ? true : void 0,
664
894
  goalRun: input.goalRun === true ? true : void 0,
@@ -778,7 +1008,7 @@ function settledStatus(task, outcome) {
778
1008
  * matching column. No-op (returns the input task) when the execution is not
779
1009
  * the task's latest or is already settled.
780
1010
  */
781
- function settleExecution(task, executionId, outcome, now, error) {
1011
+ function settleExecution(task, executionId, outcome, now, error, summary) {
782
1012
  const index = task.executions.findIndex((execution) => execution.id === executionId);
783
1013
  if (index === -1) return task;
784
1014
  const execution = task.executions[index];
@@ -787,7 +1017,8 @@ function settleExecution(task, executionId, outcome, now, error) {
787
1017
  ...execution,
788
1018
  endedAt: now,
789
1019
  result: outcome,
790
- error
1020
+ error,
1021
+ ...summary === void 0 ? {} : { summary }
791
1022
  };
792
1023
  const executions = [...task.executions];
793
1024
  executions[index] = settled;
@@ -921,15 +1152,38 @@ function checkParentLink(tasks, childId, parentId, maxSubtaskDepth, lineage) {
921
1152
  }
922
1153
  /**
923
1154
  * The tasks one run request opens executions for: the requested task first,
924
- * then its on-board descendants within the configured depth. Archived tasks
925
- * never run; a participant that already has an open execution is skipped by
926
- * the caller, which cannot start it twice.
1155
+ * then its on-board descendants within the configured depth. This is the
1156
+ * SHAPE of a cascade — every walk that must see the whole tree (settlement,
1157
+ * archive/restore, the running lock) reads it. The run path filters it with
1158
+ * {@link joinsCascadeRun}: archived tasks never run, a participant that already
1159
+ * has an open execution is skipped by the caller, which cannot start it twice,
1160
+ * and a finished descendant is left alone.
927
1161
  */
928
1162
  function cascadeTargets(tasks, rootId, maxSubtaskDepth) {
929
1163
  const root = tasks.find((task) => task.id === rootId);
930
1164
  if (root === void 0) return [];
931
1165
  return [root, ...descendantTasks(tasks, rootId, maxSubtaskDepth)];
932
1166
  }
1167
+ /**
1168
+ * Whether a cascade member takes part in a new run.
1169
+ *
1170
+ * The task the user ran is always a member: the request names that card, and
1171
+ * the operator asked for it to run whatever its column says. A descendant does
1172
+ * not join once it sits in the `done` column — its work is finished, so running
1173
+ * the parent again is a run of the parent, never a second execution of work
1174
+ * that is already done. The rule keys on the column alone, so it covers both a
1175
+ * subtask that ran and one an operator moved to done by hand, and it holds for
1176
+ * every trigger: a manual run, a re-run, and a due occurrence of a schedule.
1177
+ * A card whose own schedule is enabled settles back into `todo`, so a scheduled
1178
+ * subtask stays a participant; to make a finished one run again, move it back
1179
+ * to `todo` or run it on its own.
1180
+ * @param task - the candidate member.
1181
+ * @param rootId - the task the run request named.
1182
+ * @returns false when this member is left alone by the run.
1183
+ */
1184
+ function joinsCascadeRun(task, rootId) {
1185
+ return task.id === rootId || task.status !== "done";
1186
+ }
933
1187
  /** The open execution of a task inside a run group, if it still exists. */
934
1188
  function openGroupExecution(task, runGroupId) {
935
1189
  return task.executions.find((execution) => execution.runGroupId === runGroupId && execution.endedAt === void 0);
@@ -989,11 +1243,12 @@ function effectiveTaskPermission(task) {
989
1243
  /**
990
1244
  * Resolve the execution targets a (sub)task actually runs with: its own value
991
1245
  * wins, and an unset target inherits the nearest ancestor up to the root.
992
- * Workspace, agent preset and model inherit the ancestor's PIN only — a
993
- * handover bundle is a per-card continuation artefact and is never inherited.
994
- * The permission inherits the ancestor's EFFECTIVE binding, and its human
995
- * confirmation travels with it, so a subtask of an already-confirmed elevated
996
- * card is runnable while a subtask's own unconfirmed binding stays gated.
1246
+ * Workspace, agent preset, model and reasoning effort inherit the ancestor's
1247
+ * PIN only — a handover bundle is a per-card continuation artefact and is never
1248
+ * inherited. The permission inherits the ancestor's EFFECTIVE binding, and its
1249
+ * human confirmation travels with it, so a subtask of an already-confirmed
1250
+ * elevated card is runnable while a subtask's own unconfirmed binding stays
1251
+ * gated.
997
1252
  */
998
1253
  /**
999
1254
  * The immutable teammate name for one team-mode member. Teammate names are
@@ -1039,23 +1294,109 @@ function stableTag(value) {
1039
1294
  function resolveExecutionTargets(task, tasks, maxSubtaskDepth = 3) {
1040
1295
  if (task.parentId === void 0) return task;
1041
1296
  const chain = [task, ...ancestorChain(tasks, task).slice(0, maxSubtaskDepth)];
1042
- const first = (key) => {
1043
- for (const candidate of chain) {
1297
+ const first = (key, candidates) => {
1298
+ for (const candidate of candidates) {
1044
1299
  const value = candidate[key];
1045
1300
  if (value !== void 0) return value;
1046
1301
  }
1047
1302
  };
1303
+ const boundary = chain.findIndex((candidate) => candidate.model !== void 0);
1304
+ const effortChain = boundary === -1 ? chain : chain.slice(0, boundary + 1);
1048
1305
  const own = effectiveTaskPermission(task);
1049
1306
  const owner = own === void 0 ? chain.slice(1).find((candidate) => effectiveTaskPermission(candidate) !== void 0) : void 0;
1050
1307
  return {
1051
1308
  ...task,
1052
- workspaceId: first("workspaceId"),
1053
- mode: first("mode"),
1054
- model: first("model"),
1309
+ workspaceId: first("workspaceId", chain),
1310
+ mode: first("mode", chain),
1311
+ model: first("model", chain),
1312
+ reasoningEffort: first("reasoningEffort", effortChain),
1055
1313
  permission: own ?? (owner === void 0 ? void 0 : effectiveTaskPermission(owner)),
1056
1314
  permissionConfirmedAt: own === void 0 ? owner?.permissionConfirmedAt : task.permissionConfirmedAt
1057
1315
  };
1058
1316
  }
1317
+ //#endregion
1318
+ //#region src/core/execution-summary.ts
1319
+ /**
1320
+ * What one execution left behind: the text of its last assistant message,
1321
+ * recorded on the execution record next to the verdict it belongs to.
1322
+ *
1323
+ * A settled execution used to carry only a verdict, so a parent card could see
1324
+ * that a subtask succeeded without ever seeing what it produced, and had to
1325
+ * guess or redo the work. The card's own content cannot answer that: card
1326
+ * content is the plan and freezes at the first execution
1327
+ * (`canEditTaskContent`), so the closing words of a run are recorded on the
1328
+ * execution record instead.
1329
+ *
1330
+ * Pure (no cordis, no runtime imports) so the settlement path is unit-testable
1331
+ * without a session, and so a text-less run degrades to "no field" rather than
1332
+ * to an empty string.
1333
+ */
1334
+ /** One rendered content block of an assistant message, or '' when it has no prose. */
1335
+ function blockProse(block) {
1336
+ if (typeof block !== "object" || block === null) return "";
1337
+ const row = block;
1338
+ return row.type === "text" && typeof row.text === "string" ? row.text : "";
1339
+ }
1340
+ /** The assistant's own prose of one message: its text blocks joined and trimmed. */
1341
+ function messageProse(content) {
1342
+ if (!Array.isArray(content)) return "";
1343
+ return content.map(blockProse).filter((part) => part !== "").join("\n").trim();
1344
+ }
1345
+ /**
1346
+ * Bound one summary, keeping its tail: the closing paragraphs carry the
1347
+ * conclusion a reader is after, and the omitted opening is announced instead of
1348
+ * silently dropped. Mirrors the evidence reader's tail bound.
1349
+ */
1350
+ function truncateExecutionSummary(text, limit = EXECUTION_SUMMARY_LIMIT) {
1351
+ if (text.length <= limit) return text;
1352
+ const notice = "[truncated " + String(text.length - limit) + " chars] ";
1353
+ return notice.length >= limit ? text.slice(-limit) : notice + text.slice(-(limit - notice.length));
1354
+ }
1355
+ /**
1356
+ * The summary one execution's own events support.
1357
+ *
1358
+ * Only events at or after `startedAt` belong to this run: a reused session
1359
+ * carries the history of earlier executions, which must not be reported as this
1360
+ * one's output. The last assistant message WITH prose wins — a trailing
1361
+ * tool-call or reasoning-only message has nothing to leave behind, so the reader
1362
+ * walks back to the last one that speaks.
1363
+ * @param events - the session events the inspection already read.
1364
+ * @param startedAt - the execution's start instant (ms epoch); 0 means "all".
1365
+ * @returns the bounded summary with the seq it came from, or undefined when the
1366
+ * run left no usable text.
1367
+ */
1368
+ function executionSummaryOf(events, startedAt) {
1369
+ const own = events.filter((event) => typeof event.time !== "number" || startedAt <= 0 || event.time >= startedAt).filter((event) => event.type === "assistant/message" && typeof event.seq === "number").sort((a, b) => a.seq - b.seq);
1370
+ for (let index = own.length - 1; index >= 0; index -= 1) {
1371
+ const event = own[index];
1372
+ const data = typeof event.data === "object" && event.data !== null ? event.data : {};
1373
+ const text = messageProse((typeof data.message === "object" && data.message !== null ? data.message : {}).content);
1374
+ if (text === "") continue;
1375
+ return {
1376
+ text: truncateExecutionSummary(text),
1377
+ seq: event.seq
1378
+ };
1379
+ }
1380
+ }
1381
+ /**
1382
+ * Repair one persisted or reported summary.
1383
+ *
1384
+ * A summary is informational, so an unreadable one is dropped on its own rather
1385
+ * than costing the execution (or the task row) it hangs on. A hand-edited
1386
+ * overlong text is bounded on the way in, so no reader ever holds more than the
1387
+ * limit.
1388
+ */
1389
+ function normalizeExecutionSummary(value) {
1390
+ if (typeof value !== "object" || value === null) return void 0;
1391
+ const row = value;
1392
+ if (typeof row.text !== "string" || typeof row.seq !== "number" || !Number.isFinite(row.seq)) return void 0;
1393
+ const text = row.text.trim();
1394
+ if (text === "") return void 0;
1395
+ return {
1396
+ text: truncateExecutionSummary(text),
1397
+ seq: row.seq
1398
+ };
1399
+ }
1059
1400
  /** Marker replacing every sensitive match. */
1060
1401
  const REDACTED_MARKER = "[REDACTED]";
1061
1402
  const SECTION_ORDER$1 = [
@@ -2277,6 +2618,7 @@ function isTaskRecordShape(value) {
2277
2618
  if (record.parentId !== void 0 && typeof record.parentId !== "string") return false;
2278
2619
  if (record.workspaceId !== void 0 && typeof record.workspaceId !== "string") return false;
2279
2620
  if (record.mode !== void 0 && typeof record.mode !== "string") return false;
2621
+ if (record.reasoningEffort !== void 0 && typeof record.reasoningEffort !== "string") return false;
2280
2622
  if (record.permission !== void 0 && typeof record.permission !== "string") return false;
2281
2623
  if (record.integrations !== void 0 && (typeof record.integrations !== "object" || record.integrations === null || Array.isArray(record.integrations))) return false;
2282
2624
  if (record.hidden !== void 0 && typeof record.hidden !== "boolean") return false;
@@ -2441,11 +2783,13 @@ function parseLedger(raw) {
2441
2783
  runGroupId: normalizeTargetId(execution.runGroupId),
2442
2784
  ownResult: isExecutionOutcome(execution.ownResult) ? execution.ownResult : void 0,
2443
2785
  ownError: typeof execution.ownError === "string" ? execution.ownError : void 0,
2786
+ summary: normalizeExecutionSummary(execution.summary),
2444
2787
  verification: normalizeVerification(execution.verification),
2445
2788
  external: execution.external === true ? true : void 0
2446
2789
  }));
2447
2790
  task.workspaceId = normalizeTargetId(row.workspaceId);
2448
2791
  task.mode = normalizeTargetId(row.mode);
2792
+ task.reasoningEffort = normalizeTargetId(row.reasoningEffort);
2449
2793
  task.archivedAt = typeof row.archivedAt === "number" && Number.isFinite(row.archivedAt) ? row.archivedAt : void 0;
2450
2794
  task.permission = isTaskPermission(row.permission) ? row.permission : void 0;
2451
2795
  task.reuseSession = row.reuseSession === true ? true : void 0;
@@ -2546,6 +2890,57 @@ function applyRestoreTask(tasks, id, now, maxSubtaskDepth = 1) {
2546
2890
  };
2547
2891
  }
2548
2892
  //#endregion
2893
+ //#region src/core/card-defaults.ts
2894
+ /** Trim one optional target: blank text means "not set", like every stored pin. */
2895
+ function textOf(value) {
2896
+ return value?.trim() ?? "";
2897
+ }
2898
+ /**
2899
+ * Resolve the execution targets a new card starts from.
2900
+ * @param defaults - the board's configured new-card defaults, if any.
2901
+ * @param source - the card this one is created from (a duplicate or a parent), if any.
2902
+ * @param picked - what the caller chose explicitly; a non-blank value wins.
2903
+ * @returns the four targets, blank where nothing supplies a value.
2904
+ */
2905
+ function resolveCardTargets(defaults, source, picked) {
2906
+ const defaultMode = textOf(defaults?.mode);
2907
+ const defaultPermission = textOf(defaults?.permission);
2908
+ const defaultModel = textOf(defaults?.model);
2909
+ const defaultEffort = defaultModel === "" ? "" : textOf(defaults?.reasoningEffort);
2910
+ const chosen = {
2911
+ mode: textOf(picked?.mode),
2912
+ permission: textOf(picked?.permission),
2913
+ model: textOf(picked?.model),
2914
+ reasoningEffort: textOf(picked?.reasoningEffort)
2915
+ };
2916
+ const copied = source === void 0 ? void 0 : {
2917
+ mode: textOf(source.task.mode),
2918
+ permission: textOf(source.task.permission),
2919
+ model: textOf(source.task.model),
2920
+ reasoningEffort: textOf(source.task.reasoningEffort)
2921
+ };
2922
+ /** The value carried over from the source card, or the board default. */
2923
+ const inherited = (key) => {
2924
+ const fallback = key === "mode" ? defaultMode : key === "model" ? defaultModel : defaultPermission;
2925
+ if (copied === void 0 || key === "permission" && source?.kind === "parent") return fallback;
2926
+ return copied[key] === "" ? fallback : copied[key];
2927
+ };
2928
+ const mode = chosen.mode === "" ? inherited("mode") : chosen.mode;
2929
+ const permission = chosen.permission === "" ? inherited("permission") : chosen.permission;
2930
+ const model = chosen.model === "" ? inherited("model") : chosen.model;
2931
+ let reasoningEffort = chosen.reasoningEffort;
2932
+ if (reasoningEffort === "" && chosen.model === "") {
2933
+ const sourced = copied === void 0 ? "" : copied.reasoningEffort;
2934
+ reasoningEffort = sourced !== "" ? sourced : model !== "" && model === defaultModel ? defaultEffort : "";
2935
+ }
2936
+ return {
2937
+ mode,
2938
+ permission,
2939
+ model,
2940
+ reasoningEffort
2941
+ };
2942
+ }
2943
+ //#endregion
2549
2944
  //#region src/core/use-cases/task-create.ts
2550
2945
  /**
2551
2946
  * Create-task use case: mint a new task from user input, rejecting a blank
@@ -2558,18 +2953,22 @@ function applyRestoreTask(tasks, id, now, maxSubtaskDepth = 1) {
2558
2953
  * appended ledger, or the unchanged ledger when the title is blank or the
2559
2954
  * requested parent link is refused.
2560
2955
  *
2561
- * A subtask inherits the execution targets its parent already pins (workspace,
2562
- * agent preset, permission, model) unless the form supplied its own; the
2563
- * parent human permission confirmation travels with an inherited permission,
2564
- * so a subtask of an already-confirmed elevated card is runnable at once.
2956
+ * The execution targets resolve through {@link resolveCardTargets}: what the
2957
+ * caller sent wins, then the parent's own pins, then - only when the caller
2958
+ * opted in with `applyCardDefaults` - the deployment's configured new-card
2959
+ * defaults. Without the flag the resolution sees no defaults at all, which is
2960
+ * exactly the inline parent inheritance this path has always applied. The
2961
+ * workspace is not part of that resolution: a subtask still takes the parent's
2962
+ * workspace, and the defaults never name one.
2565
2963
  * @param tasks - current ledger.
2566
2964
  * @param input - raw user input (title/description/prompt + optional schedule/parent).
2567
2965
  * @param now - clock instant (ms epoch).
2568
2966
  * @param id - minted task id.
2569
2967
  * @param maxSubtaskDepth - deployment subtask depth limit.
2570
2968
  * @param hostTimeZone - zone a rule that stores no zone of its own follows.
2969
+ * @param cardDefaults - the deployment's new-card defaults, read live at creation.
2571
2970
  */
2572
- function applyCreateTask(tasks, input, now, id, maxSubtaskDepth = 1, hostTimeZone = resolveHostTimeZone()) {
2971
+ function applyCreateTask(tasks, input, now, id, maxSubtaskDepth = 1, hostTimeZone = resolveHostTimeZone(), cardDefaults) {
2573
2972
  if (input.title.trim() === "") return {
2574
2973
  task: void 0,
2575
2974
  tasks,
@@ -2595,11 +2994,22 @@ function applyCreateTask(tasks, input, now, id, maxSubtaskDepth = 1, hostTimeZon
2595
2994
  error: `subtask depth limit (${limit}) exceeded`
2596
2995
  };
2597
2996
  }
2598
- let task = createTask(parent === void 0 ? input : {
2997
+ const seed = resolveCardTargets(input.applyCardDefaults === true ? cardDefaults : void 0, parent === void 0 ? void 0 : {
2998
+ kind: "parent",
2999
+ task: parent
3000
+ }, {
3001
+ mode: input.mode,
3002
+ permission: input.permission,
3003
+ model: input.model,
3004
+ reasoningEffort: input.reasoningEffort
3005
+ });
3006
+ let task = createTask({
2599
3007
  ...input,
2600
- workspaceId: input.workspaceId ?? parent.workspaceId,
2601
- mode: input.mode ?? parent.mode,
2602
- model: input.model ?? parent.model
3008
+ workspaceId: input.workspaceId ?? parent?.workspaceId,
3009
+ mode: seed.mode,
3010
+ permission: isTaskPermission(seed.permission) ? seed.permission : void 0,
3011
+ model: seed.model,
3012
+ reasoningEffort: seed.reasoningEffort
2603
3013
  }, now, id);
2604
3014
  const requested = input.schedule;
2605
3015
  if (requested?.enabled === true) {
@@ -3119,6 +3529,7 @@ function applyUpdateTask(tasks, id, patch, now) {
3119
3529
  const mode = "mode" in patch ? normalizeTargetId(patch.mode) : void 0;
3120
3530
  const permission = "permission" in patch ? normalizePermission(task.permission, patch.permission) : void 0;
3121
3531
  const model = "model" in patch ? normalizeTargetId(patch.model) : void 0;
3532
+ const reasoningEffort = "reasoningEffort" in patch ? normalizeTargetId(patch.reasoningEffort) : void 0;
3122
3533
  const next = {
3123
3534
  ...task,
3124
3535
  ...rest,
@@ -3144,6 +3555,7 @@ function applyUpdateTask(tasks, id, patch, now) {
3144
3555
  if (mode !== void 0 || "mode" in patch) next.mode = mode;
3145
3556
  if (permission !== void 0 || "permission" in patch) next.permission = permission;
3146
3557
  if (model !== void 0 || "model" in patch) next.model = model;
3558
+ if (reasoningEffort !== void 0 || "reasoningEffort" in patch) next.reasoningEffort = reasoningEffort;
3147
3559
  return next;
3148
3560
  });
3149
3561
  }
@@ -3229,6 +3641,7 @@ function validImportedSchedule(value) {
3229
3641
  }
3230
3642
  function validImportedKnownFields(value) {
3231
3643
  if (value.tags !== void 0 && !isTaskTagList(value.tags)) return false;
3644
+ if (value.model !== void 0 && typeof value.model !== "string") return false;
3232
3645
  if (value.integrations !== void 0 && normalizeTaskIntegrations(value.integrations) === void 0) return false;
3233
3646
  if (value.schedule !== void 0 && !validImportedSchedule(value.schedule)) return false;
3234
3647
  if (value.executions !== void 0) {
@@ -3281,7 +3694,9 @@ function importedTask(value) {
3281
3694
  ...task.parentId === void 0 ? {} : { parentId: task.parentId },
3282
3695
  ...task.workspaceId === void 0 ? {} : { workspaceId: task.workspaceId },
3283
3696
  ...task.mode === void 0 ? {} : { mode: task.mode },
3697
+ ...typeof task.model !== "string" || task.model.trim() === "" ? {} : { model: task.model },
3284
3698
  ...task.permission === void 0 ? {} : { permission: task.permission },
3699
+ ...task.reasoningEffort === void 0 ? {} : { reasoningEffort: task.reasoningEffort },
3285
3700
  ...task.reuseSession === void 0 ? {} : { reuseSession: task.reuseSession },
3286
3701
  ...task.goalRun === void 0 ? {} : { goalRun: task.goalRun },
3287
3702
  ...task.skipVerification === void 0 ? {} : { skipVerification: task.skipVerification },
@@ -3330,6 +3745,8 @@ function createInput(value) {
3330
3745
  "freeze",
3331
3746
  "handover",
3332
3747
  "model",
3748
+ "reasoningEffort",
3749
+ "applyCardDefaults",
3333
3750
  "reuseSession",
3334
3751
  "teamRun",
3335
3752
  "goalRun",
@@ -3339,7 +3756,8 @@ function createInput(value) {
3339
3756
  ])) return false;
3340
3757
  if (input.parentId !== void 0 && (typeof input.parentId !== "string" || input.parentId.trim() === "")) return false;
3341
3758
  if (typeof input.title !== "string" || typeof input.description !== "string" || typeof input.prompt !== "string") return false;
3342
- if (!optionalString(input.workspaceId) || !optionalString(input.mode) || !optionalString(input.model)) return false;
3759
+ if (!optionalString(input.workspaceId) || !optionalString(input.mode) || !optionalString(input.model) || !optionalString(input.reasoningEffort)) return false;
3760
+ if (input.applyCardDefaults !== void 0 && typeof input.applyCardDefaults !== "boolean") return false;
3343
3761
  if (input.reuseSession !== void 0 && typeof input.reuseSession !== "boolean") return false;
3344
3762
  if (input.teamRun !== void 0 && typeof input.teamRun !== "boolean") return false;
3345
3763
  if (input.goalRun !== void 0 && typeof input.goalRun !== "boolean") return false;
@@ -3380,6 +3798,7 @@ function updatePatch(value) {
3380
3798
  "freeze",
3381
3799
  "handover",
3382
3800
  "model",
3801
+ "reasoningEffort",
3383
3802
  "reuseSession",
3384
3803
  "teamRun",
3385
3804
  "goalRun",
@@ -3396,7 +3815,8 @@ function updatePatch(value) {
3396
3815
  "prompt",
3397
3816
  "workspaceId",
3398
3817
  "mode",
3399
- "model"
3818
+ "model",
3819
+ "reasoningEffort"
3400
3820
  ]) if (!optionalString(patch[key])) return false;
3401
3821
  if (patch.permission !== void 0 && !isTaskPermission(patch.permission)) return false;
3402
3822
  if (patch.tags !== void 0 && patch.tags !== null && !isTaskTagList(patch.tags)) return false;
@@ -3985,11 +4405,24 @@ var HostTaskLedger = class {
3985
4405
  * instead of remounting the row.
3986
4406
  */
3987
4407
  depthLimit;
4408
+ /** Live reader of the deployment's new-card defaults (a volatile config read). */
4409
+ cardDefaults;
4410
+ /**
4411
+ * Live reader of the daily token cap (0 = no gate). The scheduled path asks it
4412
+ * per due occurrence, so a cap raised after a skipped occurrence admits the
4413
+ * next one without a restart.
4414
+ */
4415
+ spendBudget;
4416
+ /** Today's measured spend in tokens, or undefined when nothing can be measured. */
4417
+ spendUsed;
3988
4418
  constructor(dir = join(dshHome(), "task-board"), now = Date.now, options = {}) {
3989
4419
  this.now = now;
3990
4420
  const baseline = options.sessionDefaultPermission;
3991
4421
  this.sessionDefault = typeof baseline === "function" ? baseline : () => baseline ?? "read-only";
3992
4422
  this.depthLimit = normalizeSubtaskDepth(options.maxSubtaskDepth ?? 1);
4423
+ this.cardDefaults = options.cardDefaults ?? (() => ({}));
4424
+ this.spendBudget = options.spendBudgetTokens ?? (() => 0);
4425
+ this.spendUsed = options.spendUsedToday ?? ((now) => usedTokensToday(now));
3993
4426
  mkdirSync(dir, { recursive: true });
3994
4427
  this.file = join(dir, "ledger-v2.json");
3995
4428
  this.lockFile = join(dir, "ledger-v2.lock");
@@ -4196,6 +4629,12 @@ var HostTaskLedger = class {
4196
4629
  this.skipOccurrence(taskId, "busy", triggeredAt);
4197
4630
  return [];
4198
4631
  }
4632
+ const spendRefusal = this.spendRefusal(triggeredAt);
4633
+ if (spendRefusal !== void 0) {
4634
+ this.document.scheduler.error = `scheduled run refused for task ${taskId}: ${spendRefusal}`;
4635
+ this.skipOccurrence(taskId, "limit", triggeredAt);
4636
+ return [];
4637
+ }
4199
4638
  if (schedule.mode === "once") return this.startCascade(task, triggeredAt, void 0, false, {
4200
4639
  consumed: 1,
4201
4640
  lastTriggeredAt: triggeredAt,
@@ -4220,6 +4659,20 @@ var HostTaskLedger = class {
4220
4659
  });
4221
4660
  }
4222
4661
  /**
4662
+ * Why a due occurrence may not open a run because the day already spent the
4663
+ * cap, or undefined when it may. A cap of 0 — the default — answers before the
4664
+ * measurement is read, so a board with no gate reads no ledger file.
4665
+ * @param now - clock instant (ms epoch).
4666
+ * @returns the refusal message, when the cap is reached.
4667
+ */
4668
+ spendRefusal(now) {
4669
+ const cap = this.spendBudget();
4670
+ if (!(cap > 0)) return void 0;
4671
+ const used = this.spendUsed(now);
4672
+ if (used === void 0 || !spendCapReached(used, cap)) return void 0;
4673
+ return spendCapMessage(used, cap);
4674
+ }
4675
+ /**
4223
4676
  * Record a due occurrence that opened no execution: roll a recurring rule to
4224
4677
  * its next occurrence (budget untouched), or stop it when there is none. A
4225
4678
  * one-shot has no second occurrence, so it always stops here with the reason.
@@ -4326,15 +4779,19 @@ var HostTaskLedger = class {
4326
4779
  * and only finalizes once every child execution in its run group has
4327
4780
  * settled, so a parent card leaves 'running' with the whole tree's verdict
4328
4781
  * rather than its own turn alone.
4782
+ *
4783
+ * `summary` is what the run left behind (see `ExecutionSummary`), passed in
4784
+ * by whichever reader observed the session. It is informational: a caller
4785
+ * without one settles exactly as before, and a settlement never waits on it.
4329
4786
  */
4330
- settle(taskId, executionId, outcome, error) {
4787
+ settle(taskId, executionId, outcome, error, summary) {
4331
4788
  const now = this.now();
4332
4789
  const task = this.document.tasks.find((item) => item.id === taskId);
4333
4790
  const execution = task?.executions.find((entry) => entry.id === executionId);
4334
4791
  if (task === void 0 || execution === void 0 || execution.endedAt !== void 0) return;
4335
4792
  const groupId = execution.runGroupId;
4336
4793
  if (groupId === void 0) {
4337
- this.document.tasks = this.document.tasks.map((item) => item.id === taskId ? settleExecution(item, executionId, outcome, now, error) : item);
4794
+ this.document.tasks = this.document.tasks.map((item) => item.id === taskId ? settleExecution(item, executionId, outcome, now, error, summary) : item);
4338
4795
  this.commit();
4339
4796
  return;
4340
4797
  }
@@ -4346,7 +4803,8 @@ var HostTaskLedger = class {
4346
4803
  executions: item.executions.map((entry) => entry.id === executionId ? {
4347
4804
  ...entry,
4348
4805
  ownResult: outcome,
4349
- ownError: error
4806
+ ownError: error,
4807
+ ...summary === void 0 ? {} : { summary }
4350
4808
  } : entry)
4351
4809
  });
4352
4810
  changed = true;
@@ -4409,7 +4867,7 @@ var HostTaskLedger = class {
4409
4867
  frozenBy: initiator
4410
4868
  }
4411
4869
  };
4412
- const result = applyCreateTask(this.document.tasks, input, now, action.id, this.maxSubtaskDepth, timeZone());
4870
+ const result = applyCreateTask(this.document.tasks, input, now, action.id, this.maxSubtaskDepth, timeZone(), this.cardDefaults());
4413
4871
  if (result.task === void 0) throw new Error(result.error ?? "invalid task");
4414
4872
  this.document.tasks = [...result.tasks];
4415
4873
  break;
@@ -4563,6 +5021,7 @@ var HostTaskLedger = class {
4563
5021
  runs = this.startCascade(task, now, initiator, action.kind === "rerun");
4564
5022
  break;
4565
5023
  }
5024
+ default: throw new Error(`unknown task board action kind: ${String(action.kind)}`);
4566
5025
  }
4567
5026
  if (runs === void 0 || runs.length === 0) this.commit();
4568
5027
  return {
@@ -4639,10 +5098,11 @@ var HostTaskLedger = class {
4639
5098
  return cascadeTargets(this.document.tasks, id, this.maxSubtaskDepth).some((task) => hasOpenExecution(task));
4640
5099
  }
4641
5100
  /**
4642
- * Open one execution per cascade participant (the requested task and its
4643
- * on-board descendants, within the depth limit) under a single run group, and
4644
- * commit the ledger once. The returned runs are ordered root-first, so the
4645
- * Host launches the parent before its subtasks.
5101
+ * Open one execution per cascade participant that still has work (the
5102
+ * requested task and its on-board descendants, within the depth limit) under
5103
+ * a single run group, and commit the ledger once. A descendant in 'done' is
5104
+ * not a participant ({@link joinsCascadeRun}). The returned runs are ordered
5105
+ * root-first, so the Host launches the parent before its subtasks.
4646
5106
  * @param root - the task the user ran.
4647
5107
  * @param now - clock instant (ms epoch).
4648
5108
  * @param initiator - the DSH session that asked for the run (audit only).
@@ -4659,6 +5119,7 @@ var HostTaskLedger = class {
4659
5119
  const runs = [];
4660
5120
  for (const task of cascadeTargets(before, root.id, this.maxSubtaskDepth)) {
4661
5121
  if (task.archivedAt !== void 0) continue;
5122
+ if (!joinsCascadeRun(task, root.id)) continue;
4662
5123
  if (hasOpenExecution(task)) continue;
4663
5124
  const opened = startExecution(rerun && task.id === root.id ? withStatus(task, "todo", now) : task, now, crypto.randomUUID(), initiator, groupId);
4664
5125
  started.set(task.id, opened.task);
@@ -5212,7 +5673,96 @@ function mostRecentWorkspaceId(items) {
5212
5673
  return best?.id ?? items[0]?.id;
5213
5674
  }
5214
5675
  //#endregion
5676
+ //#region src/core/reasoning-effort.ts
5677
+ /** Trim one optional effort: blank text means "not set", like every other pinned target. */
5678
+ function normalizeReasoningEffort(value) {
5679
+ const trimmed = value?.trim();
5680
+ return trimmed === void 0 || trimmed === "" ? void 0 : trimmed;
5681
+ }
5682
+ /**
5683
+ * Complete one route through the host catalog: a qualified route must match its
5684
+ * provider group, and a bare model id matches the first group carrying it —
5685
+ * which is the provider the request then names.
5686
+ * @param catalog - the host model catalog, when this deployment serves one.
5687
+ * @param route - the route as the card pins it.
5688
+ * @returns the completed route with its reasoning metadata, or undefined when
5689
+ * the catalog declares no such model.
5690
+ */
5691
+ function declaredRoute(catalog, route) {
5692
+ const groups = catalog?.groups ?? [];
5693
+ const matched = route.provider === void 0 || route.provider === "" ? groups.find((group) => group.models.some((model) => model.id === route.model)) : groups.find((group) => group.id === route.provider);
5694
+ const model = matched?.models.find((candidate) => candidate.id === route.model);
5695
+ if (matched === void 0 || model === void 0) return void 0;
5696
+ return {
5697
+ provider: matched.id,
5698
+ model: model.id,
5699
+ ...model.reasoning === void 0 ? {} : { reasoning: model.reasoning }
5700
+ };
5701
+ }
5702
+ /**
5703
+ * Resolve the effort one execution sends.
5704
+ * @param requested - the card's stored effort (absent or blank = inherit).
5705
+ * @param catalog - the host model catalog, when this deployment serves one.
5706
+ * @param route - the route the execution will actually run at.
5707
+ * @returns the effort to send, or the dropped value that will not be sent.
5708
+ */
5709
+ function resolveReasoningEffort(requested, catalog, route) {
5710
+ const effort = normalizeReasoningEffort(requested);
5711
+ if (effort === void 0) return {};
5712
+ if (route === void 0) return { dropped: effort };
5713
+ return declaredRoute(catalog, route)?.reasoning?.efforts.some((option) => option.id === effort) === true ? { effort } : { dropped: effort };
5714
+ }
5715
+ //#endregion
5215
5716
  //#region src/host-runner.ts
5717
+ /**
5718
+ * Mint the in-process owner peer this plugin's Host calls speak for.
5719
+ *
5720
+ * The 0.2.1 gateway made `peer` mandatory on every request, and the
5721
+ * authorization layer reads only `peer.principal`: a principal of
5722
+ * `{ kind: 'owner' }` is how host-local code states that the call IS the local
5723
+ * user driving their own Host, so the gateway answers it directly instead of
5724
+ * running a remote-access decision (only non-owner principals are judged).
5725
+ * That is exactly the task board's position — it creates, renames, prompts,
5726
+ * and reads sessions as the Host itself, which before 0.2.1 was the implicit
5727
+ * privilege of every in-process caller. The board claims owner explicitly, and
5728
+ * only ever inside its own Host process: no wire field can set a principal,
5729
+ * and this plugin never forwards a browser-supplied one.
5730
+ *
5731
+ * `interactions` stays `'none'`: the board only invokes methods and opens the
5732
+ * short `session/follow` stream. The gateway's interactions check gates
5733
+ * exactly the forwarded-event endpoints (opening an event stream, answering a
5734
+ * waterfall), which this caller never touches; an `'answer'` peer would
5735
+ * additionally receive forwarded Host events, a capability the board neither
5736
+ * needs nor wants.
5737
+ *
5738
+ * The peer's signal aborts once `ctx` disposes, so streams opened for it end
5739
+ * with the plugin fiber, and `dispose()` is idempotent with racing calls
5740
+ * sharing one completion. The id carries no credential — the protocol fixes
5741
+ * `principal` as the only identity persisted in a session log — so a fresh
5742
+ * unique id per mount is sufficient.
5743
+ */
5744
+ function createOwnerPeer(ctx) {
5745
+ const controller = new AbortController();
5746
+ let completion;
5747
+ const peer = {
5748
+ id: `task-board-owner:${crypto.randomUUID()}`,
5749
+ ctx,
5750
+ principal: { kind: "owner" },
5751
+ signal: controller.signal,
5752
+ interactions: "none",
5753
+ dispose() {
5754
+ if (completion === void 0) {
5755
+ controller.abort();
5756
+ completion = Promise.resolve();
5757
+ }
5758
+ return completion;
5759
+ }
5760
+ };
5761
+ ctx.effect(() => () => {
5762
+ peer.dispose();
5763
+ }, "task-board owner peer");
5764
+ return peer;
5765
+ }
5216
5766
  function sessionAddress(sessionId) {
5217
5767
  return {
5218
5768
  kind: "session",
@@ -5413,27 +5963,39 @@ function invokeWireArgs(namespace, method, request) {
5413
5963
  if (namespace === "session" && method === "list") return { _request: request };
5414
5964
  return { request };
5415
5965
  }
5416
- var HostExecutionRunner = class {
5966
+ var HostExecutionRunner = class HostExecutionRunner {
5417
5967
  gateway;
5418
5968
  commands;
5419
5969
  workspaceRegistry;
5420
- /** Newest scanned event sequence per session with no matching execution end. */
5970
+ /**
5971
+ * Newest event sequence per session whose COMPLETE history walk (reaching
5972
+ * the execution boundary) found no matching execution end. A later walk may
5973
+ * trust everything at or below it and examine only newer records.
5974
+ */
5421
5975
  scanMemos = /* @__PURE__ */ new Map();
5422
5976
  unavailableAttempts;
5423
5977
  unavailableBackoffMs;
5978
+ /**
5979
+ * The peer every request speaks for. Production passes the peer bound to the
5980
+ * plugin fiber; a bare runner (unit tests around fake gateways) gets one
5981
+ * bound to a fresh root context instead.
5982
+ */
5983
+ ownerPeer;
5424
5984
  unsupportedSessionListWarned = false;
5425
- constructor(gateway, commands, workspaceRegistry, unavailableRetry) {
5985
+ constructor(gateway, commands, workspaceRegistry, unavailableRetry, ownerPeer) {
5426
5986
  this.gateway = gateway;
5427
5987
  this.commands = commands;
5428
5988
  this.workspaceRegistry = workspaceRegistry;
5429
5989
  this.unavailableAttempts = unavailableRetry?.attempts ?? SERVICE_UNAVAILABLE_ATTEMPTS;
5430
5990
  this.unavailableBackoffMs = unavailableRetry?.backoffMs ?? SERVICE_UNAVAILABLE_BACKOFF_MS;
5991
+ this.ownerPeer = ownerPeer ?? createOwnerPeer(new Context());
5431
5992
  }
5432
5993
  invoke(namespace, method, request, signal) {
5433
5994
  return this.gateway.invoke({
5434
5995
  namespace,
5435
5996
  method,
5436
5997
  args: invokeWireArgs(namespace, method, request),
5998
+ peer: this.ownerPeer,
5437
5999
  ...signal === void 0 ? {} : { signal }
5438
6000
  });
5439
6001
  }
@@ -5443,6 +6005,7 @@ var HostExecutionRunner = class {
5443
6005
  namespace,
5444
6006
  method,
5445
6007
  args: { request },
6008
+ peer: this.ownerPeer,
5446
6009
  ...signal === void 0 ? {} : { signal }
5447
6010
  });
5448
6011
  }
@@ -5484,7 +6047,7 @@ var HostExecutionRunner = class {
5484
6047
  try {
5485
6048
  options.onSession?.(reused);
5486
6049
  await this.assertReusedPreset(reused, mode);
5487
- await this.pinAndPrompt(reused, task, permission, options.promptContext, options.onGoalArmed, options.goalEnabled === true);
6050
+ await this.pinAndPrompt(reused, task, permission, options.promptContext, options.onGoalArmed, options.goalEnabled === true, options.catalog);
5488
6051
  } catch (error) {
5489
6052
  throw new SessionLaunchError(reused, error);
5490
6053
  }
@@ -5500,7 +6063,7 @@ var HostExecutionRunner = class {
5500
6063
  sessionId,
5501
6064
  title: task.title
5502
6065
  });
5503
- await this.pinAndPrompt(sessionId, task, permission, options.promptContext, options.onGoalArmed, options.goalEnabled === true);
6066
+ await this.pinAndPrompt(sessionId, task, permission, options.promptContext, options.onGoalArmed, options.goalEnabled === true, options.catalog);
5504
6067
  } catch (error) {
5505
6068
  throw new SessionLaunchError(sessionId, error);
5506
6069
  }
@@ -5527,30 +6090,85 @@ var HostExecutionRunner = class {
5527
6090
  throw new Error("reused session " + sessionId + " was composed from agent preset " + (typeof recorded === "string" ? "\"" + recorded + "\"" : "an unreadable value") + ", but the task pins \"" + pinned + "\"");
5528
6091
  }
5529
6092
  /**
6093
+ * Split a `provider/model` pin. A pin without a provider keeps only the model
6094
+ * id: the provider is the one the host catalog declares for it, resolved at
6095
+ * launch because the session wire contract requires a provider.
6096
+ */
6097
+ static pinnedRoute(model) {
6098
+ const raw = model?.trim();
6099
+ if (raw === void 0 || raw === "") return void 0;
6100
+ const slash = raw.indexOf("/");
6101
+ if (slash < 0) return { model: raw };
6102
+ const provider = raw.slice(0, slash).trim();
6103
+ const modelId = raw.slice(slash + 1).trim();
6104
+ if (provider === "" || modelId === "") return void 0;
6105
+ return {
6106
+ provider,
6107
+ model: modelId
6108
+ };
6109
+ }
6110
+ /**
6111
+ * The route a card that pins no model actually runs at: the session's own
6112
+ * recorded selection (the durable fold the GUI reads; `next` is the pending
6113
+ * user choice, `lastUsed` what the last request consumed), or — for a session
6114
+ * that has selected none yet, which is exactly a session that would start at
6115
+ * the deployment default — the host default from the catalog.
6116
+ *
6117
+ * A route that cannot be READ is undefined and the effort is not sent:
6118
+ * falling back to the host default there would silently switch the model of a
6119
+ * session this run only meant to continue.
6120
+ */
6121
+ async sessionRoute(sessionId, catalog) {
6122
+ let selection;
6123
+ try {
6124
+ const projections = await this.invoke("session", "projections", { sessionId });
6125
+ selection = projections?.values?.modelSelection?.next ?? projections?.values?.modelSelection?.lastUsed;
6126
+ } catch (error) {
6127
+ console.warn("[dsh-task-board] session/projections failed while resolving the execution model route", error);
6128
+ return;
6129
+ }
6130
+ if (typeof selection?.provider === "string" && selection.provider !== "" && typeof selection.model === "string" && selection.model !== "") return {
6131
+ provider: selection.provider,
6132
+ model: selection.model
6133
+ };
6134
+ return catalog?.default === void 0 ? void 0 : {
6135
+ provider: catalog.default.provider,
6136
+ model: catalog.default.model
6137
+ };
6138
+ }
6139
+ /**
5530
6140
  * Re-assert the pinned execution contract on a session and queue the task
5531
6141
  * prompt. Shared by the fresh-session and reuse paths so both apply exactly
5532
- * the same permission/model pins before the prompt.
6142
+ * the same permission/model/effort pins before the prompt. A session that
6143
+ * refuses a selection carrying a catalog-confirmed effort throws here, so the
6144
+ * prompt is never queued behind a run at the wrong level.
5533
6145
  */
5534
- async pinAndPrompt(sessionId, task, permission, context = {}, onGoalArmed, goalEnabled = false) {
6146
+ async pinAndPrompt(sessionId, task, permission, context = {}, onGoalArmed, goalEnabled = false, catalog) {
5535
6147
  if (permission !== void 0) {
5536
6148
  if (this.commands === void 0) throw new Error("permission command dispatcher is unavailable");
5537
6149
  const command = await this.commands.execute(sessionId, "/permission " + permission, AbortSignal.timeout(3e4));
5538
6150
  if (command === void 0) throw new Error("permission command was not acknowledged");
5539
6151
  if (command.kind !== "success") throw new Error(command.text ?? "permission command failed");
5540
6152
  }
5541
- if (task.model !== void 0 && task.model.trim() !== "") {
5542
- const rawModel = task.model.trim();
5543
- const slashIdx = rawModel.indexOf("/");
5544
- const provider = slashIdx >= 0 ? rawModel.slice(0, slashIdx).trim() : void 0;
5545
- const modelId = slashIdx >= 0 ? rawModel.slice(slashIdx + 1).trim() : rawModel;
6153
+ const requestedEffort = normalizeReasoningEffort(task.reasoningEffort);
6154
+ const route = HostExecutionRunner.pinnedRoute(task.model) ?? (requestedEffort === void 0 ? void 0 : await this.sessionRoute(sessionId, catalog));
6155
+ if (route !== void 0) {
6156
+ const routeLabel = `${route.provider === void 0 ? "" : route.provider + "/"}${route.model}`;
6157
+ const decision = resolveReasoningEffort(requestedEffort, catalog, route);
6158
+ if (decision.dropped !== void 0) console.warn(`[dsh-task-board] model route ${routeLabel} does not declare reasoning effort "${decision.dropped}"; session ${sessionId} runs at the model default`);
6159
+ const declared = declaredRoute(catalog, route);
6160
+ const provider = declared?.provider ?? route.provider;
6161
+ const modelId = declared?.model ?? route.model;
5546
6162
  try {
5547
6163
  await this.invoke("session", "selectModel", {
5548
6164
  sessionId,
5549
- ...provider ? { provider } : {},
5550
- model: modelId
6165
+ ...provider === void 0 ? {} : { provider },
6166
+ model: modelId,
6167
+ ...decision.effort === void 0 ? {} : { reasoningEffort: decision.effort }
5551
6168
  });
5552
6169
  } catch (modelError) {
5553
- console.warn(`[dsh-task-board] failed to select model "${task.model}" for session ${sessionId}, falling back to default:`, modelError);
6170
+ if (decision.effort !== void 0) throw new Error(`session ${sessionId} refused the model selection "${provider === void 0 ? modelId : provider + "/" + modelId}" with reasoning effort "${decision.effort}": ` + (modelError instanceof Error ? modelError.message : String(modelError)));
6171
+ console.warn(`[dsh-task-board] failed to select model "${provider === void 0 ? modelId : provider + "/" + modelId}" for session ${sessionId}, falling back to default:`, modelError);
5554
6172
  }
5555
6173
  }
5556
6174
  await this.invoke("session", "prompt", {
@@ -5765,10 +6383,13 @@ var HostExecutionRunner = class {
5765
6383
  }
5766
6384
  const openingEvents = opening.records.map((record) => ({ event: recordEvent(record) }));
5767
6385
  const newestSeq = openingEvents.reduce((newest, entry) => newest === void 0 ? entry.event.seq : Math.max(newest, entry.event.seq), void 0);
5768
- if (newestSeq !== void 0 && this.scanMemos.get(sessionId) === newestSeq) return { outcome: "pending" };
6386
+ const scannedThrough = this.scanMemos.get(sessionId);
6387
+ if (newestSeq !== void 0 && scannedThrough === newestSeq) return { outcome: "pending" };
6388
+ const oldestOpeningSeq = openingEvents.reduce((oldest, entry) => oldest === void 0 ? entry.event.seq : Math.min(oldest, entry.event.seq), void 0);
6389
+ const coveredThrough = scannedThrough !== void 0 && oldestOpeningSeq !== void 0 && oldestOpeningSeq <= scannedThrough;
5769
6390
  const events = [...openingEvents];
5770
6391
  let beforeSeq;
5771
- let reachedExecutionBoundary = !opening.hasMore;
6392
+ let reachedExecutionBoundary = !opening.hasMore || coveredThrough;
5772
6393
  for (let page = 0; page < HISTORY_PAGE_LIMIT && !reachedExecutionBoundary; page += 1) {
5773
6394
  let history;
5774
6395
  try {
@@ -5789,11 +6410,11 @@ var HostExecutionRunner = class {
5789
6410
  const pageEntries = pageEvents(history);
5790
6411
  events.push(...pageEntries);
5791
6412
  const oldestTime = pageEntries.reduce((oldest, entry) => oldest === void 0 ? entry.event.time : Math.min(oldest, entry.event.time), void 0);
5792
- if (!history.hasMore || oldestTime !== void 0 && oldestTime <= startedAt) {
6413
+ const oldestSeq = pageEntries.reduce((oldest, entry) => oldest === void 0 ? entry.event.seq : Math.min(oldest, entry.event.seq), void 0);
6414
+ if (!history.hasMore || oldestTime !== void 0 && oldestTime <= startedAt || scannedThrough !== void 0 && oldestSeq !== void 0 && oldestSeq <= scannedThrough) {
5793
6415
  reachedExecutionBoundary = true;
5794
6416
  break;
5795
6417
  }
5796
- const oldestSeq = pageEntries.reduce((oldest, entry) => oldest === void 0 ? entry.event.seq : Math.min(oldest, entry.event.seq), void 0);
5797
6418
  if (oldestSeq === void 0 || oldestSeq === beforeSeq) return { outcome: "pending" };
5798
6419
  beforeSeq = oldestSeq;
5799
6420
  }
@@ -5808,14 +6429,21 @@ var HostExecutionRunner = class {
5808
6429
  return { outcome: "pending" };
5809
6430
  }
5810
6431
  this.scanMemos.delete(sessionId);
6432
+ const closing = executionSummaryOf(events.map((entry) => entry.event), startedAt);
6433
+ const carried = closing === void 0 ? {} : { summary: closing };
5811
6434
  const reason = nonCompletedTurnEnd(turnEnd.event.data);
5812
- if (reason === void 0) return await this.goalVerdict(sessionId) ?? { outcome: "succeeded" };
6435
+ if (reason === void 0) return {
6436
+ ...await this.goalVerdict(sessionId) ?? { outcome: "succeeded" },
6437
+ ...carried
6438
+ };
5813
6439
  return reason === "error" ? {
5814
6440
  outcome: "failed",
5815
- error: "agent turn ended with an error"
6441
+ error: "agent turn ended with an error",
6442
+ ...carried
5816
6443
  } : {
5817
6444
  outcome: "failed",
5818
- error: "agent turn ended without completing: " + reason
6445
+ error: "agent turn ended without completing: " + reason,
6446
+ ...carried
5819
6447
  };
5820
6448
  }
5821
6449
  };
@@ -6550,6 +7178,13 @@ const MAX_TIMER_DELAY_MS = 2147483647;
6550
7178
  */
6551
7179
  const UNREADABLE_SETTLE_POLLS = 24;
6552
7180
  /**
7181
+ * Why a member of a run never started: the Host stopped while its launch was
7182
+ * still waiting for an admission slot. Recorded rather than left open, so the
7183
+ * card leaves the running column instead of waiting for the next Host start's
7184
+ * interrupted-start recovery.
7185
+ */
7186
+ const ABANDONED_LAUNCH_REASON = "host stopped before this execution started";
7187
+ /**
6553
7188
  * Why an enforced goal execution settled failed while its acceptance DID run:
6554
7189
  * attempts were recorded and none of them passed. The judge answered about the
6555
7190
  * work and the work did not pass.
@@ -6574,10 +7209,20 @@ const NEVER_INVOKED_VERIFICATION_REASON = "goal 验收未触发:本次执行
6574
7209
  */
6575
7210
  const INVALID_ONLY_VERIFICATION_REASON = "goal 验收无效:本次执行只记录了无效验收(裁判未能给出与任务要求对应、且可定位到本次证据的否决依据),看板已停止调用裁判。这**不是**有证据的质量判负:验收本身不可用,本次运行因没有匹配的通过记录而结束。请检查验收环境与证据可见性,或用 task_board_manage(action=reset-verification) 清除记录的无效验收后重新完成目标。";
6576
7211
  /**
6577
- * Actions that can move an armed trigger. Only these re-arm the native timer;
6578
- * an unrelated card edit leaves the pending fire untouched.
7212
+ * Actions that can change the instant the schedule timer is armed at. Only
7213
+ * these re-arm the native timer; an unrelated card edit leaves the pending fire
7214
+ * untouched.
7215
+ *
7216
+ * The set is the write surface of a rule itself rather than a guess at the UI
7217
+ * flows that reach it: `create` and `import` land a card that already carries
7218
+ * an enabled rule (the new-task dialog and the one-time browser import),
7219
+ * `set-schedule` edits one, and `delete`/`archive` drop one. `update` is
7220
+ * deliberately absent — the update patch cannot carry a schedule — and neither
7221
+ * can the run, move, lineage, permission, verification or label actions.
6579
7222
  */
6580
7223
  const SCHEDULE_WRITE_ACTIONS = /* @__PURE__ */ new Set([
7224
+ "create",
7225
+ "import",
6581
7226
  "set-schedule",
6582
7227
  "delete",
6583
7228
  "archive"
@@ -6597,6 +7242,57 @@ const PROCESS_TIMERS = {
6597
7242
  };
6598
7243
  }
6599
7244
  };
7245
+ /**
7246
+ * The new-card defaults a snapshot publishes, or undefined when this
7247
+ * deployment configures none. A target the board configures nothing for is
7248
+ * omitted instead of published blank, so the browser can tell "no default
7249
+ * model" from "a blank one" (only a hand-edited settings document can express
7250
+ * the latter).
7251
+ */
7252
+ function cardDefaultsOf(defaults) {
7253
+ const mode = normalizeTargetId(defaults.mode);
7254
+ const permission = normalizeTargetId(defaults.permission);
7255
+ const model = normalizeTargetId(defaults.model);
7256
+ const reasoningEffort = normalizeTargetId(defaults.reasoningEffort);
7257
+ const published = {
7258
+ ...mode === void 0 ? {} : { mode },
7259
+ ...isTaskPermission(permission) ? { permission } : {},
7260
+ ...model === void 0 ? {} : { model },
7261
+ ...reasoningEffort === void 0 ? {} : { reasoningEffort }
7262
+ };
7263
+ return Object.keys(published).length === 0 ? void 0 : published;
7264
+ }
7265
+ /**
7266
+ * Every action kind this board accepts, keyed by the kind itself.
7267
+ *
7268
+ * Written as a total record of `TaskBoardAction['kind']` on purpose: a new member
7269
+ * of that union does not compile until it is listed here, so the table cannot
7270
+ * drift behind the protocol. `apply()` validates against it because a caller
7271
+ * reaching the board through the in-process capability face forwards its action
7272
+ * object verbatim, with no envelope parser in front of it — the HTTP route was the
7273
+ * only entrance before that face existed, and its parser is what used to turn an
7274
+ * unknown kind into a refusal.
7275
+ */
7276
+ const ACTION_KINDS = {
7277
+ import: true,
7278
+ create: true,
7279
+ update: true,
7280
+ delete: true,
7281
+ move: true,
7282
+ archive: true,
7283
+ restore: true,
7284
+ settle: true,
7285
+ "reset-verification": true,
7286
+ "record-external-outcome": true,
7287
+ "set-schedule": true,
7288
+ run: true,
7289
+ rerun: true,
7290
+ "confirm-permission": true,
7291
+ "set-parent": true,
7292
+ "rename-tag": true,
7293
+ "delete-tag": true,
7294
+ "extension-action": true
7295
+ };
6600
7296
  var TaskBoardHostService = class {
6601
7297
  ledger;
6602
7298
  runner;
@@ -6618,6 +7314,12 @@ var TaskBoardHostService = class {
6618
7314
  pollInFlight = false;
6619
7315
  active = true;
6620
7316
  /**
7317
+ * Admission control for the session-creating half of a run: one board action
7318
+ * opens a whole subtree, and this is what keeps the Host from asking DSH for
7319
+ * every member's session at once (see {@link LaunchAdmissionQueue}).
7320
+ */
7321
+ launches;
7322
+ /**
6621
7323
  * Consecutive unreadable-history polls per open execution (see
6622
7324
  * {@link noteUnreadableInspection}). Cleared as soon as an inspection
6623
7325
  * resolves, so a transient reader failure never fails a card.
@@ -6630,6 +7332,21 @@ var TaskBoardHostService = class {
6630
7332
  timers;
6631
7333
  /** Live reader of the global native-/goal switch; frozen per execution. */
6632
7334
  goalRunEnabled;
7335
+ /** Live reader of the deployment's new-card defaults (published and applied per create). */
7336
+ cardDefaults;
7337
+ /**
7338
+ * Live reader of the run-launch admission width: how many launches may be in
7339
+ * flight at once. Read at every admission, so a settings edit bounds the next
7340
+ * launch without remounting the row. Absent means the default.
7341
+ */
7342
+ runLaunchWidth;
7343
+ /**
7344
+ * Live reader of the daily token cap; 0 means no gate. Read at each run
7345
+ * action, so closing or raising the cap binds the next action.
7346
+ */
7347
+ spendBudgetTokens;
7348
+ /** Today's measured spend: absent measurement reads as "cannot see", never as zero. */
7349
+ spendUsedToday;
6633
7350
  lastPowerJson = "";
6634
7351
  now;
6635
7352
  /** The deployment's workspaces, consulted to resolve a card that pins none. */
@@ -6643,15 +7360,23 @@ var TaskBoardHostService = class {
6643
7360
  constructor(gateway, options = {}) {
6644
7361
  this.ledger = options.ledger ?? new HostTaskLedger(void 0, void 0, {
6645
7362
  sessionDefaultPermission: options.sessionDefaultPermission,
6646
- maxSubtaskDepth: options.maxSubtaskDepth
7363
+ maxSubtaskDepth: options.maxSubtaskDepth,
7364
+ cardDefaults: options.cardDefaults,
7365
+ spendBudgetTokens: options.spendBudgetTokens,
7366
+ spendUsedToday: options.spendUsedToday
6647
7367
  });
6648
- this.runner = new HostExecutionRunner(gateway, options.commandDispatcher, options.workspaceRegistry);
7368
+ this.runner = new HostExecutionRunner(gateway, options.commandDispatcher, options.workspaceRegistry, void 0, options.ownerPeer);
6649
7369
  this.workspaceRegistry = options.workspaceRegistry;
6650
7370
  this.team = options.team;
6651
7371
  this.timers = options.timers ?? PROCESS_TIMERS;
6652
7372
  this.power = options.power ?? new PowerInhibitor();
6653
7373
  this.now = options.now ?? Date.now;
6654
7374
  this.goalRunEnabled = options.goalRunEnabled ?? (() => false);
7375
+ this.cardDefaults = options.cardDefaults ?? (() => ({}));
7376
+ this.runLaunchWidth = options.runLaunchWidth ?? (() => 3);
7377
+ this.spendBudgetTokens = options.spendBudgetTokens ?? (() => 0);
7378
+ this.spendUsedToday = options.spendUsedToday ?? ((now) => usedTokensToday(now));
7379
+ this.launches = new LaunchAdmissionQueue(() => normalizeRunLaunchWidth(this.runLaunchWidth()));
6655
7380
  this.verificationSettings = options.verificationSettings ?? (() => ({
6656
7381
  enabled: false,
6657
7382
  model: "",
@@ -6728,6 +7453,7 @@ var TaskBoardHostService = class {
6728
7453
  snapshot() {
6729
7454
  const state = this.ledger.state();
6730
7455
  const published = this.extensions.published();
7456
+ const cardDefaults = cardDefaultsOf(this.cardDefaults());
6731
7457
  return {
6732
7458
  schemaVersion: 6,
6733
7459
  revision: state.revision,
@@ -6738,6 +7464,7 @@ var TaskBoardHostService = class {
6738
7464
  maxSubtaskDepth: this.ledger.maxSubtaskDepth,
6739
7465
  teamRunAvailable: this.team !== void 0,
6740
7466
  goalRunEnabled: this.goalRunEnabled(),
7467
+ ...cardDefaults === void 0 ? {} : { cardDefaults },
6741
7468
  ...Object.keys(published).length === 0 ? {} : { extensions: published }
6742
7469
  };
6743
7470
  }
@@ -6815,6 +7542,8 @@ var TaskBoardHostService = class {
6815
7542
  }
6816
7543
  apply(requestId, action, initiator) {
6817
7544
  if (!this.active) throw new Error("task board is disabled");
7545
+ const kind = action?.kind;
7546
+ if (typeof kind !== "string" || !Object.hasOwn(ACTION_KINDS, kind)) throw new Error(`unknown task board action kind: ${String(kind)}`);
6818
7547
  if (action.kind === "extension-action") return this.handleExtensionAction(action);
6819
7548
  return this.applyBoardAction(requestId, action, initiator);
6820
7549
  }
@@ -6828,6 +7557,7 @@ var TaskBoardHostService = class {
6828
7557
  if (this.team === void 0 && (action.kind === "run" || action.kind === "rerun")) {
6829
7558
  if (this.ledger.state().tasks.find((item) => item.id === action.taskId)?.teamRun === true) throw new Error("Agent Teams is unavailable in this deployment");
6830
7559
  }
7560
+ if (action.kind === "run" || action.kind === "rerun") this.assertSpendCap();
6831
7561
  const result = this.ledger.applyRequest(requestId, this.withInheritedWorkspace(action, initiator), initiator);
6832
7562
  if (result.runs !== void 0) this.dispatchRuns(result.runs);
6833
7563
  if (SCHEDULE_WRITE_ACTIONS.has(action.kind)) this.refreshSchedule();
@@ -6841,6 +7571,24 @@ var TaskBoardHostService = class {
6841
7571
  power: this.power.snapshot()
6842
7572
  };
6843
7573
  }
7574
+ /**
7575
+ * Refuse a run whose day already spent the cap.
7576
+ *
7577
+ * A cap of 0 — the shipped default — answers before the measurement is read:
7578
+ * no ledger file is opened and nothing is summed, which is what keeps a board
7579
+ * that never configured a cap identical to the one before it existed.
7580
+ *
7581
+ * The refusal is a thrown message rather than a code: the wire hands its text
7582
+ * to the caller as board-refused, exactly like every other refusal this board
7583
+ * makes.
7584
+ */
7585
+ assertSpendCap() {
7586
+ const cap = this.spendBudgetTokens();
7587
+ if (!(cap > 0)) return;
7588
+ const used = this.spendUsedToday(this.now());
7589
+ if (used === void 0 || !spendCapReached(used, cap)) return;
7590
+ throw new Error(spendCapMessage(used, cap));
7591
+ }
6844
7592
  /** Route one provider action and answer the resulting board snapshot. */
6845
7593
  async handleExtensionAction(action) {
6846
7594
  await this.extensions.handleAction({
@@ -6870,6 +7618,8 @@ var TaskBoardHostService = class {
6870
7618
  }
6871
7619
  dispose() {
6872
7620
  this.disposed = true;
7621
+ const abandoned = this.launches.drain();
7622
+ if (abandoned.length > 0) safeConsoleError(`[dsh-task-board] ${abandoned.length} run member(s) were still waiting for a launch slot when the Host stopped; each is settled as cancelled`);
6873
7623
  this.extensions.dispose();
6874
7624
  this.clearScheduleTimer();
6875
7625
  this.clearPollBackoff();
@@ -6879,7 +7629,7 @@ var TaskBoardHostService = class {
6879
7629
  this.ledger.dispose();
6880
7630
  this.listeners.clear();
6881
7631
  }
6882
- async launch(opened, others = [], schedule) {
7632
+ async launch(opened, others = [], schedule, freezeContract) {
6883
7633
  /** The session this launch attached to the execution, once it exists. */
6884
7634
  let attached;
6885
7635
  try {
@@ -6895,14 +7645,13 @@ var TaskBoardHostService = class {
6895
7645
  ...team ? { team: true } : {},
6896
7646
  ...schedule === void 0 ? {} : { schedule }
6897
7647
  };
6898
- const settings = this.verificationSettings();
6899
- const globalGoalEnabled = this.goalRunEnabled() === true;
7648
+ const { settings, globalGoalEnabled, catalog } = await (freezeContract ?? (() => this.freezeRunContract()))();
6900
7649
  const goalEnabled = globalGoalEnabled && opened.task.goalRun === true;
6901
7650
  const skippedBy = opened.task.skipVerification === true ? "skipped" : "disabled";
6902
7651
  const contract = resolveContract({
6903
7652
  ...settings,
6904
7653
  enabled: settings.enabled && opened.task.skipVerification !== true
6905
- }, await this.verificationCatalog());
7654
+ }, catalog);
6906
7655
  const notArmed = globalGoalEnabled ? "goal-unavailable" : "goal-disabled";
6907
7656
  const initial = {
6908
7657
  contract,
@@ -6914,6 +7663,7 @@ var TaskBoardHostService = class {
6914
7663
  ...reuseSessionId === void 0 ? {} : { reuseSessionId },
6915
7664
  ...promptContext === void 0 ? {} : { promptContext },
6916
7665
  goalEnabled,
7666
+ catalog,
6917
7667
  onSession: (id) => {
6918
7668
  attached = id;
6919
7669
  this.ledger.attachSession(opened.task.id, opened.execution.id, id);
@@ -6927,14 +7677,52 @@ var TaskBoardHostService = class {
6927
7677
  } catch (error) {
6928
7678
  const launchedSession = error instanceof SessionLaunchError ? error.sessionId : void 0;
6929
7679
  if (launchedSession !== void 0) this.ledger.attachSession(opened.task.id, opened.execution.id, launchedSession);
6930
- if (schedule !== void 0 && attached === void 0 && launchedSession === void 0) this.ledger.refundScheduledOccurrence(opened.task.id, this.now());
7680
+ if (schedule !== void 0 && attached === void 0 && launchedSession === void 0) this.refundUnstartedSchedule(opened.task.id);
6931
7681
  this.settleAndNotify(opened.task.id, opened.execution.id, "failed", error instanceof Error ? error.message : String(error));
6932
7682
  }
6933
7683
  }
7684
+ /**
7685
+ * Read the acceptance contract one run group freezes, in the order the board
7686
+ * has always read it: the acceptance settings, then the global native-/goal
7687
+ * switch, then the model catalog that both resolves the contract's route and
7688
+ * decides the reasoning effort the session may be given.
7689
+ */
7690
+ async freezeRunContract() {
7691
+ return {
7692
+ settings: this.verificationSettings(),
7693
+ globalGoalEnabled: this.goalRunEnabled() === true,
7694
+ catalog: await this.verificationCatalog()
7695
+ };
7696
+ }
7697
+ /**
7698
+ * A {@link RunContractFreezer} that reads once and hands the SAME value to
7699
+ * every later caller of one run group. A read that fails is not cached: the
7700
+ * next member reads again, exactly as a per-execution read would have.
7701
+ */
7702
+ contractFreezerForRunGroup() {
7703
+ let pending;
7704
+ return () => {
7705
+ pending ??= this.freezeRunContract().catch((error) => {
7706
+ pending = void 0;
7707
+ throw error;
7708
+ });
7709
+ return pending;
7710
+ };
7711
+ }
7712
+ /**
7713
+ * Give back the occurrence a launch consumed, for a launch that never reached
7714
+ * a session: a failed launch, or one the Host abandoned while it was still
7715
+ * waiting for an admission slot. A manual run, and a launch that DID reach a
7716
+ * session, are never refunded.
7717
+ */
7718
+ refundUnstartedSchedule(taskId) {
7719
+ this.ledger.refundScheduledOccurrence(taskId, this.now());
7720
+ this.refreshSchedule();
7721
+ }
6934
7722
  scheduleTeammate(opened, leadSessionId) {
6935
- this.spawnTeammate(opened, leadSessionId).catch((error) => {
7723
+ this.enqueueLaunch(opened, () => this.spawnTeammate(opened, leadSessionId).catch((error) => {
6936
7724
  safeConsoleError("[dsh-task-board] teammate spawn settlement failed", error);
6937
- });
7725
+ }));
6938
7726
  }
6939
7727
  /**
6940
7728
  * Spawn one teammate inside the Lead session and attach the teammate's
@@ -7048,10 +7836,10 @@ var TaskBoardHostService = class {
7048
7836
  }
7049
7837
  this.unreadablePolls.delete(execution.executionId);
7050
7838
  if (result.outcome === "succeeded" && verificationRequired(verification) && passedAttempt(verification) === void 0) {
7051
- this.settleAndNotify(execution.taskId, execution.executionId, "failed", verificationNeverInvoked(verification) ? NEVER_INVOKED_VERIFICATION_REASON : verificationOnlyInvalid(verification) ? INVALID_ONLY_VERIFICATION_REASON : NO_MATCHING_PASS_VERIFICATION_REASON);
7839
+ this.settleAndNotify(execution.taskId, execution.executionId, "failed", verificationNeverInvoked(verification) ? NEVER_INVOKED_VERIFICATION_REASON : verificationOnlyInvalid(verification) ? INVALID_ONLY_VERIFICATION_REASON : NO_MATCHING_PASS_VERIFICATION_REASON, result.summary);
7052
7840
  continue;
7053
7841
  }
7054
- this.settleAndNotify(execution.taskId, execution.executionId, result.outcome, "error" in result ? result.error : void 0);
7842
+ this.settleAndNotify(execution.taskId, execution.executionId, result.outcome, "error" in result ? result.error : void 0, result.summary);
7055
7843
  } catch {}
7056
7844
  }
7057
7845
  const open = new Set(executions.map((execution) => execution.executionId));
@@ -7066,14 +7854,14 @@ var TaskBoardHostService = class {
7066
7854
  * ancestor of it — in the running column with no way out. The first poll of
7067
7855
  * each streak is logged, so the Host log names the session.
7068
7856
  */
7069
- settleAndNotify(taskId, executionId, outcome, error) {
7857
+ settleAndNotify(taskId, executionId, outcome, error, summary) {
7070
7858
  const before = this.ledger.getTask(taskId);
7071
7859
  if (before?.executions.find((entry) => entry.id === executionId)?.endedAt !== void 0) {
7072
- this.ledger.settle(taskId, executionId, outcome, error);
7860
+ this.ledger.settle(taskId, executionId, outcome, error, summary);
7073
7861
  return;
7074
7862
  }
7075
7863
  const previousStatus = before?.status;
7076
- this.ledger.settle(taskId, executionId, outcome, error);
7864
+ this.ledger.settle(taskId, executionId, outcome, error, summary);
7077
7865
  const task = this.ledger.getTask(taskId);
7078
7866
  if (task !== void 0 && previousStatus !== void 0 && previousStatus !== task.status) this.extensions.emitStatusChanged({
7079
7867
  taskId,
@@ -7224,13 +8012,21 @@ var TaskBoardHostService = class {
7224
8012
  * member then launches on its own so one refused participant cannot hold the
7225
8013
  * others back. A team run's members are spawned inside the root's Lead
7226
8014
  * session instead, once that session exists.
8015
+ *
8016
+ * Every launch of one run set goes through the admission queue, which admits
8017
+ * at most `runLaunchWidth` of them at a time — the whole subtree still opens,
8018
+ * members just enter the running column in batches. Order inside the group is
8019
+ * the order they are enqueued here, so the root's session always exists before
8020
+ * any member's, and one member's launch settling (or failing) is what admits
8021
+ * the next. All members share the one contract this group freezes.
7227
8022
  */
7228
8023
  dispatchRuns(runs, schedule) {
7229
8024
  if (runs.length === 0) return;
7230
8025
  const root = runs.find((run) => run.dispatch !== "teammate") ?? runs[0];
7231
8026
  const others = runs.filter((run) => run !== root);
7232
- this.scheduleLaunch(root, others, schedule);
7233
- for (const run of others) if (run.dispatch !== "teammate") this.scheduleLaunch(run, [], schedule);
8027
+ const freezeContract = this.contractFreezerForRunGroup();
8028
+ this.scheduleLaunch(root, others, schedule, freezeContract);
8029
+ for (const run of others) if (run.dispatch !== "teammate") this.scheduleLaunch(run, [], schedule, freezeContract);
7234
8030
  }
7235
8031
  /**
7236
8032
  * Move one execution's applicability without touching its frozen contract or
@@ -7244,10 +8040,50 @@ var TaskBoardHostService = class {
7244
8040
  applicability
7245
8041
  });
7246
8042
  }
7247
- scheduleLaunch(opened, others = [], schedule) {
7248
- this.launch(opened, others, schedule).catch((error) => {
8043
+ scheduleLaunch(opened, others = [], schedule, freezeContract) {
8044
+ this.enqueueLaunch(opened, () => this.launch(opened, others, schedule, freezeContract).catch((error) => {
7249
8045
  safeConsoleError("[dsh-task-board] execution launch settlement failed", error);
7250
- });
8046
+ }), schedule);
8047
+ }
8048
+ /**
8049
+ * Hand one launch to the admission queue, or abandon it on the spot when the
8050
+ * Host is already stopping: a queue entry created after {@link dispose} would
8051
+ * otherwise never be drained, and its card would sit in the running column
8052
+ * until the next Host start recovered it.
8053
+ */
8054
+ enqueueLaunch(opened, start, schedule) {
8055
+ const launch = {
8056
+ groupId: opened.execution.runGroupId ?? opened.task.id,
8057
+ start: async () => {
8058
+ if (!this.isExecutionOpen(opened)) return;
8059
+ await start();
8060
+ },
8061
+ abandon: () => this.abandonQueuedRun(opened, schedule)
8062
+ };
8063
+ if (this.disposed) {
8064
+ launch.abandon();
8065
+ return;
8066
+ }
8067
+ this.launches.enqueue(launch);
8068
+ }
8069
+ /** Whether one opened execution is still open in the ledger. */
8070
+ isExecutionOpen(opened) {
8071
+ const execution = this.ledger.getTask(opened.task.id)?.executions.find((entry) => entry.id === opened.execution.id);
8072
+ return execution !== void 0 && execution.endedAt === void 0;
8073
+ }
8074
+ /**
8075
+ * Take one launch that never started out of the running column.
8076
+ *
8077
+ * Settled as CANCELLED, not failed: nothing about the run's work went wrong —
8078
+ * the Host stopped before the launch got a slot, which is exactly what the
8079
+ * next start's interrupted-start recovery records for an execution that never
8080
+ * reached a session. A scheduled occurrence that never reached a session is
8081
+ * refunded on the same terms as any other pre-session failure, so a run the
8082
+ * Host never started cannot silently spend the user's run budget.
8083
+ */
8084
+ abandonQueuedRun(opened, schedule) {
8085
+ if (schedule !== void 0) this.refundUnstartedSchedule(opened.task.id);
8086
+ this.settleAndNotify(opened.task.id, opened.execution.id, "cancelled", ABANDONED_LAUNCH_REASON);
7251
8087
  }
7252
8088
  schedulePoll() {
7253
8089
  if (this.pollInFlight || this.disposed) return;
@@ -7712,6 +8548,7 @@ function taskSummary(task, tasks, sessionDefault) {
7712
8548
  ...task.mode === void 0 ? {} : { mode: task.mode },
7713
8549
  ...task.permission === void 0 ? {} : { permission: task.permission },
7714
8550
  ...task.model === void 0 ? {} : { model: task.model },
8551
+ ...task.reasoningEffort === void 0 ? {} : { reasoningEffort: task.reasoningEffort },
7715
8552
  ...task.reuseSession === true ? { reuseSession: true } : {},
7716
8553
  ...task.teamRun === true ? { teamRun: true } : {},
7717
8554
  ...task.goalRun === true ? { goalRun: true } : {},
@@ -7809,7 +8646,7 @@ function buildSetParentTool(host) {
7809
8646
  "Attach an existing task under a parent (making it a subtask) or detach it back to the root board by setting its parentId.",
7810
8647
  "Pass an empty parentId to detach.",
7811
8648
  "The Host refuses the link when the parent is unknown or archived, when the moved task is one of its own descendants, when the resulting depth exceeds the deployment subtask limit (default one level, maximum three), or while the task has an unsettled execution (its link may still be a running cascade parent pointer).",
7812
- "Running a task runs its whole subtree concurrently; a parent card settles only after its own turn and every direct subtask settle."
8649
+ "Running a task opens one run group over its subtree concurrently and leaves a subtask that already sits in the done column alone; a parent card settles only after its own turn and every direct subtask it opened have settled."
7813
8650
  ].join(" "),
7814
8651
  parameters: {
7815
8652
  taskId: {
@@ -7861,7 +8698,7 @@ function buildRunTool(host) {
7861
8698
  taskId: {
7862
8699
  type: "string",
7863
8700
  required: true,
7864
- description: "The task to run; running a root task runs its whole subtree."
8701
+ description: "The task to run; running a root task runs its whole subtree, minus the subtasks that are already in the done column."
7865
8702
  },
7866
8703
  rerun: {
7867
8704
  type: "boolean",
@@ -8060,7 +8897,7 @@ function buildScheduleTool(host) {
8060
8897
  "Arm, change, or disarm a task scheduled runs. Two kinds of plan exist: a recurring 5-field cron rule (day-of-month and day-of-week follow Vixie semantics: both restricted means OR, otherwise AND), and a one-shot that runs once at a future instant.",
8061
8898
  "For a one-shot pass mode \"once\" with at (the planned instant, ms since epoch UTC). For a recurring rule pass mode \"cron\" (or omit mode) with a cron expression, optionally capped by maxRuns (a positive whole number of scheduled executions; omit for unlimited, pass 0 to clear a cap).",
8062
8899
  "The wall clock is read in the rule stored IANA time zone; omit timeZone to use the Host zone reported by task_board_list/task_board_get. DST gaps are skipped and an ambiguous fall-back time fires once, at the earlier instant.",
8063
- "A due scheduled task runs the same cascade a manual run does, so a root task runs its whole subtask tree.",
8900
+ "A due scheduled task runs the same cascade a manual run does, so a root task runs its whole subtask tree minus the subtasks already in the done column.",
8064
8901
  "The scheduler counts executions it actually starts; once a rule reaches its run budget it stops itself in the ledger, and a manual run never consumes the budget. A schedule whose tree contains an unconfirmed above-default permission is refused and does not consume the budget; the reason is reported in the list board summary as schedulerError.",
8065
8902
  "Missed occurrences during Host downtime are skipped, never queued (a one-shot whose instant passed while the Host was down is stopped as missed); a task that is already running skips its occurrence without consuming the budget."
8066
8903
  ].join(" "),
@@ -8241,7 +9078,7 @@ function buildCreateTool(host) {
8241
9078
  name: "task_board_create",
8242
9079
  description: [
8243
9080
  "Create a task on the DSH task board, or a subtask by passing parentId.",
8244
- "A subtask inherits every execution target it does not override (workspace, agent preset, permission, model) from its parent, and inherits the parent human permission confirmation together with an inherited binding.",
9081
+ "A subtask inherits every execution target it does not override (workspace, agent preset, permission, model, reasoning effort) from its parent, and inherits the parent human permission confirmation together with an inherited binding.",
8245
9082
  "The deployment caps subtask depth (default one level, maximum three): a subtask of a subtask is refused unless the board is configured deeper.",
8246
9083
  "The task lands in the todo column and does NOT run; call task_board_run to execute it."
8247
9084
  ].join(" "),
@@ -8269,16 +9106,20 @@ function buildCreateTool(host) {
8269
9106
  },
8270
9107
  mode: {
8271
9108
  type: "string",
8272
- description: "Agent preset id the execution session is composed from; omit for the deployment default or the parent value."
9109
+ description: "Agent preset id the execution session is composed from; omit to adopt the board new-card default, and the deployment default when none is configured."
8273
9110
  },
8274
9111
  permission: {
8275
9112
  type: "string",
8276
9113
  enum: [...TASK_PERMISSIONS],
8277
- description: "Permission preset for the execution session. Omit to inherit the parent binding; a value above the session default needs a human confirmation in the board UI before the card can run."
9114
+ description: "Permission preset for the execution session; omit to adopt the board new-card default. An omitted permission is never taken from a parent: the launch resolves the parent binding instead. A value above the session default needs a human confirmation in the board UI before the card can run."
8278
9115
  },
8279
9116
  model: {
8280
9117
  type: "string",
8281
- description: "Pinned model as provider/model (or a model id); omit for the host default or the parent value."
9118
+ description: "Pinned model as provider/model (or a model id); omit to adopt the board new-card default, and the host default when none is configured."
9119
+ },
9120
+ reasoningEffort: {
9121
+ type: "string",
9122
+ description: "Reasoning effort id for that model (an adapter-owned level such as \"high\"); omit to adopt the board new-card default for that model, and the model own default when none applies. Only an effort the target model declares is sent; an empty string clears it back to the default."
8282
9123
  },
8283
9124
  reuseSession: {
8284
9125
  type: "boolean",
@@ -8365,6 +9206,8 @@ function buildCreateTool(host) {
8365
9206
  ...args.mode === void 0 || args.mode === "" ? {} : { mode: args.mode },
8366
9207
  ...args.permission === void 0 ? {} : { permission: args.permission },
8367
9208
  ...args.model === void 0 || args.model === "" ? {} : { model: args.model },
9209
+ ...args.reasoningEffort === void 0 || args.reasoningEffort === "" ? {} : { reasoningEffort: args.reasoningEffort },
9210
+ applyCardDefaults: true,
8368
9211
  ...args.reuseSession === true ? { reuseSession: true } : {},
8369
9212
  ...args.teamRun === true ? { teamRun: true } : {},
8370
9213
  ...args.goalRun === true ? { goalRun: true } : {},
@@ -8400,7 +9243,7 @@ function buildUpdateTool(host) {
8400
9243
  return defineTool({
8401
9244
  name: "task_board_update",
8402
9245
  description: [
8403
- "Edit a task board card: title, description, prompt, labels, and the execution targets (workspace, agent preset, permission, model, session reuse).",
9246
+ "Edit a task board card: title, description, prompt, labels, and the execution targets (workspace, agent preset, permission, model, reasoning effort, session reuse).",
8404
9247
  "Only the fields you pass change; pass an empty string to clear a target, or an empty labels array to clear the labels.",
8405
9248
  "Title, description and prompt freeze once the task has started executing; the execution targets stay editable because they only affect future runs.",
8406
9249
  "Changing the pinned permission re-arms the permission confirmation gate."
@@ -8445,6 +9288,10 @@ function buildUpdateTool(host) {
8445
9288
  type: "string",
8446
9289
  description: "New pinned model; an empty string clears it."
8447
9290
  },
9291
+ reasoningEffort: {
9292
+ type: "string",
9293
+ description: "New reasoning effort id for the pinned model; an empty string clears it back to the model own default. Only an effort the target model declares is sent at run time."
9294
+ },
8448
9295
  reuseSession: {
8449
9296
  type: "boolean",
8450
9297
  description: "Continue later runs in the previous execution session."
@@ -8493,6 +9340,7 @@ function buildUpdateTool(host) {
8493
9340
  if (has(args, "workspaceId") && typeof args.workspaceId === "string") patch.workspaceId = args.workspaceId;
8494
9341
  if (has(args, "mode") && typeof args.mode === "string") patch.mode = args.mode;
8495
9342
  if (has(args, "model") && typeof args.model === "string") patch.model = args.model;
9343
+ if (has(args, "reasoningEffort") && typeof args.reasoningEffort === "string") patch.reasoningEffort = args.reasoningEffort;
8496
9344
  if (has(args, "permission") && typeof args.permission === "string") patch.permission = args.permission === "" ? void 0 : args.permission;
8497
9345
  if (has(args, "reuseSession")) patch.reuseSession = args.reuseSession === true;
8498
9346
  if (has(args, "teamRun")) patch.teamRun = args.teamRun === true;
@@ -8625,12 +9473,26 @@ function isLoopbackHostname(hostname) {
8625
9473
  return isIPv4Loopback(hostname);
8626
9474
  }
8627
9475
  /**
9476
+ * Whether a reverse proxy stood between the client and this host: the request
9477
+ * carries CF-Connecting-IP or X-Forwarded-For. Either header is stamped by a
9478
+ * hop that forwards traffic, so the request did not originate on this machine.
9479
+ * @param request - node HTTP request.
9480
+ * @returns true when a forwarding header is present.
9481
+ */
9482
+ function isProxiedRequest(request) {
9483
+ return request.headers["cf-connecting-ip"] !== void 0 || request.headers["x-forwarded-for"] !== void 0;
9484
+ }
9485
+ /**
8628
9486
  * Request-level trust fence: a loopback socket address AND a loopback Host
8629
9487
  * header, plus browser same-origin markers. The socket address is
8630
- * authoritative; X-Forwarded-For is never trusted.
9488
+ * authoritative for a direct connection; a request that carries a forwarding
9489
+ * header is refused outright, because a proxy in front of the host makes both
9490
+ * the socket address and the Host header describe the proxy rather than the
9491
+ * client. X-Forwarded-For is therefore never evidence *for* loopback.
8631
9492
  */
8632
9493
  function isLoopbackRequest(request) {
8633
9494
  if (!isLoopbackAddress(request.socket.remoteAddress)) return false;
9495
+ if (isProxiedRequest(request)) return false;
8634
9496
  const host = request.headers.host;
8635
9497
  if (typeof host !== "string") return false;
8636
9498
  let hostUrl;
@@ -10080,8 +10942,14 @@ const Config = z.object({
10080
10942
  sessionDefaultPermission: z.union(TASK_PERMISSIONS),
10081
10943
  maxSubtaskDepth: z.number().min(1).max(3).default(1).volatile(),
10082
10944
  sessionPollSeconds: z.number().min(1).max(300).default(5).volatile(),
10945
+ runLaunchWidth: z.number().min(1).max(16).default(3).volatile(),
10946
+ spendBudgetTokens: z.number().min(0).default(0).volatile(),
10083
10947
  teamProvider: z.string().min(1).default(DEFAULT_TEAM_PROVIDER),
10084
10948
  goalRunEnabled: z.boolean().default(false).volatile(),
10949
+ cardDefaultMode: z.string().default("").volatile(),
10950
+ cardDefaultPermission: z.union([...TASK_PERMISSIONS, ""]).default("").volatile(),
10951
+ cardDefaultModel: z.string().default("").volatile(),
10952
+ cardDefaultReasoningEffort: z.string().default("").volatile(),
10085
10953
  goalVerification: z.boolean().default(true).volatile(),
10086
10954
  goalVerificationModel: z.string().default("").volatile(),
10087
10955
  goalVerificationReasoningEffort: z.string().default("").volatile(),
@@ -10264,6 +11132,50 @@ function resolveLlmRuntime(ctx) {
10264
11132
  }
10265
11133
  }
10266
11134
  /**
11135
+ * Resolve the optional `sessionController` service. Like the tool registry and
11136
+ * the llm runtime, it is read dynamically so capture-only test contexts that do
11137
+ * not mount the full session controller still activate the board.
11138
+ * @param ctx - the plugin context.
11139
+ * @returns the session controller face, or undefined when unavailable.
11140
+ */
11141
+ function resolveSessionController(ctx) {
11142
+ try {
11143
+ const controller = ctx.get?.("sessionController");
11144
+ return controller !== void 0 && typeof controller.resolveAgent === "function" ? controller : void 0;
11145
+ } catch {
11146
+ return;
11147
+ }
11148
+ }
11149
+ /**
11150
+ * Resolve the live Agent for an execution session, resuming a cold persisted
11151
+ * session through `sessionController.resolveAgent` when it is not yet in
11152
+ * `ctx.agents` (issue #1861).
11153
+ *
11154
+ * A fresh run (`session/create`) or a session the browser is currently
11155
+ * following is already in `ctx.agents`, so the fast path returns immediately.
11156
+ * A scheduled or manual reuse of a cold session — one that `session/list`
11157
+ * reports as idle from disk without activating its Agent — is not in
11158
+ * `ctx.agents` when `pinAndPrompt` runs `/permission` ahead of
11159
+ * `session/selectModel` and `session/prompt`; delegating to
11160
+ * `sessionController.resolveAgent` resumes it with its recorded preset and
11161
+ * model-selection state, matching what those gateway endpoints do next.
11162
+ * @param ctx - the plugin context.
11163
+ * @param sessionId - the target execution session id.
11164
+ * @returns the live Agent for `sessionId`.
11165
+ */
11166
+ async function resolveExecutionAgent(ctx, sessionId) {
11167
+ const live = ctx.agents.get(sessionId);
11168
+ if (live !== void 0) return live;
11169
+ const controller = resolveSessionController(ctx);
11170
+ if (controller !== void 0) {
11171
+ const resolved = await controller.resolveAgent(sessionId);
11172
+ if ("agent" in resolved && resolved.agent !== void 0) return resolved.agent;
11173
+ const detail = "error" in resolved && typeof resolved.error?.message === "string" && resolved.error.message !== "" ? `: ${resolved.error.message}` : "";
11174
+ throw new Error(`execution session ${sessionId} is not available${detail}`);
11175
+ }
11176
+ throw new Error(`execution session ${sessionId} is not available`);
11177
+ }
11178
+ /**
10267
11179
  * Activate the board's host half: ledger, routes, cron scheduler, power
10268
11180
  * inhibitor, and the model-facing announcement.
10269
11181
  *
@@ -10289,6 +11201,18 @@ function applyImpl(ctx, config) {
10289
11201
  /** Current roster-poll cadence in seconds (read live: the settings card edits it in place). */
10290
11202
  const sessionPollSeconds = () => readConfigField(config?.sessionPollSeconds, 5);
10291
11203
  /**
11204
+ * Current run-launch admission width. Read live on every admission, so the
11205
+ * settings card bounds the next launch of a run that is still queueing without
11206
+ * remounting the row; the Host clamps a hand-edited value into the schema range.
11207
+ */
11208
+ const runLaunchWidth = () => readConfigField(config?.runLaunchWidth, 3);
11209
+ /**
11210
+ * Current daily token cap, read at each gate like the width above. The value
11211
+ * decides first: 0 — the default — ends the gate before a file is opened, so
11212
+ * a board that never set a cap pays nothing for it.
11213
+ */
11214
+ const spendBudgetTokens = () => readConfigField(config?.spendBudgetTokens, 0);
11215
+ /**
10292
11216
  * The baseline the permission confirmation gate judges against: the row's own
10293
11217
  * `sessionDefaultPermission` when the deployment pins one, otherwise the Host's
10294
11218
  * default preset. Read per call through the ledger, so a Host Settings change
@@ -10320,18 +11244,37 @@ function applyImpl(ctx, config) {
10320
11244
  * executions that start afterwards.
10321
11245
  */
10322
11246
  const goalRunEnabled = () => readConfigField(config?.goalRunEnabled, false);
11247
+ /**
11248
+ * Live reader of the new-card defaults, read at every use like the switch
11249
+ * above: the create dialog prefills from the published snapshot, and each
11250
+ * creating session re-reads them when it submits the create. A blank value
11251
+ * means "not set" and reaches the resolver as an absent target.
11252
+ */
11253
+ const cardDefaults = () => {
11254
+ const permission = readConfigField(config?.cardDefaultPermission, "");
11255
+ return {
11256
+ mode: readConfigField(config?.cardDefaultMode, "").trim() || void 0,
11257
+ permission: isTaskPermission(permission) ? permission : void 0,
11258
+ model: readConfigField(config?.cardDefaultModel, "").trim() || void 0,
11259
+ reasoningEffort: readConfigField(config?.cardDefaultReasoningEffort, "").trim() || void 0
11260
+ };
11261
+ };
11262
+ const ownerPeer = createOwnerPeer(ctx);
10323
11263
  const host = new TaskBoardHostService(ctx.typertGateway, {
10324
11264
  workspaceRegistry: ctx.workspaceRegistry,
11265
+ ownerPeer,
10325
11266
  sessionDefaultPermission,
10326
11267
  maxSubtaskDepth: maxSubtaskDepth(),
10327
11268
  goalRunEnabled,
11269
+ runLaunchWidth,
11270
+ spendBudgetTokens,
11271
+ cardDefaults,
10328
11272
  verificationSettings,
10329
11273
  verificationCatalog,
10330
11274
  timers: resolveHostTimers(ctx),
10331
11275
  team: buildTeamDispatcher(ctx, config?.teamProvider ?? "spawn"),
10332
11276
  commandDispatcher: { async execute(sessionId, line, signal) {
10333
- const agent = ctx.agents.get(sessionId);
10334
- if (agent === void 0) throw new Error(`execution session ${sessionId} is not available`);
11277
+ const agent = await resolveExecutionAgent(ctx, sessionId);
10335
11278
  return (await ctx.commands.execute(agent, line, [], signal))?.result;
10336
11279
  } }
10337
11280
  });
@@ -10340,7 +11283,11 @@ function applyImpl(ctx, config) {
10340
11283
  host.start();
10341
11284
  if (typeof ctx.provide === "function") ctx.provide(TASK_BOARD_SERVICE_NAME, {
10342
11285
  registerExtension: (extension) => host.registerExtension(extension),
10343
- isExtensionEnabled: (extensionId) => host.extensions.isActive(extensionId)
11286
+ isExtensionEnabled: (extensionId) => host.extensions.isActive(extensionId),
11287
+ snapshot: () => host.snapshot(),
11288
+ apply: (requestId, action, initiator) => host.apply(requestId, action, initiator),
11289
+ subscribe: (listener) => host.subscribe(listener),
11290
+ verificationOptions: () => host.verificationOptions()
10344
11291
  });
10345
11292
  let disposeTools;
10346
11293
  const setToolsEnabled = (active) => {
@@ -10455,4 +11402,4 @@ function applyImpl(ctx, config) {
10455
11402
  sync();
10456
11403
  }
10457
11404
  //#endregion
10458
- export { Config, DEFAULT_GOAL_RUN, DEFAULT_GOAL_VERIFICATION, DEFAULT_PROXY_TOKEN_ENV, DEFAULT_TEAM_PROVIDER, TASK_BOARD_GUIDANCE, apply, buildTeamDispatcher, inject, readConfigField, resolveAgentTeams, resolveHostDefaultPermission, resolveHostTimers, resolveLlmRuntime, resolveProxyAccess, resolveToolRegistry };
11405
+ export { Config, DEFAULT_GOAL_RUN, DEFAULT_GOAL_VERIFICATION, DEFAULT_PROXY_TOKEN_ENV, DEFAULT_TEAM_PROVIDER, TASK_BOARD_GUIDANCE, apply, buildTeamDispatcher, inject, readConfigField, resolveAgentTeams, resolveExecutionAgent, resolveHostDefaultPermission, resolveHostTimers, resolveLlmRuntime, resolveProxyAccess, resolveSessionController, resolveToolRegistry };