@linxin666/dsh-client-ui-task-board 0.4.6 → 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.
Files changed (73) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +15 -6
  3. package/README.zh.md +15 -6
  4. package/lib/client.js +1634 -822
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +1072 -125
  7. package/lib/types/client/CardDefaultPresetField.d.ts +35 -0
  8. package/lib/types/client/PluginSettingsCard.d.ts +39 -0
  9. package/lib/types/client/TaskBoardSettingsCard.d.ts +56 -0
  10. package/lib/types/client/board/ReasoningEffortField.d.ts +25 -0
  11. package/lib/types/client/board/model-options.d.ts +67 -0
  12. package/lib/types/client/board/preset-label.d.ts +21 -0
  13. package/lib/types/client/board/preset-roster.d.ts +45 -0
  14. package/lib/types/client/board/team-run-promotion.d.ts +26 -0
  15. package/lib/types/client/locales.d.ts +18 -0
  16. package/lib/types/client/telemetry.d.ts +14 -2
  17. package/lib/types/core/card-defaults.d.ts +78 -0
  18. package/lib/types/core/controller.d.ts +32 -7
  19. package/lib/types/core/execution-summary.d.ts +52 -0
  20. package/lib/types/core/extension.d.ts +34 -0
  21. package/lib/types/core/launch-width.d.ts +31 -0
  22. package/lib/types/core/reasoning-effort.d.ts +57 -0
  23. package/lib/types/core/spend-budget.d.ts +28 -0
  24. package/lib/types/core/subtask.d.ts +30 -8
  25. package/lib/types/core/tasks.d.ts +51 -1
  26. package/lib/types/core/use-cases/task-create.d.ts +10 -5
  27. package/lib/types/core/use-cases/task-update.d.ts +1 -1
  28. package/lib/types/host/launch-admission.d.ts +72 -0
  29. package/lib/types/host-ledger.d.ts +33 -6
  30. package/lib/types/host-runner.d.ts +83 -5
  31. package/lib/types/host-service.d.ts +116 -2
  32. package/lib/types/host-spend.d.ts +52 -0
  33. package/lib/types/index.d.ts +98 -0
  34. package/lib/types/loopback.d.ts +20 -1
  35. package/lib/types/protocol.d.ts +13 -0
  36. package/package.json +28 -28
  37. package/src/client/CardDefaultPresetField.tsx +101 -0
  38. package/src/client/PluginSettingsCard.tsx +63 -3
  39. package/src/client/TaskBoardSettingsCard.tsx +251 -16
  40. package/src/client/board/LinkSubtaskModal.tsx +8 -0
  41. package/src/client/board/NewTaskModal.tsx +86 -40
  42. package/src/client/board/ReasoningEffortField.tsx +50 -0
  43. package/src/client/board/TaskDetail.tsx +42 -6
  44. package/src/client/board/model-options.ts +178 -0
  45. package/src/client/board/preset-label.ts +32 -0
  46. package/src/client/board/preset-roster.ts +58 -0
  47. package/src/client/board/team-run-promotion.ts +39 -0
  48. package/src/client/index.ts +98 -94
  49. package/src/client/locales.ts +38 -2
  50. package/src/client/settings-card.module.css +70 -1
  51. package/src/client/settings-entry-form.ts +0 -1
  52. package/src/client/telemetry.ts +47 -2
  53. package/src/core/card-defaults.ts +132 -0
  54. package/src/core/controller.ts +44 -9
  55. package/src/core/execution-summary.ts +96 -0
  56. package/src/core/extension.ts +34 -0
  57. package/src/core/launch-width.ts +38 -0
  58. package/src/core/reasoning-effort.ts +92 -0
  59. package/src/core/spend-budget.ts +35 -0
  60. package/src/core/store.ts +9 -0
  61. package/src/core/subtask.ts +48 -13
  62. package/src/core/tasks.ts +63 -1
  63. package/src/core/use-cases/task-create.ts +27 -16
  64. package/src/core/use-cases/task-update.ts +6 -1
  65. package/src/host/agent-tools.ts +21 -8
  66. package/src/host/launch-admission.ts +140 -0
  67. package/src/host-ledger.ts +80 -10
  68. package/src/host-runner.ts +199 -25
  69. package/src/host-service.ts +340 -27
  70. package/src/host-spend.ts +105 -0
  71. package/src/index.ts +182 -2
  72. package/src/loopback.ts +25 -1
  73. package/src/protocol.ts +28 -4
@@ -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
@@ -18,10 +18,13 @@ import type {} from '@deepseek-ai/dsh-tools'
18
18
  import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
19
19
  import type { LlmRuntime } from '@deepseek-ai/dsh-llm'
20
20
  import { TaskBoardHostService, type HostTimerFace, type TaskBoardTeamDispatcher } from './host-service.ts'
21
+ import { createOwnerPeer } from './host-runner.ts'
21
22
  import { parseTaskDraft, TaskParseError } from './host-ai.ts'
22
23
  import { TASK_PERMISSIONS, isTaskPermission, type TaskPermission } from './core/tasks.ts'
23
24
  import { DEFAULT_SUBTASK_DEPTH, SUBTASK_DEPTH_MAX, SUBTASK_DEPTH_MIN } from './core/subtask.ts'
24
25
  import { DEFAULT_SESSION_POLL_SECONDS, SESSION_POLL_MAX_SECONDS, SESSION_POLL_MIN_SECONDS } from './core/poll-cadence.ts'
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'
25
28
  import {
26
29
  DEFAULT_VERIFICATION_BUDGET_SECONDS,
27
30
  DEFAULT_VERIFICATION_CALL_TIMEOUT_SECONDS,
@@ -33,10 +36,12 @@ import {
33
36
  verificationCallTimeoutMs,
34
37
  } from './core/verification-budget.ts'
35
38
  import { DEFAULT_SESSION_PERMISSION } from './core/handover.ts'
39
+ import type { CardDefaults } from './core/card-defaults.ts'
36
40
  import { buildTaskBoardTools, TASK_BOARD_TOOL_NAMES } from './host/agent-tools.ts'
37
41
  import { PLUGIN_TOOL_SECTION_ORDERS, visibleToolText } from './tool-surface.ts'
38
42
  import { makeTaskBoardRoutes } from './host-routes.ts'
39
43
  import { TASK_BOARD_SERVICE_NAME, type TaskBoardExtension } from './core/extension.ts'
44
+ import type { TaskBoardAction } from './protocol.ts'
40
45
  import { mountOnce } from './mount-once.ts'
41
46
  import { createGoalVerificationGate, type GoalFace } from './host/verification-gate.ts'
42
47
  import { normalizeCatalog, type ModelCatalogView, type VerificationSettings } from './core/verification.ts'
@@ -106,6 +111,26 @@ export interface Config {
106
111
  * at all, so this cadence only bounds how quickly a running card settles.
107
112
  */
108
113
  sessionPollSeconds?: Volatile<number>
114
+ /**
115
+ * How many run launches this board may have in flight at once (1..16,
116
+ * default 3). One run opens its whole subtree, so without a bound the Host
117
+ * asks DSH for every member's session in the same tick; this is the mechanism
118
+ * that enforces the repository's measured guidance for heavy implementation
119
+ * subagents. Members wait their turn instead of being dropped: the subtree
120
+ * still opens completely, they only enter the running column in batches. Read
121
+ * at each admission, so an edit bounds the next launch of a run that is still
122
+ * queueing.
123
+ */
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>
109
134
  /**
110
135
  * Continuable-subagent provider the Agent Teams service uses to compose a
111
136
  * teammate. Matches the Agent Teams tool plugin's `freshProvider` default;
@@ -128,6 +153,33 @@ export interface Config {
128
153
  * becomes a goal run.
129
154
  */
130
155
  goalRunEnabled?: Volatile<boolean>
156
+ /**
157
+ * Agent preset a NEW card starts from (volatile, default blank = not set).
158
+ * A prefill, never a pin: the create dialog opens with it selected, the
159
+ * caller may override it, and the card stores what it was created with. It
160
+ * reaches the create path only when that caller opts in with
161
+ * `applyCardDefaults`, so the extension provider's own create and the legacy
162
+ * import are untouched.
163
+ */
164
+ cardDefaultMode?: Volatile<string>
165
+ /**
166
+ * Permission a NEW card starts from (volatile, default blank = not set), one
167
+ * of the three presets. A prefill like the rest: a value above
168
+ * `sessionDefaultPermission` still has to be confirmed by a human before the
169
+ * card may run, because the pre-execution gate is what decides that.
170
+ */
171
+ cardDefaultPermission?: Volatile<TaskPermission | ''>
172
+ /**
173
+ * Model a NEW card starts from (volatile, default blank = not set).
174
+ */
175
+ cardDefaultModel?: Volatile<string>
176
+ /**
177
+ * Reasoning level a NEW card starts from (volatile, default blank = not set).
178
+ * Bound to `cardDefaultModel` exactly as a card's own level is bound to its
179
+ * own model: it applies only while the card's final model IS that default
180
+ * model, and a blank `cardDefaultModel` makes it inert.
181
+ */
182
+ cardDefaultReasoningEffort?: Volatile<string>
131
183
  /**
132
184
  * Goal acceptance for executions this board starts (default ON). When on,
133
185
  * update_goal(action: complete) inside a task execution is refused until an
@@ -205,10 +257,22 @@ export interface ConfigInput {
205
257
  maxSubtaskDepth?: number
206
258
  /** Roster-poll cadence in seconds while the board has work to reconcile. */
207
259
  sessionPollSeconds?: number
260
+ /** Concurrent run launches allowed at once, 1..16. */
261
+ runLaunchWidth?: number
262
+ /** Daily token ceiling for board runs; 0 disables the gate. */
263
+ spendBudgetTokens?: number
208
264
  /** Continuable-subagent provider the Agent Teams service composes a teammate from. */
209
265
  teamProvider?: string
210
266
  /** Global native /goal switch; default off, frozen per execution. */
211
267
  goalRunEnabled?: boolean
268
+ /** Agent preset a new card starts from; blank = not set. */
269
+ cardDefaultMode?: string
270
+ /** Permission a new card starts from; blank = not set. */
271
+ cardDefaultPermission?: TaskPermission | ''
272
+ /** Model a new card starts from; blank = not set. */
273
+ cardDefaultModel?: string
274
+ /** Reasoning level a new card starts from; blank = not set. */
275
+ cardDefaultReasoningEffort?: string
212
276
  /** Goal acceptance switch. */
213
277
  goalVerification?: boolean
214
278
  /** Judge model route for goal acceptance; blank inherits the host default. */
@@ -230,8 +294,14 @@ export const Config: z<ConfigInput, Config> = z.object({
230
294
  sessionDefaultPermission: z.union(TASK_PERMISSIONS),
231
295
  maxSubtaskDepth: z.number().min(SUBTASK_DEPTH_MIN).max(SUBTASK_DEPTH_MAX).default(DEFAULT_SUBTASK_DEPTH).volatile(),
232
296
  sessionPollSeconds: z.number().min(SESSION_POLL_MIN_SECONDS).max(SESSION_POLL_MAX_SECONDS).default(DEFAULT_SESSION_POLL_SECONDS).volatile(),
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(),
233
299
  teamProvider: z.string().min(1).default(DEFAULT_TEAM_PROVIDER),
234
300
  goalRunEnabled: z.boolean().default(false).volatile(),
301
+ cardDefaultMode: z.string().default('').volatile(),
302
+ cardDefaultPermission: z.union([...TASK_PERMISSIONS, '']).default('').volatile(),
303
+ cardDefaultModel: z.string().default('').volatile(),
304
+ cardDefaultReasoningEffort: z.string().default('').volatile(),
235
305
  goalVerification: z.boolean().default(true).volatile(),
236
306
  goalVerificationModel: z.string().default('').volatile(),
237
307
  goalVerificationReasoningEffort: z.string().default('').volatile(),
@@ -465,6 +535,70 @@ export function resolveLlmRuntime(ctx: Context): LlmRuntime | undefined {
465
535
  }
466
536
  }
467
537
 
538
+ /**
539
+ * The subset of `sessionController` the board uses to wake a cold persisted
540
+ * session before running a slash command on it (issue #1861).
541
+ */
542
+ interface SessionControllerFace {
543
+ resolveAgent(
544
+ sessionId: Parameters<Context['agents']['get']>[0],
545
+ ): Promise<
546
+ | { readonly agent: Parameters<Context['commands']['execute']>[0] }
547
+ | { readonly error: { readonly message?: string } }
548
+ >
549
+ }
550
+
551
+ /**
552
+ * Resolve the optional `sessionController` service. Like the tool registry and
553
+ * the llm runtime, it is read dynamically so capture-only test contexts that do
554
+ * not mount the full session controller still activate the board.
555
+ * @param ctx - the plugin context.
556
+ * @returns the session controller face, or undefined when unavailable.
557
+ */
558
+ export function resolveSessionController(ctx: Context): SessionControllerFace | undefined {
559
+ try {
560
+ const controller = (ctx as { get?: (name: string) => unknown }).get?.('sessionController') as SessionControllerFace | undefined
561
+ return controller !== undefined && typeof controller.resolveAgent === 'function' ? controller : undefined
562
+ } catch {
563
+ return undefined
564
+ }
565
+ }
566
+
567
+ /**
568
+ * Resolve the live Agent for an execution session, resuming a cold persisted
569
+ * session through `sessionController.resolveAgent` when it is not yet in
570
+ * `ctx.agents` (issue #1861).
571
+ *
572
+ * A fresh run (`session/create`) or a session the browser is currently
573
+ * following is already in `ctx.agents`, so the fast path returns immediately.
574
+ * A scheduled or manual reuse of a cold session — one that `session/list`
575
+ * reports as idle from disk without activating its Agent — is not in
576
+ * `ctx.agents` when `pinAndPrompt` runs `/permission` ahead of
577
+ * `session/selectModel` and `session/prompt`; delegating to
578
+ * `sessionController.resolveAgent` resumes it with its recorded preset and
579
+ * model-selection state, matching what those gateway endpoints do next.
580
+ * @param ctx - the plugin context.
581
+ * @param sessionId - the target execution session id.
582
+ * @returns the live Agent for `sessionId`.
583
+ */
584
+ export async function resolveExecutionAgent(
585
+ ctx: Context,
586
+ sessionId: Parameters<Context['agents']['get']>[0],
587
+ ): Promise<Parameters<Context['commands']['execute']>[0]> {
588
+ const live = ctx.agents.get(sessionId)
589
+ if (live !== undefined) return live
590
+ const controller = resolveSessionController(ctx)
591
+ if (controller !== undefined) {
592
+ const resolved = await controller.resolveAgent(sessionId)
593
+ if ('agent' in resolved && resolved.agent !== undefined) return resolved.agent
594
+ const detail = 'error' in resolved && typeof resolved.error?.message === 'string' && resolved.error.message !== ''
595
+ ? `: ${resolved.error.message}`
596
+ : ''
597
+ throw new Error(`execution session ${sessionId} is not available${detail}`)
598
+ }
599
+ throw new Error(`execution session ${sessionId} is not available`)
600
+ }
601
+
468
602
  /**
469
603
  * Activate the board's host half: ledger, routes, cron scheduler, power
470
604
  * inhibitor, and the model-facing announcement.
@@ -491,6 +625,18 @@ function applyImpl(ctx: Context, config?: Config): void {
491
625
  const maxSubtaskDepth = (): number => readConfigField(config?.maxSubtaskDepth, DEFAULT_SUBTASK_DEPTH)
492
626
  /** Current roster-poll cadence in seconds (read live: the settings card edits it in place). */
493
627
  const sessionPollSeconds = (): number => readConfigField(config?.sessionPollSeconds, DEFAULT_SESSION_POLL_SECONDS)
628
+ /**
629
+ * Current run-launch admission width. Read live on every admission, so the
630
+ * settings card bounds the next launch of a run that is still queueing without
631
+ * remounting the row; the Host clamps a hand-edited value into the schema range.
632
+ */
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)
494
640
  /**
495
641
  * The baseline the permission confirmation gate judges against: the row's own
496
642
  * `sessionDefaultPermission` when the deployment pins one, otherwise the Host's
@@ -529,19 +675,41 @@ function applyImpl(ctx: Context, config?: Config): void {
529
675
  * executions that start afterwards.
530
676
  */
531
677
  const goalRunEnabled = (): boolean => readConfigField(config?.goalRunEnabled, DEFAULT_GOAL_RUN)
678
+ /**
679
+ * Live reader of the new-card defaults, read at every use like the switch
680
+ * above: the create dialog prefills from the published snapshot, and each
681
+ * creating session re-reads them when it submits the create. A blank value
682
+ * means "not set" and reaches the resolver as an absent target.
683
+ */
684
+ const cardDefaults = (): CardDefaults => {
685
+ const permission = readConfigField<TaskPermission | ''>(config?.cardDefaultPermission, '')
686
+ return {
687
+ mode: readConfigField(config?.cardDefaultMode, '').trim() || undefined,
688
+ permission: isTaskPermission(permission) ? permission : undefined,
689
+ model: readConfigField(config?.cardDefaultModel, '').trim() || undefined,
690
+ reasoningEffort: readConfigField(config?.cardDefaultReasoningEffort, '').trim() || undefined,
691
+ }
692
+ }
693
+ // The 0.2.1 gateway requires every request to name the peer it speaks for:
694
+ // the board calls as the host-local owner, so its peer is minted on this
695
+ // fiber and aborts with it (see createOwnerPeer).
696
+ const ownerPeer = createOwnerPeer(ctx)
532
697
  const host = new TaskBoardHostService(ctx.typertGateway, {
533
698
  workspaceRegistry: ctx.workspaceRegistry,
699
+ ownerPeer,
534
700
  sessionDefaultPermission,
535
701
  maxSubtaskDepth: maxSubtaskDepth(),
536
702
  goalRunEnabled,
703
+ runLaunchWidth,
704
+ spendBudgetTokens,
705
+ cardDefaults,
537
706
  verificationSettings,
538
707
  verificationCatalog,
539
708
  timers: resolveHostTimers(ctx),
540
709
  team: buildTeamDispatcher(ctx, config?.teamProvider ?? DEFAULT_TEAM_PROVIDER),
541
710
  commandDispatcher: {
542
711
  async execute(sessionId, line, signal) {
543
- const agent = ctx.agents.get(sessionId)
544
- if (agent === undefined) throw new Error(`execution session ${sessionId} is not available`)
712
+ const agent = await resolveExecutionAgent(ctx, sessionId)
545
713
  return (await ctx.commands.execute(agent, line, [], signal))?.result
546
714
  },
547
715
  },
@@ -556,10 +724,22 @@ function applyImpl(ctx: Context, config?: Config): void {
556
724
  // provider package can resolve it and admit itself; the board itself knows
557
725
  // no provider vocabulary. A capture-only test context implements no service
558
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.
559
735
  if (typeof (ctx as { provide?: unknown }).provide === 'function') {
560
736
  ctx.provide(TASK_BOARD_SERVICE_NAME, {
561
737
  registerExtension: (extension: TaskBoardExtension) => host.registerExtension(extension),
562
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(),
563
743
  })
564
744
  }
565
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
package/src/protocol.ts CHANGED
@@ -93,6 +93,14 @@ export interface TaskBoardSnapshot {
93
93
  * flight.
94
94
  */
95
95
  goalRunEnabled?: boolean
96
+ /**
97
+ * New-card defaults this deployment configures: what the create dialog opens
98
+ * with, and what the create path fills an omitted target from when the caller
99
+ * opts in (`applyCardDefaults`). A target the board configures nothing for is
100
+ * omitted rather than published blank, so the browser can tell "no default
101
+ * model" from "a blank one".
102
+ */
103
+ cardDefaults?: { mode?: string; permission?: TaskPermission; model?: string; reasoningEffort?: string }
96
104
  /**
97
105
  * Read-only summaries published by running extensions, keyed by extension id.
98
106
  * The board forwards them verbatim; it never interprets their shape.
@@ -263,6 +271,9 @@ function validImportedKnownFields(value: Record<string, unknown>): boolean {
263
271
  // must carry a well-formed list or none at all, so a hand-edited export
264
272
  // cannot smuggle a malformed tag past the gate.
265
273
  if (value.tags !== undefined && !isTaskTagList(value.tags)) return false
274
+ // The model pin is carried by the import (with the level bound to it), so a
275
+ // non-string value is refused here like the other carried known fields.
276
+ if (value.model !== undefined && typeof value.model !== 'string') return false
266
277
  if (value.integrations !== undefined && normalizeTaskIntegrations(value.integrations) === undefined) return false
267
278
  if (value.schedule !== undefined && !validImportedSchedule(value.schedule)) return false
268
279
  if (value.executions !== undefined) {
@@ -326,7 +337,15 @@ function importedTask(value: unknown): TaskRecord | undefined {
326
337
  ...(task.parentId === undefined ? {} : { parentId: task.parentId }),
327
338
  ...(task.workspaceId === undefined ? {} : { workspaceId: task.workspaceId }),
328
339
  ...(task.mode === undefined ? {} : { mode: task.mode }),
340
+ // The model pin rides the import together with the level bound to it: the
341
+ // two are one pair, and an imported level without its model would run at
342
+ // whatever route the session happens to be on. Blank text means "no pin",
343
+ // like every other target, so it is not carried as a pin of its own.
344
+ ...(typeof task.model !== 'string' || task.model.trim() === '' ? {} : { model: task.model }),
329
345
  ...(task.permission === undefined ? {} : { permission: task.permission }),
346
+ // The reasoning effort rides the import like the other execution targets: it
347
+ // is the user's own card preference, not a verdict.
348
+ ...(task.reasoningEffort === undefined ? {} : { reasoningEffort: task.reasoningEffort }),
330
349
  ...(task.reuseSession === undefined ? {} : { reuseSession: task.reuseSession }),
331
350
  ...(task.goalRun === undefined ? {} : { goalRun: task.goalRun }),
332
351
  // The per-card acceptance opt-out rides the import like the /goal opt-in:
@@ -372,10 +391,15 @@ function handoverPayload(value: unknown): TaskHandoverInput | undefined {
372
391
 
373
392
  function createInput(value: unknown): value is NewTaskInput {
374
393
  const input = record(value)
375
- if (input === undefined || !exactKeys(input, ['title', 'description', 'prompt', 'parentId', 'workspaceId', 'mode', 'permission', 'schedule', 'freeze', 'handover', 'model', 'reuseSession', 'teamRun', 'goalRun', 'skipVerification', 'tags', 'integrations'])) return false
394
+ if (input === undefined || !exactKeys(input, ['title', 'description', 'prompt', 'parentId', 'workspaceId', 'mode', 'permission', 'schedule', 'freeze', 'handover', 'model', 'reasoningEffort', 'applyCardDefaults', 'reuseSession', 'teamRun', 'goalRun', 'skipVerification', 'tags', 'integrations'])) return false
376
395
  if (input.parentId !== undefined && (typeof input.parentId !== 'string' || input.parentId.trim() === '')) return false
377
396
  if (typeof input.title !== 'string' || typeof input.description !== 'string' || typeof input.prompt !== 'string') return false
378
- if (!optionalString(input.workspaceId) || !optionalString(input.mode) || !optionalString(input.model)) return false
397
+ // The reasoning effort is an adapter-owned id the Host resolves against the
398
+ // live model catalog, so this gate only keeps a malformed value (a number, an
399
+ // object, null) off the ledger; blank text means "inherit" like every other
400
+ // pinned target.
401
+ if (!optionalString(input.workspaceId) || !optionalString(input.mode) || !optionalString(input.model) || !optionalString(input.reasoningEffort)) return false
402
+ if (input.applyCardDefaults !== undefined && typeof input.applyCardDefaults !== 'boolean') return false
379
403
  if (input.reuseSession !== undefined && typeof input.reuseSession !== 'boolean') return false
380
404
  if (input.teamRun !== undefined && typeof input.teamRun !== 'boolean') return false
381
405
  if (input.goalRun !== undefined && typeof input.goalRun !== 'boolean') return false
@@ -402,7 +426,7 @@ function createInput(value: unknown): value is NewTaskInput {
402
426
 
403
427
  function updatePatch(value: unknown): boolean {
404
428
  const patch = record(value)
405
- if (patch === undefined || !exactKeys(patch, ['title', 'description', 'prompt', 'workspaceId', 'mode', 'permission', 'freeze', 'handover', 'model', 'reuseSession', 'teamRun', 'goalRun', 'skipVerification', 'tags'])) return false
429
+ if (patch === undefined || !exactKeys(patch, ['title', 'description', 'prompt', 'workspaceId', 'mode', 'permission', 'freeze', 'handover', 'model', 'reasoningEffort', 'reuseSession', 'teamRun', 'goalRun', 'skipVerification', 'tags'])) return false
406
430
  // null (or false) clears the reuse opt-in; only a real boolean is accepted.
407
431
  if (patch.reuseSession !== undefined && patch.reuseSession !== null && typeof patch.reuseSession !== 'boolean') return false
408
432
  if (patch.teamRun !== undefined && patch.teamRun !== null && typeof patch.teamRun !== 'boolean') return false
@@ -412,7 +436,7 @@ function updatePatch(value: unknown): boolean {
412
436
  // The acceptance opt-out is the mirror tri-state: null/false return the card
413
437
  // to inheriting the board-wide switch, true pins it out of the gate.
414
438
  if (patch.skipVerification !== undefined && patch.skipVerification !== null && typeof patch.skipVerification !== 'boolean') return false
415
- for (const key of ['title', 'description', 'prompt', 'workspaceId', 'mode', 'model'] as const) {
439
+ for (const key of ['title', 'description', 'prompt', 'workspaceId', 'mode', 'model', 'reasoningEffort'] as const) {
416
440
  if (!optionalString(patch[key])) return false
417
441
  }
418
442
  if (patch.permission !== undefined && !isTaskPermission(patch.permission)) return false