@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
@@ -1,51 +1,23 @@
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'
6
8
  import { HostTaskLedger, type OpenedRun, type OpenExecutionReference } from './host-ledger.ts'
7
- import { HostExecutionRunner, SessionLaunchError, promptText, type GatewayPeer, type SessionCommandDispatcher, type SessionSummary, type TaskBoardWorkspaceRegistry } from './host-runner.ts'
8
- import { teammateName } from './core/subtask.ts'
9
+ import { HostExecutionRunner, SessionLaunchError, type GatewayPeer, type SessionCommandDispatcher, type SessionSummary, type TaskBoardWorkspaceRegistry } from './host-runner.ts'
10
+ import { LIANGSHEN_PRESET_ID } from './core/subtask.ts'
9
11
  import { workspaceOwningSession } from './core/workspace-target.ts'
10
12
  import { PowerInhibitor } from './power-inhibitor.ts'
11
13
  import { TASK_BOARD_SCHEMA_VERSION, type TaskBoardAction, type TaskBoardEventPayload, type TaskBoardSnapshot } from './protocol.ts'
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
 
19
- /** One teammate the Host asks the Agent Teams service to spawn for a team run. */
20
- export interface TeamSpawnInput {
21
- /** Session id of the run's Team Lead (the root task's execution session). */
22
- leadSessionId: string
23
- /** Immutable lower-kebab-case teammate name, unique inside the Team. */
24
- name: string
25
- /** Short description of the delegated responsibility. */
26
- description: string
27
- /** The subtask's execution prompt. */
28
- prompt: string
29
- }
30
-
31
- /** Result of one teammate spawn attempt. */
32
- export interface TeamSpawnResult {
33
- /** The teammate's session id when it reached the active edge. */
34
- sessionId?: string
35
- /** Why the spawn failed: a thrown call, or a member that settled as failed. */
36
- error?: string
37
- }
38
-
39
- /**
40
- * The Agent Teams capability the Host needs for team-mode runs. The plugin
41
- * builds it from the optional `agentTeams` service; it is absent when this
42
- * deployment does not serve that service, in which case a team run is refused
43
- * instead of silently degrading into a plain cascade.
44
- */
45
- export interface TaskBoardTeamDispatcher {
46
- spawn(input: TeamSpawnInput): Promise<TeamSpawnResult>
47
- }
48
-
49
21
  /** Ceiling for the roster-poll failure backoff: a broken session tree is retried at most once a minute. */
50
22
  const POLL_FAILURE_MAX_BACKOFF_MS = 60_000
51
23
  /**
@@ -123,7 +95,7 @@ export const NEVER_INVOKED_VERIFICATION_REASON = 'goal 验收未触发:本次
123
95
  export const INVALID_ONLY_VERIFICATION_REASON = 'goal 验收无效:本次执行只记录了无效验收(裁判未能给出与任务要求对应、且可定位到本次证据的否决依据),看板已停止调用裁判。这**不是**有证据的质量判负:验收本身不可用,本次运行因没有匹配的通过记录而结束。请检查验收环境与证据可见性,或用 task_board_manage(action=reset-verification) 清除记录的无效验收后重新完成目标。'
124
96
 
125
97
  /**
126
- * Provenance of one cron-triggered cascade: when the rule fired and the zone
98
+ * Provenance of one cron-triggered run: when the rule fired and the zone
127
99
  * its wall clock was read in. Passed into every launched prompt of that run so
128
100
  * a scheduled job knows its own clock rather than inferring one.
129
101
  */
@@ -197,6 +169,38 @@ function cardDefaultsOf(defaults: CardDefaults): TaskBoardSnapshot['cardDefaults
197
169
  return Object.keys(published).length === 0 ? undefined : published
198
170
  }
199
171
 
172
+ /**
173
+ * Every action kind this board accepts, keyed by the kind itself.
174
+ *
175
+ * Written as a total record of `TaskBoardAction['kind']` on purpose: a new member
176
+ * of that union does not compile until it is listed here, so the table cannot
177
+ * drift behind the protocol. `apply()` validates against it because a caller
178
+ * reaching the board through the in-process capability face forwards its action
179
+ * object verbatim, with no envelope parser in front of it — the HTTP route was the
180
+ * only entrance before that face existed, and its parser is what used to turn an
181
+ * unknown kind into a refusal.
182
+ */
183
+ const ACTION_KINDS: Readonly<Record<TaskBoardAction['kind'], true>> = {
184
+ import: true,
185
+ create: true,
186
+ update: true,
187
+ delete: true,
188
+ move: true,
189
+ archive: true,
190
+ restore: true,
191
+ settle: true,
192
+ 'reset-verification': true,
193
+ 'record-external-outcome': true,
194
+ 'set-schedule': true,
195
+ run: true,
196
+ rerun: true,
197
+ 'confirm-permission': true,
198
+ 'set-parent': true,
199
+ 'rename-tag': true,
200
+ 'delete-tag': true,
201
+ 'extension-action': true,
202
+ }
203
+
200
204
  export class TaskBoardHostService {
201
205
  readonly ledger: HostTaskLedger
202
206
  readonly runner: HostExecutionRunner
@@ -232,7 +236,6 @@ export class TaskBoardHostService {
232
236
  private preventIdleSleep = false
233
237
  private readonly verificationSettings: () => VerificationSettings
234
238
  private readonly verificationCatalog: () => Promise<ModelCatalogView | undefined>
235
- private readonly team: TaskBoardTeamDispatcher | undefined
236
239
  private readonly timers: HostTimerFace
237
240
  /** Live reader of the global native-/goal switch; frozen per execution. */
238
241
  private readonly goalRunEnabled: () => boolean
@@ -244,6 +247,13 @@ export class TaskBoardHostService {
244
247
  * launch without remounting the row. Absent means the default.
245
248
  */
246
249
  private readonly runLaunchWidth: () => number
250
+ /**
251
+ * Live reader of the daily token cap; 0 means no gate. Read at each run
252
+ * action, so closing or raising the cap binds the next action.
253
+ */
254
+ private readonly spendBudgetTokens: () => number
255
+ /** Today's measured spend: absent measurement reads as "cannot see", never as zero. */
256
+ private readonly spendUsedToday: (now: number) => number | undefined
247
257
  private lastPowerJson = ''
248
258
  private readonly now: () => number
249
259
  /** The deployment's workspaces, consulted to resolve a card that pins none. */
@@ -281,7 +291,6 @@ export class TaskBoardHostService {
281
291
  * without remounting the row. Absent means the deployment configures none.
282
292
  */
283
293
  cardDefaults?: () => CardDefaults
284
- team?: TaskBoardTeamDispatcher
285
294
  timers?: HostTimerFace
286
295
  /**
287
296
  * Live GLOBAL native /goal switch (a volatile config read). Read ONCE per
@@ -306,21 +315,36 @@ export class TaskBoardHostService {
306
315
  * is still queueing. Absent means the default width.
307
316
  */
308
317
  runLaunchWidth?: () => number
318
+ /**
319
+ * Live daily token cap (a volatile config read). 0 — the default, and what
320
+ * every deployment that never configured one keeps — ends the gate before
321
+ * anything is measured. A positive cap refuses a run whose day already spent
322
+ * it, on both the action path and the cron path.
323
+ */
324
+ spendBudgetTokens?: () => number
325
+ /**
326
+ * Today's measured spend in tokens, or undefined when this deployment keeps
327
+ * no readable usage ledger. Defaults to the family usage ledger reader.
328
+ */
329
+ spendUsedToday?: (now: number) => number | undefined
309
330
  } = {}) {
310
331
  this.ledger = options.ledger ?? new HostTaskLedger(undefined, undefined, {
311
332
  sessionDefaultPermission: options.sessionDefaultPermission,
312
333
  maxSubtaskDepth: options.maxSubtaskDepth,
313
334
  cardDefaults: options.cardDefaults,
335
+ spendBudgetTokens: options.spendBudgetTokens,
336
+ spendUsedToday: options.spendUsedToday,
314
337
  })
315
338
  this.runner = new HostExecutionRunner(gateway, options.commandDispatcher, options.workspaceRegistry, undefined, options.ownerPeer)
316
339
  this.workspaceRegistry = options.workspaceRegistry
317
- this.team = options.team
318
340
  this.timers = options.timers ?? PROCESS_TIMERS
319
341
  this.power = options.power ?? new PowerInhibitor()
320
342
  this.now = options.now ?? Date.now
321
343
  this.goalRunEnabled = options.goalRunEnabled ?? (() => false)
322
344
  this.cardDefaults = options.cardDefaults ?? (() => ({}))
323
345
  this.runLaunchWidth = options.runLaunchWidth ?? (() => DEFAULT_RUN_LAUNCH_WIDTH)
346
+ this.spendBudgetTokens = options.spendBudgetTokens ?? (() => DEFAULT_SPEND_BUDGET_TOKENS)
347
+ this.spendUsedToday = options.spendUsedToday ?? (now => usedTokensToday(now))
324
348
  this.launches = new LaunchAdmissionQueue(() => normalizeRunLaunchWidth(this.runLaunchWidth()))
325
349
  this.verificationSettings = options.verificationSettings ?? (() => ({ enabled: false, model: '', reasoningEffort: '' }))
326
350
  this.verificationCatalog = options.verificationCatalog ?? (async () => undefined)
@@ -421,7 +445,6 @@ export class TaskBoardHostService {
421
445
  power: this.power.snapshot(),
422
446
  sessionDefaultPermission: this.ledger.sessionDefaultPermission,
423
447
  maxSubtaskDepth: this.ledger.maxSubtaskDepth,
424
- teamRunAvailable: this.team !== undefined,
425
448
  // The GLOBAL native-/goal switch is published live for the UI, but the
426
449
  // service freezes its own read at launch: this mirror is for the FORM
427
450
  // (enable/disable + explanation), never for a run already in flight.
@@ -509,6 +532,15 @@ export class TaskBoardHostService {
509
532
  apply(requestId: string, action: TaskBoardAction, initiator?: string): TaskBoardSnapshot | Promise<TaskBoardSnapshot>
510
533
  apply(requestId: string, action: TaskBoardAction, initiator?: string): TaskBoardSnapshot | Promise<TaskBoardSnapshot> {
511
534
  if (!this.active) throw new Error('task board is disabled')
535
+ // A caller that never met the HTTP envelope parser can name a kind this build
536
+ // does not implement. It is refused here, in the board's own vocabulary: the
537
+ // ledger has no case for it, and letting it through committed an unchanged
538
+ // document under a fresh revision — which every connected client then reloads
539
+ // a whole snapshot for.
540
+ const kind = (action as { kind?: unknown } | null | undefined)?.kind
541
+ if (typeof kind !== 'string' || !Object.hasOwn(ACTION_KINDS, kind)) {
542
+ throw new Error(`unknown task board action kind: ${String(kind)}`)
543
+ }
512
544
  // Provider actions never touch the ledger directly: the registry routes the
513
545
  // action to the owning extension, whose own capability calls come back
514
546
  // through applyBoardAction and every board gate below.
@@ -525,13 +557,7 @@ export class TaskBoardHostService {
525
557
  */
526
558
  private applyBoardAction(requestId: string, action: Exclude<TaskBoardAction, { kind: 'extension-action' }>, initiator?: string): TaskBoardSnapshot {
527
559
  const before = this.statusMap()
528
- // Fail closed before the ledger opens anything: a card opted into team
529
- // execution cannot run in a deployment that serves no Agent Teams service,
530
- // and silently degrading it to a plain cascade would misreport the work.
531
- if (this.team === undefined && (action.kind === 'run' || action.kind === 'rerun')) {
532
- const task = this.ledger.state().tasks.find(item => item.id === action.taskId)
533
- if (task?.teamRun === true) throw new Error('Agent Teams is unavailable in this deployment')
534
- }
560
+ if (action.kind === 'run' || action.kind === 'rerun') this.assertSpendCap()
535
561
  const result = this.ledger.applyRequest(requestId, this.withInheritedWorkspace(action, initiator), initiator)
536
562
  if (result.runs !== undefined) this.dispatchRuns(result.runs)
537
563
  // A committed write that can move a rule moves the nearest trigger;
@@ -551,6 +577,25 @@ export class TaskBoardHostService {
551
577
  }
552
578
  }
553
579
 
580
+ /**
581
+ * Refuse a run whose day already spent the cap.
582
+ *
583
+ * A cap of 0 — the shipped default — answers before the measurement is read:
584
+ * no ledger file is opened and nothing is summed, which is what keeps a board
585
+ * that never configured a cap identical to the one before it existed.
586
+ *
587
+ * The refusal is a thrown message rather than a code: the wire hands its text
588
+ * to the caller as board-refused, exactly like every other refusal this board
589
+ * makes.
590
+ */
591
+ private assertSpendCap(): void {
592
+ const cap = this.spendBudgetTokens()
593
+ if (!(cap > 0)) return
594
+ const used = this.spendUsedToday(this.now())
595
+ if (used === undefined || !spendCapReached(used, cap)) return
596
+ throw new Error(spendCapMessage(used, cap))
597
+ }
598
+
554
599
  /** Route one provider action and answer the resulting board snapshot. */
555
600
  private async handleExtensionAction(action: Extract<TaskBoardAction, { kind: 'extension-action' }>): Promise<TaskBoardSnapshot> {
556
601
  await this.extensions.handleAction({
@@ -601,27 +646,31 @@ export class TaskBoardHostService {
601
646
  this.listeners.clear()
602
647
  }
603
648
 
604
- private async launch(opened: OpenedRun, others: readonly OpenedRun[] = [], schedule?: ScheduledRunContext, freezeContract?: RunContractFreezer): Promise<void> {
649
+ private async launch(opened: OpenedRun, schedule?: ScheduledRunContext, freezeContract?: RunContractFreezer): Promise<void> {
605
650
  /** The session this launch attached to the execution, once it exists. */
606
651
  let attached: string | undefined
607
652
  try {
608
- // A team run always mints a fresh Lead session: teammates are immutable
609
- // children of that session, so reusing an older one would collide on
610
- // their names and orphan the previous team.
611
- const team = opened.task.teamRun === true
612
- const reuseSessionId = team ? undefined : await this.reuseSessionFor(opened.task)
613
- // Both modes tell the launched agent what else this run opens; only a team
614
- // run names teammates, because only then does this session own them.
615
- const peers = others.length === 0 ? undefined : others.map(other => ({
616
- id: other.task.id,
617
- title: other.task.title,
618
- ...(team ? { name: teammateName(other.task.title, other.execution.runGroupId ?? other.task.id, other.task.id) } : {}),
619
- }))
653
+ // One run opens ONE session: the card's own. Its unfinished subtasks are
654
+ // dispatched from inside that session, so a card that carries them is
655
+ // forced under the dispatcher preset and told which cards to pick up. The
656
+ // force is applied here, per execution; the card's stored `mode` is
657
+ // never rewritten by it.
658
+ const forcedPreset = this.ledger.hasOutstandingDescendants(opened.task.id) ? LIANGSHEN_PRESET_ID : undefined
659
+ const descendants = forcedPreset === undefined ? [] : this.ledger.outstandingDescendants(opened.task.id)
660
+ // A forced preset is not the card's own composition, so continuing a
661
+ // session composed from another preset would be refused anyway: mint a
662
+ // fresh one and run the tree the way this execution requires.
663
+ const reuseSessionId = forcedPreset === undefined ? await this.reuseSessionFor(opened.task) : undefined
620
664
  // A cron-triggered run additionally states its own firing instant and
621
665
  // rule zone, so a scheduled job can resolve "today" without guessing.
622
- const promptContext = peers === undefined && schedule === undefined ? undefined : {
623
- ...(peers === undefined ? {} : { peers }),
624
- ...(team ? { team: true } : {}),
666
+ const promptContext = descendants.length === 0 && schedule === undefined ? undefined : {
667
+ ...(descendants.length === 0 ? {} : {
668
+ descendants: descendants.map(descendant => ({
669
+ id: descendant.id,
670
+ title: descendant.title,
671
+ status: descendant.status,
672
+ })),
673
+ }),
625
674
  ...(schedule === undefined ? {} : { schedule }),
626
675
  }
627
676
  // Freeze this execution's acceptance contract BEFORE the session is
@@ -662,11 +711,12 @@ export class TaskBoardHostService {
662
711
  const initial: ExecutionVerification = {
663
712
  contract,
664
713
  attempts: [],
665
- applicability: team ? 'team-member' : !contract.enabled ? skippedBy : notArmed,
714
+ applicability: !contract.enabled ? skippedBy : notArmed,
666
715
  }
667
716
  this.ledger.setVerification(opened.task.id, opened.execution.id, initial)
668
717
  const sessionId = await this.runner.launch(opened.task, {
669
718
  ...(reuseSessionId === undefined ? {} : { reuseSessionId }),
719
+ ...(forcedPreset === undefined ? {} : { agentPreset: forcedPreset }),
670
720
  ...(promptContext === undefined ? {} : { promptContext }),
671
721
  // The frozen global switch travels with the launch, so the runner's
672
722
  // arming decision is exactly the one made above.
@@ -680,13 +730,10 @@ export class TaskBoardHostService {
680
730
  this.ledger.attachSession(opened.task.id, opened.execution.id, id)
681
731
  },
682
732
  onGoalArmed: (armed) => {
683
- this.setApplicability(opened.task.id, opened.execution.id, team
684
- ? 'team-member'
685
- : !contract.enabled ? skippedBy : armed ? 'enforced' : notArmed)
733
+ this.setApplicability(opened.task.id, opened.execution.id, !contract.enabled ? skippedBy : armed ? 'enforced' : notArmed)
686
734
  },
687
735
  })
688
736
  if (attached === undefined) this.ledger.attachSession(opened.task.id, opened.execution.id, sessionId)
689
- if (team) for (const teammate of others) this.scheduleTeammate(teammate, sessionId)
690
737
  } catch (error) {
691
738
  const launchedSession = error instanceof SessionLaunchError ? error.sessionId : undefined
692
739
  if (launchedSession !== undefined) {
@@ -747,42 +794,6 @@ export class TaskBoardHostService {
747
794
  this.refreshSchedule()
748
795
  }
749
796
 
750
- private scheduleTeammate(opened: OpenedRun, leadSessionId: string): void {
751
- this.enqueueLaunch(opened, () => this.spawnTeammate(opened, leadSessionId).catch(error => {
752
- safeConsoleError('[dsh-task-board] teammate spawn settlement failed', error)
753
- }))
754
- }
755
-
756
- /**
757
- * Spawn one teammate inside the Lead session and attach the teammate's
758
- * session to the subtask execution, so the existing session monitor settles
759
- * it from the teammate's own turn like any other execution. A spawn that
760
- * fails settles the subtask as failed immediately, which then folds into the
761
- * Lead's cascade verdict.
762
- */
763
- private async spawnTeammate(opened: OpenedRun, leadSessionId: string): Promise<void> {
764
- const team = this.team
765
- if (team === undefined) {
766
- this.settleAndNotify(opened.task.id, opened.execution.id, 'failed', 'Agent Teams is unavailable in this deployment')
767
- return
768
- }
769
- try {
770
- const member = await team.spawn({
771
- leadSessionId,
772
- name: teammateName(opened.task.title, opened.execution.runGroupId ?? opened.task.id, opened.task.id),
773
- description: opened.task.title,
774
- prompt: promptText(opened.task),
775
- })
776
- if (member.sessionId === undefined || member.sessionId === '') {
777
- this.settleAndNotify(opened.task.id, opened.execution.id, 'failed', member.error ?? 'teammate provisioning failed')
778
- return
779
- }
780
- this.ledger.attachSession(opened.task.id, opened.execution.id, member.sessionId)
781
- } catch (error) {
782
- this.settleAndNotify(opened.task.id, opened.execution.id, 'failed', error instanceof Error ? error.message : String(error))
783
- }
784
- }
785
-
786
797
  /**
787
798
  * One roster pass, and whether it could read the session tree.
788
799
  *
@@ -915,10 +926,13 @@ export class TaskBoardHostService {
915
926
  : verificationOnlyInvalid(verification)
916
927
  ? INVALID_ONLY_VERIFICATION_REASON
917
928
  : NO_MATCHING_PASS_VERIFICATION_REASON,
929
+ result.summary,
918
930
  )
919
931
  continue
920
932
  }
921
- this.settleAndNotify(execution.taskId, execution.executionId, result.outcome, 'error' in result ? result.error : undefined)
933
+ // The run's closing text rides whichever verdict it earned: a failed
934
+ // execution still leaves what it managed to say.
935
+ this.settleAndNotify(execution.taskId, execution.executionId, result.outcome, 'error' in result ? result.error : undefined, result.summary)
922
936
  } catch {
923
937
  // A transient inspection failure never settles a running execution.
924
938
  }
@@ -938,20 +952,20 @@ export class TaskBoardHostService {
938
952
  * ancestor of it — in the running column with no way out. The first poll of
939
953
  * each streak is logged, so the Host log names the session.
940
954
  */
941
- private settleAndNotify(taskId: string, executionId: string, outcome: ExecutionOutcome, error?: string): void {
955
+ private settleAndNotify(taskId: string, executionId: string, outcome: ExecutionOutcome, error?: string, summary?: ExecutionSummary): void {
942
956
  const before = this.ledger.getTask(taskId)
943
957
  if (before?.executions.find(entry => entry.id === executionId)?.endedAt !== undefined) {
944
958
  // Already settled: the ledger would no-op, and re-emitting would report
945
959
  // the same settlement twice.
946
- this.ledger.settle(taskId, executionId, outcome, error)
960
+ this.ledger.settle(taskId, executionId, outcome, error, summary)
947
961
  return
948
962
  }
949
- const previousStatus = before?.status
950
- this.ledger.settle(taskId, executionId, outcome, error)
951
- const task = this.ledger.getTask(taskId)
952
- if (task !== undefined && previousStatus !== undefined && previousStatus !== task.status) {
953
- this.extensions.emitStatusChanged({ taskId, status: task.status, previous: previousStatus })
954
- }
963
+ // One settlement can move more than the settled card: a run whose own card
964
+ // is terminal also writes the inherited verdict onto the subtasks it never
965
+ // dispatched. Compare the whole board so the provider events cover those too.
966
+ const statuses = this.statusMap()
967
+ this.ledger.settle(taskId, executionId, outcome, error, summary)
968
+ this.emitStatusChanges(statuses)
955
969
  this.extensions.emitExecutionSettled({
956
970
  taskId,
957
971
  executionId,
@@ -1129,28 +1143,18 @@ export class TaskBoardHostService {
1129
1143
  }
1130
1144
 
1131
1145
  /**
1132
- * Launch one run set. The root goes first and receives the run shape in its
1133
- * prompt (which members this run opens, and how they run); every plain-cascade
1134
- * member then launches on its own so one refused participant cannot hold the
1135
- * others back. A team run's members are spawned inside the root's Lead
1136
- * session instead, once that session exists.
1146
+ * Launch the one run a run request opened. A run request names one card and
1147
+ * opens one execution for it; the card's own session dispatches its subtasks
1148
+ * as subagents, so nothing else is enqueued here.
1137
1149
  *
1138
- * Every launch of one run set goes through the admission queue, which admits
1139
- * at most `runLaunchWidth` of them at a time — the whole subtree still opens,
1140
- * members just enter the running column in batches. Order inside the group is
1141
- * the order they are enqueued here, so the root's session always exists before
1142
- * any member's, and one member's launch settling (or failing) is what admits
1143
- * the next. All members share the one contract this group freezes.
1150
+ * The launch still goes through the admission queue, which admits at most
1151
+ * `runLaunchWidth` launches at a time — that bound now applies across
1152
+ * concurrent runs rather than across the members of one run.
1144
1153
  */
1145
1154
  private dispatchRuns(runs: readonly OpenedRun[], schedule?: ScheduledRunContext): void {
1146
- if (runs.length === 0) return
1147
- const root = runs.find(run => run.dispatch !== 'teammate') ?? runs[0]
1148
- const others = runs.filter(run => run !== root)
1149
- const freezeContract = this.contractFreezerForRunGroup()
1150
- this.scheduleLaunch(root, others, schedule, freezeContract)
1151
- for (const run of others) {
1152
- if (run.dispatch !== 'teammate') this.scheduleLaunch(run, [], schedule, freezeContract)
1153
- }
1155
+ const root = runs[0]
1156
+ if (root === undefined) return
1157
+ this.scheduleLaunch(root, schedule, this.contractFreezerForRunGroup())
1154
1158
  }
1155
1159
 
1156
1160
  /**
@@ -1163,8 +1167,8 @@ export class TaskBoardHostService {
1163
1167
  this.ledger.setVerification(taskId, executionId, { ...verification, applicability })
1164
1168
  }
1165
1169
 
1166
- private scheduleLaunch(opened: OpenedRun, others: readonly OpenedRun[] = [], schedule?: ScheduledRunContext, freezeContract?: RunContractFreezer): void {
1167
- this.enqueueLaunch(opened, () => this.launch(opened, others, schedule, freezeContract).catch(error => {
1170
+ private scheduleLaunch(opened: OpenedRun, schedule?: ScheduledRunContext, freezeContract?: RunContractFreezer): void {
1171
+ this.enqueueLaunch(opened, () => this.launch(opened, schedule, freezeContract).catch(error => {
1168
1172
  safeConsoleError('[dsh-task-board] execution launch settlement failed', error)
1169
1173
  }), schedule)
1170
1174
  }
@@ -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
+ }