@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.
@@ -5,7 +5,9 @@ import { dirname, join } from 'node:path'
5
5
  import { dshHome } from './dsh-home.ts'
6
6
  import { isValidCron, isValidTimeZone, nextRunAtMs, resolveHostTimeZone } from './core/schedule.ts'
7
7
  import { isTaskRecord, parseLedger } from './core/store.ts'
8
- import { canMoveManually, hasOpenExecution, retainRecentExecutions, scheduleExhausted, scheduleRunBudget, settleExecution, settledStatus, startExecution, withSchedule, withStatus, type ExecutionOutcome, type ExecutionRecord, type ScheduleMode, type ScheduleStopReason, type TaskRecord } from './core/tasks.ts'
8
+ import { DEFAULT_SPEND_BUDGET_TOKENS, spendCapMessage, spendCapReached } from './core/spend-budget.ts'
9
+ import { usedTokensToday } from './host-spend.ts'
10
+ import { canMoveManually, hasOpenExecution, retainRecentExecutions, scheduleExhausted, scheduleRunBudget, settleExecution, settledStatus, startExecution, withSchedule, withStatus, type ExecutionOutcome, type ExecutionRecord, type ExecutionSummary, type ScheduleMode, type ScheduleStopReason, type TaskRecord } from './core/tasks.ts'
9
11
  import {
10
12
  DEFAULT_SUBTASK_DEPTH,
11
13
  cascadeTargets,
@@ -493,12 +495,24 @@ export class HostTaskLedger {
493
495
  /** Live reader of the deployment's new-card defaults (a volatile config read). */
494
496
  private readonly cardDefaults: () => CardDefaults
495
497
 
496
- constructor(dir: string = join(dshHome(), 'task-board'), private readonly now: () => number = Date.now, options: { sessionDefaultPermission?: TaskPermission | (() => TaskPermission); maxSubtaskDepth?: number; cardDefaults?: () => CardDefaults } = {}) {
498
+ /**
499
+ * Live reader of the daily token cap (0 = no gate). The scheduled path asks it
500
+ * per due occurrence, so a cap raised after a skipped occurrence admits the
501
+ * next one without a restart.
502
+ */
503
+ private readonly spendBudget: () => number
504
+
505
+ /** Today's measured spend in tokens, or undefined when nothing can be measured. */
506
+ private readonly spendUsed: (now: number) => number | undefined
507
+
508
+ constructor(dir: string = join(dshHome(), 'task-board'), private readonly now: () => number = Date.now, options: { sessionDefaultPermission?: TaskPermission | (() => TaskPermission); maxSubtaskDepth?: number; cardDefaults?: () => CardDefaults; spendBudgetTokens?: () => number; spendUsedToday?: (now: number) => number | undefined } = {}) {
497
509
  // Resolved before the load/repair passes below: they can evaluate the gate.
498
510
  const baseline = options.sessionDefaultPermission
499
511
  this.sessionDefault = typeof baseline === 'function' ? baseline : () => baseline ?? DEFAULT_SESSION_PERMISSION
500
512
  this.depthLimit = normalizeSubtaskDepth(options.maxSubtaskDepth ?? DEFAULT_SUBTASK_DEPTH)
501
513
  this.cardDefaults = options.cardDefaults ?? (() => ({}))
514
+ this.spendBudget = options.spendBudgetTokens ?? (() => DEFAULT_SPEND_BUDGET_TOKENS)
515
+ this.spendUsed = options.spendUsedToday ?? (now => usedTokensToday(now))
502
516
  mkdirSync(dir, { recursive: true })
503
517
  this.file = join(dir, 'ledger-v2.json')
504
518
  this.lockFile = join(dir, 'ledger-v2.lock')
@@ -753,6 +767,17 @@ export class HostTaskLedger {
753
767
  return []
754
768
  }
755
769
 
770
+ const spendRefusal = this.spendRefusal(triggeredAt)
771
+ if (spendRefusal !== undefined) {
772
+ // A scheduled occurrence has no client to throw at, so the refusal lands
773
+ // on the board's own scheduler error and the occurrence is skipped without
774
+ // consuming the rule's run budget: raising the cap, or the day rolling
775
+ // over, admits the next trigger instead of leaving a spent rule behind.
776
+ this.document.scheduler.error = `scheduled run refused for task ${taskId}: ${spendRefusal}`
777
+ this.skipOccurrence(taskId, 'limit', triggeredAt)
778
+ return []
779
+ }
780
+
756
781
  if (schedule.mode === 'once') {
757
782
  // The single planned instant is due: open its one run and stop the rule
758
783
  // in the same commit, so the budget can never produce a second one.
@@ -779,6 +804,21 @@ export class HostTaskLedger {
779
804
  })
780
805
  }
781
806
 
807
+ /**
808
+ * Why a due occurrence may not open a run because the day already spent the
809
+ * cap, or undefined when it may. A cap of 0 — the default — answers before the
810
+ * measurement is read, so a board with no gate reads no ledger file.
811
+ * @param now - clock instant (ms epoch).
812
+ * @returns the refusal message, when the cap is reached.
813
+ */
814
+ private spendRefusal(now: number): string | undefined {
815
+ const cap = this.spendBudget()
816
+ if (!(cap > 0)) return undefined
817
+ const used = this.spendUsed(now)
818
+ if (used === undefined || !spendCapReached(used, cap)) return undefined
819
+ return spendCapMessage(used, cap)
820
+ }
821
+
782
822
  /**
783
823
  * Record a due occurrence that opened no execution: roll a recurring rule to
784
824
  * its next occurrence (budget untouched), or stop it when there is none. A
@@ -877,8 +917,12 @@ export class HostTaskLedger {
877
917
  * and only finalizes once every child execution in its run group has
878
918
  * settled, so a parent card leaves 'running' with the whole tree's verdict
879
919
  * rather than its own turn alone.
920
+ *
921
+ * `summary` is what the run left behind (see `ExecutionSummary`), passed in
922
+ * by whichever reader observed the session. It is informational: a caller
923
+ * without one settles exactly as before, and a settlement never waits on it.
880
924
  */
881
- settle(taskId: string, executionId: string, outcome: ExecutionOutcome, error?: string): void {
925
+ settle(taskId: string, executionId: string, outcome: ExecutionOutcome, error?: string, summary?: ExecutionSummary): void {
882
926
  const now = this.now()
883
927
  const task = this.document.tasks.find(item => item.id === taskId)
884
928
  const execution = task?.executions.find(entry => entry.id === executionId)
@@ -886,17 +930,22 @@ export class HostTaskLedger {
886
930
  const groupId = execution.runGroupId
887
931
  if (groupId === undefined) {
888
932
  this.document.tasks = this.document.tasks.map(item => item.id === taskId
889
- ? settleExecution(item, executionId, outcome, now, error)
933
+ ? settleExecution(item, executionId, outcome, now, error, summary)
890
934
  : item)
891
935
  this.commit()
892
936
  return
893
937
  }
894
938
  let changed = false
895
939
  if (execution.ownResult === undefined) {
940
+ // A cascade parent records its own turn's closing text with its own
941
+ // outcome; the fold that finalizes the card carries no session of its own
942
+ // and leaves what is already here in place.
896
943
  this.document.tasks = this.document.tasks.map(item => item.id !== taskId ? item : {
897
944
  ...item,
898
945
  updatedAt: now,
899
- executions: item.executions.map(entry => entry.id === executionId ? { ...entry, ownResult: outcome, ownError: error } : entry),
946
+ executions: item.executions.map(entry => entry.id === executionId
947
+ ? { ...entry, ownResult: outcome, ownError: error, ...(summary === undefined ? {} : { summary }) }
948
+ : entry),
900
949
  })
901
950
  changed = true
902
951
  }
@@ -1176,6 +1225,15 @@ export class HostTaskLedger {
1176
1225
  runs = this.startCascade(task, now, initiator, action.kind === 'rerun')
1177
1226
  break
1178
1227
  }
1228
+ default: {
1229
+ // Defence in depth. Every kind above is reachable only through
1230
+ // TaskBoardHostService.apply(), which validates the kind first; this
1231
+ // default exists so a future call path that reaches the ledger directly
1232
+ // fails loudly instead of falling through to the commit below — which is
1233
+ // exactly what an unknown kind did while the switch had no default:
1234
+ // unchanged document, new revision.
1235
+ throw new Error(`unknown task board action kind: ${String((action as { kind?: unknown }).kind)}`)
1236
+ }
1179
1237
  }
1180
1238
  // startCascade committed the opened participants itself; committing again
1181
1239
  // here would bump the revision twice for one action.
@@ -7,7 +7,8 @@ import { teammateName } from './core/subtask.ts'
7
7
  import { mostRecentWorkspaceId } from './core/workspace-target.ts'
8
8
  import { declaredRoute, normalizeReasoningEffort, resolveReasoningEffort, type ReasoningRoute } from './core/reasoning-effort.ts'
9
9
  import type { ModelCatalogView } from './core/verification.ts'
10
- import type { TaskPermission, TaskRecord } from './core/tasks.ts'
10
+ import type { ExecutionSummary, TaskPermission, TaskRecord } from './core/tasks.ts'
11
+ import { executionSummaryOf } from './core/execution-summary.ts'
11
12
 
12
13
  /**
13
14
  * Host services needed to validate a task's workspace before creating a
@@ -169,9 +170,9 @@ export type ExecutionInspection =
169
170
  * forever.
170
171
  */
171
172
  | { outcome: 'pending'; unreadable?: true; reason?: string }
172
- | { outcome: 'succeeded' }
173
- | { outcome: 'failed'; error: string }
174
- | { outcome: 'cancelled'; error: string }
173
+ | { outcome: 'succeeded'; summary?: ExecutionSummary }
174
+ | { outcome: 'failed'; error: string; summary?: ExecutionSummary }
175
+ | { outcome: 'cancelled'; error: string; summary?: ExecutionSummary }
175
176
 
176
177
  /** A post-create launch failure that still identifies the session to the ledger. */
177
178
  export class SessionLaunchError extends Error {
@@ -909,13 +910,20 @@ export class HostExecutionRunner {
909
910
  return { outcome: 'pending' }
910
911
  }
911
912
  this.scanMemos.delete(sessionId)
913
+ // What the run left behind rides the verdict the caller settles with, for a
914
+ // success and a failure alike: the events are in hand here, and no later
915
+ // reader can recover them once the session is gone. A run with no assistant
916
+ // prose carries no field at all, so settling stays a decision about the
917
+ // verdict alone.
918
+ const closing = executionSummaryOf(events.map(entry => entry.event), startedAt)
919
+ const carried = closing === undefined ? {} : { summary: closing }
912
920
  const reason = nonCompletedTurnEnd(turnEnd.event.data)
913
- if (reason === undefined) return await this.goalVerdict(sessionId) ?? { outcome: 'succeeded' }
921
+ if (reason === undefined) return { ...(await this.goalVerdict(sessionId) ?? { outcome: 'succeeded' as const }), ...carried }
914
922
  // `error` keeps its historical wording; every other non-completed reason
915
923
  // (aborted / blocked / max-tokens / interrupted) now reports instead of
916
924
  // silently counting as success.
917
925
  return reason === 'error'
918
- ? { outcome: 'failed', error: 'agent turn ended with an error' }
919
- : { outcome: 'failed', error: 'agent turn ended without completing: ' + reason }
926
+ ? { outcome: 'failed', error: 'agent turn ended with an error', ...carried }
927
+ : { outcome: 'failed', error: 'agent turn ended without completing: ' + reason, ...carried }
920
928
  }
921
929
  }
@@ -1,5 +1,7 @@
1
1
  import type { TypertGateway } from '@deepseek-ai/dsh-api-gateway'
2
2
  import { DEFAULT_RUN_LAUNCH_WIDTH, normalizeRunLaunchWidth } from './core/launch-width.ts'
3
+ import { DEFAULT_SPEND_BUDGET_TOKENS, spendCapMessage, spendCapReached } from './core/spend-budget.ts'
4
+ import { usedTokensToday } from './host-spend.ts'
3
5
  import { DEFAULT_SESSION_POLL_SECONDS, normalizeSessionPollSeconds, sessionPollMs } from './core/poll-cadence.ts'
4
6
  import { reusableSessionId } from './core/session-reuse.ts'
5
7
  import { LaunchAdmissionQueue, type QueuedLaunch } from './host/launch-admission.ts'
@@ -12,7 +14,7 @@ import { TASK_BOARD_SCHEMA_VERSION, type TaskBoardAction, type TaskBoardEventPay
12
14
  import type { CardDefaults } from './core/card-defaults.ts'
13
15
  import { TaskBoardExtensionRegistry } from './host/extension-registry.ts'
14
16
  import type { TaskBoardExtension } from './core/extension.ts'
15
- import { isTaskPermission, normalizeTargetId, type ExecutionOutcome, type ScheduleMode, type TaskRecord, type TaskStatus } from './core/tasks.ts'
17
+ import { isTaskPermission, normalizeTargetId, type ExecutionOutcome, type ExecutionSummary, type ScheduleMode, type TaskRecord, type TaskStatus } from './core/tasks.ts'
16
18
  import { passedAttempt, resolveContract, verificationNeverInvoked, verificationOnlyInvalid, verificationRequired, withAcceptanceDetailCleared, type ExecutionVerification, type ModelCatalogView, type VerificationContract, type VerificationSettings } from './core/verification.ts'
17
19
  import type { TaskPermission } from './core/handover.ts'
18
20
 
@@ -197,6 +199,38 @@ function cardDefaultsOf(defaults: CardDefaults): TaskBoardSnapshot['cardDefaults
197
199
  return Object.keys(published).length === 0 ? undefined : published
198
200
  }
199
201
 
202
+ /**
203
+ * Every action kind this board accepts, keyed by the kind itself.
204
+ *
205
+ * Written as a total record of `TaskBoardAction['kind']` on purpose: a new member
206
+ * of that union does not compile until it is listed here, so the table cannot
207
+ * drift behind the protocol. `apply()` validates against it because a caller
208
+ * reaching the board through the in-process capability face forwards its action
209
+ * object verbatim, with no envelope parser in front of it — the HTTP route was the
210
+ * only entrance before that face existed, and its parser is what used to turn an
211
+ * unknown kind into a refusal.
212
+ */
213
+ const ACTION_KINDS: Readonly<Record<TaskBoardAction['kind'], true>> = {
214
+ import: true,
215
+ create: true,
216
+ update: true,
217
+ delete: true,
218
+ move: true,
219
+ archive: true,
220
+ restore: true,
221
+ settle: true,
222
+ 'reset-verification': true,
223
+ 'record-external-outcome': true,
224
+ 'set-schedule': true,
225
+ run: true,
226
+ rerun: true,
227
+ 'confirm-permission': true,
228
+ 'set-parent': true,
229
+ 'rename-tag': true,
230
+ 'delete-tag': true,
231
+ 'extension-action': true,
232
+ }
233
+
200
234
  export class TaskBoardHostService {
201
235
  readonly ledger: HostTaskLedger
202
236
  readonly runner: HostExecutionRunner
@@ -244,6 +278,13 @@ export class TaskBoardHostService {
244
278
  * launch without remounting the row. Absent means the default.
245
279
  */
246
280
  private readonly runLaunchWidth: () => number
281
+ /**
282
+ * Live reader of the daily token cap; 0 means no gate. Read at each run
283
+ * action, so closing or raising the cap binds the next action.
284
+ */
285
+ private readonly spendBudgetTokens: () => number
286
+ /** Today's measured spend: absent measurement reads as "cannot see", never as zero. */
287
+ private readonly spendUsedToday: (now: number) => number | undefined
247
288
  private lastPowerJson = ''
248
289
  private readonly now: () => number
249
290
  /** The deployment's workspaces, consulted to resolve a card that pins none. */
@@ -306,11 +347,25 @@ export class TaskBoardHostService {
306
347
  * is still queueing. Absent means the default width.
307
348
  */
308
349
  runLaunchWidth?: () => number
350
+ /**
351
+ * Live daily token cap (a volatile config read). 0 — the default, and what
352
+ * every deployment that never configured one keeps — ends the gate before
353
+ * anything is measured. A positive cap refuses a run whose day already spent
354
+ * it, on both the action path and the cron path.
355
+ */
356
+ spendBudgetTokens?: () => number
357
+ /**
358
+ * Today's measured spend in tokens, or undefined when this deployment keeps
359
+ * no readable usage ledger. Defaults to the family usage ledger reader.
360
+ */
361
+ spendUsedToday?: (now: number) => number | undefined
309
362
  } = {}) {
310
363
  this.ledger = options.ledger ?? new HostTaskLedger(undefined, undefined, {
311
364
  sessionDefaultPermission: options.sessionDefaultPermission,
312
365
  maxSubtaskDepth: options.maxSubtaskDepth,
313
366
  cardDefaults: options.cardDefaults,
367
+ spendBudgetTokens: options.spendBudgetTokens,
368
+ spendUsedToday: options.spendUsedToday,
314
369
  })
315
370
  this.runner = new HostExecutionRunner(gateway, options.commandDispatcher, options.workspaceRegistry, undefined, options.ownerPeer)
316
371
  this.workspaceRegistry = options.workspaceRegistry
@@ -321,6 +376,8 @@ export class TaskBoardHostService {
321
376
  this.goalRunEnabled = options.goalRunEnabled ?? (() => false)
322
377
  this.cardDefaults = options.cardDefaults ?? (() => ({}))
323
378
  this.runLaunchWidth = options.runLaunchWidth ?? (() => DEFAULT_RUN_LAUNCH_WIDTH)
379
+ this.spendBudgetTokens = options.spendBudgetTokens ?? (() => DEFAULT_SPEND_BUDGET_TOKENS)
380
+ this.spendUsedToday = options.spendUsedToday ?? (now => usedTokensToday(now))
324
381
  this.launches = new LaunchAdmissionQueue(() => normalizeRunLaunchWidth(this.runLaunchWidth()))
325
382
  this.verificationSettings = options.verificationSettings ?? (() => ({ enabled: false, model: '', reasoningEffort: '' }))
326
383
  this.verificationCatalog = options.verificationCatalog ?? (async () => undefined)
@@ -509,6 +566,15 @@ export class TaskBoardHostService {
509
566
  apply(requestId: string, action: TaskBoardAction, initiator?: string): TaskBoardSnapshot | Promise<TaskBoardSnapshot>
510
567
  apply(requestId: string, action: TaskBoardAction, initiator?: string): TaskBoardSnapshot | Promise<TaskBoardSnapshot> {
511
568
  if (!this.active) throw new Error('task board is disabled')
569
+ // A caller that never met the HTTP envelope parser can name a kind this build
570
+ // does not implement. It is refused here, in the board's own vocabulary: the
571
+ // ledger has no case for it, and letting it through committed an unchanged
572
+ // document under a fresh revision — which every connected client then reloads
573
+ // a whole snapshot for.
574
+ const kind = (action as { kind?: unknown } | null | undefined)?.kind
575
+ if (typeof kind !== 'string' || !Object.hasOwn(ACTION_KINDS, kind)) {
576
+ throw new Error(`unknown task board action kind: ${String(kind)}`)
577
+ }
512
578
  // Provider actions never touch the ledger directly: the registry routes the
513
579
  // action to the owning extension, whose own capability calls come back
514
580
  // through applyBoardAction and every board gate below.
@@ -532,6 +598,7 @@ export class TaskBoardHostService {
532
598
  const task = this.ledger.state().tasks.find(item => item.id === action.taskId)
533
599
  if (task?.teamRun === true) throw new Error('Agent Teams is unavailable in this deployment')
534
600
  }
601
+ if (action.kind === 'run' || action.kind === 'rerun') this.assertSpendCap()
535
602
  const result = this.ledger.applyRequest(requestId, this.withInheritedWorkspace(action, initiator), initiator)
536
603
  if (result.runs !== undefined) this.dispatchRuns(result.runs)
537
604
  // A committed write that can move a rule moves the nearest trigger;
@@ -551,6 +618,25 @@ export class TaskBoardHostService {
551
618
  }
552
619
  }
553
620
 
621
+ /**
622
+ * Refuse a run whose day already spent the cap.
623
+ *
624
+ * A cap of 0 — the shipped default — answers before the measurement is read:
625
+ * no ledger file is opened and nothing is summed, which is what keeps a board
626
+ * that never configured a cap identical to the one before it existed.
627
+ *
628
+ * The refusal is a thrown message rather than a code: the wire hands its text
629
+ * to the caller as board-refused, exactly like every other refusal this board
630
+ * makes.
631
+ */
632
+ private assertSpendCap(): void {
633
+ const cap = this.spendBudgetTokens()
634
+ if (!(cap > 0)) return
635
+ const used = this.spendUsedToday(this.now())
636
+ if (used === undefined || !spendCapReached(used, cap)) return
637
+ throw new Error(spendCapMessage(used, cap))
638
+ }
639
+
554
640
  /** Route one provider action and answer the resulting board snapshot. */
555
641
  private async handleExtensionAction(action: Extract<TaskBoardAction, { kind: 'extension-action' }>): Promise<TaskBoardSnapshot> {
556
642
  await this.extensions.handleAction({
@@ -915,10 +1001,13 @@ export class TaskBoardHostService {
915
1001
  : verificationOnlyInvalid(verification)
916
1002
  ? INVALID_ONLY_VERIFICATION_REASON
917
1003
  : NO_MATCHING_PASS_VERIFICATION_REASON,
1004
+ result.summary,
918
1005
  )
919
1006
  continue
920
1007
  }
921
- this.settleAndNotify(execution.taskId, execution.executionId, result.outcome, 'error' in result ? result.error : undefined)
1008
+ // The run's closing text rides whichever verdict it earned: a failed
1009
+ // execution still leaves what it managed to say.
1010
+ this.settleAndNotify(execution.taskId, execution.executionId, result.outcome, 'error' in result ? result.error : undefined, result.summary)
922
1011
  } catch {
923
1012
  // A transient inspection failure never settles a running execution.
924
1013
  }
@@ -938,16 +1027,16 @@ export class TaskBoardHostService {
938
1027
  * ancestor of it — in the running column with no way out. The first poll of
939
1028
  * each streak is logged, so the Host log names the session.
940
1029
  */
941
- private settleAndNotify(taskId: string, executionId: string, outcome: ExecutionOutcome, error?: string): void {
1030
+ private settleAndNotify(taskId: string, executionId: string, outcome: ExecutionOutcome, error?: string, summary?: ExecutionSummary): void {
942
1031
  const before = this.ledger.getTask(taskId)
943
1032
  if (before?.executions.find(entry => entry.id === executionId)?.endedAt !== undefined) {
944
1033
  // Already settled: the ledger would no-op, and re-emitting would report
945
1034
  // the same settlement twice.
946
- this.ledger.settle(taskId, executionId, outcome, error)
1035
+ this.ledger.settle(taskId, executionId, outcome, error, summary)
947
1036
  return
948
1037
  }
949
1038
  const previousStatus = before?.status
950
- this.ledger.settle(taskId, executionId, outcome, error)
1039
+ this.ledger.settle(taskId, executionId, outcome, error, summary)
951
1040
  const task = this.ledger.getTask(taskId)
952
1041
  if (task !== undefined && previousStatus !== undefined && previousStatus !== task.status) {
953
1042
  this.extensions.emitStatusChanged({ taskId, status: task.status, previous: previousStatus })
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Today's measured spend, read from the usage ledger this deployment keeps at
3
+ * `$DSH_HOME/dsh-usage/usage-ledger.json`.
4
+ *
5
+ * The measure is the family usage ledger rather than a counter this plugin
6
+ * accumulates from `session/event`, for two reasons. The ledger is durable, so
7
+ * a cap cannot be reset by restarting the Host (the Loader remounts a row on
8
+ * any config change, and a spend counter that lived only in memory would forget
9
+ * the day). And a second fold of the same events inside the board would have to
10
+ * persist its own totals to be worth anything, which means a second writer of
11
+ * spend state in one process.
12
+ *
13
+ * What that costs: the file belongs to the dsh-usage plugin, so a deployment
14
+ * that does not mount it keeps no ledger and the cap cannot measure anything.
15
+ * That case is reported once per process and the gate then refuses nothing —
16
+ * wedging the board because a sibling plugin is absent would be worse than a
17
+ * cap that says it cannot see. The 3 s flush debounce of that plugin is the
18
+ * other cost: the reading trails the busiest moments by at most one debounce.
19
+ * @module @linxin666/dsh-task-board/host-spend
20
+ */
21
+
22
+ import { readFileSync } from 'node:fs'
23
+ import { join } from 'node:path'
24
+ import { dshHome } from './dsh-home.ts'
25
+
26
+ /**
27
+ * The token fields one ledger bucket totals. Billed input is uncached input
28
+ * plus both cache buckets; output already includes reasoning, so reasoning is
29
+ * deliberately not added again — the sum is the one the usage panel shows.
30
+ */
31
+ const TOKEN_FIELDS = ['inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens'] as const
32
+
33
+ /** Reported at most once per process: an unmeasurable cap is a startup fact, not a per-run one. */
34
+ let reportedUnmeasurable = false
35
+
36
+ /**
37
+ * Local-date key (`YYYY-MM-DD`) of an instant, the bucketing the usage ledger
38
+ * itself uses: the cap and the usage panel therefore roll over at the same
39
+ * local midnight.
40
+ * @param ms - clock instant (ms epoch).
41
+ * @returns the day key.
42
+ */
43
+ export function spendDateKey(ms: number): string {
44
+ const date = new Date(ms)
45
+ const month = String(date.getMonth() + 1).padStart(2, '0')
46
+ const day = String(date.getDate()).padStart(2, '0')
47
+ return `${date.getFullYear()}-${month}-${day}`
48
+ }
49
+
50
+ /**
51
+ * Total tokens one ledger day recorded, across every provider and model of that
52
+ * day. Anything that is not a finite token count contributes 0, so a ledger
53
+ * written by another version degrades to a smaller reading instead of NaN.
54
+ * @param day - one day bucket as the ledger stores it, when it is one.
55
+ * @returns the day's token total.
56
+ */
57
+ export function ledgerDayTokens(day: unknown): number {
58
+ if (typeof day !== 'object' || day === null) return 0
59
+ let total = 0
60
+ for (const models of Object.values(day as Record<string, unknown>)) {
61
+ if (typeof models !== 'object' || models === null) continue
62
+ for (const bucket of Object.values(models as Record<string, unknown>)) {
63
+ if (typeof bucket !== 'object' || bucket === null) continue
64
+ for (const field of TOKEN_FIELDS) {
65
+ const value = (bucket as Record<string, unknown>)[field]
66
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) total += value
67
+ }
68
+ }
69
+ }
70
+ return total
71
+ }
72
+
73
+ /**
74
+ * Path of the usage ledger for this DSH home.
75
+ * @returns the absolute ledger path.
76
+ */
77
+ export function spendLedgerPath(): string {
78
+ return join(dshHome(), 'dsh-usage', 'usage-ledger.json')
79
+ }
80
+
81
+ /**
82
+ * Tokens already spent today, or undefined when no measurement is available.
83
+ *
84
+ * Undefined is "cannot see", not "spent nothing": the caller fails open and
85
+ * reports it, because a spend cap that cannot read its own source must never
86
+ * decide that no work may run.
87
+ * @param now - clock instant (ms epoch).
88
+ * @param path - ledger path (test seam).
89
+ * @returns today's token total, or undefined when the ledger is unreadable.
90
+ */
91
+ export function usedTokensToday(now: number = Date.now(), path: string = spendLedgerPath()): number | undefined {
92
+ try {
93
+ const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'))
94
+ const days = typeof parsed === 'object' && parsed !== null ? (parsed as { days?: unknown }).days : undefined
95
+ if (typeof days !== 'object' || days === null) return undefined
96
+ return ledgerDayTokens((days as Record<string, unknown>)[spendDateKey(now)])
97
+ } catch (error) {
98
+ if (!reportedUnmeasurable) {
99
+ reportedUnmeasurable = true
100
+ const detail = error instanceof Error ? error.message : String(error)
101
+ console.warn(`[dsh-task-board] spend cap cannot be measured from ${path}: ${detail}; runs are not gated until that ledger is readable`)
102
+ }
103
+ return undefined
104
+ }
105
+ }
package/src/index.ts CHANGED
@@ -24,6 +24,7 @@ import { TASK_PERMISSIONS, isTaskPermission, type TaskPermission } from './core/
24
24
  import { DEFAULT_SUBTASK_DEPTH, SUBTASK_DEPTH_MAX, SUBTASK_DEPTH_MIN } from './core/subtask.ts'
25
25
  import { DEFAULT_SESSION_POLL_SECONDS, SESSION_POLL_MAX_SECONDS, SESSION_POLL_MIN_SECONDS } from './core/poll-cadence.ts'
26
26
  import { DEFAULT_RUN_LAUNCH_WIDTH, RUN_LAUNCH_WIDTH_MAX, RUN_LAUNCH_WIDTH_MIN } from './core/launch-width.ts'
27
+ import { DEFAULT_SPEND_BUDGET_TOKENS } from './core/spend-budget.ts'
27
28
  import {
28
29
  DEFAULT_VERIFICATION_BUDGET_SECONDS,
29
30
  DEFAULT_VERIFICATION_CALL_TIMEOUT_SECONDS,
@@ -40,6 +41,7 @@ import { buildTaskBoardTools, TASK_BOARD_TOOL_NAMES } from './host/agent-tools.t
40
41
  import { PLUGIN_TOOL_SECTION_ORDERS, visibleToolText } from './tool-surface.ts'
41
42
  import { makeTaskBoardRoutes } from './host-routes.ts'
42
43
  import { TASK_BOARD_SERVICE_NAME, type TaskBoardExtension } from './core/extension.ts'
44
+ import type { TaskBoardAction } from './protocol.ts'
43
45
  import { mountOnce } from './mount-once.ts'
44
46
  import { createGoalVerificationGate, type GoalFace } from './host/verification-gate.ts'
45
47
  import { normalizeCatalog, type ModelCatalogView, type VerificationSettings } from './core/verification.ts'
@@ -120,6 +122,15 @@ export interface Config {
120
122
  * queueing.
121
123
  */
122
124
  runLaunchWidth?: Volatile<number>
125
+ /**
126
+ * Daily token ceiling for the work this board dispatches (default 0 = no
127
+ * gate). Tokens, not money: the ledger the board measures against prices
128
+ * DeepSeek's own routes only, so a cost cap would read 0 elsewhere. Read at
129
+ * each gate, so an edit binds the next run without a remount; a manual
130
+ * run/rerun whose day already spent the cap is refused, and a due occurrence
131
+ * is skipped onto the scheduler with its run budget untouched.
132
+ */
133
+ spendBudgetTokens?: Volatile<number>
123
134
  /**
124
135
  * Continuable-subagent provider the Agent Teams service uses to compose a
125
136
  * teammate. Matches the Agent Teams tool plugin's `freshProvider` default;
@@ -248,6 +259,8 @@ export interface ConfigInput {
248
259
  sessionPollSeconds?: number
249
260
  /** Concurrent run launches allowed at once, 1..16. */
250
261
  runLaunchWidth?: number
262
+ /** Daily token ceiling for board runs; 0 disables the gate. */
263
+ spendBudgetTokens?: number
251
264
  /** Continuable-subagent provider the Agent Teams service composes a teammate from. */
252
265
  teamProvider?: string
253
266
  /** Global native /goal switch; default off, frozen per execution. */
@@ -282,6 +295,7 @@ export const Config: z<ConfigInput, Config> = z.object({
282
295
  maxSubtaskDepth: z.number().min(SUBTASK_DEPTH_MIN).max(SUBTASK_DEPTH_MAX).default(DEFAULT_SUBTASK_DEPTH).volatile(),
283
296
  sessionPollSeconds: z.number().min(SESSION_POLL_MIN_SECONDS).max(SESSION_POLL_MAX_SECONDS).default(DEFAULT_SESSION_POLL_SECONDS).volatile(),
284
297
  runLaunchWidth: z.number().min(RUN_LAUNCH_WIDTH_MIN).max(RUN_LAUNCH_WIDTH_MAX).default(DEFAULT_RUN_LAUNCH_WIDTH).volatile(),
298
+ spendBudgetTokens: z.number().min(DEFAULT_SPEND_BUDGET_TOKENS).default(DEFAULT_SPEND_BUDGET_TOKENS).volatile(),
285
299
  teamProvider: z.string().min(1).default(DEFAULT_TEAM_PROVIDER),
286
300
  goalRunEnabled: z.boolean().default(false).volatile(),
287
301
  cardDefaultMode: z.string().default('').volatile(),
@@ -617,6 +631,12 @@ function applyImpl(ctx: Context, config?: Config): void {
617
631
  * remounting the row; the Host clamps a hand-edited value into the schema range.
618
632
  */
619
633
  const runLaunchWidth = (): number => readConfigField(config?.runLaunchWidth, DEFAULT_RUN_LAUNCH_WIDTH)
634
+ /**
635
+ * Current daily token cap, read at each gate like the width above. The value
636
+ * decides first: 0 — the default — ends the gate before a file is opened, so
637
+ * a board that never set a cap pays nothing for it.
638
+ */
639
+ const spendBudgetTokens = (): number => readConfigField(config?.spendBudgetTokens, DEFAULT_SPEND_BUDGET_TOKENS)
620
640
  /**
621
641
  * The baseline the permission confirmation gate judges against: the row's own
622
642
  * `sessionDefaultPermission` when the deployment pins one, otherwise the Host's
@@ -681,6 +701,7 @@ function applyImpl(ctx: Context, config?: Config): void {
681
701
  maxSubtaskDepth: maxSubtaskDepth(),
682
702
  goalRunEnabled,
683
703
  runLaunchWidth,
704
+ spendBudgetTokens,
684
705
  cardDefaults,
685
706
  verificationSettings,
686
707
  verificationCatalog,
@@ -703,10 +724,22 @@ function applyImpl(ctx: Context, config?: Config): void {
703
724
  // provider package can resolve it and admit itself; the board itself knows
704
725
  // no provider vocabulary. A capture-only test context implements no service
705
726
  // registry and the board still serves its own surfaces.
727
+ //
728
+ // The same service carries the read/write face an in-process consumer drives
729
+ // the board through — the remote bridge's board plugin reads and applies over
730
+ // it instead of opening an HTTP surface of its own, which the board's routes
731
+ // would refuse anyway (their guard admits a browser-shaped request, not a
732
+ // process). Every member is a forward of the Host service method of the same
733
+ // name: no gate, no normalization and no state lives here, so a consumer
734
+ // reaching the board this way is refused by exactly what refuses a browser.
706
735
  if (typeof (ctx as { provide?: unknown }).provide === 'function') {
707
736
  ctx.provide(TASK_BOARD_SERVICE_NAME, {
708
737
  registerExtension: (extension: TaskBoardExtension) => host.registerExtension(extension),
709
738
  isExtensionEnabled: (extensionId: string) => host.extensions.isActive(extensionId),
739
+ snapshot: () => host.snapshot(),
740
+ apply: (requestId: string, action: TaskBoardAction, initiator?: string) => host.apply(requestId, action, initiator),
741
+ subscribe: (listener: () => void) => host.subscribe(listener),
742
+ verificationOptions: () => host.verificationOptions(),
710
743
  })
711
744
  }
712
745
 
package/src/loopback.ts CHANGED
@@ -8,6 +8,14 @@
8
8
  * Semantics: RFC 5735 IPv4 127/8, ::1, IPv4-mapped ::ffff:127/8 (matching the
9
9
  * remote-web-ui gate), localhost hostnames, plus the browser same-origin
10
10
  * markers (sec-fetch-site and Origin) for the request-level fence.
11
+ *
12
+ * A reverse proxy in front of the host rewrites the Host header to its own
13
+ * upstream literal (a Cloudflare tunnel, frp and an nginx reverse proxy all
14
+ * dial 127.0.0.1:<port>), and the socket the origin sees is the proxy's, which
15
+ * is loopback by construction. Both halves of the fence then hold for a public
16
+ * request. Forwarding headers are the signal that a hop stands in between: a
17
+ * request that carries CF-Connecting-IP or X-Forwarded-For is answered through
18
+ * a proxy and is never treated as a local one (issue #1906).
11
19
  * @module dsh-web-shared/host/loopback
12
20
  */
13
21
 
@@ -36,13 +44,29 @@ export function isLoopbackHostname(hostname: string): boolean {
36
44
  return isIPv4Loopback(hostname)
37
45
  }
38
46
 
47
+ /**
48
+ * Whether a reverse proxy stood between the client and this host: the request
49
+ * carries CF-Connecting-IP or X-Forwarded-For. Either header is stamped by a
50
+ * hop that forwards traffic, so the request did not originate on this machine.
51
+ * @param request - node HTTP request.
52
+ * @returns true when a forwarding header is present.
53
+ */
54
+ export function isProxiedRequest(request: IncomingMessage): boolean {
55
+ return request.headers['cf-connecting-ip'] !== undefined
56
+ || request.headers['x-forwarded-for'] !== undefined
57
+ }
58
+
39
59
  /**
40
60
  * Request-level trust fence: a loopback socket address AND a loopback Host
41
61
  * header, plus browser same-origin markers. The socket address is
42
- * authoritative; X-Forwarded-For is never trusted.
62
+ * authoritative for a direct connection; a request that carries a forwarding
63
+ * header is refused outright, because a proxy in front of the host makes both
64
+ * the socket address and the Host header describe the proxy rather than the
65
+ * client. X-Forwarded-For is therefore never evidence *for* loopback.
43
66
  */
44
67
  export function isLoopbackRequest(request: IncomingMessage): boolean {
45
68
  if (!isLoopbackAddress(request.socket.remoteAddress)) return false
69
+ if (isProxiedRequest(request)) return false
46
70
  const host = request.headers.host
47
71
  if (typeof host !== 'string') return false
48
72
  let hostUrl: URL