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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
@@ -877,7 +1008,7 @@ function settledStatus(task, outcome) {
877
1008
  * matching column. No-op (returns the input task) when the execution is not
878
1009
  * the task's latest or is already settled.
879
1010
  */
880
- function settleExecution(task, executionId, outcome, now, error) {
1011
+ function settleExecution(task, executionId, outcome, now, error, summary) {
881
1012
  const index = task.executions.findIndex((execution) => execution.id === executionId);
882
1013
  if (index === -1) return task;
883
1014
  const execution = task.executions[index];
@@ -886,7 +1017,8 @@ function settleExecution(task, executionId, outcome, now, error) {
886
1017
  ...execution,
887
1018
  endedAt: now,
888
1019
  result: outcome,
889
- error
1020
+ error,
1021
+ ...summary === void 0 ? {} : { summary }
890
1022
  };
891
1023
  const executions = [...task.executions];
892
1024
  executions[index] = settled;
@@ -1182,6 +1314,89 @@ function resolveExecutionTargets(task, tasks, maxSubtaskDepth = 3) {
1182
1314
  permissionConfirmedAt: own === void 0 ? owner?.permissionConfirmedAt : task.permissionConfirmedAt
1183
1315
  };
1184
1316
  }
1317
+ //#endregion
1318
+ //#region src/core/execution-summary.ts
1319
+ /**
1320
+ * What one execution left behind: the text of its last assistant message,
1321
+ * recorded on the execution record next to the verdict it belongs to.
1322
+ *
1323
+ * A settled execution used to carry only a verdict, so a parent card could see
1324
+ * that a subtask succeeded without ever seeing what it produced, and had to
1325
+ * guess or redo the work. The card's own content cannot answer that: card
1326
+ * content is the plan and freezes at the first execution
1327
+ * (`canEditTaskContent`), so the closing words of a run are recorded on the
1328
+ * execution record instead.
1329
+ *
1330
+ * Pure (no cordis, no runtime imports) so the settlement path is unit-testable
1331
+ * without a session, and so a text-less run degrades to "no field" rather than
1332
+ * to an empty string.
1333
+ */
1334
+ /** One rendered content block of an assistant message, or '' when it has no prose. */
1335
+ function blockProse(block) {
1336
+ if (typeof block !== "object" || block === null) return "";
1337
+ const row = block;
1338
+ return row.type === "text" && typeof row.text === "string" ? row.text : "";
1339
+ }
1340
+ /** The assistant's own prose of one message: its text blocks joined and trimmed. */
1341
+ function messageProse(content) {
1342
+ if (!Array.isArray(content)) return "";
1343
+ return content.map(blockProse).filter((part) => part !== "").join("\n").trim();
1344
+ }
1345
+ /**
1346
+ * Bound one summary, keeping its tail: the closing paragraphs carry the
1347
+ * conclusion a reader is after, and the omitted opening is announced instead of
1348
+ * silently dropped. Mirrors the evidence reader's tail bound.
1349
+ */
1350
+ function truncateExecutionSummary(text, limit = EXECUTION_SUMMARY_LIMIT) {
1351
+ if (text.length <= limit) return text;
1352
+ const notice = "[truncated " + String(text.length - limit) + " chars] ";
1353
+ return notice.length >= limit ? text.slice(-limit) : notice + text.slice(-(limit - notice.length));
1354
+ }
1355
+ /**
1356
+ * The summary one execution's own events support.
1357
+ *
1358
+ * Only events at or after `startedAt` belong to this run: a reused session
1359
+ * carries the history of earlier executions, which must not be reported as this
1360
+ * one's output. The last assistant message WITH prose wins — a trailing
1361
+ * tool-call or reasoning-only message has nothing to leave behind, so the reader
1362
+ * walks back to the last one that speaks.
1363
+ * @param events - the session events the inspection already read.
1364
+ * @param startedAt - the execution's start instant (ms epoch); 0 means "all".
1365
+ * @returns the bounded summary with the seq it came from, or undefined when the
1366
+ * run left no usable text.
1367
+ */
1368
+ function executionSummaryOf(events, startedAt) {
1369
+ const own = events.filter((event) => typeof event.time !== "number" || startedAt <= 0 || event.time >= startedAt).filter((event) => event.type === "assistant/message" && typeof event.seq === "number").sort((a, b) => a.seq - b.seq);
1370
+ for (let index = own.length - 1; index >= 0; index -= 1) {
1371
+ const event = own[index];
1372
+ const data = typeof event.data === "object" && event.data !== null ? event.data : {};
1373
+ const text = messageProse((typeof data.message === "object" && data.message !== null ? data.message : {}).content);
1374
+ if (text === "") continue;
1375
+ return {
1376
+ text: truncateExecutionSummary(text),
1377
+ seq: event.seq
1378
+ };
1379
+ }
1380
+ }
1381
+ /**
1382
+ * Repair one persisted or reported summary.
1383
+ *
1384
+ * A summary is informational, so an unreadable one is dropped on its own rather
1385
+ * than costing the execution (or the task row) it hangs on. A hand-edited
1386
+ * overlong text is bounded on the way in, so no reader ever holds more than the
1387
+ * limit.
1388
+ */
1389
+ function normalizeExecutionSummary(value) {
1390
+ if (typeof value !== "object" || value === null) return void 0;
1391
+ const row = value;
1392
+ if (typeof row.text !== "string" || typeof row.seq !== "number" || !Number.isFinite(row.seq)) return void 0;
1393
+ const text = row.text.trim();
1394
+ if (text === "") return void 0;
1395
+ return {
1396
+ text: truncateExecutionSummary(text),
1397
+ seq: row.seq
1398
+ };
1399
+ }
1185
1400
  /** Marker replacing every sensitive match. */
1186
1401
  const REDACTED_MARKER = "[REDACTED]";
1187
1402
  const SECTION_ORDER$1 = [
@@ -2568,6 +2783,7 @@ function parseLedger(raw) {
2568
2783
  runGroupId: normalizeTargetId(execution.runGroupId),
2569
2784
  ownResult: isExecutionOutcome(execution.ownResult) ? execution.ownResult : void 0,
2570
2785
  ownError: typeof execution.ownError === "string" ? execution.ownError : void 0,
2786
+ summary: normalizeExecutionSummary(execution.summary),
2571
2787
  verification: normalizeVerification(execution.verification),
2572
2788
  external: execution.external === true ? true : void 0
2573
2789
  }));
@@ -4191,12 +4407,22 @@ var HostTaskLedger = class {
4191
4407
  depthLimit;
4192
4408
  /** Live reader of the deployment's new-card defaults (a volatile config read). */
4193
4409
  cardDefaults;
4410
+ /**
4411
+ * Live reader of the daily token cap (0 = no gate). The scheduled path asks it
4412
+ * per due occurrence, so a cap raised after a skipped occurrence admits the
4413
+ * next one without a restart.
4414
+ */
4415
+ spendBudget;
4416
+ /** Today's measured spend in tokens, or undefined when nothing can be measured. */
4417
+ spendUsed;
4194
4418
  constructor(dir = join(dshHome(), "task-board"), now = Date.now, options = {}) {
4195
4419
  this.now = now;
4196
4420
  const baseline = options.sessionDefaultPermission;
4197
4421
  this.sessionDefault = typeof baseline === "function" ? baseline : () => baseline ?? "read-only";
4198
4422
  this.depthLimit = normalizeSubtaskDepth(options.maxSubtaskDepth ?? 1);
4199
4423
  this.cardDefaults = options.cardDefaults ?? (() => ({}));
4424
+ this.spendBudget = options.spendBudgetTokens ?? (() => 0);
4425
+ this.spendUsed = options.spendUsedToday ?? ((now) => usedTokensToday(now));
4200
4426
  mkdirSync(dir, { recursive: true });
4201
4427
  this.file = join(dir, "ledger-v2.json");
4202
4428
  this.lockFile = join(dir, "ledger-v2.lock");
@@ -4403,6 +4629,12 @@ var HostTaskLedger = class {
4403
4629
  this.skipOccurrence(taskId, "busy", triggeredAt);
4404
4630
  return [];
4405
4631
  }
4632
+ const spendRefusal = this.spendRefusal(triggeredAt);
4633
+ if (spendRefusal !== void 0) {
4634
+ this.document.scheduler.error = `scheduled run refused for task ${taskId}: ${spendRefusal}`;
4635
+ this.skipOccurrence(taskId, "limit", triggeredAt);
4636
+ return [];
4637
+ }
4406
4638
  if (schedule.mode === "once") return this.startCascade(task, triggeredAt, void 0, false, {
4407
4639
  consumed: 1,
4408
4640
  lastTriggeredAt: triggeredAt,
@@ -4427,6 +4659,20 @@ var HostTaskLedger = class {
4427
4659
  });
4428
4660
  }
4429
4661
  /**
4662
+ * Why a due occurrence may not open a run because the day already spent the
4663
+ * cap, or undefined when it may. A cap of 0 — the default — answers before the
4664
+ * measurement is read, so a board with no gate reads no ledger file.
4665
+ * @param now - clock instant (ms epoch).
4666
+ * @returns the refusal message, when the cap is reached.
4667
+ */
4668
+ spendRefusal(now) {
4669
+ const cap = this.spendBudget();
4670
+ if (!(cap > 0)) return void 0;
4671
+ const used = this.spendUsed(now);
4672
+ if (used === void 0 || !spendCapReached(used, cap)) return void 0;
4673
+ return spendCapMessage(used, cap);
4674
+ }
4675
+ /**
4430
4676
  * Record a due occurrence that opened no execution: roll a recurring rule to
4431
4677
  * its next occurrence (budget untouched), or stop it when there is none. A
4432
4678
  * one-shot has no second occurrence, so it always stops here with the reason.
@@ -4533,15 +4779,19 @@ var HostTaskLedger = class {
4533
4779
  * and only finalizes once every child execution in its run group has
4534
4780
  * settled, so a parent card leaves 'running' with the whole tree's verdict
4535
4781
  * rather than its own turn alone.
4782
+ *
4783
+ * `summary` is what the run left behind (see `ExecutionSummary`), passed in
4784
+ * by whichever reader observed the session. It is informational: a caller
4785
+ * without one settles exactly as before, and a settlement never waits on it.
4536
4786
  */
4537
- settle(taskId, executionId, outcome, error) {
4787
+ settle(taskId, executionId, outcome, error, summary) {
4538
4788
  const now = this.now();
4539
4789
  const task = this.document.tasks.find((item) => item.id === taskId);
4540
4790
  const execution = task?.executions.find((entry) => entry.id === executionId);
4541
4791
  if (task === void 0 || execution === void 0 || execution.endedAt !== void 0) return;
4542
4792
  const groupId = execution.runGroupId;
4543
4793
  if (groupId === void 0) {
4544
- this.document.tasks = this.document.tasks.map((item) => item.id === taskId ? settleExecution(item, executionId, outcome, now, error) : item);
4794
+ this.document.tasks = this.document.tasks.map((item) => item.id === taskId ? settleExecution(item, executionId, outcome, now, error, summary) : item);
4545
4795
  this.commit();
4546
4796
  return;
4547
4797
  }
@@ -4553,7 +4803,8 @@ var HostTaskLedger = class {
4553
4803
  executions: item.executions.map((entry) => entry.id === executionId ? {
4554
4804
  ...entry,
4555
4805
  ownResult: outcome,
4556
- ownError: error
4806
+ ownError: error,
4807
+ ...summary === void 0 ? {} : { summary }
4557
4808
  } : entry)
4558
4809
  });
4559
4810
  changed = true;
@@ -4770,6 +5021,7 @@ var HostTaskLedger = class {
4770
5021
  runs = this.startCascade(task, now, initiator, action.kind === "rerun");
4771
5022
  break;
4772
5023
  }
5024
+ default: throw new Error(`unknown task board action kind: ${String(action.kind)}`);
4773
5025
  }
4774
5026
  if (runs === void 0 || runs.length === 0) this.commit();
4775
5027
  return {
@@ -6177,14 +6429,21 @@ var HostExecutionRunner = class HostExecutionRunner {
6177
6429
  return { outcome: "pending" };
6178
6430
  }
6179
6431
  this.scanMemos.delete(sessionId);
6432
+ const closing = executionSummaryOf(events.map((entry) => entry.event), startedAt);
6433
+ const carried = closing === void 0 ? {} : { summary: closing };
6180
6434
  const reason = nonCompletedTurnEnd(turnEnd.event.data);
6181
- if (reason === void 0) return await this.goalVerdict(sessionId) ?? { outcome: "succeeded" };
6435
+ if (reason === void 0) return {
6436
+ ...await this.goalVerdict(sessionId) ?? { outcome: "succeeded" },
6437
+ ...carried
6438
+ };
6182
6439
  return reason === "error" ? {
6183
6440
  outcome: "failed",
6184
- error: "agent turn ended with an error"
6441
+ error: "agent turn ended with an error",
6442
+ ...carried
6185
6443
  } : {
6186
6444
  outcome: "failed",
6187
- error: "agent turn ended without completing: " + reason
6445
+ error: "agent turn ended without completing: " + reason,
6446
+ ...carried
6188
6447
  };
6189
6448
  }
6190
6449
  };
@@ -7003,6 +7262,37 @@ function cardDefaultsOf(defaults) {
7003
7262
  };
7004
7263
  return Object.keys(published).length === 0 ? void 0 : published;
7005
7264
  }
7265
+ /**
7266
+ * Every action kind this board accepts, keyed by the kind itself.
7267
+ *
7268
+ * Written as a total record of `TaskBoardAction['kind']` on purpose: a new member
7269
+ * of that union does not compile until it is listed here, so the table cannot
7270
+ * drift behind the protocol. `apply()` validates against it because a caller
7271
+ * reaching the board through the in-process capability face forwards its action
7272
+ * object verbatim, with no envelope parser in front of it — the HTTP route was the
7273
+ * only entrance before that face existed, and its parser is what used to turn an
7274
+ * unknown kind into a refusal.
7275
+ */
7276
+ const ACTION_KINDS = {
7277
+ import: true,
7278
+ create: true,
7279
+ update: true,
7280
+ delete: true,
7281
+ move: true,
7282
+ archive: true,
7283
+ restore: true,
7284
+ settle: true,
7285
+ "reset-verification": true,
7286
+ "record-external-outcome": true,
7287
+ "set-schedule": true,
7288
+ run: true,
7289
+ rerun: true,
7290
+ "confirm-permission": true,
7291
+ "set-parent": true,
7292
+ "rename-tag": true,
7293
+ "delete-tag": true,
7294
+ "extension-action": true
7295
+ };
7006
7296
  var TaskBoardHostService = class {
7007
7297
  ledger;
7008
7298
  runner;
@@ -7050,6 +7340,13 @@ var TaskBoardHostService = class {
7050
7340
  * launch without remounting the row. Absent means the default.
7051
7341
  */
7052
7342
  runLaunchWidth;
7343
+ /**
7344
+ * Live reader of the daily token cap; 0 means no gate. Read at each run
7345
+ * action, so closing or raising the cap binds the next action.
7346
+ */
7347
+ spendBudgetTokens;
7348
+ /** Today's measured spend: absent measurement reads as "cannot see", never as zero. */
7349
+ spendUsedToday;
7053
7350
  lastPowerJson = "";
7054
7351
  now;
7055
7352
  /** The deployment's workspaces, consulted to resolve a card that pins none. */
@@ -7064,7 +7361,9 @@ var TaskBoardHostService = class {
7064
7361
  this.ledger = options.ledger ?? new HostTaskLedger(void 0, void 0, {
7065
7362
  sessionDefaultPermission: options.sessionDefaultPermission,
7066
7363
  maxSubtaskDepth: options.maxSubtaskDepth,
7067
- cardDefaults: options.cardDefaults
7364
+ cardDefaults: options.cardDefaults,
7365
+ spendBudgetTokens: options.spendBudgetTokens,
7366
+ spendUsedToday: options.spendUsedToday
7068
7367
  });
7069
7368
  this.runner = new HostExecutionRunner(gateway, options.commandDispatcher, options.workspaceRegistry, void 0, options.ownerPeer);
7070
7369
  this.workspaceRegistry = options.workspaceRegistry;
@@ -7075,6 +7374,8 @@ var TaskBoardHostService = class {
7075
7374
  this.goalRunEnabled = options.goalRunEnabled ?? (() => false);
7076
7375
  this.cardDefaults = options.cardDefaults ?? (() => ({}));
7077
7376
  this.runLaunchWidth = options.runLaunchWidth ?? (() => 3);
7377
+ this.spendBudgetTokens = options.spendBudgetTokens ?? (() => 0);
7378
+ this.spendUsedToday = options.spendUsedToday ?? ((now) => usedTokensToday(now));
7078
7379
  this.launches = new LaunchAdmissionQueue(() => normalizeRunLaunchWidth(this.runLaunchWidth()));
7079
7380
  this.verificationSettings = options.verificationSettings ?? (() => ({
7080
7381
  enabled: false,
@@ -7241,6 +7542,8 @@ var TaskBoardHostService = class {
7241
7542
  }
7242
7543
  apply(requestId, action, initiator) {
7243
7544
  if (!this.active) throw new Error("task board is disabled");
7545
+ const kind = action?.kind;
7546
+ if (typeof kind !== "string" || !Object.hasOwn(ACTION_KINDS, kind)) throw new Error(`unknown task board action kind: ${String(kind)}`);
7244
7547
  if (action.kind === "extension-action") return this.handleExtensionAction(action);
7245
7548
  return this.applyBoardAction(requestId, action, initiator);
7246
7549
  }
@@ -7254,6 +7557,7 @@ var TaskBoardHostService = class {
7254
7557
  if (this.team === void 0 && (action.kind === "run" || action.kind === "rerun")) {
7255
7558
  if (this.ledger.state().tasks.find((item) => item.id === action.taskId)?.teamRun === true) throw new Error("Agent Teams is unavailable in this deployment");
7256
7559
  }
7560
+ if (action.kind === "run" || action.kind === "rerun") this.assertSpendCap();
7257
7561
  const result = this.ledger.applyRequest(requestId, this.withInheritedWorkspace(action, initiator), initiator);
7258
7562
  if (result.runs !== void 0) this.dispatchRuns(result.runs);
7259
7563
  if (SCHEDULE_WRITE_ACTIONS.has(action.kind)) this.refreshSchedule();
@@ -7267,6 +7571,24 @@ var TaskBoardHostService = class {
7267
7571
  power: this.power.snapshot()
7268
7572
  };
7269
7573
  }
7574
+ /**
7575
+ * Refuse a run whose day already spent the cap.
7576
+ *
7577
+ * A cap of 0 — the shipped default — answers before the measurement is read:
7578
+ * no ledger file is opened and nothing is summed, which is what keeps a board
7579
+ * that never configured a cap identical to the one before it existed.
7580
+ *
7581
+ * The refusal is a thrown message rather than a code: the wire hands its text
7582
+ * to the caller as board-refused, exactly like every other refusal this board
7583
+ * makes.
7584
+ */
7585
+ assertSpendCap() {
7586
+ const cap = this.spendBudgetTokens();
7587
+ if (!(cap > 0)) return;
7588
+ const used = this.spendUsedToday(this.now());
7589
+ if (used === void 0 || !spendCapReached(used, cap)) return;
7590
+ throw new Error(spendCapMessage(used, cap));
7591
+ }
7270
7592
  /** Route one provider action and answer the resulting board snapshot. */
7271
7593
  async handleExtensionAction(action) {
7272
7594
  await this.extensions.handleAction({
@@ -7514,10 +7836,10 @@ var TaskBoardHostService = class {
7514
7836
  }
7515
7837
  this.unreadablePolls.delete(execution.executionId);
7516
7838
  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);
7839
+ this.settleAndNotify(execution.taskId, execution.executionId, "failed", verificationNeverInvoked(verification) ? NEVER_INVOKED_VERIFICATION_REASON : verificationOnlyInvalid(verification) ? INVALID_ONLY_VERIFICATION_REASON : NO_MATCHING_PASS_VERIFICATION_REASON, result.summary);
7518
7840
  continue;
7519
7841
  }
7520
- this.settleAndNotify(execution.taskId, execution.executionId, result.outcome, "error" in result ? result.error : void 0);
7842
+ this.settleAndNotify(execution.taskId, execution.executionId, result.outcome, "error" in result ? result.error : void 0, result.summary);
7521
7843
  } catch {}
7522
7844
  }
7523
7845
  const open = new Set(executions.map((execution) => execution.executionId));
@@ -7532,14 +7854,14 @@ var TaskBoardHostService = class {
7532
7854
  * ancestor of it — in the running column with no way out. The first poll of
7533
7855
  * each streak is logged, so the Host log names the session.
7534
7856
  */
7535
- settleAndNotify(taskId, executionId, outcome, error) {
7857
+ settleAndNotify(taskId, executionId, outcome, error, summary) {
7536
7858
  const before = this.ledger.getTask(taskId);
7537
7859
  if (before?.executions.find((entry) => entry.id === executionId)?.endedAt !== void 0) {
7538
- this.ledger.settle(taskId, executionId, outcome, error);
7860
+ this.ledger.settle(taskId, executionId, outcome, error, summary);
7539
7861
  return;
7540
7862
  }
7541
7863
  const previousStatus = before?.status;
7542
- this.ledger.settle(taskId, executionId, outcome, error);
7864
+ this.ledger.settle(taskId, executionId, outcome, error, summary);
7543
7865
  const task = this.ledger.getTask(taskId);
7544
7866
  if (task !== void 0 && previousStatus !== void 0 && previousStatus !== task.status) this.extensions.emitStatusChanged({
7545
7867
  taskId,
@@ -9151,12 +9473,26 @@ function isLoopbackHostname(hostname) {
9151
9473
  return isIPv4Loopback(hostname);
9152
9474
  }
9153
9475
  /**
9476
+ * Whether a reverse proxy stood between the client and this host: the request
9477
+ * carries CF-Connecting-IP or X-Forwarded-For. Either header is stamped by a
9478
+ * hop that forwards traffic, so the request did not originate on this machine.
9479
+ * @param request - node HTTP request.
9480
+ * @returns true when a forwarding header is present.
9481
+ */
9482
+ function isProxiedRequest(request) {
9483
+ return request.headers["cf-connecting-ip"] !== void 0 || request.headers["x-forwarded-for"] !== void 0;
9484
+ }
9485
+ /**
9154
9486
  * Request-level trust fence: a loopback socket address AND a loopback Host
9155
9487
  * header, plus browser same-origin markers. The socket address is
9156
- * authoritative; X-Forwarded-For is never trusted.
9488
+ * authoritative for a direct connection; a request that carries a forwarding
9489
+ * header is refused outright, because a proxy in front of the host makes both
9490
+ * the socket address and the Host header describe the proxy rather than the
9491
+ * client. X-Forwarded-For is therefore never evidence *for* loopback.
9157
9492
  */
9158
9493
  function isLoopbackRequest(request) {
9159
9494
  if (!isLoopbackAddress(request.socket.remoteAddress)) return false;
9495
+ if (isProxiedRequest(request)) return false;
9160
9496
  const host = request.headers.host;
9161
9497
  if (typeof host !== "string") return false;
9162
9498
  let hostUrl;
@@ -10607,6 +10943,7 @@ const Config = z.object({
10607
10943
  maxSubtaskDepth: z.number().min(1).max(3).default(1).volatile(),
10608
10944
  sessionPollSeconds: z.number().min(1).max(300).default(5).volatile(),
10609
10945
  runLaunchWidth: z.number().min(1).max(16).default(3).volatile(),
10946
+ spendBudgetTokens: z.number().min(0).default(0).volatile(),
10610
10947
  teamProvider: z.string().min(1).default(DEFAULT_TEAM_PROVIDER),
10611
10948
  goalRunEnabled: z.boolean().default(false).volatile(),
10612
10949
  cardDefaultMode: z.string().default("").volatile(),
@@ -10870,6 +11207,12 @@ function applyImpl(ctx, config) {
10870
11207
  */
10871
11208
  const runLaunchWidth = () => readConfigField(config?.runLaunchWidth, 3);
10872
11209
  /**
11210
+ * Current daily token cap, read at each gate like the width above. The value
11211
+ * decides first: 0 — the default — ends the gate before a file is opened, so
11212
+ * a board that never set a cap pays nothing for it.
11213
+ */
11214
+ const spendBudgetTokens = () => readConfigField(config?.spendBudgetTokens, 0);
11215
+ /**
10873
11216
  * The baseline the permission confirmation gate judges against: the row's own
10874
11217
  * `sessionDefaultPermission` when the deployment pins one, otherwise the Host's
10875
11218
  * default preset. Read per call through the ledger, so a Host Settings change
@@ -10924,6 +11267,7 @@ function applyImpl(ctx, config) {
10924
11267
  maxSubtaskDepth: maxSubtaskDepth(),
10925
11268
  goalRunEnabled,
10926
11269
  runLaunchWidth,
11270
+ spendBudgetTokens,
10927
11271
  cardDefaults,
10928
11272
  verificationSettings,
10929
11273
  verificationCatalog,
@@ -10939,7 +11283,11 @@ function applyImpl(ctx, config) {
10939
11283
  host.start();
10940
11284
  if (typeof ctx.provide === "function") ctx.provide(TASK_BOARD_SERVICE_NAME, {
10941
11285
  registerExtension: (extension) => host.registerExtension(extension),
10942
- isExtensionEnabled: (extensionId) => host.extensions.isActive(extensionId)
11286
+ isExtensionEnabled: (extensionId) => host.extensions.isActive(extensionId),
11287
+ snapshot: () => host.snapshot(),
11288
+ apply: (requestId, action, initiator) => host.apply(requestId, action, initiator),
11289
+ subscribe: (listener) => host.subscribe(listener),
11290
+ verificationOptions: () => host.verificationOptions()
10943
11291
  });
10944
11292
  let disposeTools;
10945
11293
  const setToolsEnabled = (active) => {