@linxin666/dsh-client-ui-task-board 0.4.7 → 0.4.9

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 (75) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +29 -22
  3. package/README.zh.md +29 -22
  4. package/lib/client.js +1553 -670
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +757 -419
  7. package/lib/types/client/PluginSettingsCard.d.ts +60 -0
  8. package/lib/types/client/TaskBoardSettingsCard.d.ts +14 -0
  9. package/lib/types/client/board/ExecutionLog.d.ts +16 -0
  10. package/lib/types/client/board/TaskForm.d.ts +4 -0
  11. package/lib/types/client/board/VerificationReport.d.ts +2 -15
  12. package/lib/types/client/body-mutations.d.ts +45 -0
  13. package/lib/types/client/locales.d.ts +44 -6
  14. package/lib/types/client/suppress-schedule-row.d.ts +86 -0
  15. package/lib/types/client/telemetry.d.ts +14 -2
  16. package/lib/types/core/controller.d.ts +1 -1
  17. package/lib/types/core/execution-summary.d.ts +52 -0
  18. package/lib/types/core/extension.d.ts +34 -0
  19. package/lib/types/core/spend-budget.d.ts +28 -0
  20. package/lib/types/core/subtask.d.ts +59 -49
  21. package/lib/types/core/tasks.d.ts +37 -9
  22. package/lib/types/core/use-cases/task-update.d.ts +1 -1
  23. package/lib/types/core/workspace-target.d.ts +23 -3
  24. package/lib/types/host/launch-admission.d.ts +8 -9
  25. package/lib/types/host-ledger.d.ts +96 -50
  26. package/lib/types/host-routes.d.ts +49 -0
  27. package/lib/types/host-runner.d.ts +24 -11
  28. package/lib/types/host-service.d.ts +38 -50
  29. package/lib/types/host-spend.d.ts +52 -0
  30. package/lib/types/index.d.ts +70 -61
  31. package/lib/types/loopback.d.ts +41 -1
  32. package/lib/types/protocol.d.ts +0 -5
  33. package/lib/types/tool-surface.d.ts +1 -0
  34. package/package.json +25 -25
  35. package/src/client/CardDefaultPresetField.tsx +1 -1
  36. package/src/client/PluginSettingsCard.tsx +140 -20
  37. package/src/client/TaskBoardSettingsCard.tsx +104 -24
  38. package/src/client/board/ExecutionLog.tsx +140 -0
  39. package/src/client/board/LinkSubtaskModal.tsx +1 -9
  40. package/src/client/board/NewTaskModal.tsx +2 -11
  41. package/src/client/board/TaskCard.tsx +45 -23
  42. package/src/client/board/TaskDetail.tsx +407 -261
  43. package/src/client/board/TaskForm.tsx +19 -4
  44. package/src/client/board/VerificationReport.tsx +143 -104
  45. package/src/client/board/task-markdown.module.css +11 -8
  46. package/src/client/board-settings.module.css +35 -7
  47. package/src/client/board.module.css +855 -115
  48. package/src/client/body-mutations.ts +133 -0
  49. package/src/client/index.ts +10 -0
  50. package/src/client/locales.ts +101 -24
  51. package/src/client/settings-card.module.css +141 -11
  52. package/src/client/suppress-schedule-row.ts +198 -0
  53. package/src/client/telemetry.ts +47 -2
  54. package/src/core/controller.ts +1 -3
  55. package/src/core/execution-summary.ts +96 -0
  56. package/src/core/extension.ts +34 -0
  57. package/src/core/spend-budget.ts +35 -0
  58. package/src/core/store.ts +4 -0
  59. package/src/core/subtask.ts +81 -76
  60. package/src/core/tasks.ts +48 -10
  61. package/src/core/use-cases/task-update.ts +1 -3
  62. package/src/core/workspace-target.ts +27 -3
  63. package/src/host/agent-tools.ts +14 -15
  64. package/src/host/launch-admission.ts +8 -9
  65. package/src/host-ledger.ts +218 -127
  66. package/src/host-routes.ts +65 -2
  67. package/src/host-runner.ts +68 -35
  68. package/src/host-service.ts +136 -132
  69. package/src/host-spend.ts +105 -0
  70. package/src/index.ts +115 -104
  71. package/src/loopback.ts +57 -1
  72. package/src/protocol.ts +2 -9
  73. package/src/tool-surface.ts +1 -0
  74. package/lib/types/client/board/team-run-promotion.d.ts +0 -26
  75. package/src/client/board/team-run-promotion.ts +0 -39
package/lib/index.js CHANGED
@@ -1,10 +1,10 @@
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
8
  import { Context } from "@deepseek-ai/cordis";
9
9
  import { ReasoningEffortId, createUserMessage } from "@deepseek-ai/dsh-llm";
10
10
  import { defineTool } from "@deepseek-ai/dsh-tools";
@@ -19,6 +19,164 @@ function normalizeRunLaunchWidth(width) {
19
19
  if (width === void 0 || !Number.isFinite(width)) return 3;
20
20
  return Math.min(Math.max(Math.trunc(width), 1), 16);
21
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
+ }
22
180
  /**
23
181
  * Clamp a configured cadence into the supported range. A value the schema
24
182
  * would refuse (non-finite, below the floor, above the ceiling) still leaves
@@ -157,41 +315,6 @@ var LaunchAdmissionQueue = class {
157
315
  }
158
316
  };
159
317
  //#endregion
160
- //#region src/dsh-home.ts
161
- /**
162
- * DSH_HOME resolution shared by the plugin family's Host halves: the
163
- * environment override wins, the platform home fallback follows. Mirrors
164
- * what dsh-pet and dsh-liangshen each used to implement locally.
165
- */
166
- /** Expand a leading ~ (or ~user) in a path, platform-style. */
167
- function expandHome(path, home = homedir()) {
168
- const j = home.startsWith("/") ? join$1 : join;
169
- if (path === "~") return home;
170
- if (path.startsWith("~/") || path.startsWith("~\\")) return j(home, path.slice(2));
171
- return path;
172
- }
173
- /**
174
- * Resolve the DSH home directory.
175
- * @param env - process environment to read DSH_HOME from.
176
- * @param home - platform home directory fallback (test seam).
177
- * @returns the absolute DSH home path.
178
- */
179
- function resolveDshHome(env = process.env, home = homedir()) {
180
- const isPosix = home.startsWith("/");
181
- const j = isPosix ? join$1 : join;
182
- const isAbs = isPosix ? isAbsolute$1 : isAbsolute;
183
- const raw = env.DSH_HOME;
184
- if (raw !== void 0 && raw.trim() !== "") {
185
- const expanded = expandHome(raw.trim(), home);
186
- return isAbs(expanded) ? expanded : j(process.cwd(), expanded);
187
- }
188
- return j(home, ".dsh");
189
- }
190
- /** Resolve the DSH home directory from the live environment. */
191
- function dshHome() {
192
- return resolveDshHome();
193
- }
194
- //#endregion
195
318
  //#region src/core/schedule.ts
196
319
  /** Inclusive ranges per field, in cron order. */
197
320
  const FIELD_RANGES = [
@@ -542,6 +665,14 @@ function normalizeTaskIntegrations(value) {
542
665
  }
543
666
  return Object.keys(result).length === 0 ? void 0 : result;
544
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;
545
676
  /**
546
677
  * Trim an execution list to at most {@link EXECUTION_HISTORY_LIMIT} records,
547
678
  * most recent last. A running (unsettled) execution is never trimmed: the
@@ -759,7 +890,6 @@ function createTask(input, now, id) {
759
890
  model: normalizeTargetId(input.model),
760
891
  reasoningEffort: normalizeTargetId(input.reasoningEffort),
761
892
  reuseSession: input.reuseSession === true ? true : void 0,
762
- teamRun: input.teamRun === true ? true : void 0,
763
893
  goalRun: input.goalRun === true ? true : void 0,
764
894
  skipVerification: input.skipVerification === true ? true : void 0,
765
895
  ...input.freeze === void 0 ? {} : { freeze: freezeOf(input.freeze, now) },
@@ -877,7 +1007,7 @@ function settledStatus(task, outcome) {
877
1007
  * matching column. No-op (returns the input task) when the execution is not
878
1008
  * the task's latest or is already settled.
879
1009
  */
880
- function settleExecution(task, executionId, outcome, now, error) {
1010
+ function settleExecution(task, executionId, outcome, now, error, summary) {
881
1011
  const index = task.executions.findIndex((execution) => execution.id === executionId);
882
1012
  if (index === -1) return task;
883
1013
  const execution = task.executions[index];
@@ -886,7 +1016,8 @@ function settleExecution(task, executionId, outcome, now, error) {
886
1016
  ...execution,
887
1017
  endedAt: now,
888
1018
  result: outcome,
889
- error
1019
+ error,
1020
+ ...summary === void 0 ? {} : { summary }
890
1021
  };
891
1022
  const executions = [...task.executions];
892
1023
  executions[index] = settled;
@@ -1019,47 +1150,71 @@ function checkParentLink(tasks, childId, parentId, maxSubtaskDepth, lineage) {
1019
1150
  return { ok: true };
1020
1151
  }
1021
1152
  /**
1022
- * The tasks one run request opens executions for: the requested task first,
1023
- * then its on-board descendants within the configured depth. This is the
1024
- * SHAPE of a cascade — every walk that must see the whole tree (settlement,
1025
- * archive/restore, the running lock) reads it. The run path filters it with
1026
- * {@link joinsCascadeRun}: archived tasks never run, a participant that already
1027
- * has an open execution is skipped by the caller, which cannot start it twice,
1028
- * and a finished descendant is left alone.
1153
+ * The tasks one run request opens executions for: the requested card ALONE.
1154
+ *
1155
+ * Running a card never expands into its subtask tree. The card's own session
1156
+ * reads its subtasks through the board tools and dispatches subagents itself,
1157
+ * so a parent run opens exactly one session. Clicking a subtask runs that
1158
+ * subtask as its own root, again without expanding its own descendants. The
1159
+ * lineage queries around this one answer questions about the tree the card's
1160
+ * agent works with (who is still outstanding, what a historical run group
1161
+ * still holds open) — never who gets a session from the Host.
1162
+ * @param tasks - the ledger.
1163
+ * @param rootId - the task the run request named.
1164
+ * @returns the one card this run opens an execution for, or [] when unknown.
1029
1165
  */
1030
- function cascadeTargets(tasks, rootId, maxSubtaskDepth) {
1166
+ function cascadeTargets(tasks, rootId) {
1031
1167
  const root = tasks.find((task) => task.id === rootId);
1032
- if (root === void 0) return [];
1033
- return [root, ...descendantTasks(tasks, rootId, maxSubtaskDepth)];
1168
+ return root === void 0 ? [] : [root];
1034
1169
  }
1035
1170
  /**
1036
- * Whether a cascade member takes part in a new run.
1037
- *
1038
- * The task the user ran is always a member: the request names that card, and
1039
- * the operator asked for it to run whatever its column says. A descendant does
1040
- * not join once it sits in the `done` column — its work is finished, so running
1041
- * the parent again is a run of the parent, never a second execution of work
1042
- * that is already done. The rule keys on the column alone, so it covers both a
1043
- * subtask that ran and one an operator moved to done by hand, and it holds for
1044
- * every trigger: a manual run, a re-run, and a due occurrence of a schedule.
1045
- * A card whose own schedule is enabled settles back into `todo`, so a scheduled
1046
- * subtask stays a participant; to make a finished one run again, move it back
1047
- * to `todo` or run it on its own.
1048
- * @param task - the candidate member.
1049
- * @param rootId - the task the run request named.
1050
- * @returns false when this member is left alone by the run.
1171
+ * A task together with every descendant within the configured depth: the
1172
+ * subtree a lineage gate (archive, restore, force-close) has to walk.
1051
1173
  */
1052
- function joinsCascadeRun(task, rootId) {
1053
- return task.id === rootId || task.status !== "done";
1174
+ function subtreeTasks(tasks, id, maxSubtaskDepth) {
1175
+ const root = tasks.find((task) => task.id === id);
1176
+ return root === void 0 ? [] : [root, ...descendantTasks(tasks, id, maxSubtaskDepth)];
1054
1177
  }
1178
+ /**
1179
+ * Whether a card still has work outstanding: anything outside the `done`
1180
+ * column. It keys on the column alone, so it covers both a subtask that ran
1181
+ * and one an operator moved to done by hand.
1182
+ */
1183
+ function isOutstanding(task) {
1184
+ return task.status !== "done";
1185
+ }
1186
+ /**
1187
+ * The descendants of a card that still have work outstanding, in breadth-first
1188
+ * order: the cards its own session is expected to dispatch. An archived
1189
+ * descendant is off the board and cannot be dispatched, so it is not listed.
1190
+ */
1191
+ function outstandingDescendants(tasks, rootId, maxSubtaskDepth) {
1192
+ return descendantTasks(tasks, rootId, maxSubtaskDepth).filter((task) => task.archivedAt === void 0 && isOutstanding(task));
1193
+ }
1194
+ /**
1195
+ * Whether any descendant of this card still sits outside the `done` column.
1196
+ * This is the ONE decision behind both the forced agent preset and the dispatch
1197
+ * section of the execution prompt: a card whose tree still holds work runs as
1198
+ * the autonomous dispatcher.
1199
+ */
1200
+ function hasOutstandingDescendants(tasks, rootId, maxSubtaskDepth) {
1201
+ return outstandingDescendants(tasks, rootId, maxSubtaskDepth).length > 0;
1202
+ }
1203
+ /**
1204
+ * Agent preset a run with unfinished subtasks is forced under. The id comes
1205
+ * from packages/dsh-liangshen (its own `LIANGSHEN_PRESET_ID`); the force is
1206
+ * applied at launch and never written into a card's `mode` field.
1207
+ */
1208
+ const LIANGSHEN_PRESET_ID = "liangshen";
1055
1209
  /** The open execution of a task inside a run group, if it still exists. */
1056
1210
  function openGroupExecution(task, runGroupId) {
1057
1211
  return task.executions.find((execution) => execution.runGroupId === runGroupId && execution.endedAt === void 0);
1058
1212
  }
1059
1213
  /**
1060
1214
  * The direct subtasks of parentTaskId whose execution in this run group is
1061
- * still open: the parent remaining waiters. The parent may settle once this
1062
- * list is empty and its own outcome is known.
1215
+ * still open: the parent's remaining waiters. A stored multi-member group (a
1216
+ * run the Host opened before it stopped spreading one run across a subtree)
1217
+ * folds once this list is empty and the parent's own outcome is known.
1063
1218
  */
1064
1219
  function pendingCascadeChildren(tasks, parentTaskId, runGroupId) {
1065
1220
  const pending = [];
@@ -1074,9 +1229,9 @@ function pendingCascadeChildren(tasks, parentTaskId, runGroupId) {
1074
1229
  return pending;
1075
1230
  }
1076
1231
  /**
1077
- * Fold a cascade parent own outcome and its children outcomes into one
1078
- * verdict: failure dominates, then cancellation, then success. The error text
1079
- * is the first failure, falling back to the first cancellation.
1232
+ * Fold a stored run-group parent's own outcome and its children's outcomes into
1233
+ * one verdict: failure dominates, then cancellation, then success. The error
1234
+ * text is the first failure, falling back to the first cancellation.
1080
1235
  */
1081
1236
  function combineCascadeOutcome(entries) {
1082
1237
  let result = "succeeded";
@@ -1118,47 +1273,6 @@ function effectiveTaskPermission(task) {
1118
1273
  * elevated card is runnable while a subtask's own unconfirmed binding stays
1119
1274
  * gated.
1120
1275
  */
1121
- /**
1122
- * The immutable teammate name for one team-mode member. Teammate names are
1123
- * lower-kebab-case and must stay unique for the lifetime of the Team: the
1124
- * run-group token separates two runs of the same tree, and the member
1125
- * discriminator separates two members of one run that reduce to the same slug.
1126
- *
1127
- * The discriminator is not cosmetic. A title with no ASCII word characters (a
1128
- * CJK title, for example) carries no slug at all, so every such title of one
1129
- * run group collides on the generic prefix; Agent Teams answers every member
1130
- * after the first with `teammate name "..." was already used in this Team`,
1131
- * and those subtasks never start. Two ASCII titles that share a slug
1132
- * (`AI 强度预测` next to `AI 配比优化`) collide the same way.
1133
- * @param title - the member task's title.
1134
- * @param token - the run group id (the task id when no group is recorded).
1135
- * @param memberId - the member task's id, which makes the name unique in the run.
1136
- * @returns the teammate name handed to the Agent Teams service.
1137
- */
1138
- function teammateName(title, token, memberId) {
1139
- const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 32).replace(/-+$/g, "");
1140
- const suffix = token.replace(/[^a-z0-9]/gi, "").slice(0, 8).toLowerCase();
1141
- const member = memberId === void 0 || memberId === "" ? void 0 : stableTag(memberId);
1142
- return [
1143
- slug === "" ? "subtask" : slug,
1144
- member,
1145
- suffix === "" ? "run" : suffix
1146
- ].filter((part) => part !== void 0).join("-");
1147
- }
1148
- /**
1149
- * A stable 4-hex tag for one member id. The name is derived twice for the same
1150
- * member — once for the Lead's prompt and once for the spawn request — so the
1151
- * tag must be a pure function of the id, never of a clock or a counter. FNV-1a
1152
- * keeps it dependency-free in `core/`, which both halves compile.
1153
- */
1154
- function stableTag(value) {
1155
- let hash = 2166136261;
1156
- for (let index = 0; index < value.length; index += 1) {
1157
- hash ^= value.charCodeAt(index);
1158
- hash = Math.imul(hash, 16777619) >>> 0;
1159
- }
1160
- return hash.toString(16).padStart(8, "0").slice(0, 4);
1161
- }
1162
1276
  function resolveExecutionTargets(task, tasks, maxSubtaskDepth = 3) {
1163
1277
  if (task.parentId === void 0) return task;
1164
1278
  const chain = [task, ...ancestorChain(tasks, task).slice(0, maxSubtaskDepth)];
@@ -1182,6 +1296,89 @@ function resolveExecutionTargets(task, tasks, maxSubtaskDepth = 3) {
1182
1296
  permissionConfirmedAt: own === void 0 ? owner?.permissionConfirmedAt : task.permissionConfirmedAt
1183
1297
  };
1184
1298
  }
1299
+ //#endregion
1300
+ //#region src/core/execution-summary.ts
1301
+ /**
1302
+ * What one execution left behind: the text of its last assistant message,
1303
+ * recorded on the execution record next to the verdict it belongs to.
1304
+ *
1305
+ * A settled execution used to carry only a verdict, so a parent card could see
1306
+ * that a subtask succeeded without ever seeing what it produced, and had to
1307
+ * guess or redo the work. The card's own content cannot answer that: card
1308
+ * content is the plan and freezes at the first execution
1309
+ * (`canEditTaskContent`), so the closing words of a run are recorded on the
1310
+ * execution record instead.
1311
+ *
1312
+ * Pure (no cordis, no runtime imports) so the settlement path is unit-testable
1313
+ * without a session, and so a text-less run degrades to "no field" rather than
1314
+ * to an empty string.
1315
+ */
1316
+ /** One rendered content block of an assistant message, or '' when it has no prose. */
1317
+ function blockProse(block) {
1318
+ if (typeof block !== "object" || block === null) return "";
1319
+ const row = block;
1320
+ return row.type === "text" && typeof row.text === "string" ? row.text : "";
1321
+ }
1322
+ /** The assistant's own prose of one message: its text blocks joined and trimmed. */
1323
+ function messageProse(content) {
1324
+ if (!Array.isArray(content)) return "";
1325
+ return content.map(blockProse).filter((part) => part !== "").join("\n").trim();
1326
+ }
1327
+ /**
1328
+ * Bound one summary, keeping its tail: the closing paragraphs carry the
1329
+ * conclusion a reader is after, and the omitted opening is announced instead of
1330
+ * silently dropped. Mirrors the evidence reader's tail bound.
1331
+ */
1332
+ function truncateExecutionSummary(text, limit = EXECUTION_SUMMARY_LIMIT) {
1333
+ if (text.length <= limit) return text;
1334
+ const notice = "[truncated " + String(text.length - limit) + " chars] ";
1335
+ return notice.length >= limit ? text.slice(-limit) : notice + text.slice(-(limit - notice.length));
1336
+ }
1337
+ /**
1338
+ * The summary one execution's own events support.
1339
+ *
1340
+ * Only events at or after `startedAt` belong to this run: a reused session
1341
+ * carries the history of earlier executions, which must not be reported as this
1342
+ * one's output. The last assistant message WITH prose wins — a trailing
1343
+ * tool-call or reasoning-only message has nothing to leave behind, so the reader
1344
+ * walks back to the last one that speaks.
1345
+ * @param events - the session events the inspection already read.
1346
+ * @param startedAt - the execution's start instant (ms epoch); 0 means "all".
1347
+ * @returns the bounded summary with the seq it came from, or undefined when the
1348
+ * run left no usable text.
1349
+ */
1350
+ function executionSummaryOf(events, startedAt) {
1351
+ 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);
1352
+ for (let index = own.length - 1; index >= 0; index -= 1) {
1353
+ const event = own[index];
1354
+ const data = typeof event.data === "object" && event.data !== null ? event.data : {};
1355
+ const text = messageProse((typeof data.message === "object" && data.message !== null ? data.message : {}).content);
1356
+ if (text === "") continue;
1357
+ return {
1358
+ text: truncateExecutionSummary(text),
1359
+ seq: event.seq
1360
+ };
1361
+ }
1362
+ }
1363
+ /**
1364
+ * Repair one persisted or reported summary.
1365
+ *
1366
+ * A summary is informational, so an unreadable one is dropped on its own rather
1367
+ * than costing the execution (or the task row) it hangs on. A hand-edited
1368
+ * overlong text is bounded on the way in, so no reader ever holds more than the
1369
+ * limit.
1370
+ */
1371
+ function normalizeExecutionSummary(value) {
1372
+ if (typeof value !== "object" || value === null) return void 0;
1373
+ const row = value;
1374
+ if (typeof row.text !== "string" || typeof row.seq !== "number" || !Number.isFinite(row.seq)) return void 0;
1375
+ const text = row.text.trim();
1376
+ if (text === "") return void 0;
1377
+ return {
1378
+ text: truncateExecutionSummary(text),
1379
+ seq: row.seq
1380
+ };
1381
+ }
1185
1382
  /** Marker replacing every sensitive match. */
1186
1383
  const REDACTED_MARKER = "[REDACTED]";
1187
1384
  const SECTION_ORDER$1 = [
@@ -1353,16 +1550,6 @@ function exceedsSessionDefault(permission, sessionDefault) {
1353
1550
  return (PERMISSION_RANK.get(permission) ?? -1) > (PERMISSION_RANK.get(sessionDefault) ?? -1);
1354
1551
  }
1355
1552
  /**
1356
- * Whether a session running at `holder` already carries `permission`: the
1357
- * permission is absent, or its rank does not exceed the holder's. A teammate
1358
- * inherits the Lead session's permission and cannot be narrowed below it, so a
1359
- * subtask's own pin is carried by a team run exactly when this holds, and a pin
1360
- * it does not carry would be silently dropped instead.
1361
- */
1362
- function permissionCarriedBy(holder, permission) {
1363
- return !exceedsSessionDefault(permission, holder);
1364
- }
1365
- /**
1366
1553
  * The confirmation-gate predicate: an elevated permission without a human
1367
1554
  * confirmation stamp. Manual run/rerun and cron must refuse such a card.
1368
1555
  */
@@ -2568,6 +2755,7 @@ function parseLedger(raw) {
2568
2755
  runGroupId: normalizeTargetId(execution.runGroupId),
2569
2756
  ownResult: isExecutionOutcome(execution.ownResult) ? execution.ownResult : void 0,
2570
2757
  ownError: typeof execution.ownError === "string" ? execution.ownError : void 0,
2758
+ summary: normalizeExecutionSummary(execution.summary),
2571
2759
  verification: normalizeVerification(execution.verification),
2572
2760
  external: execution.external === true ? true : void 0
2573
2761
  }));
@@ -3332,7 +3520,6 @@ function applyUpdateTask(tasks, id, patch, now) {
3332
3520
  if ("tags" in patch) next.tags = tagsPatch == null ? void 0 : normalizeTags(tagsPatch);
3333
3521
  if ("permission" in patch && patch.permission !== void 0 && patch.permission !== task.permission || "handover" in patch) next.permissionConfirmedAt = void 0;
3334
3522
  if ("reuseSession" in patch) next.reuseSession = patch.reuseSession === true ? true : void 0;
3335
- if ("teamRun" in patch) next.teamRun = patch.teamRun === true ? true : void 0;
3336
3523
  if ("goalRun" in patch) next.goalRun = patch.goalRun === true ? true : void 0;
3337
3524
  if ("skipVerification" in patch) next.skipVerification = patch.skipVerification === true ? true : void 0;
3338
3525
  if (workspaceId !== void 0 || "workspaceId" in patch) next.workspaceId = workspaceId;
@@ -3532,7 +3719,6 @@ function createInput(value) {
3532
3719
  "reasoningEffort",
3533
3720
  "applyCardDefaults",
3534
3721
  "reuseSession",
3535
- "teamRun",
3536
3722
  "goalRun",
3537
3723
  "skipVerification",
3538
3724
  "tags",
@@ -3543,7 +3729,6 @@ function createInput(value) {
3543
3729
  if (!optionalString(input.workspaceId) || !optionalString(input.mode) || !optionalString(input.model) || !optionalString(input.reasoningEffort)) return false;
3544
3730
  if (input.applyCardDefaults !== void 0 && typeof input.applyCardDefaults !== "boolean") return false;
3545
3731
  if (input.reuseSession !== void 0 && typeof input.reuseSession !== "boolean") return false;
3546
- if (input.teamRun !== void 0 && typeof input.teamRun !== "boolean") return false;
3547
3732
  if (input.goalRun !== void 0 && typeof input.goalRun !== "boolean") return false;
3548
3733
  if (input.skipVerification !== void 0 && typeof input.skipVerification !== "boolean") return false;
3549
3734
  if (input.permission !== void 0 && !isTaskPermission(input.permission)) return false;
@@ -3584,13 +3769,11 @@ function updatePatch(value) {
3584
3769
  "model",
3585
3770
  "reasoningEffort",
3586
3771
  "reuseSession",
3587
- "teamRun",
3588
3772
  "goalRun",
3589
3773
  "skipVerification",
3590
3774
  "tags"
3591
3775
  ])) return false;
3592
3776
  if (patch.reuseSession !== void 0 && patch.reuseSession !== null && typeof patch.reuseSession !== "boolean") return false;
3593
- if (patch.teamRun !== void 0 && patch.teamRun !== null && typeof patch.teamRun !== "boolean") return false;
3594
3777
  if (patch.goalRun !== void 0 && patch.goalRun !== null && typeof patch.goalRun !== "boolean") return false;
3595
3778
  if (patch.skipVerification !== void 0 && patch.skipVerification !== null && typeof patch.skipVerification !== "boolean") return false;
3596
3779
  for (const key of [
@@ -3849,11 +4032,16 @@ function parseEnvelopeAction(value) {
3849
4032
  //#region src/host-ledger.ts
3850
4033
  /** Human-facing text for a refused binding, per surface. */
3851
4034
  function bindingRefusalMessage(refusal, sessionDefault, surface) {
3852
- if (refusal.kind === "subtask-pin") return `team run cannot honor the permission binding of subtask "${refusal.title}": a teammate runs inside the Lead session and inherits its permission, which that pin exceeds; clear the card's permission or run the tree without Agent Team`;
3853
4035
  if (surface === "schedule") return `task "${refusal.title}" has an unconfirmed above-default permission`;
3854
4036
  if (refusal.kind === "root") return `confirmation-required: the effective permission is above the session default (${sessionDefault}); confirm the card's permission binding first`;
3855
4037
  return `confirmation-required: subtask "${refusal.title}" inherits an above-default permission; confirm that card's permission binding first`;
3856
4038
  }
4039
+ /**
4040
+ * Prefix of the `initiatedBy` an inherited descendant verdict carries. The Host
4041
+ * recorded it on the run card's behalf (see `inheritVerdictForDescendants`), not
4042
+ * an outside agent that reported its own work.
4043
+ */
4044
+ const PARENT_RUN_INITIATOR_PREFIX = "parent-run:";
3857
4045
  const MAX_REQUEST_CACHE = 256;
3858
4046
  function timeZone() {
3859
4047
  return resolveHostTimeZone();
@@ -4109,7 +4297,7 @@ function mergeTask(a, b) {
4109
4297
  * missing, cyclic, or names an archived parent while the child is on board is
4110
4298
  * dropped (the task becomes a root) instead of dropping the task. A chain
4111
4299
  * deeper than the current `maxSubtaskDepth` is deliberately KEPT: the limit
4112
- * gates new links, it never deletes a stored one, and every cascade walk is
4300
+ * gates new links, it never deletes a stored one, and every lineage walk is
4113
4301
  * bounded by the limit anyway. The Host is the only writer of these links, so
4114
4302
  * this is a last-resort guard against a hand-edited or imported document.
4115
4303
  */
@@ -4191,12 +4379,22 @@ var HostTaskLedger = class {
4191
4379
  depthLimit;
4192
4380
  /** Live reader of the deployment's new-card defaults (a volatile config read). */
4193
4381
  cardDefaults;
4382
+ /**
4383
+ * Live reader of the daily token cap (0 = no gate). The scheduled path asks it
4384
+ * per due occurrence, so a cap raised after a skipped occurrence admits the
4385
+ * next one without a restart.
4386
+ */
4387
+ spendBudget;
4388
+ /** Today's measured spend in tokens, or undefined when nothing can be measured. */
4389
+ spendUsed;
4194
4390
  constructor(dir = join(dshHome(), "task-board"), now = Date.now, options = {}) {
4195
4391
  this.now = now;
4196
4392
  const baseline = options.sessionDefaultPermission;
4197
4393
  this.sessionDefault = typeof baseline === "function" ? baseline : () => baseline ?? "read-only";
4198
4394
  this.depthLimit = normalizeSubtaskDepth(options.maxSubtaskDepth ?? 1);
4199
4395
  this.cardDefaults = options.cardDefaults ?? (() => ({}));
4396
+ this.spendBudget = options.spendBudgetTokens ?? (() => 0);
4397
+ this.spendUsed = options.spendUsedToday ?? ((now) => usedTokensToday(now));
4200
4398
  mkdirSync(dir, { recursive: true });
4201
4399
  this.file = join(dir, "ledger-v2.json");
4202
4400
  this.lockFile = join(dir, "ledger-v2.lock");
@@ -4369,10 +4567,10 @@ var HostTaskLedger = class {
4369
4567
  }
4370
4568
  }
4371
4569
  /**
4372
- * Open the cascade one due schedule triggers: an empty array means nothing
4373
- * ran (already running, or a participant whose elevated permission is still
4374
- * unconfirmed, a one-shot whose instant was missed, or an exhausted budget),
4375
- * and the rule's own state says which.
4570
+ * Open the one run a due schedule triggers: an empty array means nothing ran
4571
+ * (already running, a card whose elevated permission is still unconfirmed, a
4572
+ * one-shot whose instant was missed, or an exhausted budget), and the rule's
4573
+ * own state says which.
4376
4574
  *
4377
4575
  * The run budget is enforced HERE, inside the single ledger writer: a rule
4378
4576
  * whose counter already reached its cap is stopped instead of opened, so no
@@ -4403,7 +4601,13 @@ var HostTaskLedger = class {
4403
4601
  this.skipOccurrence(taskId, "busy", triggeredAt);
4404
4602
  return [];
4405
4603
  }
4406
- if (schedule.mode === "once") return this.startCascade(task, triggeredAt, void 0, false, {
4604
+ const spendRefusal = this.spendRefusal(triggeredAt);
4605
+ if (spendRefusal !== void 0) {
4606
+ this.document.scheduler.error = `scheduled run refused for task ${taskId}: ${spendRefusal}`;
4607
+ this.skipOccurrence(taskId, "limit", triggeredAt);
4608
+ return [];
4609
+ }
4610
+ if (schedule.mode === "once") return this.startRun(task, triggeredAt, void 0, false, {
4407
4611
  consumed: 1,
4408
4612
  lastTriggeredAt: triggeredAt,
4409
4613
  endedReason: "fired"
@@ -4419,7 +4623,7 @@ var HostTaskLedger = class {
4419
4623
  const consumed = schedule.runCount + 1;
4420
4624
  const budget = scheduleRunBudget(schedule);
4421
4625
  const spent = budget !== void 0 && consumed >= budget;
4422
- return this.startCascade(task, triggeredAt, void 0, false, {
4626
+ return this.startRun(task, triggeredAt, void 0, false, {
4423
4627
  consumed: 1,
4424
4628
  nextRunAt: spent ? void 0 : next,
4425
4629
  lastTriggeredAt: triggeredAt,
@@ -4427,6 +4631,20 @@ var HostTaskLedger = class {
4427
4631
  });
4428
4632
  }
4429
4633
  /**
4634
+ * Why a due occurrence may not open a run because the day already spent the
4635
+ * cap, or undefined when it may. A cap of 0 — the default — answers before the
4636
+ * measurement is read, so a board with no gate reads no ledger file.
4637
+ * @param now - clock instant (ms epoch).
4638
+ * @returns the refusal message, when the cap is reached.
4639
+ */
4640
+ spendRefusal(now) {
4641
+ const cap = this.spendBudget();
4642
+ if (!(cap > 0)) return void 0;
4643
+ const used = this.spendUsed(now);
4644
+ if (used === void 0 || !spendCapReached(used, cap)) return void 0;
4645
+ return spendCapMessage(used, cap);
4646
+ }
4647
+ /**
4430
4648
  * Record a due occurrence that opened no execution: roll a recurring rule to
4431
4649
  * its next occurrence (budget untouched), or stop it when there is none. A
4432
4650
  * one-shot has no second occurrence, so it always stops here with the reason.
@@ -4462,8 +4680,8 @@ var HostTaskLedger = class {
4462
4680
  * failed without creating a session (see
4463
4681
  * {@link applyScheduleRefund}). Called by the service on the failed-launch
4464
4682
  * path only; a manual run and a launch that did reach a session are never
4465
- * refunded. A no-op for a task with no rule, so a failed cascade member does
4466
- * not touch anything.
4683
+ * refunded. A no-op for a task with no rule, so a failed run does not touch
4684
+ * anything.
4467
4685
  * @param taskId - the task whose occurrence is being refunded.
4468
4686
  * @param now - clock instant (ms epoch).
4469
4687
  */
@@ -4529,19 +4747,25 @@ var HostTaskLedger = class {
4529
4747
  this.commit(false);
4530
4748
  }
4531
4749
  /**
4532
- * Settle one execution. A cascade participant first records its OWN outcome
4533
- * and only finalizes once every child execution in its run group has
4534
- * settled, so a parent card leaves 'running' with the whole tree's verdict
4535
- * rather than its own turn alone.
4750
+ * Settle one execution. A NEW run is a single-member group, so it settles on
4751
+ * its own turn. A run group the Host opened before it stopped spreading one
4752
+ * run across a subtree is folded here instead: a stored participant records
4753
+ * its OWN outcome and only finalizes once every child execution in its group
4754
+ * has settled, so a parent card leaves 'running' with the whole group's
4755
+ * verdict rather than its own turn alone.
4756
+ *
4757
+ * `summary` is what the run left behind (see `ExecutionSummary`), passed in
4758
+ * by whichever reader observed the session. It is informational: a caller
4759
+ * without one settles exactly as before, and a settlement never waits on it.
4536
4760
  */
4537
- settle(taskId, executionId, outcome, error) {
4761
+ settle(taskId, executionId, outcome, error, summary) {
4538
4762
  const now = this.now();
4539
4763
  const task = this.document.tasks.find((item) => item.id === taskId);
4540
4764
  const execution = task?.executions.find((entry) => entry.id === executionId);
4541
4765
  if (task === void 0 || execution === void 0 || execution.endedAt !== void 0) return;
4542
4766
  const groupId = execution.runGroupId;
4543
4767
  if (groupId === void 0) {
4544
- this.document.tasks = this.document.tasks.map((item) => item.id === taskId ? settleExecution(item, executionId, outcome, now, error) : item);
4768
+ this.document.tasks = this.document.tasks.map((item) => item.id === taskId ? settleExecution(item, executionId, outcome, now, error, summary) : item);
4545
4769
  this.commit();
4546
4770
  return;
4547
4771
  }
@@ -4553,15 +4777,82 @@ var HostTaskLedger = class {
4553
4777
  executions: item.executions.map((entry) => entry.id === executionId ? {
4554
4778
  ...entry,
4555
4779
  ownResult: outcome,
4556
- ownError: error
4780
+ ownError: error,
4781
+ ...summary === void 0 ? {} : { summary }
4557
4782
  } : entry)
4558
4783
  });
4559
4784
  changed = true;
4560
4785
  }
4561
4786
  if (task.teamRun === true && this.closeTeamMembers(taskId, groupId, execution.ownResult ?? outcome, execution.ownError ?? error, now)) changed = true;
4562
4787
  if (this.settleCascade(taskId, groupId, now)) changed = true;
4788
+ if (this.inheritVerdictForDescendants(taskId, executionId, groupId, now)) changed = true;
4563
4789
  if (changed) this.commit();
4564
4790
  }
4791
+ /**
4792
+ * Record the run's verdict on the outstanding descendants its root was asked
4793
+ * to dispatch.
4794
+ *
4795
+ * A card with unfinished subtasks runs as an autonomous dispatcher: its
4796
+ * session reads the subtasks, dispatches them with subagents, and is asked to
4797
+ * write their conclusions back with
4798
+ * `task_board_manage({action:'record-external-outcome'})` before it finishes.
4799
+ * A run that never wrote one back would leave those cards parked with no
4800
+ * record of what the parent decided about them, so once the RUN CARD's
4801
+ * execution reached a decisive terminal record, every outstanding descendant
4802
+ * this run opened no execution for inherits that verdict as an external
4803
+ * record.
4804
+ *
4805
+ * Idempotent by construction: a card that already carries an execution in
4806
+ * this run group (the fold owns it), an open execution (it is running on its
4807
+ * own), or a terminal record stamped after this run started (the dispatching
4808
+ * agent's own backfill, or an earlier pass of this one) is left alone. Only a
4809
+ * decisive verdict is inherited: a cancelled run judged nothing about the
4810
+ * subtasks, and a subtask already in the done column has nothing left to
4811
+ * inherit.
4812
+ * @param taskId - the card whose execution just settled.
4813
+ * @param executionId - that execution.
4814
+ * @param groupId - its run group.
4815
+ * @param now - clock instant (ms epoch).
4816
+ * @returns whether the document changed.
4817
+ */
4818
+ inheritVerdictForDescendants(taskId, executionId, groupId, now) {
4819
+ const root = this.document.tasks.find((item) => item.id === taskId);
4820
+ if (root === void 0) return false;
4821
+ const execution = root.executions.find((entry) => entry.id === executionId);
4822
+ if (execution?.endedAt === void 0 || execution.result === void 0) return false;
4823
+ if (execution.result !== "succeeded" && execution.result !== "failed") return false;
4824
+ const verdict = execution.result;
4825
+ if (ancestorChain(this.document.tasks, root).some((ancestor) => ancestor.executions.some((entry) => entry.runGroupId === groupId))) return false;
4826
+ const descendants = new Set(outstandingDescendants(this.document.tasks, root.id, this.maxSubtaskDepth).map((task) => task.id));
4827
+ if (descendants.size === 0) return false;
4828
+ const note = `本次执行由父卡「${root.title}」统一判定,本卡未单独开会话执行;结论继承自父卡运行`;
4829
+ let changed = false;
4830
+ this.document.tasks = this.document.tasks.map((task) => {
4831
+ if (!descendants.has(task.id)) return task;
4832
+ if (task.executions.some((entry) => entry.runGroupId === groupId)) return task;
4833
+ if (task.executions.some((entry) => entry.endedAt === void 0)) return task;
4834
+ if (task.executions.some((entry) => entry.endedAt !== void 0 && entry.startedAt >= execution.startedAt)) return task;
4835
+ changed = true;
4836
+ const inherited = {
4837
+ id: crypto.randomUUID(),
4838
+ sessionId: void 0,
4839
+ startedAt: now,
4840
+ endedAt: now,
4841
+ result: verdict,
4842
+ error: note,
4843
+ initiatedBy: PARENT_RUN_INITIATOR_PREFIX + root.id,
4844
+ external: true,
4845
+ runGroupId: groupId
4846
+ };
4847
+ return {
4848
+ ...task,
4849
+ status: settledStatus(task, verdict),
4850
+ updatedAt: now,
4851
+ executions: retainRecentExecutions([...task.executions, inherited])
4852
+ };
4853
+ });
4854
+ return changed;
4855
+ }
4565
4856
  attachSession(taskId, executionId, sessionId) {
4566
4857
  const now = this.now();
4567
4858
  if (this.document.tasks.find((item) => item.id === taskId)?.executions.find((entry) => entry.id === executionId)?.endedAt !== void 0) return;
@@ -4696,7 +4987,7 @@ var HostTaskLedger = class {
4696
4987
  if (task.archivedAt !== void 0) throw new Error("archived task is read-only");
4697
4988
  if (!task.executions.some((entry) => entry.endedAt === void 0)) throw new Error("task has no open execution");
4698
4989
  const reason = "execution closed manually by " + (initiator === void 0 || initiator === "" ? "the operator" : initiator) + ": no verdict was recorded";
4699
- for (const member of cascadeTargets(this.document.tasks, action.taskId, this.maxSubtaskDepth)) for (const execution of member.executions) {
4990
+ for (const member of subtreeTasks(this.document.tasks, action.taskId, this.maxSubtaskDepth)) for (const execution of member.executions) {
4700
4991
  if (execution.endedAt !== void 0) continue;
4701
4992
  this.document.tasks = this.document.tasks.map((item) => item.id !== member.id ? item : settleExecution(item, execution.id, "cancelled", now, reason));
4702
4993
  }
@@ -4767,9 +5058,10 @@ var HostTaskLedger = class {
4767
5058
  if (task === void 0 || hasOpenExecution(task)) throw new Error("task is already running or missing");
4768
5059
  const refusal = this.bindingRefusal(task);
4769
5060
  if (refusal !== void 0) throw new Error(bindingRefusalMessage(refusal, this.sessionDefaultPermission, "run"));
4770
- runs = this.startCascade(task, now, initiator, action.kind === "rerun");
5061
+ runs = this.startRun(task, now, initiator, action.kind === "rerun");
4771
5062
  break;
4772
5063
  }
5064
+ default: throw new Error(`unknown task board action kind: ${String(action.kind)}`);
4773
5065
  }
4774
5066
  if (runs === void 0 || runs.length === 0) this.commit();
4775
5067
  return {
@@ -4795,100 +5087,68 @@ var HostTaskLedger = class {
4795
5087
  /**
4796
5088
  * The binding that makes a run illegal, if any.
4797
5089
  *
4798
- * A plain cascade launches one session per participant, so every participant
4799
- * carries its own resolved binding and each one gates the run. A team run
4800
- * launches only the Lead session: the Lead's binding gates it, and a
4801
- * teammate inherits that session's permission, so a subtask's OWN pin is
4802
- * refused exactly when the Lead session does not already carry it — the
4803
- * teammate could never be given that authority, and dropping the pin
4804
- * silently would misreport the work (an inherited binding is the Lead's own
4805
- * and stays allowed once the Lead is confirmed).
5090
+ * Only the card being run gets a session, so only ITS resolved binding gates
5091
+ * the run: a subtask's own elevated permission is that subtask's gate when the
5092
+ * subtask is run, and no longer blocks its parent from running.
4806
5093
  * @param root - the task being run.
4807
5094
  * @returns the first refusal, or undefined when the run may start.
4808
5095
  */
4809
5096
  bindingRefusal(root) {
4810
- const participants = this.cascadeParticipants(root.id);
4811
- if (root.teamRun === true) {
4812
- const lead = participants.find((participant) => participant.id === root.id);
4813
- if (lead !== void 0 && requiresPermissionConfirmation(lead, this.sessionDefaultPermission)) return {
4814
- kind: "root",
4815
- title: lead.title
4816
- };
4817
- const leadPermission = effectivePermission(lead ?? root) ?? this.sessionDefaultPermission;
4818
- const pinned = participants.find((participant) => {
4819
- if (participant.id === root.id) return false;
4820
- const raw = this.document.tasks.find((task) => task.id === participant.id);
4821
- return raw !== void 0 && !permissionCarriedBy(leadPermission, effectivePermission(raw));
4822
- });
4823
- return pinned === void 0 ? void 0 : {
4824
- kind: "subtask-pin",
4825
- title: pinned.title
4826
- };
4827
- }
4828
- const unconfirmed = participants.find((participant) => requiresPermissionConfirmation(participant, this.sessionDefaultPermission));
4829
- if (unconfirmed === void 0) return void 0;
5097
+ if (!requiresPermissionConfirmation(resolveExecutionTargets(root, this.document.tasks, this.maxSubtaskDepth), this.sessionDefaultPermission)) return void 0;
4830
5098
  return {
4831
- kind: unconfirmed.id === root.id ? "root" : "inherited",
4832
- title: unconfirmed.title
5099
+ kind: root.parentId === void 0 ? "root" : "inherited",
5100
+ title: root.title
4833
5101
  };
4834
5102
  }
4835
- /**
4836
- * The tasks a cascade from `rootId` would actually open executions for, with
4837
- * their effective execution targets resolved. Archived members never run, and
4838
- * a member that already has an open execution is skipped (a task cannot run
4839
- * twice), so the result is the participant set the launch will use.
4840
- */
4841
- cascadeParticipants(rootId) {
4842
- return cascadeTargets(this.document.tasks, rootId, this.maxSubtaskDepth).map((participant) => resolveExecutionTargets(participant, this.document.tasks, this.maxSubtaskDepth)).filter((participant) => participant.archivedAt === void 0 && !hasOpenExecution(participant));
4843
- }
4844
5103
  /** Whether a task or any of its subtasks still has an open execution. */
4845
5104
  subtreeHasOpenExecution(id) {
4846
- return cascadeTargets(this.document.tasks, id, this.maxSubtaskDepth).some((task) => hasOpenExecution(task));
5105
+ return subtreeTasks(this.document.tasks, id, this.maxSubtaskDepth).some((task) => hasOpenExecution(task));
5106
+ }
5107
+ /** The descendants of a card that still hold work, as the launch prompt names them. */
5108
+ outstandingDescendants(taskId) {
5109
+ return outstandingDescendants(this.document.tasks, taskId, this.maxSubtaskDepth);
5110
+ }
5111
+ /** Whether a card still has a subtask outside the done column. */
5112
+ hasOutstandingDescendants(taskId) {
5113
+ return hasOutstandingDescendants(this.document.tasks, taskId, this.maxSubtaskDepth);
4847
5114
  }
4848
5115
  /**
4849
- * Open one execution per cascade participant that still has work (the
4850
- * requested task and its on-board descendants, within the depth limit) under
4851
- * a single run group, and commit the ledger once. A descendant in 'done' is
4852
- * not a participant ({@link joinsCascadeRun}). The returned runs are ordered
4853
- * root-first, so the Host launches the parent before its subtasks.
5116
+ * Open ONE execution for the requested card, under a fresh run group, and
5117
+ * commit the ledger once. The group stays single-member on purpose: a run
5118
+ * never opens a session for a subtask (that card's own agent dispatches
5119
+ * subagents inside this session), and the group id is what later lets the
5120
+ * settlement fold a HISTORICAL multi-member group it opened before this
5121
+ * behavior changed.
4854
5122
  * @param root - the task the user ran.
4855
5123
  * @param now - clock instant (ms epoch).
4856
5124
  * @param initiator - the DSH session that asked for the run (audit only).
4857
5125
  * @param rerun - true to reset the root to 'todo' before starting it.
4858
5126
  * @param progress - when set, this run was a due occurrence and the root's
4859
5127
  * rule is advanced (counter, next target, stop/skip record) in the same
4860
- * atomic commit that opened the executions.
5128
+ * atomic commit that opened the execution.
4861
5129
  */
4862
- startCascade(root, now, initiator, rerun = false, progress) {
5130
+ startRun(root, now, initiator, rerun = false, progress) {
4863
5131
  const before = this.document.tasks;
5132
+ const [participant] = cascadeTargets(before, root.id);
5133
+ if (participant === void 0 || participant.archivedAt !== void 0) return [];
5134
+ if (hasOpenExecution(participant)) return [];
4864
5135
  const groupId = crypto.randomUUID();
4865
- const team = root.teamRun === true;
4866
- const started = /* @__PURE__ */ new Map();
4867
- const runs = [];
4868
- for (const task of cascadeTargets(before, root.id, this.maxSubtaskDepth)) {
4869
- if (task.archivedAt !== void 0) continue;
4870
- if (!joinsCascadeRun(task, root.id)) continue;
4871
- if (hasOpenExecution(task)) continue;
4872
- const opened = startExecution(rerun && task.id === root.id ? withStatus(task, "todo", now) : task, now, crypto.randomUUID(), initiator, groupId);
4873
- started.set(task.id, opened.task);
4874
- runs.push({
4875
- task: resolveExecutionTargets(opened.task, before, this.maxSubtaskDepth),
4876
- execution: opened.execution,
4877
- ...team && task.id !== root.id ? { dispatch: "teammate" } : {}
4878
- });
4879
- }
4880
- if (runs.length === 0) return [];
4881
- let tasks = before.map((task) => started.get(task.id) ?? task);
5136
+ const opened = startExecution(rerun ? withStatus(participant, "todo", now) : participant, now, crypto.randomUUID(), initiator, groupId);
5137
+ let tasks = before.map((task) => task.id === participant.id ? opened.task : task);
4882
5138
  if (progress !== void 0) tasks = applyScheduleProgress(tasks, root.id, progress, now);
4883
5139
  this.document.tasks = [...tasks];
4884
5140
  this.commit();
4885
- return runs;
5141
+ return [{
5142
+ task: resolveExecutionTargets(opened.task, before, this.maxSubtaskDepth),
5143
+ execution: opened.execution
5144
+ }];
4886
5145
  }
4887
5146
  /**
4888
- * Finalize every cascade parent that is ready, walking from `taskId` up the
4889
- * lineage: a member settles once its own outcome is recorded and none of its
4890
- * group children is still open, and its verdict folds those children in
4891
- * (failure dominates, then cancellation).
5147
+ * Finalize every stored run-group parent that is ready, walking from `taskId`
5148
+ * up the lineage: a member settles once its own outcome is recorded and none
5149
+ * of its group children is still open, and its verdict folds those children in
5150
+ * (failure dominates, then cancellation). A single-member group — every run
5151
+ * this Host opens now — settles on its own turn exactly as any plain run does.
4892
5152
  */
4893
5153
  settleCascade(taskId, groupId, now) {
4894
5154
  let changed = false;
@@ -4926,11 +5186,12 @@ var HostTaskLedger = class {
4926
5186
  * members are all settled. The Host poll calls this on every tick, so a run
4927
5187
  * can no longer be left in the running column by a settle nobody observed:
4928
5188
  *
4929
- * - A team run is governed by its Lead. Once the Lead's own outcome is
5189
+ * - A stored team run is governed by its Lead. Once the Lead's own outcome is
4930
5190
  * recorded, its still-open members are settled with that verdict. A
4931
5191
  * teammate is a durable member of the Team and may never report a turn of
4932
- * its own, and without this the whole lineage waits on it forever.
4933
- * - A cascade parent whose members are all settled is finalized here even
5192
+ * its own, and without this the whole lineage waits on it forever. New runs
5193
+ * never start a team, so this only closes a group the ledger already holds.
5194
+ * - A stored group parent whose members are all settled is finalized here even
4934
5195
  * when the settle that completed the tree happened in another process, or
4935
5196
  * was interrupted between its child write and its parent write.
4936
5197
  *
@@ -5420,6 +5681,18 @@ function mostRecentWorkspaceId(items) {
5420
5681
  }
5421
5682
  return best?.id ?? items[0]?.id;
5422
5683
  }
5684
+ /**
5685
+ * The failure text the Host records when a card names no workspace and the
5686
+ * deployment has none to resolve it to: the run is refused before any session
5687
+ * exists instead of letting `session.create` fall back to the Host process
5688
+ * working directory (the desktop app's profile directory), which is never the
5689
+ * project the user meant.
5690
+ *
5691
+ * A finished sentence rather than a code: the ledger stores it as the
5692
+ * execution's failure text, which the agent tools serve to a model and which
5693
+ * any client prints verbatim. It names the fix, not the mechanism.
5694
+ */
5695
+ const MISSING_WORKSPACE_REASON = "this card pins no workspace; choose a workspace on the card before running";
5423
5696
  //#endregion
5424
5697
  //#region src/core/reasoning-effort.ts
5425
5698
  /** Trim one optional effort: blank text means "not set", like every other pinned target. */
@@ -5585,19 +5858,17 @@ function escapeProvenanceDelimiter(value) {
5585
5858
  return value.replaceAll("来源声明 开始", "来源声明·开始").replaceAll("来源声明 结束", "来源声明·结束");
5586
5859
  }
5587
5860
  /**
5588
- * The execution-shape section: what else this run opens. A plain cascade opens
5589
- * one independent session per member; a team run starts every other member as a
5590
- * teammate inside THIS session, so the prompt names the Team tools instead.
5861
+ * The dispatch section: this run is the card's own session, and the card still
5862
+ * has unfinished subtasks. The Host opens no session for them, so the prompt
5863
+ * states what the session must do itself — read each card, dispatch subagents
5864
+ * in dependency order, and write the conclusions back before finishing. A card
5865
+ * with no outstanding descendant gets no section at all.
5591
5866
  */
5592
- function peerPromptPreamble(context) {
5593
- const peers = context.peers ?? [];
5594
- if (peers.length === 0) return void 0;
5595
- if (context.team === true) {
5596
- const lines = peers.map((peer) => `- ${escapeProvenanceDelimiter(peer.title)}(teammate: ${peer.name ?? teammateName(peer.title, peer.id, peer.id)})`);
5597
- return `本任务是 Agent Team 的 Lead:本次运行不额外开启独立会话,以下 ${peers.length} 个子任务成员已在本会话中作为 teammate 启动。用 list_agents / send_message / wait_agent 协调它们,用任务看板工具读写它们在看板上的卡片:\n${lines.join("\n")}`;
5598
- }
5599
- const lines = peers.map((peer) => `- ${escapeProvenanceDelimiter(peer.title)}(任务 ${peer.id})`);
5600
- return `本次运行同时并发开启 ${peers.length} 个独立 DSH 会话执行下列子任务成员(可用 task_board_* 工具查看它们的进度):\n${lines.join("\n")}`;
5867
+ function dispatchPromptPreamble(context) {
5868
+ const descendants = context.descendants ?? [];
5869
+ if (descendants.length === 0) return void 0;
5870
+ const lines = descendants.map((descendant) => `- ${escapeProvenanceDelimiter(descendant.title)}(任务 ${descendant.id},状态 ${descendant.status})`);
5871
+ return `本卡还有 ${descendants.length} 个未完成的子任务,本次执行不会为它们额外开启会话,由你在本会话内自行派发:\n${lines.join("\n")}\n先用 task_board_get 读取每张子卡的内容与执行目标,再用 subagent 按依赖顺序派发(互不依赖的可以并发),完工前用 task_board_manage({action:'record-external-outcome', result, initiatedBy, summary}) 一次性回填各子卡的结论。`;
5601
5872
  }
5602
5873
  /**
5603
5874
  * The scheduled-run section: this execution was triggered by the card's
@@ -5628,7 +5899,7 @@ function promptText(task, context = {}) {
5628
5899
  tagPromptPreamble(task),
5629
5900
  handoverPreamble,
5630
5901
  schedulePromptPreamble(context),
5631
- peerPromptPreamble(context)
5902
+ dispatchPromptPreamble(context)
5632
5903
  ].filter((part) => part !== void 0);
5633
5904
  const preamble = preambles.length === 0 ? void 0 : preambles.join("\n\n");
5634
5905
  const freeze = task.freeze;
@@ -5780,13 +6051,14 @@ var HostExecutionRunner = class HostExecutionRunner {
5780
6051
  */
5781
6052
  async launch(task, options = {}) {
5782
6053
  const workspaceId = task.handover?.workspaceId ?? task.workspaceId ?? this.recentWorkspaceId();
5783
- const mode = task.handover?.mode ?? task.mode;
6054
+ const mode = options.agentPreset ?? task.handover?.mode ?? task.mode;
5784
6055
  const permission = task.handover?.permission ?? task.permission;
5785
6056
  if (workspaceId !== void 0 && this.workspaceRegistry !== void 0) {
5786
6057
  if (!this.workspaceRegistry.list().some((item) => item.id === workspaceId)) throw new Error("workspace not found: " + workspaceId);
5787
6058
  }
5788
6059
  if (mode !== void 0) {
5789
6060
  const preset = (await this.invoke("agentPresets", "list", {})).presets?.find((item) => item.id === mode);
6061
+ if (preset === void 0 && options.agentPreset !== void 0) throw new Error("agent preset not found: " + mode + " (a card with unfinished subtasks runs under the liangshen preset, which this deployment does not serve)");
5790
6062
  if (preset === void 0) throw new Error("agent preset not found: " + mode);
5791
6063
  if (preset.broken !== void 0) throw new Error("agent preset is unavailable: " + preset.broken);
5792
6064
  }
@@ -5801,8 +6073,9 @@ var HostExecutionRunner = class HostExecutionRunner {
5801
6073
  }
5802
6074
  return reused;
5803
6075
  }
6076
+ if (workspaceId === void 0) throw new Error(MISSING_WORKSPACE_REASON);
5804
6077
  const sessionId = (await this.invoke("session", "create", {
5805
- ...workspaceId === void 0 ? {} : { workspaceId },
6078
+ workspaceId,
5806
6079
  ...mode === void 0 ? {} : { agentPreset: mode }
5807
6080
  })).sessionId;
5808
6081
  options.onSession?.(sessionId);
@@ -6177,14 +6450,21 @@ var HostExecutionRunner = class HostExecutionRunner {
6177
6450
  return { outcome: "pending" };
6178
6451
  }
6179
6452
  this.scanMemos.delete(sessionId);
6453
+ const closing = executionSummaryOf(events.map((entry) => entry.event), startedAt);
6454
+ const carried = closing === void 0 ? {} : { summary: closing };
6180
6455
  const reason = nonCompletedTurnEnd(turnEnd.event.data);
6181
- if (reason === void 0) return await this.goalVerdict(sessionId) ?? { outcome: "succeeded" };
6456
+ if (reason === void 0) return {
6457
+ ...await this.goalVerdict(sessionId) ?? { outcome: "succeeded" },
6458
+ ...carried
6459
+ };
6182
6460
  return reason === "error" ? {
6183
6461
  outcome: "failed",
6184
- error: "agent turn ended with an error"
6462
+ error: "agent turn ended with an error",
6463
+ ...carried
6185
6464
  } : {
6186
6465
  outcome: "failed",
6187
- error: "agent turn ended without completing: " + reason
6466
+ error: "agent turn ended without completing: " + reason,
6467
+ ...carried
6188
6468
  };
6189
6469
  }
6190
6470
  };
@@ -7003,6 +7283,37 @@ function cardDefaultsOf(defaults) {
7003
7283
  };
7004
7284
  return Object.keys(published).length === 0 ? void 0 : published;
7005
7285
  }
7286
+ /**
7287
+ * Every action kind this board accepts, keyed by the kind itself.
7288
+ *
7289
+ * Written as a total record of `TaskBoardAction['kind']` on purpose: a new member
7290
+ * of that union does not compile until it is listed here, so the table cannot
7291
+ * drift behind the protocol. `apply()` validates against it because a caller
7292
+ * reaching the board through the in-process capability face forwards its action
7293
+ * object verbatim, with no envelope parser in front of it — the HTTP route was the
7294
+ * only entrance before that face existed, and its parser is what used to turn an
7295
+ * unknown kind into a refusal.
7296
+ */
7297
+ const ACTION_KINDS = {
7298
+ import: true,
7299
+ create: true,
7300
+ update: true,
7301
+ delete: true,
7302
+ move: true,
7303
+ archive: true,
7304
+ restore: true,
7305
+ settle: true,
7306
+ "reset-verification": true,
7307
+ "record-external-outcome": true,
7308
+ "set-schedule": true,
7309
+ run: true,
7310
+ rerun: true,
7311
+ "confirm-permission": true,
7312
+ "set-parent": true,
7313
+ "rename-tag": true,
7314
+ "delete-tag": true,
7315
+ "extension-action": true
7316
+ };
7006
7317
  var TaskBoardHostService = class {
7007
7318
  ledger;
7008
7319
  runner;
@@ -7038,7 +7349,6 @@ var TaskBoardHostService = class {
7038
7349
  preventIdleSleep = false;
7039
7350
  verificationSettings;
7040
7351
  verificationCatalog;
7041
- team;
7042
7352
  timers;
7043
7353
  /** Live reader of the global native-/goal switch; frozen per execution. */
7044
7354
  goalRunEnabled;
@@ -7050,6 +7360,13 @@ var TaskBoardHostService = class {
7050
7360
  * launch without remounting the row. Absent means the default.
7051
7361
  */
7052
7362
  runLaunchWidth;
7363
+ /**
7364
+ * Live reader of the daily token cap; 0 means no gate. Read at each run
7365
+ * action, so closing or raising the cap binds the next action.
7366
+ */
7367
+ spendBudgetTokens;
7368
+ /** Today's measured spend: absent measurement reads as "cannot see", never as zero. */
7369
+ spendUsedToday;
7053
7370
  lastPowerJson = "";
7054
7371
  now;
7055
7372
  /** The deployment's workspaces, consulted to resolve a card that pins none. */
@@ -7064,17 +7381,20 @@ var TaskBoardHostService = class {
7064
7381
  this.ledger = options.ledger ?? new HostTaskLedger(void 0, void 0, {
7065
7382
  sessionDefaultPermission: options.sessionDefaultPermission,
7066
7383
  maxSubtaskDepth: options.maxSubtaskDepth,
7067
- cardDefaults: options.cardDefaults
7384
+ cardDefaults: options.cardDefaults,
7385
+ spendBudgetTokens: options.spendBudgetTokens,
7386
+ spendUsedToday: options.spendUsedToday
7068
7387
  });
7069
7388
  this.runner = new HostExecutionRunner(gateway, options.commandDispatcher, options.workspaceRegistry, void 0, options.ownerPeer);
7070
7389
  this.workspaceRegistry = options.workspaceRegistry;
7071
- this.team = options.team;
7072
7390
  this.timers = options.timers ?? PROCESS_TIMERS;
7073
7391
  this.power = options.power ?? new PowerInhibitor();
7074
7392
  this.now = options.now ?? Date.now;
7075
7393
  this.goalRunEnabled = options.goalRunEnabled ?? (() => false);
7076
7394
  this.cardDefaults = options.cardDefaults ?? (() => ({}));
7077
7395
  this.runLaunchWidth = options.runLaunchWidth ?? (() => 3);
7396
+ this.spendBudgetTokens = options.spendBudgetTokens ?? (() => 0);
7397
+ this.spendUsedToday = options.spendUsedToday ?? ((now) => usedTokensToday(now));
7078
7398
  this.launches = new LaunchAdmissionQueue(() => normalizeRunLaunchWidth(this.runLaunchWidth()));
7079
7399
  this.verificationSettings = options.verificationSettings ?? (() => ({
7080
7400
  enabled: false,
@@ -7161,7 +7481,6 @@ var TaskBoardHostService = class {
7161
7481
  power: this.power.snapshot(),
7162
7482
  sessionDefaultPermission: this.ledger.sessionDefaultPermission,
7163
7483
  maxSubtaskDepth: this.ledger.maxSubtaskDepth,
7164
- teamRunAvailable: this.team !== void 0,
7165
7484
  goalRunEnabled: this.goalRunEnabled(),
7166
7485
  ...cardDefaults === void 0 ? {} : { cardDefaults },
7167
7486
  ...Object.keys(published).length === 0 ? {} : { extensions: published }
@@ -7241,6 +7560,8 @@ var TaskBoardHostService = class {
7241
7560
  }
7242
7561
  apply(requestId, action, initiator) {
7243
7562
  if (!this.active) throw new Error("task board is disabled");
7563
+ const kind = action?.kind;
7564
+ if (typeof kind !== "string" || !Object.hasOwn(ACTION_KINDS, kind)) throw new Error(`unknown task board action kind: ${String(kind)}`);
7244
7565
  if (action.kind === "extension-action") return this.handleExtensionAction(action);
7245
7566
  return this.applyBoardAction(requestId, action, initiator);
7246
7567
  }
@@ -7251,9 +7572,7 @@ var TaskBoardHostService = class {
7251
7572
  */
7252
7573
  applyBoardAction(requestId, action, initiator) {
7253
7574
  const before = this.statusMap();
7254
- if (this.team === void 0 && (action.kind === "run" || action.kind === "rerun")) {
7255
- if (this.ledger.state().tasks.find((item) => item.id === action.taskId)?.teamRun === true) throw new Error("Agent Teams is unavailable in this deployment");
7256
- }
7575
+ if (action.kind === "run" || action.kind === "rerun") this.assertSpendCap();
7257
7576
  const result = this.ledger.applyRequest(requestId, this.withInheritedWorkspace(action, initiator), initiator);
7258
7577
  if (result.runs !== void 0) this.dispatchRuns(result.runs);
7259
7578
  if (SCHEDULE_WRITE_ACTIONS.has(action.kind)) this.refreshSchedule();
@@ -7267,6 +7586,24 @@ var TaskBoardHostService = class {
7267
7586
  power: this.power.snapshot()
7268
7587
  };
7269
7588
  }
7589
+ /**
7590
+ * Refuse a run whose day already spent the cap.
7591
+ *
7592
+ * A cap of 0 — the shipped default — answers before the measurement is read:
7593
+ * no ledger file is opened and nothing is summed, which is what keeps a board
7594
+ * that never configured a cap identical to the one before it existed.
7595
+ *
7596
+ * The refusal is a thrown message rather than a code: the wire hands its text
7597
+ * to the caller as board-refused, exactly like every other refusal this board
7598
+ * makes.
7599
+ */
7600
+ assertSpendCap() {
7601
+ const cap = this.spendBudgetTokens();
7602
+ if (!(cap > 0)) return;
7603
+ const used = this.spendUsedToday(this.now());
7604
+ if (used === void 0 || !spendCapReached(used, cap)) return;
7605
+ throw new Error(spendCapMessage(used, cap));
7606
+ }
7270
7607
  /** Route one provider action and answer the resulting board snapshot. */
7271
7608
  async handleExtensionAction(action) {
7272
7609
  await this.extensions.handleAction({
@@ -7307,20 +7644,19 @@ var TaskBoardHostService = class {
7307
7644
  this.ledger.dispose();
7308
7645
  this.listeners.clear();
7309
7646
  }
7310
- async launch(opened, others = [], schedule, freezeContract) {
7647
+ async launch(opened, schedule, freezeContract) {
7311
7648
  /** The session this launch attached to the execution, once it exists. */
7312
7649
  let attached;
7313
7650
  try {
7314
- const team = opened.task.teamRun === true;
7315
- const reuseSessionId = team ? void 0 : await this.reuseSessionFor(opened.task);
7316
- const peers = others.length === 0 ? void 0 : others.map((other) => ({
7317
- id: other.task.id,
7318
- title: other.task.title,
7319
- ...team ? { name: teammateName(other.task.title, other.execution.runGroupId ?? other.task.id, other.task.id) } : {}
7320
- }));
7321
- const promptContext = peers === void 0 && schedule === void 0 ? void 0 : {
7322
- ...peers === void 0 ? {} : { peers },
7323
- ...team ? { team: true } : {},
7651
+ const forcedPreset = this.ledger.hasOutstandingDescendants(opened.task.id) ? LIANGSHEN_PRESET_ID : void 0;
7652
+ const descendants = forcedPreset === void 0 ? [] : this.ledger.outstandingDescendants(opened.task.id);
7653
+ const reuseSessionId = forcedPreset === void 0 ? await this.reuseSessionFor(opened.task) : void 0;
7654
+ const promptContext = descendants.length === 0 && schedule === void 0 ? void 0 : {
7655
+ ...descendants.length === 0 ? {} : { descendants: descendants.map((descendant) => ({
7656
+ id: descendant.id,
7657
+ title: descendant.title,
7658
+ status: descendant.status
7659
+ })) },
7324
7660
  ...schedule === void 0 ? {} : { schedule }
7325
7661
  };
7326
7662
  const { settings, globalGoalEnabled, catalog } = await (freezeContract ?? (() => this.freezeRunContract()))();
@@ -7334,11 +7670,12 @@ var TaskBoardHostService = class {
7334
7670
  const initial = {
7335
7671
  contract,
7336
7672
  attempts: [],
7337
- applicability: team ? "team-member" : !contract.enabled ? skippedBy : notArmed
7673
+ applicability: !contract.enabled ? skippedBy : notArmed
7338
7674
  };
7339
7675
  this.ledger.setVerification(opened.task.id, opened.execution.id, initial);
7340
7676
  const sessionId = await this.runner.launch(opened.task, {
7341
7677
  ...reuseSessionId === void 0 ? {} : { reuseSessionId },
7678
+ ...forcedPreset === void 0 ? {} : { agentPreset: forcedPreset },
7342
7679
  ...promptContext === void 0 ? {} : { promptContext },
7343
7680
  goalEnabled,
7344
7681
  catalog,
@@ -7347,11 +7684,10 @@ var TaskBoardHostService = class {
7347
7684
  this.ledger.attachSession(opened.task.id, opened.execution.id, id);
7348
7685
  },
7349
7686
  onGoalArmed: (armed) => {
7350
- this.setApplicability(opened.task.id, opened.execution.id, team ? "team-member" : !contract.enabled ? skippedBy : armed ? "enforced" : notArmed);
7687
+ this.setApplicability(opened.task.id, opened.execution.id, !contract.enabled ? skippedBy : armed ? "enforced" : notArmed);
7351
7688
  }
7352
7689
  });
7353
7690
  if (attached === void 0) this.ledger.attachSession(opened.task.id, opened.execution.id, sessionId);
7354
- if (team) for (const teammate of others) this.scheduleTeammate(teammate, sessionId);
7355
7691
  } catch (error) {
7356
7692
  const launchedSession = error instanceof SessionLaunchError ? error.sessionId : void 0;
7357
7693
  if (launchedSession !== void 0) this.ledger.attachSession(opened.task.id, opened.execution.id, launchedSession);
@@ -7397,40 +7733,6 @@ var TaskBoardHostService = class {
7397
7733
  this.ledger.refundScheduledOccurrence(taskId, this.now());
7398
7734
  this.refreshSchedule();
7399
7735
  }
7400
- scheduleTeammate(opened, leadSessionId) {
7401
- this.enqueueLaunch(opened, () => this.spawnTeammate(opened, leadSessionId).catch((error) => {
7402
- safeConsoleError("[dsh-task-board] teammate spawn settlement failed", error);
7403
- }));
7404
- }
7405
- /**
7406
- * Spawn one teammate inside the Lead session and attach the teammate's
7407
- * session to the subtask execution, so the existing session monitor settles
7408
- * it from the teammate's own turn like any other execution. A spawn that
7409
- * fails settles the subtask as failed immediately, which then folds into the
7410
- * Lead's cascade verdict.
7411
- */
7412
- async spawnTeammate(opened, leadSessionId) {
7413
- const team = this.team;
7414
- if (team === void 0) {
7415
- this.settleAndNotify(opened.task.id, opened.execution.id, "failed", "Agent Teams is unavailable in this deployment");
7416
- return;
7417
- }
7418
- try {
7419
- const member = await team.spawn({
7420
- leadSessionId,
7421
- name: teammateName(opened.task.title, opened.execution.runGroupId ?? opened.task.id, opened.task.id),
7422
- description: opened.task.title,
7423
- prompt: promptText(opened.task)
7424
- });
7425
- if (member.sessionId === void 0 || member.sessionId === "") {
7426
- this.settleAndNotify(opened.task.id, opened.execution.id, "failed", member.error ?? "teammate provisioning failed");
7427
- return;
7428
- }
7429
- this.ledger.attachSession(opened.task.id, opened.execution.id, member.sessionId);
7430
- } catch (error) {
7431
- this.settleAndNotify(opened.task.id, opened.execution.id, "failed", error instanceof Error ? error.message : String(error));
7432
- }
7433
- }
7434
7736
  /**
7435
7737
  * One roster pass, and whether it could read the session tree.
7436
7738
  *
@@ -7514,10 +7816,10 @@ var TaskBoardHostService = class {
7514
7816
  }
7515
7817
  this.unreadablePolls.delete(execution.executionId);
7516
7818
  if (result.outcome === "succeeded" && verificationRequired(verification) && passedAttempt(verification) === void 0) {
7517
- this.settleAndNotify(execution.taskId, execution.executionId, "failed", verificationNeverInvoked(verification) ? NEVER_INVOKED_VERIFICATION_REASON : verificationOnlyInvalid(verification) ? INVALID_ONLY_VERIFICATION_REASON : NO_MATCHING_PASS_VERIFICATION_REASON);
7819
+ 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);
7518
7820
  continue;
7519
7821
  }
7520
- this.settleAndNotify(execution.taskId, execution.executionId, result.outcome, "error" in result ? result.error : void 0);
7822
+ this.settleAndNotify(execution.taskId, execution.executionId, result.outcome, "error" in result ? result.error : void 0, result.summary);
7521
7823
  } catch {}
7522
7824
  }
7523
7825
  const open = new Set(executions.map((execution) => execution.executionId));
@@ -7532,20 +7834,14 @@ var TaskBoardHostService = class {
7532
7834
  * ancestor of it — in the running column with no way out. The first poll of
7533
7835
  * each streak is logged, so the Host log names the session.
7534
7836
  */
7535
- settleAndNotify(taskId, executionId, outcome, error) {
7536
- const before = this.ledger.getTask(taskId);
7537
- if (before?.executions.find((entry) => entry.id === executionId)?.endedAt !== void 0) {
7538
- this.ledger.settle(taskId, executionId, outcome, error);
7837
+ settleAndNotify(taskId, executionId, outcome, error, summary) {
7838
+ if (this.ledger.getTask(taskId)?.executions.find((entry) => entry.id === executionId)?.endedAt !== void 0) {
7839
+ this.ledger.settle(taskId, executionId, outcome, error, summary);
7539
7840
  return;
7540
7841
  }
7541
- const previousStatus = before?.status;
7542
- this.ledger.settle(taskId, executionId, outcome, error);
7543
- const task = this.ledger.getTask(taskId);
7544
- if (task !== void 0 && previousStatus !== void 0 && previousStatus !== task.status) this.extensions.emitStatusChanged({
7545
- taskId,
7546
- status: task.status,
7547
- previous: previousStatus
7548
- });
7842
+ const statuses = this.statusMap();
7843
+ this.ledger.settle(taskId, executionId, outcome, error, summary);
7844
+ this.emitStatusChanges(statuses);
7549
7845
  this.extensions.emitExecutionSettled({
7550
7846
  taskId,
7551
7847
  executionId,
@@ -7685,26 +7981,18 @@ var TaskBoardHostService = class {
7685
7981
  return this.ledger.armedScheduleCount();
7686
7982
  }
7687
7983
  /**
7688
- * Launch one run set. The root goes first and receives the run shape in its
7689
- * prompt (which members this run opens, and how they run); every plain-cascade
7690
- * member then launches on its own so one refused participant cannot hold the
7691
- * others back. A team run's members are spawned inside the root's Lead
7692
- * session instead, once that session exists.
7984
+ * Launch the one run a run request opened. A run request names one card and
7985
+ * opens one execution for it; the card's own session dispatches its subtasks
7986
+ * as subagents, so nothing else is enqueued here.
7693
7987
  *
7694
- * Every launch of one run set goes through the admission queue, which admits
7695
- * at most `runLaunchWidth` of them at a time — the whole subtree still opens,
7696
- * members just enter the running column in batches. Order inside the group is
7697
- * the order they are enqueued here, so the root's session always exists before
7698
- * any member's, and one member's launch settling (or failing) is what admits
7699
- * the next. All members share the one contract this group freezes.
7988
+ * The launch still goes through the admission queue, which admits at most
7989
+ * `runLaunchWidth` launches at a time — that bound now applies across
7990
+ * concurrent runs rather than across the members of one run.
7700
7991
  */
7701
7992
  dispatchRuns(runs, schedule) {
7702
- if (runs.length === 0) return;
7703
- const root = runs.find((run) => run.dispatch !== "teammate") ?? runs[0];
7704
- const others = runs.filter((run) => run !== root);
7705
- const freezeContract = this.contractFreezerForRunGroup();
7706
- this.scheduleLaunch(root, others, schedule, freezeContract);
7707
- for (const run of others) if (run.dispatch !== "teammate") this.scheduleLaunch(run, [], schedule, freezeContract);
7993
+ const root = runs[0];
7994
+ if (root === void 0) return;
7995
+ this.scheduleLaunch(root, schedule, this.contractFreezerForRunGroup());
7708
7996
  }
7709
7997
  /**
7710
7998
  * Move one execution's applicability without touching its frozen contract or
@@ -7718,8 +8006,8 @@ var TaskBoardHostService = class {
7718
8006
  applicability
7719
8007
  });
7720
8008
  }
7721
- scheduleLaunch(opened, others = [], schedule, freezeContract) {
7722
- this.enqueueLaunch(opened, () => this.launch(opened, others, schedule, freezeContract).catch((error) => {
8009
+ scheduleLaunch(opened, schedule, freezeContract) {
8010
+ this.enqueueLaunch(opened, () => this.launch(opened, schedule, freezeContract).catch((error) => {
7723
8011
  safeConsoleError("[dsh-task-board] execution launch settlement failed", error);
7724
8012
  }), schedule);
7725
8013
  }
@@ -8323,7 +8611,7 @@ function buildSetParentTool(host) {
8323
8611
  description: [
8324
8612
  "Attach an existing task under a parent (making it a subtask) or detach it back to the root board by setting its parentId.",
8325
8613
  "Pass an empty parentId to detach.",
8326
- "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).",
8614
+ "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 stored run group parent pointer).",
8327
8615
  "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."
8328
8616
  ].join(" "),
8329
8617
  parameters: {
@@ -8366,17 +8654,16 @@ function buildRunTool(host) {
8366
8654
  name: "task_board_run",
8367
8655
  description: [
8368
8656
  "Run a task on the board now, or re-run a settled one.",
8369
- "Running a task also runs its whole subtask tree CONCURRENTLY: the Host opens one real DSH session per member under one run group, each replaying its card pinned workspace, agent preset, permission and model; a subtask that does not pin them inherits its nearest ancestor.",
8370
- "The parent card stays in the running column until its own turn and every direct subtask have settled, and it fails when any member failed; one failing subtask never stops the others.",
8657
+ "Running a card opens ONE session for that card: no session is opened for its subtasks, and the card agent dispatches them itself with subagent. A card whose subtasks are still unfinished runs under the liangshen agent preset and is told which cards to pick up.",
8658
+ "Clicking a subtask runs that subtask as its own root, again without opening anything for its descendants.",
8371
8659
  "A card whose effective permission is above the deployment session default is refused with confirmation-required until a HUMAN confirms the binding in the board UI; this tool cannot confirm it.",
8372
- "A card whose task carries teamRun instead starts ONE Team Lead session and the Host spawns a teammate per subtask inside it, so those cards run as an Agent Team rather than as independent sessions; that mode needs the deployment Agent Teams service and is refused when it is missing.",
8373
8660
  "Executions consume real API quota. Sessions are created asynchronously, so read their ids and outcomes back with task_board_get."
8374
8661
  ].join(" "),
8375
8662
  parameters: {
8376
8663
  taskId: {
8377
8664
  type: "string",
8378
8665
  required: true,
8379
- description: "The task to run; running a root task runs its whole subtree, minus the subtasks that are already in the done column."
8666
+ description: "The task to run; only this card gets a session, its unfinished subtasks are dispatched by that session own agent."
8380
8667
  },
8381
8668
  rerun: {
8382
8669
  type: "boolean",
@@ -8408,7 +8695,7 @@ function buildRunTool(host) {
8408
8695
  ok: true,
8409
8696
  started,
8410
8697
  ...root === void 0 ? {} : { task: taskSummary(root, snapshot.tasks, snapshot.sessionDefaultPermission) },
8411
- note: "Executions run asynchronously; call task_board_get to read session ids and the settled outcome. The parent settles only after its own turn and every direct subtask settle."
8698
+ note: "Executions run asynchronously; call task_board_get to read session ids and the settled outcome."
8412
8699
  });
8413
8700
  } catch (error) {
8414
8701
  const message = messageOf(error);
@@ -8424,7 +8711,7 @@ function buildManageTool(host) {
8424
8711
  "Move, archive, restore, delete, or settle one task board card.",
8425
8712
  "move-backlog, move-todo, move-running, move-done and move-failed are the manual column moves and cover every column; a card the runner is executing (one with an open execution) cannot be moved.",
8426
8713
  "A manual move writes the card column only and never fabricates an execution record, so the card reports a declaration rather than evidence of a run: done/failed declare work finished (or failed) outside a Host-run execution — human work, an external system, a decision made elsewhere — and running says the work is under way without a tracked session. Use task_board_run when the work should actually run in a session here.",
8427
- "record-external-outcome is the record-backed version of move-done and move-failed: use it when YOU, or another agent outside this Host, actually finished or failed the card with your own model, so the terminal column and the run history both derive from one execution record. It takes result (succeeded or failed) and initiatedBy (who completed it, for example your own agent name) plus an optional summary, and it is refused while the card still has an open execution: the Host stays the only authority over a run it is executing. It cannot record running or cancelled — those remain Host-only.",
8714
+ "record-external-outcome is the record-backed version of move-done and move-failed: use it when YOU, or another agent outside this Host, actually finished or failed the card with your own model, so the terminal column and the run history both derive from one execution record. It takes result (succeeded or failed) and initiatedBy (who completed it, for example your own agent name) plus an optional summary, and it is refused while the card still has an open execution: the Host stays the only authority over a run it is executing. It cannot record running or cancelled — those remain Host-only. A parent card that dispatched its subtasks uses it once, at the end, to backfill every subtask card with the conclusion it reached; the Host records an inherited verdict on a subtask the parent never wrote back, so the write-back is what keeps each subtask conclusion its own.",
8428
8715
  "settle force-closes the open execution of a card the board can no longer observe (a stuck running card) and records it cancelled with the caller as the reason, so the card returns to the todo column and can be run again.",
8429
8716
  "reset-verification clears the acceptance anomalies (timeouts, authentication failures, an unresolvable judge route, or an attempt the time budget ended) recorded on a card open execution, so the next update_goal(action: complete) runs a fresh acceptance. It is refused unless that execution really carries such anomalies, it never clears a quality verdict, and a spent anomaly budget otherwise HOLDS the card open instead of failing it: tell the user the acceptance environment is unusable and that this action is how they clear it once they have fixed it.",
8430
8717
  "archive takes the whole subtask tree off the board and is refused while any member has an unsettled execution; restore brings the task, its ancestors and its subtree back; delete removes one card and is refused while it still has subtasks (detach or delete them first) or while it runs.",
@@ -8575,7 +8862,7 @@ function buildScheduleTool(host) {
8575
8862
  "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.",
8576
8863
  "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).",
8577
8864
  "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.",
8578
- "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.",
8865
+ "A due scheduled task runs exactly what a manual run of that card does: one session for the card, never one per subtask.",
8579
8866
  "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.",
8580
8867
  "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."
8581
8868
  ].join(" "),
@@ -8729,7 +9016,11 @@ function buildListTool(host) {
8729
9016
  function buildGetTool(host) {
8730
9017
  return defineTool({
8731
9018
  name: "task_board_get",
8732
- description: ["Read one task board card in full: prompt, description, labels, column, parent link, direct subtasks, execution targets, schedule, permission gate state, and the last ten execution attempts with their session ids and outcomes.", "Use it before running or editing a card, and after a run to read the settled outcome."].join(" "),
9019
+ description: [
9020
+ "Read one task board card in full: prompt, description, labels, column, parent link, direct subtasks, execution targets, schedule, permission gate state, and the last ten execution attempts with their session ids and outcomes.",
9021
+ "Use it before running or editing a card, after a run to read the settled outcome, and to read each subtask card before dispatching it with subagent.",
9022
+ "A card written before team runs were retired may still report teamRun: true; the field is history and never changes how the Host runs the card."
9023
+ ].join(" "),
8733
9024
  parameters: { taskId: {
8734
9025
  type: "string",
8735
9026
  required: true,
@@ -8803,10 +9094,6 @@ function buildCreateTool(host) {
8803
9094
  type: "boolean",
8804
9095
  description: "Continue later runs in the previous execution session instead of a fresh conversation."
8805
9096
  },
8806
- teamRun: {
8807
- type: "boolean",
8808
- description: "Run this task as an Agent Team: running it starts one Team Lead session and the Host spawns a teammate per subtask inside it. Omit or false for one independent session per member. Refused when the deployment serves no Agent Teams service."
8809
- },
8810
9097
  goalRun: {
8811
9098
  type: "boolean",
8812
9099
  description: "Start each run with dsh built-in /goal so the session keeps working continuation rounds until the goal completes. Off by default: omit (or pass false) for a single plain turn, and pass true to opt this card in. It only takes effect while the deployment global native /goal switch is on."
@@ -8887,7 +9174,6 @@ function buildCreateTool(host) {
8887
9174
  ...args.reasoningEffort === void 0 || args.reasoningEffort === "" ? {} : { reasoningEffort: args.reasoningEffort },
8888
9175
  applyCardDefaults: true,
8889
9176
  ...args.reuseSession === true ? { reuseSession: true } : {},
8890
- ...args.teamRun === true ? { teamRun: true } : {},
8891
9177
  ...args.goalRun === true ? { goalRun: true } : {},
8892
9178
  ...args.skipVerification === true ? { skipVerification: true } : {},
8893
9179
  ...tags.length === 0 ? {} : { tags },
@@ -8974,10 +9260,6 @@ function buildUpdateTool(host) {
8974
9260
  type: "boolean",
8975
9261
  description: "Continue later runs in the previous execution session."
8976
9262
  },
8977
- teamRun: {
8978
- type: "boolean",
8979
- description: "Switches this task between a plain cascade (one session per member) and an Agent Team run (Lead session plus a teammate per subtask)."
8980
- },
8981
9263
  goalRun: {
8982
9264
  type: "boolean",
8983
9265
  description: "Whether each run starts with dsh built-in /goal (default false, one plain turn). Pass true to opt this card in, or false to return it to the default."
@@ -9021,7 +9303,6 @@ function buildUpdateTool(host) {
9021
9303
  if (has(args, "reasoningEffort") && typeof args.reasoningEffort === "string") patch.reasoningEffort = args.reasoningEffort;
9022
9304
  if (has(args, "permission") && typeof args.permission === "string") patch.permission = args.permission === "" ? void 0 : args.permission;
9023
9305
  if (has(args, "reuseSession")) patch.reuseSession = args.reuseSession === true;
9024
- if (has(args, "teamRun")) patch.teamRun = args.teamRun === true;
9025
9306
  if (has(args, "goalRun")) patch.goalRun = args.goalRun === true ? true : false;
9026
9307
  if (has(args, "skipVerification")) patch.skipVerification = args.skipVerification === true ? true : false;
9027
9308
  if (has(args, "tags")) {
@@ -9083,7 +9364,8 @@ function buildUpdateTool(host) {
9083
9364
  */
9084
9365
  const PLUGIN_TOOL_SECTION_ORDERS = {
9085
9366
  ssh: 150,
9086
- "task-board": 200
9367
+ "task-board": 200,
9368
+ agents: 220
9087
9369
  };
9088
9370
  /**
9089
9371
  * Build a section provider that renders \`text\` only while at least one of
@@ -9151,12 +9433,26 @@ function isLoopbackHostname(hostname) {
9151
9433
  return isIPv4Loopback(hostname);
9152
9434
  }
9153
9435
  /**
9436
+ * Whether a reverse proxy stood between the client and this host: the request
9437
+ * carries CF-Connecting-IP or X-Forwarded-For. Either header is stamped by a
9438
+ * hop that forwards traffic, so the request did not originate on this machine.
9439
+ * @param request - node HTTP request.
9440
+ * @returns true when a forwarding header is present.
9441
+ */
9442
+ function isProxiedRequest(request) {
9443
+ return request.headers["cf-connecting-ip"] !== void 0 || request.headers["x-forwarded-for"] !== void 0;
9444
+ }
9445
+ /**
9154
9446
  * Request-level trust fence: a loopback socket address AND a loopback Host
9155
9447
  * header, plus browser same-origin markers. The socket address is
9156
- * authoritative; X-Forwarded-For is never trusted.
9448
+ * authoritative for a direct connection; a request that carries a forwarding
9449
+ * header is refused outright, because a proxy in front of the host makes both
9450
+ * the socket address and the Host header describe the proxy rather than the
9451
+ * client. X-Forwarded-For is therefore never evidence *for* loopback.
9157
9452
  */
9158
9453
  function isLoopbackRequest(request) {
9159
9454
  if (!isLoopbackAddress(request.socket.remoteAddress)) return false;
9455
+ if (isProxiedRequest(request)) return false;
9160
9456
  const host = request.headers.host;
9161
9457
  if (typeof host !== "string") return false;
9162
9458
  let hostUrl;
@@ -9175,6 +9471,32 @@ function isLoopbackRequest(request) {
9175
9471
  return false;
9176
9472
  }
9177
9473
  }
9474
+ /**
9475
+ * Whether a forwarded request landed on this machine's loopback upstream: a
9476
+ * forwarding header (the proxy's own stamp), a loopback socket address (the
9477
+ * proxy dials 127.0.0.1:<port>), and a loopback Host header (the proxy rewrote
9478
+ * the authority to its upstream literal).
9479
+ *
9480
+ * This is a fact about the route, not a trust decision. A public request to a
9481
+ * tunnel satisfies all three by construction, because the proxy is the client
9482
+ * of this process: only a caller that operates the proxy can decide it stands
9483
+ * for the browser, which is why every consumer keeps this behind an explicit
9484
+ * default-off switch and its own browser markers. isLoopbackRequest is
9485
+ * unchanged and still refuses a forwarded request (issue #1906).
9486
+ * @param request - node HTTP request.
9487
+ * @returns true when a forwarding header, a loopback socket, and a loopback Host all hold.
9488
+ */
9489
+ function isForwardedLoopbackRequest(request) {
9490
+ if (!isProxiedRequest(request)) return false;
9491
+ if (!isLoopbackAddress(request.socket.remoteAddress)) return false;
9492
+ const host = request.headers.host;
9493
+ if (typeof host !== "string") return false;
9494
+ try {
9495
+ return isLoopbackHostname(new URL("http://" + host).hostname);
9496
+ } catch {
9497
+ return false;
9498
+ }
9499
+ }
9178
9500
  //#endregion
9179
9501
  //#region src/host-routes.ts
9180
9502
  const ACTION_LIMIT = 64 * 1024;
@@ -9209,7 +9531,9 @@ function resolveAccess(access) {
9209
9531
  if (trustedProxyHosts.size > 0 && (access.proxyToken === void 0 || access.proxyToken === "")) throw new Error("task-board: authenticated proxy hosts require a non-empty proxy token");
9210
9532
  return {
9211
9533
  trustedProxyHosts,
9212
- ...access.proxyToken === void 0 ? {} : { proxyToken: access.proxyToken }
9534
+ trustForwardedProxy: access.trustForwardedProxy ?? (() => false),
9535
+ ...access.proxyToken === void 0 ? {} : { proxyToken: access.proxyToken },
9536
+ ...access.connection === void 0 ? {} : { connection: access.connection }
9213
9537
  };
9214
9538
  }
9215
9539
  /**
@@ -9279,10 +9603,29 @@ function matchesToken(candidate, expected) {
9279
9603
  * tripwire, the socket/Host/origin-equality checks carry the authority).
9280
9604
  * Authenticated proxies must be explicitly allowlisted and replace the
9281
9605
  * internal token header after their own authentication step.
9606
+ *
9607
+ * A third party's proxy cannot inject that token, so a deployment whose own
9608
+ * tunnel dials the loopback upstream (issue #1918) can instead turn on
9609
+ * trustForwardedProxy: a forwarded request that landed on this machine
9610
+ * (loopback socket AND loopback Host) is then admitted on the same browser
9611
+ * marker alone. The switch defaults off, so an unconfigured board keeps
9612
+ * refusing every forwarded request (issue #1906).
9613
+ *
9614
+ * A deployment behind a reverse proxy or ingress that DSH itself serves
9615
+ * (`--trusted-host`, TLS terminated at the edge) is admitted by the Host's
9616
+ * `connection` service instead: a request whose Host/Origin fence and signed
9617
+ * browser session it accepts needs no board-specific allowlist, which is why
9618
+ * the check runs first when the service is mounted (issue #1930). The fence
9619
+ * below stays untouched as the fallback, so a deployment without the service,
9620
+ * and every direct client the service does not admit, keeps exactly the
9621
+ * pre-existing decision.
9282
9622
  */
9283
9623
  function isTrustedTaskBoardRequest(req, access) {
9624
+ const connection = access.connection?.();
9625
+ if (connection !== void 0 && connection.requestRejection(req) === void 0) return true;
9284
9626
  if (!browserSameOriginMarker(req)) return false;
9285
9627
  if (isLoopbackRequest(req)) return true;
9628
+ if (access.trustForwardedProxy() && req.headers["sec-fetch-site"] !== "cross-site" && isForwardedLoopbackRequest(req)) return true;
9286
9629
  if (!isLoopbackAddress(req.socket.remoteAddress)) return false;
9287
9630
  const host = req.headers.host;
9288
9631
  if (typeof host !== "string") return false;
@@ -10592,22 +10935,18 @@ const inject = [
10592
10935
  ];
10593
10936
  /** Model-facing announcement: plugin presence, capabilities, and limits. */
10594
10937
  const TASK_BOARD_GUIDANCE = "本机已安装 dsh-task-board 插件(DSH Web GUI 的任务看板):侧边栏「任务看板」入口;在 dsh-web 插件全家桶仓库(packages/dsh-task-board)统一维护,经聚合包 web-ui-all 一键安装。能力:多列看板管理任务;Host 权威账本;关闭浏览器后仍由 Host 执行和结算;任务可钉住工作区、agent 预设和权限;任务可建子任务(深度上限可配 1..3,默认 1 层,子任务不能再带子任务),执行父任务会并发执行其子任务树,子任务可单独覆盖权限与模型;另注册 task_board_* agent 工具(list/get/create/update/set_parent/run/manage/schedule),任何会话都可直接读写看板、子任务与定时计划,但运行任务会真实执行并消耗额度,高于会话默认权限的绑定仍必须由用户在 GUI 人工确认(工具刻意不提供确认能力);支持 Host 本地时区的 5 段 cron,错过的触发点不补跑;可选且默认关闭的空闲系统睡眠保护允许屏幕熄灭,但不承诺拦截合盖、手动睡眠、休眠、关机或唤醒已睡眠机器。执行消耗 API 额度。用户提到「任务看板 / 看板 / 定时任务」时即指本插件,请据此协作。若你同时用 todo_write 维护会话顶部的可见计划列表,最终回复前必须再次调用 todo_write 收尾:没有剩余工作时不要保留 in_progress,已完成的最后一步要标为 completed。";
10595
- /**
10596
- * Continuable-subagent provider for fresh teammates, matching the Agent Teams
10597
- * tool plugin's own `freshProvider` default.
10598
- */
10599
- const DEFAULT_TEAM_PROVIDER = "spawn";
10600
10938
  const Config = z.object({
10601
10939
  announceToAgent: z.boolean().default(false).volatile(),
10602
10940
  enabled: z.boolean().default(true).volatile(),
10603
10941
  preventIdleSleep: z.boolean().default(false).volatile(),
10604
10942
  trustedProxyHosts: z.array(z.string()).default([]),
10605
10943
  proxyTokenEnv: z.string().min(1).default(DEFAULT_PROXY_TOKEN_ENV),
10944
+ trustForwardedProxy: z.boolean().default(false).volatile(),
10606
10945
  sessionDefaultPermission: z.union(TASK_PERMISSIONS),
10607
10946
  maxSubtaskDepth: z.number().min(1).max(3).default(1).volatile(),
10608
10947
  sessionPollSeconds: z.number().min(1).max(300).default(5).volatile(),
10609
10948
  runLaunchWidth: z.number().min(1).max(16).default(3).volatile(),
10610
- teamProvider: z.string().min(1).default(DEFAULT_TEAM_PROVIDER),
10949
+ spendBudgetTokens: z.number().min(0).default(0).volatile(),
10611
10950
  goalRunEnabled: z.boolean().default(false).volatile(),
10612
10951
  cardDefaultMode: z.string().default("").volatile(),
10613
10952
  cardDefaultPermission: z.union([...TASK_PERMISSIONS, ""]).default("").volatile(),
@@ -10643,19 +10982,64 @@ function readConfigField(field, fallback) {
10643
10982
  if (typeof field === "object" && field !== null && typeof field.get === "function") return field.get();
10644
10983
  return field;
10645
10984
  }
10646
- /** Resolve proxy access without ever placing the token value in plugin config. */
10985
+ /**
10986
+ * Resolve proxy access without ever placing the token value in plugin config.
10987
+ *
10988
+ * The forwarded-proxy switch travels as a reader rather than a value: it is
10989
+ * schema-volatile, so the fence must read it when a request arrives instead of
10990
+ * when the routes are registered.
10991
+ * @param config - the resolved plugin config.
10992
+ * @param env - environment holding the proxy token value.
10993
+ * @returns the route access handed to {@link makeTaskBoardRoutes}.
10994
+ */
10647
10995
  function resolveProxyAccess(config, env = process.env) {
10996
+ const trustForwardedProxy = () => readConfigField(config?.trustForwardedProxy, false);
10648
10997
  const trustedProxyHosts = config?.trustedProxyHosts ?? [];
10649
- if (trustedProxyHosts.length === 0) return { trustedProxyHosts };
10998
+ if (trustedProxyHosts.length === 0) return {
10999
+ trustedProxyHosts,
11000
+ trustForwardedProxy
11001
+ };
10650
11002
  const proxyTokenEnv = config?.proxyTokenEnv ?? "DSH_TASK_BOARD_PROXY_TOKEN";
10651
11003
  if (proxyTokenEnv.trim() === "") throw new Error("task-board: proxyTokenEnv must not be empty");
10652
11004
  const proxyToken = env[proxyTokenEnv];
10653
11005
  if (proxyToken === void 0 || proxyToken === "") throw new Error(`task-board: trustedProxyHosts requires a non-empty ${proxyTokenEnv} environment variable`);
10654
11006
  return {
10655
11007
  trustedProxyHosts,
10656
- proxyToken
11008
+ proxyToken,
11009
+ trustForwardedProxy
10657
11010
  };
10658
11011
  }
11012
+ /**
11013
+ /**
11014
+ * Schema default for the forwarded-proxy switch, re-read for hand-built
11015
+ * contexts. Deliberately false: a deployment that never configured it keeps
11016
+ * refusing every forwarded request, which is the #1906 fence.
11017
+ */
11018
+ const DEFAULT_TRUST_FORWARDED_PROXY = false;
11019
+ /**
11020
+ * Resolve the composition's optional `connection` service.
11021
+ *
11022
+ * The service is the Host's own browser-session authority: it fronts every
11023
+ * `/api` request with the Host/Origin fence and the signed `dsh-auth-*` cookie,
11024
+ * which is what a deployment behind a reverse proxy or ingress validates on the
11025
+ * same authority the GUI is served from. The board bridges it instead of
11026
+ * repeating that check, so a proxy request the Host already authenticated is
11027
+ * admitted without a board-specific host allowlist (issue #1930). It is
11028
+ * deliberately resolved like the agent-tool registry rather than injected:
11029
+ * a composition that serves no connection keeps mounting the board on the
11030
+ * pre-existing loopback fence, and one that mounts the service later is picked
11031
+ * up on the next request because the fence asks this resolver each time.
11032
+ * @param ctx - the plugin context.
11033
+ * @returns the trust face, or undefined when this deployment serves none.
11034
+ */
11035
+ function resolveConnectionTrust(ctx) {
11036
+ try {
11037
+ const connection = ctx.get("connection");
11038
+ return connection !== void 0 && typeof connection.requestRejection === "function" ? connection : void 0;
11039
+ } catch {
11040
+ return;
11041
+ }
11042
+ }
10659
11043
  /** The lookup half of a resolved registry, when it exposes one. */
10660
11044
  function lookupOf(registry) {
10661
11045
  return registry !== void 0 && typeof registry.get === "function" ? { get: registry.get.bind(registry) } : void 0;
@@ -10721,65 +11105,6 @@ function resolveHostDefaultPermission(ctx) {
10721
11105
  }
10722
11106
  }
10723
11107
  /**
10724
- * How long one teammate may take to reach its durable active or failed edge.
10725
- * Agent Teams provisioning normally resolves in seconds; the bound exists so a
10726
- * hung spawn settles the subtask instead of holding the cascade open forever.
10727
- */
10728
- const TEAMMATE_PROVISION_TIMEOUT_MS = 6e5;
10729
- /**
10730
- * Resolve the optional Agent Teams service. Like the tool registry and the llm
10731
- * runtime, it is deliberately not injected: a deployment without Agent Teams
10732
- * must still mount the whole board and only lose team-mode runs.
10733
- * @param ctx - the plugin context.
10734
- * @returns the service, or undefined when this deployment serves none.
10735
- */
10736
- function resolveAgentTeams(ctx) {
10737
- try {
10738
- const teams = ctx.get("agentTeams");
10739
- return teams !== void 0 && typeof teams.spawnTeammate === "function" ? teams : void 0;
10740
- } catch {
10741
- return;
10742
- }
10743
- }
10744
- /**
10745
- * Build the team dispatcher: the run's Lead session spawns one teammate per
10746
- * subtask through the Agent Teams service, and the teammate's session id is
10747
- * attached to that subtask's execution so the ordinary session monitor settles
10748
- * it. Returns undefined when the deployment serves no Agent Teams service or
10749
- * no live-agent registry, which makes a team run fail closed.
10750
- * @param ctx - the plugin context.
10751
- * @param provider - the continuable-subagent provider for fresh teammates.
10752
- * @returns the dispatcher, or undefined when team runs cannot be served.
10753
- */
10754
- function buildTeamDispatcher(ctx, provider) {
10755
- const teams = resolveAgentTeams(ctx);
10756
- if (teams === void 0) return void 0;
10757
- if (typeof ctx.agents?.get !== "function") return void 0;
10758
- return { async spawn(input) {
10759
- const lead = ctx.agents.get(input.leadSessionId);
10760
- if (lead === void 0) return { error: `lead session ${input.leadSessionId} is not live` };
10761
- try {
10762
- const member = (await teams.spawnTeammate(lead, {
10763
- name: input.name,
10764
- description: input.description,
10765
- prompt: [{
10766
- type: "text",
10767
- text: input.prompt
10768
- }],
10769
- context: "fresh",
10770
- provider,
10771
- signal: AbortSignal.timeout(TEAMMATE_PROVISION_TIMEOUT_MS)
10772
- }))?.member;
10773
- if (member === void 0) return { error: "Agent Teams returned no teammate" };
10774
- if (member.phase === "failed") return { error: member.error ?? "teammate provisioning failed" };
10775
- if (typeof member.id !== "string" || member.id === "") return { error: "Agent Teams returned no teammate session" };
10776
- return { sessionId: member.id };
10777
- } catch (error) {
10778
- return { error: `teammate provisioning failed: ${error instanceof Error ? error.message : String(error)}` };
10779
- }
10780
- } };
10781
- }
10782
- /**
10783
11108
  * Read the optional `llm` service. The board deliberately does not inject it:
10784
11109
  * a deployment without a model must still mount the board, and the parse route
10785
11110
  * answers a typed failure instead of the plugin failing to load (issue #1540).
@@ -10870,6 +11195,12 @@ function applyImpl(ctx, config) {
10870
11195
  */
10871
11196
  const runLaunchWidth = () => readConfigField(config?.runLaunchWidth, 3);
10872
11197
  /**
11198
+ * Current daily token cap, read at each gate like the width above. The value
11199
+ * decides first: 0 — the default — ends the gate before a file is opened, so
11200
+ * a board that never set a cap pays nothing for it.
11201
+ */
11202
+ const spendBudgetTokens = () => readConfigField(config?.spendBudgetTokens, 0);
11203
+ /**
10873
11204
  * The baseline the permission confirmation gate judges against: the row's own
10874
11205
  * `sessionDefaultPermission` when the deployment pins one, otherwise the Host's
10875
11206
  * default preset. Read per call through the ledger, so a Host Settings change
@@ -10924,11 +11255,11 @@ function applyImpl(ctx, config) {
10924
11255
  maxSubtaskDepth: maxSubtaskDepth(),
10925
11256
  goalRunEnabled,
10926
11257
  runLaunchWidth,
11258
+ spendBudgetTokens,
10927
11259
  cardDefaults,
10928
11260
  verificationSettings,
10929
11261
  verificationCatalog,
10930
11262
  timers: resolveHostTimers(ctx),
10931
- team: buildTeamDispatcher(ctx, config?.teamProvider ?? "spawn"),
10932
11263
  commandDispatcher: { async execute(sessionId, line, signal) {
10933
11264
  const agent = await resolveExecutionAgent(ctx, sessionId);
10934
11265
  return (await ctx.commands.execute(agent, line, [], signal))?.result;
@@ -10939,7 +11270,11 @@ function applyImpl(ctx, config) {
10939
11270
  host.start();
10940
11271
  if (typeof ctx.provide === "function") ctx.provide(TASK_BOARD_SERVICE_NAME, {
10941
11272
  registerExtension: (extension) => host.registerExtension(extension),
10942
- isExtensionEnabled: (extensionId) => host.extensions.isActive(extensionId)
11273
+ isExtensionEnabled: (extensionId) => host.extensions.isActive(extensionId),
11274
+ snapshot: () => host.snapshot(),
11275
+ apply: (requestId, action, initiator) => host.apply(requestId, action, initiator),
11276
+ subscribe: (listener) => host.subscribe(listener),
11277
+ verificationOptions: () => host.verificationOptions()
10943
11278
  });
10944
11279
  let disposeTools;
10945
11280
  const setToolsEnabled = (active) => {
@@ -11004,7 +11339,10 @@ function applyImpl(ctx, config) {
11004
11339
  handle.dispose();
11005
11340
  });
11006
11341
  }
11007
- const routes = makeTaskBoardRoutes(host, resolveProxyAccess(config), { parseTask: async (request, signal) => {
11342
+ const routes = makeTaskBoardRoutes(host, {
11343
+ ...resolveProxyAccess(config),
11344
+ connection: () => resolveConnectionTrust(ctx)
11345
+ }, { parseTask: async (request, signal) => {
11008
11346
  const llm = resolveLlmRuntime(ctx);
11009
11347
  if (llm === void 0) throw new TaskParseError("no-model", "this deployment serves no llm service");
11010
11348
  return await parseTaskDraft(llm, request, signal);
@@ -11054,4 +11392,4 @@ function applyImpl(ctx, config) {
11054
11392
  sync();
11055
11393
  }
11056
11394
  //#endregion
11057
- 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 };
11395
+ export { Config, DEFAULT_GOAL_RUN, DEFAULT_GOAL_VERIFICATION, DEFAULT_PROXY_TOKEN_ENV, DEFAULT_TRUST_FORWARDED_PROXY, TASK_BOARD_GUIDANCE, apply, inject, readConfigField, resolveConnectionTrust, resolveExecutionAgent, resolveHostDefaultPermission, resolveHostTimers, resolveLlmRuntime, resolveProxyAccess, resolveSessionController, resolveToolRegistry };