@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.
@@ -54,6 +54,19 @@ export interface PluginSettingsCardProps<TKey extends string = string> {
54
54
  onSave: () => void
55
55
  /** Drop every staged edit. */
56
56
  onDiscard: () => void
57
+ /**
58
+ * Id applied to the card's title element, so a header control (an immediate
59
+ * toggle in `headerAction`) can name itself through `aria-labelledby`
60
+ * instead of repeating the title as a string.
61
+ */
62
+ titleId?: string
63
+ /**
64
+ * Render the header only, with no body region. A card whose whole setting is
65
+ * the header control (a switch whose explanation is the description) has no
66
+ * controls to lay out below it, and an empty body would draw a divider line
67
+ * with nothing under it.
68
+ */
69
+ headerOnly?: boolean
57
70
  /**
58
71
  * Render the controls expanded on arrival (still collapsible). Defaults to
59
72
  * true: promoted first-level sections show their settings immediately.
@@ -71,6 +84,13 @@ export interface PluginSettingsCardProps<TKey extends string = string> {
71
84
  * edits, so the footer would sit there permanently disabled.
72
85
  */
73
86
  hideFooter?: boolean
87
+ /**
88
+ * Optional control rendered at the header's trailing edge, before the pending
89
+ * badge and the chevron. A card whose setting is one immediate flip (it
90
+ * applies outside the staged form) puts its ToggleSwitch here, so the control
91
+ * is reachable without opening the card and matches a plugin card's shape.
92
+ */
93
+ headerAction?: ReactNode
74
94
  /** Render children even when the settings namespace is not exposed by the host. */
75
95
  renderChildrenWhenNotExposed?: boolean
76
96
  /** Hide the 'not exposed' warning banner when the settings namespace is not exposed. */
@@ -100,9 +120,10 @@ export function PluginSettingsCard<TKey extends string = string>(props: PluginSe
100
120
  <div className={css.headerStatic}>
101
121
  {props.icon !== undefined ? <span className={css.mark} aria-hidden="true">{props.icon}</span> : null}
102
122
  <span className={css.headText}>
103
- <span className={css.name} title={title}>{title}</span>
123
+ <span className={css.name} id={props.titleId} title={title}>{title}</span>
104
124
  <span className={css.description} title={description}>{props.descriptionNode ?? description}</span>
105
125
  </span>
126
+ {props.headerAction !== undefined ? <span className={css.headerAction}>{props.headerAction}</span> : null}
106
127
  {state.dirty ? <span className={css.pending} title={props.t('settings.unsaved')}>{props.t('settings.unsaved')}</span> : null}
107
128
  </div>
108
129
  )
@@ -116,9 +137,10 @@ export function PluginSettingsCard<TKey extends string = string>(props: PluginSe
116
137
  >
117
138
  {props.icon !== undefined ? <span className={css.mark} aria-hidden="true">{props.icon}</span> : null}
118
139
  <span className={css.headText}>
119
- <span className={css.name} title={title}>{title}</span>
140
+ <span className={css.name} id={props.titleId} title={title}>{title}</span>
120
141
  <span className={css.description} title={description}>{props.descriptionNode ?? description}</span>
121
142
  </span>
143
+ {props.headerAction !== undefined ? <span className={css.headerAction}>{props.headerAction}</span> : null}
122
144
  {state.dirty ? <span className={css.pending} title={props.t('settings.unsaved')}>{props.t('settings.unsaved')}</span> : null}
123
145
  <svg
124
146
  width="14"
@@ -154,10 +176,13 @@ export function PluginSettingsCard<TKey extends string = string>(props: PluginSe
154
176
  </li>
155
177
  )
156
178
  }
179
+ // A header-only card has no body region at all: the divider would otherwise
180
+ // sit above an empty box.
181
+ const bodyVisible = expanded && props.headerOnly !== true
157
182
  return (
158
183
  <li className={cardClass}>
159
184
  {header}
160
- {expanded
185
+ {bodyVisible
161
186
  ? (
162
187
  <div className={css.body}>
163
188
  {!state.writable ? <p className={css.readOnly} role="status">{props.t('settings.readOnly')}</p> : null}
@@ -562,3 +587,38 @@ export function ChoiceField(props: FieldProps & {
562
587
  </div>
563
588
  )
564
589
  }
590
+
591
+ /**
592
+ * An immediate boolean toggle drawn as a switch track, for a setting that
593
+ * applies on flip rather than through a staged save. It is a real button with
594
+ * `role="switch"` and `aria-checked`, so keyboard and assistive activation
595
+ * arrive as a click and the state is announced instead of inferred from a
596
+ * checkbox tick.
597
+ */
598
+ export function ToggleSwitch(props: {
599
+ /** Id of the element naming the switch (the card's title). */
600
+ labelledBy?: string
601
+ /** Accessible name when no element labels it. */
602
+ ariaLabel?: string
603
+ /** Current state. */
604
+ checked: boolean
605
+ /** Disables the switch while a write is in flight or the Host refuses writes. */
606
+ disabled?: boolean
607
+ /** Called with the requested next state. */
608
+ onChange: (next: boolean) => void
609
+ }) {
610
+ return (
611
+ <button
612
+ type="button"
613
+ className={css.toggle}
614
+ role="switch"
615
+ aria-checked={props.checked}
616
+ aria-labelledby={props.labelledBy}
617
+ aria-label={props.labelledBy === undefined ? props.ariaLabel : undefined}
618
+ disabled={props.disabled}
619
+ onClick={() => { props.onChange(!props.checked) }}
620
+ >
621
+ <span className={css.toggleTrack}><span className={css.toggleThumb} /></span>
622
+ </button>
623
+ )
624
+ }
@@ -108,6 +108,24 @@ function runLaunchWidthField(): FieldSpec {
108
108
  }
109
109
  }
110
110
 
111
+ /**
112
+ * The daily token cap field: whole tokens, 0 for "no gate". Every non-negative
113
+ * whole number is a legal cap, so the draft only has to be one; a blank draft
114
+ * clears the entry back to the schema default (0).
115
+ */
116
+ function spendBudgetField(): FieldSpec {
117
+ return {
118
+ field: 'spendBudgetTokens',
119
+ format: value => typeof value === 'number' && Number.isInteger(value) ? String(value) : '',
120
+ parse: (text) => {
121
+ const trimmed = text.trim()
122
+ if (trimmed === '') return { kind: 'clear' }
123
+ if (!/^\d+$/.test(trimmed)) return undefined
124
+ return { kind: 'set', value: Number(trimmed) }
125
+ },
126
+ }
127
+ }
128
+
111
129
  /**
112
130
  * The judge-model field: blank inherits the host model catalog default, and a
113
131
  * non-blank draft must be a qualified provider/model route. An unparseable
@@ -145,6 +163,11 @@ export interface TaskBoardSettings {
145
163
  * action creates; members enter the running column in batches, none is dropped.
146
164
  */
147
165
  runLaunchWidth?: number
166
+ /**
167
+ * Daily token ceiling for the work this board dispatches; 0 means no gate.
168
+ * Tokens, not money: only DeepSeek's own routes are priced.
169
+ */
170
+ spendBudgetTokens?: number
148
171
  /**
149
172
  * GLOBAL native /goal switch (default off): the master control over whether
150
173
  * this board starts a run with dsh's built-in /goal at all. Frozen per
@@ -187,6 +210,8 @@ export interface TaskBoardSettingsCardState extends CardShell {
187
210
  sessionPollSeconds: CardFieldState
188
211
  /** Run-launch admission width field. */
189
212
  runLaunchWidth: CardFieldState
213
+ /** Daily token cap field. */
214
+ spendBudgetTokens: CardFieldState
190
215
  /** GLOBAL native /goal switch. */
191
216
  goalRunEnabled: CardFieldState
192
217
  /** Goal-acceptance switch. */
@@ -237,6 +262,7 @@ export class TaskBoardSettingsCardController {
237
262
  subtaskDepthField(),
238
263
  sessionPollField(),
239
264
  runLaunchWidthField(),
265
+ spendBudgetField(),
240
266
  booleanField('goalRunEnabled'),
241
267
  booleanField('goalVerification'),
242
268
  modelRouteField('goalVerificationModel'),
@@ -261,6 +287,7 @@ export class TaskBoardSettingsCardController {
261
287
  maxSubtaskDepth: this.form.field('maxSubtaskDepth'),
262
288
  sessionPollSeconds: this.form.field('sessionPollSeconds'),
263
289
  runLaunchWidth: this.form.field('runLaunchWidth'),
290
+ spendBudgetTokens: this.form.field('spendBudgetTokens'),
264
291
  goalRunEnabled: this.form.field('goalRunEnabled'),
265
292
  goalVerification: this.form.field('goalVerification'),
266
293
  goalVerificationModel: this.form.field('goalVerificationModel'),
@@ -530,6 +557,16 @@ export function TaskBoardSettingsCard(props: TaskBoardSettingsCardProps) {
530
557
  onEdit={(text) => { props.edit('runLaunchWidth', text) }}
531
558
  onReset={() => { props.resetField('runLaunchWidth') }}
532
559
  />
560
+ <ValueField
561
+ id="settings-task-board-spend-budget"
562
+ label={t('settings.spendBudgetTokens')}
563
+ hint={t('settings.spendBudgetTokensHint')}
564
+ numeric
565
+ {...fieldProps}
566
+ {...state.spendBudgetTokens}
567
+ onEdit={(text) => { props.edit('spendBudgetTokens', text) }}
568
+ onReset={() => { props.resetField('spendBudgetTokens') }}
569
+ />
533
570
  </PluginSettingsCard>
534
571
 
535
572
  <PluginSettingsCard
@@ -302,6 +302,8 @@ export const zh = {
302
302
  'settings.maxSubtaskDepthOption': '{depth} 层',
303
303
  'settings.runLaunchWidth': '并发启动上限',
304
304
  'settings.runLaunchWidthHint': '默认 3。一次执行会开启整棵子任务树,但同一刻最多只有这么多个成员在创建会话并入队 Prompt,其余成员排队等待——全部都会启动,只是分批进入运行列。默认值取自本仓「重型实施子代理并发 ≤ 3」的实测纪律。取值 1–16:越大启动越快,Host 的内存与 swap 压力越高。执行中修改只影响尚未入列的启动。',
305
+ 'settings.spendBudgetTokens': '每日 token 上限',
306
+ 'settings.spendBudgetTokensHint': '默认 0,表示不设闸,行为与没有这项设置时完全一致(不读账本、不计数)。设为正整数后,今日已用 token 达到该值时:手动执行与重新执行被拒绝,调用方看到的拒绝文本就是原因;到点的定时执行把原因写进调度错误并跳过本次触发,不消耗计划次数,因此调高上限或跨过本地零点后下一次触发照常执行。计量单位是 token 而不是金额:使用账本只对 DeepSeek 官方路由计价,其他路由恒为 0。今日已用取自该账本按本地日期分桶的输入、缓存读写与输出之和,与「使用统计」面板的口径一致。',
305
307
  'settings.runBehaviorTitle': '运行行为',
306
308
  'settings.runBehaviorCardHint': '全局原生 /goal 执行开关(总开关,默认关闭)。',
307
309
  'settings.goalRunGlobal': '全局启用 DSH 原生 /goal 执行',
@@ -748,6 +750,8 @@ export const en: Record<keyof typeof zh, string> = {
748
750
  'settings.maxSubtaskDepthOption': '{depth} levels',
749
751
  'settings.runLaunchWidth': 'Concurrent run launches',
750
752
  'settings.runLaunchWidthHint': 'Default 3. A run opens its whole subtree, but only this many members create their session and queue their prompt at the same time; the rest wait their turn. Every member still starts, entering the running column in batches. The default comes from this repository\'s measured guidance for heavy implementation subagents (at most three). Range 1 to 16: a larger width starts runs sooner and costs the Host more memory and swap. Edited during a run, it bounds the launches that have not been admitted yet.',
753
+ 'settings.spendBudgetTokens': 'Daily token cap',
754
+ 'settings.spendBudgetTokensHint': 'Default 0 means no gate: behavior is exactly what it was before this setting existed, with no ledger read and no counting. With a positive cap, once today\'s measured spend reaches it a manual run or re-run is refused and the caller sees that message as the refusal, while a due schedule writes the reason to the scheduler error and skips that occurrence without spending a planned run — raising the cap, or the local day rolling over, lets the next trigger run as usual. The unit is tokens rather than money: the usage ledger prices only DeepSeek\'s own routes and stays 0 on every other route. Today\'s spend is that ledger\'s local-date bucket summed over input, cache read/write and output, the same measure the usage panel shows.',
751
755
  'settings.runBehaviorTitle': 'Run behavior',
752
756
  'settings.runBehaviorCardHint': 'The global native /goal switch (master control, off by default).',
753
757
  'settings.goalRunGlobal': 'Global: run tasks with dsh native /goal',
@@ -111,6 +111,14 @@
111
111
  line-height: 17px;
112
112
  }
113
113
 
114
+ /* Header trailing control (an immediate toggle): a flex item that keeps its
115
+ natural width while the title block takes the remaining space. */
116
+ .headerAction {
117
+ flex: none;
118
+ display: inline-flex;
119
+ align-items: center;
120
+ }
121
+
114
122
  .chevron {
115
123
  color: var(--dsw-alias-label-tertiary);
116
124
  flex: none;
@@ -428,6 +436,65 @@
428
436
  line-height: 1.5;
429
437
  }
430
438
 
439
+ /* Immediate boolean toggle: the official switch shape (30x16 track, 12px
440
+ thumb). The on state fills with the primary-action pair rather than a fixed
441
+ state color, so it stays legible in every theme; disabled dims through
442
+ opacity instead of a second palette. */
443
+ .toggle {
444
+ appearance: none;
445
+ display: inline-flex;
446
+ align-items: center;
447
+ background: transparent;
448
+ border: 0;
449
+ border-radius: 999px;
450
+ margin: 0;
451
+ padding: 0;
452
+ cursor: pointer;
453
+ font: inherit;
454
+ }
455
+
456
+ .toggleTrack {
457
+ position: relative;
458
+ flex: none;
459
+ width: 30px;
460
+ height: 16px;
461
+ border-radius: 999px;
462
+ /* Off must still read as a rail: border-l2 is an alpha hairline color and
463
+ leaves the track nearly invisible on a card surface. */
464
+ background: var(--dsw-alias-label-dimmed);
465
+ transition: background 0.18s ease;
466
+ }
467
+
468
+ .toggleThumb {
469
+ position: absolute;
470
+ top: 2px;
471
+ left: 2px;
472
+ width: 12px;
473
+ height: 12px;
474
+ border-radius: 50%;
475
+ background: var(--dsw-alias-bg-layer-3);
476
+ transition: left 0.18s ease;
477
+ }
478
+
479
+ .toggle[aria-checked='true'] .toggleTrack {
480
+ background: var(--dsw-alias-button-primary-fill, var(--dsw-alias-label-primary));
481
+ }
482
+
483
+ .toggle[aria-checked='true'] .toggleThumb {
484
+ left: 16px;
485
+ background: var(--dsw-alias-label-primary-foreground, var(--dsw-alias-bg-layer-3));
486
+ }
487
+
488
+ .toggle:focus-visible {
489
+ outline: 2px solid var(--dsw-alias-brand-primary);
490
+ outline-offset: 2px;
491
+ }
492
+
493
+ .toggle:disabled {
494
+ opacity: 0.45;
495
+ cursor: default;
496
+ }
497
+
431
498
  @media (prefers-reduced-motion: reduce) {
432
499
  .card,
433
500
  .header,
@@ -438,7 +505,9 @@
438
505
  .save,
439
506
  .selectChevron,
440
507
  .selectChevronOpen,
441
- .selectPopup {
508
+ .selectPopup,
509
+ .toggleTrack,
510
+ .toggleThumb {
442
511
  transition: none;
443
512
  }
444
513
  }
@@ -7,8 +7,12 @@
7
7
  * The payload carries no conversation data and no identifiers beyond a random
8
8
  * UUID generated in localStorage; the server hashes it with a deployment salt
9
9
  * before storage and never persists IP addresses. Sends are fire-and-forget:
10
- * failures stay silent and simply retry on a later mount or day. The system
11
- * is documented in docs/telemetry.md.
10
+ * failures stay silent and simply retry on a later mount or day. Frames where
11
+ * storage is unavailable report nothing.
12
+ *
13
+ * The family-wide opt-out and the browser's Do Not Track signal both suppress
14
+ * the heartbeat; the Web Plugins settings switch writes the same localStorage
15
+ * key. The system is documented in docs/telemetry.md.
12
16
  */
13
17
 
14
18
  export type TelemetryChannel = 'market' | 'npm' | 'unknown'
@@ -22,6 +26,9 @@ export interface TelemetryItem {
22
26
  channel?: TelemetryChannel
23
27
  }
24
28
 
29
+ /** localStorage key carrying the family-wide telemetry opt-out ('1' = off). */
30
+ export const TELEMETRY_OPT_OUT_KEY = 'dsh-web-ui-telemetry-opt-out'
31
+
25
32
  const VISITOR_KEY = 'dsh-web-ui-telemetry-visitor'
26
33
  const DAY_KEY_PREFIX = 'dsh-web-ui-telemetry-day:'
27
34
  const ENDPOINT = 'https://dsh-market.com/api/telemetry/event'
@@ -41,6 +48,41 @@ function bakedVersion(): string | undefined {
41
48
  }
42
49
  }
43
50
 
51
+ /** Whether the user switched the family-wide opt-out on (reads storage only). */
52
+ export function isTelemetryOptedOut(): boolean {
53
+ try {
54
+ return localStorage.getItem(TELEMETRY_OPT_OUT_KEY) === '1'
55
+ } catch {
56
+ // Storage unavailable: there is no stored opt-out to honour.
57
+ return false
58
+ }
59
+ }
60
+
61
+ /** Turn the family-wide opt-out on or off (writing '1' / removing the key); never throws. */
62
+ export function setTelemetryOptedOut(optedOut: boolean): void {
63
+ try {
64
+ if (optedOut) localStorage.setItem(TELEMETRY_OPT_OUT_KEY, '1')
65
+ else localStorage.removeItem(TELEMETRY_OPT_OUT_KEY)
66
+ } catch {
67
+ // Storage unavailable: the preference cannot be persisted on this machine.
68
+ }
69
+ }
70
+
71
+ /** Whether the browser itself asks not to be tracked; a failed read means no signal. */
72
+ function doNotTrackRequested(): boolean {
73
+ try {
74
+ // '1' per the DNT header spec, 'yes' from older Firefox builds.
75
+ return navigator.doNotTrack === '1' || navigator.doNotTrack === 'yes'
76
+ } catch {
77
+ return false
78
+ }
79
+ }
80
+
81
+ /** Whether a heartbeat must be suppressed right now: opt-out stored, or the browser asks not to be tracked. */
82
+ export function isTelemetrySuppressed(): boolean {
83
+ return isTelemetryOptedOut() || doNotTrackRequested()
84
+ }
85
+
44
86
  /** Read or lazily create the anonymous visitor id; null when storage is unavailable. */
45
87
  function visitorId(): string | null {
46
88
  try {
@@ -74,6 +116,9 @@ function pruneDayKeys(today: string): void {
74
116
  */
75
117
  export function reportDailyHeartbeat(items: readonly TelemetryItem[]): void {
76
118
  try {
119
+ // First guard: a stored opt-out or the browser's Do Not Track stops every
120
+ // read below from minting an id, marking the day, or reaching the network.
121
+ if (isTelemetrySuppressed()) return
77
122
  if (items.length === 0) return
78
123
  const today = new Date().toISOString().slice(0, 10)
79
124
  // Automation contexts (CDP-driven QA browsers, fresh isolated profiles)
@@ -0,0 +1,96 @@
1
+ /**
2
+ * What one execution left behind: the text of its last assistant message,
3
+ * recorded on the execution record next to the verdict it belongs to.
4
+ *
5
+ * A settled execution used to carry only a verdict, so a parent card could see
6
+ * that a subtask succeeded without ever seeing what it produced, and had to
7
+ * guess or redo the work. The card's own content cannot answer that: card
8
+ * content is the plan and freezes at the first execution
9
+ * (`canEditTaskContent`), so the closing words of a run are recorded on the
10
+ * execution record instead.
11
+ *
12
+ * Pure (no cordis, no runtime imports) so the settlement path is unit-testable
13
+ * without a session, and so a text-less run degrades to "no field" rather than
14
+ * to an empty string.
15
+ */
16
+ import { EXECUTION_SUMMARY_LIMIT, type ExecutionSummary } from './tasks.ts'
17
+
18
+ /** Structural view of one session event, as both readers expose it. */
19
+ export interface SummaryEvent {
20
+ type?: unknown
21
+ seq?: unknown
22
+ time?: unknown
23
+ data?: unknown
24
+ }
25
+
26
+ /** One rendered content block of an assistant message, or '' when it has no prose. */
27
+ function blockProse(block: unknown): string {
28
+ if (typeof block !== 'object' || block === null) return ''
29
+ const row = block as Record<string, unknown>
30
+ // Only prose: reasoning and tool traffic are the acceptance evidence's job,
31
+ // and a summary that opened with a tool call would bury the conclusion.
32
+ return row.type === 'text' && typeof row.text === 'string' ? row.text : ''
33
+ }
34
+
35
+ /** The assistant's own prose of one message: its text blocks joined and trimmed. */
36
+ function messageProse(content: unknown): string {
37
+ if (!Array.isArray(content)) return ''
38
+ return content.map(blockProse).filter(part => part !== '').join('\n').trim()
39
+ }
40
+
41
+ /**
42
+ * Bound one summary, keeping its tail: the closing paragraphs carry the
43
+ * conclusion a reader is after, and the omitted opening is announced instead of
44
+ * silently dropped. Mirrors the evidence reader's tail bound.
45
+ */
46
+ export function truncateExecutionSummary(text: string, limit = EXECUTION_SUMMARY_LIMIT): string {
47
+ if (text.length <= limit) return text
48
+ const notice = '[truncated ' + String(text.length - limit) + ' chars] '
49
+ return notice.length >= limit ? text.slice(-limit) : notice + text.slice(-(limit - notice.length))
50
+ }
51
+
52
+ /**
53
+ * The summary one execution's own events support.
54
+ *
55
+ * Only events at or after `startedAt` belong to this run: a reused session
56
+ * carries the history of earlier executions, which must not be reported as this
57
+ * one's output. The last assistant message WITH prose wins — a trailing
58
+ * tool-call or reasoning-only message has nothing to leave behind, so the reader
59
+ * walks back to the last one that speaks.
60
+ * @param events - the session events the inspection already read.
61
+ * @param startedAt - the execution's start instant (ms epoch); 0 means "all".
62
+ * @returns the bounded summary with the seq it came from, or undefined when the
63
+ * run left no usable text.
64
+ */
65
+ export function executionSummaryOf(events: readonly SummaryEvent[], startedAt: number): ExecutionSummary | undefined {
66
+ const own = events
67
+ .filter(event => typeof event.time !== 'number' || startedAt <= 0 || event.time >= startedAt)
68
+ .filter(event => event.type === 'assistant/message' && typeof event.seq === 'number')
69
+ .sort((a, b) => (a.seq as number) - (b.seq as number))
70
+ for (let index = own.length - 1; index >= 0; index -= 1) {
71
+ const event = own[index]
72
+ const data = typeof event.data === 'object' && event.data !== null ? event.data as Record<string, unknown> : {}
73
+ const message = typeof data.message === 'object' && data.message !== null ? data.message as Record<string, unknown> : {}
74
+ const text = messageProse(message.content)
75
+ if (text === '') continue
76
+ return { text: truncateExecutionSummary(text), seq: event.seq as number }
77
+ }
78
+ return undefined
79
+ }
80
+
81
+ /**
82
+ * Repair one persisted or reported summary.
83
+ *
84
+ * A summary is informational, so an unreadable one is dropped on its own rather
85
+ * than costing the execution (or the task row) it hangs on. A hand-edited
86
+ * overlong text is bounded on the way in, so no reader ever holds more than the
87
+ * limit.
88
+ */
89
+ export function normalizeExecutionSummary(value: unknown): ExecutionSummary | undefined {
90
+ if (typeof value !== 'object' || value === null) return undefined
91
+ const row = value as Record<string, unknown>
92
+ if (typeof row.text !== 'string' || typeof row.seq !== 'number' || !Number.isFinite(row.seq)) return undefined
93
+ const text = row.text.trim()
94
+ if (text === '') return undefined
95
+ return { text: truncateExecutionSummary(text), seq: row.seq }
96
+ }
@@ -12,6 +12,7 @@
12
12
  * @module dsh-task-board/core/extension
13
13
  */
14
14
  import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
15
+ import type { TaskBoardAction, TaskBoardSnapshot, TaskBoardVerificationOptions } from '../protocol.ts'
15
16
  import type { ExecutionOutcome, TaskRecord, TaskStatus } from './tasks.ts'
16
17
 
17
18
  /** Cordis service name the host and browser halves each publish. */
@@ -338,6 +339,39 @@ export interface TaskBoardHostFace {
338
339
  registerExtension(extension: TaskBoardExtension): () => void
339
340
  /** Whether the board currently runs a given extension (board x extension). */
340
341
  isExtensionEnabled(extensionId: string): boolean
342
+ /**
343
+ * The whole ledger as the board builds it, tasks included.
344
+ *
345
+ * Part of the read/write face an IN-PROCESS consumer drives the board through
346
+ * (the remote bridge plugin forwarding it to a paired phone); a browser half
347
+ * reads the same document over the board's own HTTP surface. Forwards
348
+ * {@link ../host-service.ts | TaskBoardHostService.snapshot}, so nothing is
349
+ * interpreted between the ledger and the caller.
350
+ */
351
+ snapshot(): TaskBoardSnapshot
352
+ /**
353
+ * Apply one action through every gate the board already has — the running
354
+ * lock, the permission confirmation, the subtask depth, the schedule budget —
355
+ * and answer the resulting snapshot.
356
+ *
357
+ * The `requestId` is the ledger's own idempotency key, so a caller that
358
+ * retries one envelope does not apply it twice. Refusals are the ledger's:
359
+ * they throw with the Host's own text, which is why this face adds no code
360
+ * table of its own.
361
+ */
362
+ apply(requestId: string, action: TaskBoardAction, initiator?: string): TaskBoardSnapshot | Promise<TaskBoardSnapshot>
363
+ /**
364
+ * Follow the board's change notifications. The listener receives no payload —
365
+ * a consumer that needs the state reads {@link snapshot} — and the returned
366
+ * disposer unsubscribes.
367
+ */
368
+ subscribe(listener: () => void): () => void
369
+ /**
370
+ * The acceptance settings, the contract they resolve to right now, and the
371
+ * model catalog the choices come from. The same document the board's own
372
+ * `/verification` route serves.
373
+ */
374
+ verificationOptions(): Promise<TaskBoardVerificationOptions>
341
375
  }
342
376
 
343
377
  declare module '@deepseek-ai/cordis' {
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The daily token ceiling both spend gates share, as pure rules: the cap
3
+ * comparison and the one refusal wording.
4
+ *
5
+ * The unit is tokens, not money. The usage ledger the board reads prices only
6
+ * DeepSeek's own routes, so a cost cap would read 0 on every other route and
7
+ * refuse nothing on exactly the deployments that need it. A cap of 0 is the
8
+ * shipped default and means "no gate": both gates answer before they read a
9
+ * file, subscribe to an event, or compute anything.
10
+ * @module @linxin666/dsh-task-board/core/spend-budget
11
+ */
12
+
13
+ /** Token cap one board day may spend; 0 disables the gate. */
14
+ export const DEFAULT_SPEND_BUDGET_TOKENS = 0
15
+
16
+ /**
17
+ * Whether a day's measured spend already reached the cap.
18
+ * @param usedTokens - tokens the day's spend measurement reported.
19
+ * @param cap - the configured cap, 0 for "no gate".
20
+ * @returns true when a run must be refused.
21
+ */
22
+ export function spendCapReached(usedTokens: number, cap: number): boolean {
23
+ return cap > 0 && usedTokens >= cap
24
+ }
25
+
26
+ /**
27
+ * The refusal text both gates report: the thrown message a client sees as
28
+ * board-refused, and the scheduler error a due occurrence records.
29
+ * @param usedTokens - tokens the day's spend measurement reported.
30
+ * @param cap - the configured cap.
31
+ * @returns the refusal message.
32
+ */
33
+ export function spendCapMessage(usedTokens: number, cap: number): string {
34
+ return `spend cap reached: ${usedTokens} tokens of ${cap} today; raise the cap in the task board settings`
35
+ }
package/src/core/store.ts CHANGED
@@ -12,6 +12,7 @@
12
12
  import { isValidCron, isValidTimeZone } from './schedule.ts'
13
13
  import { SCHEDULE_STOP_REASONS, isTaskPermission, isTaskStatus, normalizeTags, normalizeTargetId, type ScheduleRule, type ScheduleStopReason, type TaskFreeze, type TaskRecord, type TaskPermission, type TaskStatus } from './tasks.ts'
14
14
  import { isExecutionOutcome } from './subtask.ts'
15
+ import { normalizeExecutionSummary } from './execution-summary.ts'
15
16
  import type { TaskHandover } from './handover.ts'
16
17
  import { sanitizeFreezeSnapshot } from './freeze-snapshot.ts'
17
18
  import { sanitizeHandover } from './handover.ts'
@@ -256,6 +257,9 @@ export function parseLedger(raw: string | null): TaskRecord[] {
256
257
  runGroupId: normalizeTargetId(execution.runGroupId),
257
258
  ownResult: isExecutionOutcome(execution.ownResult) ? execution.ownResult : undefined,
258
259
  ownError: typeof execution.ownError === 'string' ? execution.ownError : undefined,
260
+ // A summary a reader does not recognize (an older document has none) is
261
+ // simply absent; a malformed one is dropped without costing the run.
262
+ summary: normalizeExecutionSummary(execution.summary),
259
263
  // A malformed acceptance block is dropped rather than dropping the
260
264
  // execution record: the board then treats that run as unverified.
261
265
  verification: normalizeVerification(execution.verification),
package/src/core/tasks.ts CHANGED
@@ -15,6 +15,29 @@ export type TaskStatus = 'backlog' | 'todo' | 'running' | 'done' | 'failed'
15
15
  /** Settled outcome of one execution attempt. */
16
16
  export type ExecutionOutcome = 'succeeded' | 'failed' | 'cancelled'
17
17
 
18
+ /**
19
+ * What one execution left behind: the text of the run's last assistant message
20
+ * and the session event it was read from.
21
+ *
22
+ * The board records a verdict per execution but no output, so a parent card
23
+ * could see that a subtask succeeded without seeing what it produced. Card
24
+ * content cannot answer that (it is the plan and freezes at the first
25
+ * execution), so the closing text rides the execution record instead.
26
+ */
27
+ export interface ExecutionSummary {
28
+ /** Last assistant message text of the run, bounded by {@link EXECUTION_SUMMARY_LIMIT}. */
29
+ text: string
30
+ /** Seq of the session event that text came from; absent text has no seq either. */
31
+ seq: number
32
+ }
33
+
34
+ /**
35
+ * Upper bound of one recorded summary, in characters. The ledger stores a
36
+ * conclusion, not a transcript: a reader that needs the whole message follows
37
+ * {@link ExecutionSummary.seq} into the session history.
38
+ */
39
+ export const EXECUTION_SUMMARY_LIMIT = 4000
40
+
18
41
  /**
19
42
  * One real execution attempt: the run's own id, the dsh session that ran it
20
43
  * (filled once the session is created), and the settled outcome once the
@@ -72,6 +95,16 @@ export interface ExecutionRecord {
72
95
  ownResult?: ExecutionOutcome
73
96
  /** Human failure text that arrived with {@link ownResult}. */
74
97
  ownError?: string
98
+ /**
99
+ * What this run left behind: the text of its last assistant message, taken
100
+ * when the settlement read the session and recorded with the verdict.
101
+ *
102
+ * Absent — never an empty string — when the session could not be read or
103
+ * carried no assistant prose, so "recorded nothing" stays distinguishable
104
+ * from "produced nothing". Settling never fails over it: a summary is
105
+ * informational, and every field above is what the board decides with.
106
+ */
107
+ summary?: ExecutionSummary
75
108
  /**
76
109
  * Goal acceptance state of this execution (task-board goal verification).
77
110
  * Fixed when the execution starts and never rewritten from later settings:
@@ -843,12 +876,21 @@ export function settleExecution(
843
876
  outcome: ExecutionOutcome,
844
877
  now: number,
845
878
  error: string | undefined,
879
+ summary?: ExecutionSummary,
846
880
  ): TaskRecord {
847
881
  const index = task.executions.findIndex(execution => execution.id === executionId)
848
882
  if (index === -1) return task
849
883
  const execution = task.executions[index]
850
884
  if (execution.endedAt !== undefined) return task
851
- const settled: ExecutionRecord = { ...execution, endedAt: now, result: outcome, error }
885
+ // A settle without one keeps whatever an earlier settle already recorded: a
886
+ // cascade parent's final fold has no session of its own to read.
887
+ const settled: ExecutionRecord = {
888
+ ...execution,
889
+ endedAt: now,
890
+ result: outcome,
891
+ error,
892
+ ...(summary === undefined ? {} : { summary }),
893
+ }
852
894
  const executions = [...task.executions]
853
895
  executions[index] = settled
854
896
  return { ...task, status: settledStatus(task, outcome), updatedAt: now, executions }