@linxin666/dsh-client-ui-task-board-ssh 0.0.0-stage → 0.4.20

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 (126) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +85 -2
  4. package/README.zh.md +86 -0
  5. package/cordis.patch.yml +15 -0
  6. package/icon.svg +5 -0
  7. package/lib/client.js +4429 -0
  8. package/lib/index.js +6100 -0
  9. package/lib/types/client/PluginSettingsCard.d.ts +255 -0
  10. package/lib/types/client/RangeBubble.d.ts +46 -0
  11. package/lib/types/client/SegmentGroup.d.ts +28 -0
  12. package/lib/types/client/index.d.ts +100 -0
  13. package/lib/types/client/locales.d.ts +125 -0
  14. package/lib/types/client/seat-props.d.ts +53 -0
  15. package/lib/types/client/settings-entry-form.d.ts +49 -0
  16. package/lib/types/client/settings-form.d.ts +237 -0
  17. package/lib/types/client/ssh/card-decoration.d.ts +23 -0
  18. package/lib/types/client/ssh/compose-section.d.ts +7 -0
  19. package/lib/types/client/ssh/detail-section.d.ts +7 -0
  20. package/lib/types/client/ssh/extension.d.ts +54 -0
  21. package/lib/types/client/ssh/log-buffer.d.ts +128 -0
  22. package/lib/types/client/ssh/log-view.d.ts +37 -0
  23. package/lib/types/client/ssh/model.d.ts +130 -0
  24. package/lib/types/client/ssh/settings-section.d.ts +134 -0
  25. package/lib/types/client/ssh/summary.d.ts +160 -0
  26. package/lib/types/client/ssh/target-form.d.ts +60 -0
  27. package/lib/types/core/action.d.ts +89 -0
  28. package/lib/types/core/adapters/claude.d.ts +15 -0
  29. package/lib/types/core/adapters/codex.d.ts +15 -0
  30. package/lib/types/core/adapters/custom.d.ts +29 -0
  31. package/lib/types/core/adapters/dsh.d.ts +21 -0
  32. package/lib/types/core/adapters/index.d.ts +25 -0
  33. package/lib/types/core/adapters/types.d.ts +76 -0
  34. package/lib/types/core/contract.d.ts +445 -0
  35. package/lib/types/core/launcher-script.d.ts +13 -0
  36. package/lib/types/core/launcher.d.ts +153 -0
  37. package/lib/types/core/ledger.d.ts +123 -0
  38. package/lib/types/core/shell.d.ts +61 -0
  39. package/lib/types/core/target.d.ts +143 -0
  40. package/lib/types/core/task-record.d.ts +63 -0
  41. package/lib/types/core/workspace.d.ts +74 -0
  42. package/lib/types/host/board.d.ts +71 -0
  43. package/lib/types/host/engine.d.ts +418 -0
  44. package/lib/types/host/extension.d.ts +59 -0
  45. package/lib/types/host/logs.d.ts +135 -0
  46. package/lib/types/host/payload.d.ts +75 -0
  47. package/lib/types/host/prompt.d.ts +44 -0
  48. package/lib/types/host/queue.d.ts +53 -0
  49. package/lib/types/host/remote.d.ts +120 -0
  50. package/lib/types/host/settings.d.ts +149 -0
  51. package/lib/types/host/timers.d.ts +20 -0
  52. package/lib/types/host/tools.d.ts +15 -0
  53. package/lib/types/host/workspace/errors.d.ts +29 -0
  54. package/lib/types/host/workspace/git.d.ts +108 -0
  55. package/lib/types/host/workspace/in-place.d.ts +36 -0
  56. package/lib/types/host/workspace/index.d.ts +28 -0
  57. package/lib/types/host/workspace/layout.d.ts +62 -0
  58. package/lib/types/host/workspace/local-git.d.ts +72 -0
  59. package/lib/types/host/workspace/remote-git.d.ts +111 -0
  60. package/lib/types/host/workspace/remote.d.ts +85 -0
  61. package/lib/types/host/workspace/types.d.ts +28 -0
  62. package/lib/types/host/workspace-seam.d.ts +100 -0
  63. package/lib/types/index.d.ts +97 -0
  64. package/lib/types/mount-once.d.ts +55 -0
  65. package/locale/en.json +6 -0
  66. package/locale/zh.json +6 -0
  67. package/package.json +89 -3
  68. package/src/client/PluginSettingsCard.tsx +838 -0
  69. package/src/client/RangeBubble.tsx +164 -0
  70. package/src/client/SegmentGroup.tsx +93 -0
  71. package/src/client/css-modules.d.ts +5 -0
  72. package/src/client/index.ts +195 -0
  73. package/src/client/locales.ts +257 -0
  74. package/src/client/seat-props.ts +58 -0
  75. package/src/client/settings-card.module.css +821 -0
  76. package/src/client/settings-entry-form.ts +141 -0
  77. package/src/client/settings-form.ts +529 -0
  78. package/src/client/ssh/card-decoration.tsx +55 -0
  79. package/src/client/ssh/compose-section.tsx +147 -0
  80. package/src/client/ssh/detail-section.tsx +345 -0
  81. package/src/client/ssh/extension.ts +271 -0
  82. package/src/client/ssh/log-buffer.ts +224 -0
  83. package/src/client/ssh/log-view.tsx +149 -0
  84. package/src/client/ssh/model.ts +299 -0
  85. package/src/client/ssh/settings-section.tsx +401 -0
  86. package/src/client/ssh/summary.ts +388 -0
  87. package/src/client/ssh/target-form.tsx +380 -0
  88. package/src/client/ssh.module.css +617 -0
  89. package/src/core/action.ts +270 -0
  90. package/src/core/adapters/claude.ts +64 -0
  91. package/src/core/adapters/codex.ts +83 -0
  92. package/src/core/adapters/custom.ts +88 -0
  93. package/src/core/adapters/dsh.ts +87 -0
  94. package/src/core/adapters/index.ts +74 -0
  95. package/src/core/adapters/types.ts +95 -0
  96. package/src/core/contract.ts +510 -0
  97. package/src/core/launcher-script.ts +313 -0
  98. package/src/core/launcher.ts +283 -0
  99. package/src/core/ledger.ts +372 -0
  100. package/src/core/shell.ts +77 -0
  101. package/src/core/target.ts +413 -0
  102. package/src/core/task-record.ts +65 -0
  103. package/src/core/workspace.ts +78 -0
  104. package/src/host/board.ts +103 -0
  105. package/src/host/engine.ts +1602 -0
  106. package/src/host/extension.ts +304 -0
  107. package/src/host/logs.ts +297 -0
  108. package/src/host/payload.ts +134 -0
  109. package/src/host/prompt.ts +89 -0
  110. package/src/host/queue.ts +73 -0
  111. package/src/host/remote.ts +328 -0
  112. package/src/host/settings.ts +294 -0
  113. package/src/host/timers.ts +33 -0
  114. package/src/host/tools.ts +259 -0
  115. package/src/host/workspace/errors.ts +43 -0
  116. package/src/host/workspace/git.ts +305 -0
  117. package/src/host/workspace/in-place.ts +58 -0
  118. package/src/host/workspace/index.ts +37 -0
  119. package/src/host/workspace/layout.ts +122 -0
  120. package/src/host/workspace/local-git.ts +164 -0
  121. package/src/host/workspace/remote-git.ts +244 -0
  122. package/src/host/workspace/remote.ts +181 -0
  123. package/src/host/workspace/types.ts +34 -0
  124. package/src/host/workspace-seam.ts +132 -0
  125. package/src/index.ts +243 -0
  126. package/src/mount-once.ts +142 -0
@@ -0,0 +1,1602 @@
1
+ /**
2
+ * The run engine: launch interception, per-host admission, remote polling,
3
+ * reconciliation, follow-up and cancellation for one board mount.
4
+ *
5
+ * One card, one run at a time, and the card's own stored payload is the whole
6
+ * state: what it pins, which run it waits on and what it already did. That is
7
+ * what lets the local host disappear mid-run — the remote process keeps going
8
+ * under `setsid nohup`, and a Host that starts again reads the same payloads and
9
+ * picks every run back up (reconciliation), closes the ones that finished while
10
+ * it was away exactly once, and keeps polling the ones still running.
11
+ *
12
+ * Two board seams are load-bearing and both are probed, never assumed:
13
+ * `launch.intercept` takes a card over before a session exists (direct mode) or
14
+ * adds the preamble a local session starts with (proxy mode), and the board's
15
+ * action seat writes the verdict back through `record-external-outcome`. A board
16
+ * revision that serves neither still gets this extension mounted: its tools
17
+ * answer, its polls stop, and the reason is logged.
18
+ *
19
+ * @module dsh-task-board-ssh/host/engine
20
+ */
21
+ import {
22
+ buildAgentCommandLine,
23
+ customAgentCommand,
24
+ customResumeSupported,
25
+ readAgentOutput,
26
+ type SshAgentCommand,
27
+ type SshAgentRunInput,
28
+ type SshCustomTemplates,
29
+ } from '../core/adapters/index.ts'
30
+ import type { DshSshHost, DshSshService, TaskBoardExtensionHost, TaskBoardLaunchContext, TaskBoardLaunchDecision, TaskBoardStatusChangedEvent, TaskBoardTaskDeletedEvent } from '../core/contract.ts'
31
+ import { SSH_ERROR_MAX_LENGTH, SSH_SUMMARY_MAX_LENGTH } from '../core/ledger.ts'
32
+ import { runFilePath, type LauncherStatus } from '../core/launcher.ts'
33
+ import { isTerminalRunPhase, type SshAgentKind, type SshAgentTarget, type SshRunPhase, type SshRunRecord, type SshTarget } from '../core/target.ts'
34
+ import type { TaskRecord } from '../core/task-record.ts'
35
+ import type { SshWorkspaceCollection, SshWorkspaceRun, SshWorkspaceStrategy } from '../core/workspace.ts'
36
+ import { SSH_INITIATOR_PREFIX, alreadyRecorded, type BoardActionSeat } from './board.ts'
37
+ import {
38
+ SSH_INTEGRATION_KEY,
39
+ findRun,
40
+ latestSessionId,
41
+ liveRunOf,
42
+ readHostPayload,
43
+ withActiveRun,
44
+ withSettledRun,
45
+ writeHostPayload,
46
+ type HostSshPayload,
47
+ type SshPendingInstruction,
48
+ } from './payload.ts'
49
+ import { LOG_WINDOW_BUDGET_BYTES, PUBLISH_BODY_LIMIT_BYTES, SshLogWindows, byteLength, sliceFromByte, takeWithinBudget } from './logs.ts'
50
+ import { SSH_DEGRADED_SUMMARY_MARKER, proxyPreamble, runPrompt } from './prompt.ts'
51
+ import { admitRuns, type SshQueueEntry } from './queue.ts'
52
+ import { SshRemote } from './remote.ts'
53
+ import type { SshProviderSettings } from './settings.ts'
54
+ import type { HostTimerFace } from './timers.ts'
55
+ import { readUntrackedFiles, untrackedNote, type SshWorkspaceStrategyResolver } from './workspace-seam.ts'
56
+
57
+ /** Poll cadence when a deployment configures none, in milliseconds. */
58
+ export const DEFAULT_POLL_INTERVAL_MS = 2_000
59
+
60
+ /** Consecutive unreadable polls after which a run is recorded as lost. */
61
+ export const LOST_AFTER_FAILURES = 3
62
+
63
+ /** Longest tail of a run's log this engine parses, in characters. */
64
+ const PARSE_WINDOW = 256 * 1024
65
+
66
+ /** What the engine needs from its mount; every member is injectable so a spec can pin it. */
67
+ export interface SshRunEngineOptions {
68
+ /** The board's capability face for this extension. */
69
+ host: TaskBoardExtensionHost
70
+ /** `dsh-ssh`'s forwarder: the only way this package reaches a remote host. */
71
+ ssh: DshSshService
72
+ /** Timer seat the poll cadence runs on. */
73
+ timers: HostTimerFace
74
+ /** Live configuration of this mount, read at use time. */
75
+ settings: () => SshProviderSettings
76
+ /** The board's in-process action seat, resolved per call so a late one is honoured. */
77
+ seat?: () => BoardActionSeat | undefined
78
+ /** Placement strategies; absent means this deployment prepares no working directory. */
79
+ workspaces?: SshWorkspaceStrategyResolver
80
+ /**
81
+ * Resolve a local workspace id to the repository root a git run bundles.
82
+ *
83
+ * The engine holds no workspace face of its own (this package reaches the
84
+ * deployment only through `taskBoard` and `dshSsh`), so the mount supplies the
85
+ * lookup. Absent means a run pinned to a local workspace fails with the
86
+ * strategy's own "repository was not resolved" refusal instead of guessing a
87
+ * path.
88
+ */
89
+ localRepository?: (workspaceId: string) => string | undefined
90
+ /** Clock (ms epoch). */
91
+ now?: () => number
92
+ /** Identifier source for request ids. */
93
+ uuid?: () => string
94
+ /** Poll cadence, in milliseconds. */
95
+ pollIntervalMs?: number
96
+ /** Ceiling for one remote command, in milliseconds. */
97
+ commandTimeoutMs?: number
98
+ /** Where a refusal or a failed remote call is reported. */
99
+ log?: (message: string, detail?: unknown) => void
100
+ }
101
+
102
+ /** One run this process is following. */
103
+ interface SshJob {
104
+ /** Card the run belongs to. */
105
+ taskId: string
106
+ /** Run identifier the remote launcher is idempotent on. */
107
+ runId: string
108
+ /** Host the run addresses. */
109
+ alias: string
110
+ /** Target pinned when the run started (immutable for the life of this run). */
111
+ target: SshTarget
112
+ /** Worktree run id this run owns (reused from an earlier run on git follow-up/rework). */
113
+ workspaceRunId: string
114
+ /** Cancellation signal wired into workspace preparation and checked around remote start. */
115
+ abort: AbortController
116
+ /** Consecutive polls that produced no usable answer. */
117
+ failures: number
118
+ /** Whether this run carries a follow-up the agent could not be resumed for. */
119
+ degraded: boolean
120
+ /**
121
+ * Whether this process is still preparing the run's remote side.
122
+ *
123
+ * The job is registered and the card enters the running column before the
124
+ * remote directory exists, because a concurrent admission must see the slot
125
+ * taken. A poll that lands in that window reads "no such run" from a host
126
+ * whose directory has not been written yet, which is not a lost run: the
127
+ * start owns the verdict until it has an answer of its own.
128
+ */
129
+ starting: boolean
130
+ }
131
+
132
+ /** Remote runs and git target remembered per card so card deletion cleans up everything. */
133
+ interface KnownTaskRuns {
134
+ alias: string
135
+ target?: SshTarget
136
+ runIds: Set<string>
137
+ }
138
+
139
+ /** A reply to a card action or a tool call: a value the caller can act on, never a throw. */
140
+ export type SshEngineReply =
141
+ | { ok: true; taskId: string; runId?: string; phase?: SshRunPhase; message?: string }
142
+ | { ok: false; code: string; error: string }
143
+
144
+ /** One card's remote-run state, as a card surface or a model reads it. */
145
+ export interface SshRunStatusView {
146
+ /** Card the view is about. */
147
+ taskId: string
148
+ /** Target the card pins, when it pins one. */
149
+ target?: SshTarget
150
+ /** Phase of the run in flight. */
151
+ phase?: SshRunPhase
152
+ /** Run in flight. */
153
+ runId?: string
154
+ /** Remote exit code, once the run settled. */
155
+ exitCode?: number
156
+ /** Bytes of the run's log the remote launcher reported. */
157
+ bytes?: number
158
+ /** Follow-up messages delivered into that run's session. */
159
+ followUps?: number
160
+ /** Session the run reported, usable to resume it. */
161
+ sessionId?: string
162
+ /** Summary the agent reported. */
163
+ summary?: string
164
+ /** Failure text, when the run failed. */
165
+ error?: string
166
+ /** Runs of this card that already settled, newest last. */
167
+ history: SshRunRecord[]
168
+ /** Whether an instruction waits for the next run. */
169
+ pending?: 'follow-up' | 'rework'
170
+ }
171
+
172
+ /** One page of a run's log. */
173
+ export type SshLogPage =
174
+ | { ok: true; taskId: string; runId: string; offset: number; nextOffset: number; bytes: number; eof: boolean; text: string }
175
+ | { ok: false; code: string; error: string }
176
+
177
+ /** Bound one free-text field to the ledger's stored budget. */
178
+ function bound(text: string, max: number): string {
179
+ return text.length <= max ? text : text.slice(0, max)
180
+ }
181
+
182
+ /** Keep the tail of a log, which is where an agent's final event is. */
183
+ function parseWindow(text: string): string {
184
+ return text.length <= PARSE_WINDOW ? text : text.slice(text.length - PARSE_WINDOW)
185
+ }
186
+
187
+ /**
188
+ * The command templates a target's agent runs with.
189
+ *
190
+ * A deployment's override wins over everything, because it exists precisely to
191
+ * replace what this package would otherwise run. A custom agent carries its own
192
+ * templates on the target; the three built-in CLIs have none.
193
+ * @param agent - the agent the target pins.
194
+ * @param settings - live configuration.
195
+ * @returns the templates, or undefined when the built-in command line applies.
196
+ */
197
+ export function agentTemplates(agent: SshAgentTarget, settings: SshProviderSettings): SshCustomTemplates | undefined {
198
+ const override = settings.agentCommands[agent.kind]
199
+ if (override !== undefined) return override
200
+ if (agent.kind !== 'custom' || agent.command === undefined) return undefined
201
+ return { command: agent.command, ...(agent.resumeCommand === undefined ? {} : { resumeCommand: agent.resumeCommand }) }
202
+ }
203
+
204
+ /**
205
+ * Whether one agent can continue an earlier session.
206
+ * @param kind - agent CLI kind.
207
+ * @param templates - the templates it runs with, when it has any.
208
+ * @returns true when a follow-up can resume instead of starting fresh.
209
+ */
210
+ export function agentResumeSupported(kind: SshAgentKind, templates: SshCustomTemplates | undefined): boolean {
211
+ if (templates !== undefined) return customResumeSupported(templates)
212
+ return kind !== 'custom'
213
+ }
214
+
215
+ /**
216
+ * The command line one run executes.
217
+ *
218
+ * A template — a custom agent's own, or a deployment's override for one of the
219
+ * built-in CLIs — replaces the built-in command line entirely, because that is
220
+ * what an override is for: the operator's own words, quoted by the template
221
+ * builder. Without one the agent's own adapter answers.
222
+ * @param input - run facts, including the session to resume when there is one.
223
+ * @param templates - the templates this run executes with, when it has any.
224
+ * @returns the quoted command line.
225
+ */
226
+ export function agentCommandLine(input: SshAgentRunInput, templates: SshCustomTemplates | undefined): SshAgentCommand {
227
+ return templates === undefined ? buildAgentCommandLine(input) : customAgentCommand(input, templates)
228
+ }
229
+
230
+ export class SshRunEngine {
231
+ private readonly host: TaskBoardExtensionHost
232
+ private readonly ssh: DshSshService
233
+ private readonly timers: HostTimerFace
234
+ private readonly settings: () => SshProviderSettings
235
+ private readonly seat: (() => BoardActionSeat | undefined) | undefined
236
+ private readonly workspaces: SshWorkspaceStrategyResolver | undefined
237
+ private readonly localRepository: ((workspaceId: string) => string | undefined) | undefined
238
+ private readonly now: () => number
239
+ private readonly uuid: () => string
240
+ private readonly pollIntervalMs: number
241
+ private readonly log: (message: string, detail?: unknown) => void
242
+ private readonly remote: SshRemote
243
+ /** Runs this process follows, keyed by card id: a card has at most one. */
244
+ private readonly jobs = new Map<string, SshJob>()
245
+ /** Known runs per card (including pre-restart history), so card deletion cleans up all remote dirs/worktrees. */
246
+ private readonly known = new Map<string, KnownTaskRuns>()
247
+ /** Hosts whose admission pass is already running. */
248
+ private readonly pumping = new Set<string>()
249
+ /** Hosts that asked for another admission pass while one was running. */
250
+ private readonly pumpAgain = new Set<string>()
251
+ /** Cards whose settlement is in progress, so a board echo does not read as a cancel. */
252
+ private readonly settling = new Set<string>()
253
+ /** Runs a person asked to cancel, so their settlement writes no verdict. */
254
+ private readonly cancelRequests = new Set<string>()
255
+ /** The log windows this extension publishes; in memory, never in a payload. */
256
+ private readonly logs = new SshLogWindows()
257
+ /**
258
+ * Local files one live run did not receive, keyed by card id.
259
+ *
260
+ * A workspace detail, not a run fact: the frozen run record has no member for
261
+ * it and the ledger keeps the account of runs, so it is carried here from the
262
+ * moment the workspace is prepared until the verdict is written. A Host that
263
+ * restarts mid-run no longer knows it, and that run's verdict then says only
264
+ * what the agent itself reported.
265
+ */
266
+ private readonly untracked = new Map<string, { runId: string; files: number }>()
267
+ private readonly disposers: Array<() => void> = []
268
+ private pollCanceller: (() => void) | undefined
269
+ private polling = false
270
+ private disposed = false
271
+
272
+ constructor(options: SshRunEngineOptions) {
273
+ this.host = options.host
274
+ this.ssh = options.ssh
275
+ this.timers = options.timers
276
+ this.settings = options.settings
277
+ this.seat = options.seat
278
+ this.workspaces = options.workspaces
279
+ this.localRepository = options.localRepository
280
+ this.now = options.now ?? (() => Date.now())
281
+ this.uuid = options.uuid ?? (() => crypto.randomUUID())
282
+ this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS
283
+ this.log = options.log ?? ((message, detail) => {
284
+ if (detail === undefined) console.error('[dsh-task-board-ssh] ' + message)
285
+ else console.error('[dsh-task-board-ssh] ' + message, detail)
286
+ })
287
+ this.remote = new SshRemote(options.ssh, {
288
+ ...(options.commandTimeoutMs === undefined ? {} : { timeoutMs: options.commandTimeoutMs }),
289
+ })
290
+ }
291
+
292
+ /** Whether the extension is on. Read at use time, so a settings edit binds the next call. */
293
+ enabled(): boolean {
294
+ return this.settings().enabled
295
+ }
296
+
297
+ /**
298
+ * Take over every launch the board routes to this extension, follow board
299
+ * events, and reconcile what the previous process left in flight.
300
+ */
301
+ start(): void {
302
+ if (this.disposed) return
303
+ const launch = this.host.launch
304
+ if (launch === undefined) {
305
+ this.log('this board revision serves no launch interception, so a remote card cannot start; the tools still answer')
306
+ } else {
307
+ try {
308
+ this.disposers.push(launch.intercept((task, context) => this.intercept(task, context)))
309
+ } catch (error) {
310
+ this.log('the launch handler could not be registered', error)
311
+ }
312
+ }
313
+ this.disposers.push(this.host.events.onStatusChanged(event => { void this.onStatusChanged(event) }))
314
+ this.disposers.push(this.host.events.onTaskDeleted(event => { void this.onTaskDeleted(event) }))
315
+ this.pollCanceller = this.timers.interval(() => { void this.poll() }, this.pollIntervalMs)
316
+ void this.reconcile().catch(error => { this.log('the reconciliation pass failed', error) })
317
+ }
318
+
319
+ /** Stop polling and forget what this process was following. No card data is touched. */
320
+ stop(): void {
321
+ this.disposed = true
322
+ this.pollCanceller?.()
323
+ this.pollCanceller = undefined
324
+ for (const dispose of this.disposers.splice(0)) {
325
+ try { dispose() } catch { /* best-effort */ }
326
+ }
327
+ for (const job of this.jobs.values()) job.abort.abort()
328
+ this.jobs.clear()
329
+ this.known.clear()
330
+ this.pumping.clear()
331
+ this.pumpAgain.clear()
332
+ this.settling.clear()
333
+ this.untracked.clear()
334
+ this.logs.clear()
335
+ this.remote.forget()
336
+ }
337
+
338
+ /**
339
+ * React to a volatile settings update (for example raising `perHostCap` or
340
+ * changing defaults): pump every host with waiting runs and publish the new summary.
341
+ */
342
+ onSettingsUpdated(): void {
343
+ if (this.disposed || !this.enabled()) return
344
+ for (const alias of this.aliasesInFlight()) {
345
+ void this.pump(alias).catch(error => { this.log(`admission pump after settings update failed for ${alias}`, error) })
346
+ }
347
+ this.publishSummary()
348
+ }
349
+
350
+ /** The hosts this deployment can pin a card to; every field of one is secret-free. */
351
+ hosts(): DshSshHost[] {
352
+ try {
353
+ return this.ssh.hosts.list()
354
+ } catch (error) {
355
+ this.log('the host inventory could not be read', error)
356
+ return []
357
+ }
358
+ }
359
+
360
+ /** Resolve one host by alias, or undefined when it is not configured. */
361
+ hostByAlias(alias: string): DshSshHost | undefined {
362
+ try {
363
+ return this.ssh.hosts.find(alias)
364
+ } catch {
365
+ return undefined
366
+ }
367
+ }
368
+
369
+ /** The card's payload, as this package reads it. */
370
+ payloadOf(taskId: string): HostSshPayload | undefined {
371
+ try {
372
+ return readHostPayload(this.host.integration.read(taskId))
373
+ } catch {
374
+ return undefined
375
+ }
376
+ }
377
+
378
+ /** The target a card pins, when it pins one. */
379
+ targetOf(taskId: string): SshTarget | undefined {
380
+ return this.payloadOf(taskId)?.target
381
+ }
382
+
383
+ /** One card's remote-run state. */
384
+ status(taskId: string): SshRunStatusView {
385
+ const payload = this.payloadOf(taskId)
386
+ const view: SshRunStatusView = { taskId, history: payload?.history ?? [] }
387
+ if (payload === undefined) return view
388
+ if (payload.target !== undefined) view.target = payload.target
389
+ if (payload.pending !== undefined) view.pending = payload.pending.kind
390
+ const run = payload.activeRun
391
+ if (run === undefined) return view
392
+ view.phase = run.phase
393
+ view.runId = run.runId
394
+ if (run.exitCode !== undefined) view.exitCode = run.exitCode
395
+ if (run.bytes !== undefined) view.bytes = run.bytes
396
+ if (run.followUps !== undefined) view.followUps = run.followUps
397
+ if (run.sessionId !== undefined) view.sessionId = run.sessionId
398
+ if (run.summary !== undefined) view.summary = run.summary
399
+ if (run.error !== undefined) view.error = run.error
400
+ return view
401
+ }
402
+
403
+ /**
404
+ * Pin (or replace) the target one card runs with.
405
+ *
406
+ * A target naming a host this deployment does not know is refused here instead
407
+ * of failing the card much later with a connection error nobody can place.
408
+ * @param taskId - card to retarget.
409
+ * @param target - the target to pin.
410
+ * @returns the reply the caller renders.
411
+ */
412
+ setTarget(taskId: string, target: SshTarget): SshEngineReply {
413
+ const task = this.host.tasks.get(taskId)
414
+ if (task === undefined) return { ok: false, code: 'task-not-found', error: `no task with id ${taskId}` }
415
+ if (task.archivedAt !== undefined) return { ok: false, code: 'task-archived', error: `task ${taskId} is archived` }
416
+ if (this.hostByAlias(target.host) === undefined) {
417
+ return { ok: false, code: 'host-not-configured', error: `dsh-ssh has no host with alias "${target.host}"` }
418
+ }
419
+ const payload = this.payloadOf(taskId)
420
+ if (payload !== undefined && liveRunOf(payload) !== undefined) {
421
+ return { ok: false, code: 'run-active', error: `cannot change the SSH target of task ${taskId} while a run is queued or running` }
422
+ }
423
+ const next: HostSshPayload = payload === undefined
424
+ ? { updatedAt: this.now(), history: [], target }
425
+ : { ...payload, target }
426
+ if (!this.writePayload(taskId, next)) {
427
+ return { ok: false, code: 'payload-refused', error: 'the board refused the target' }
428
+ }
429
+ this.publishSummary()
430
+ return { ok: true, taskId, message: 'target pinned' }
431
+ }
432
+
433
+ /**
434
+ * Start a card's pinned run now, through the board's own run action so the
435
+ * card reaches the running column the same way the run button puts it there.
436
+ * @param taskId - card to run.
437
+ * @returns the reply the caller renders.
438
+ */
439
+ runNow(taskId: string): SshEngineReply {
440
+ const target = this.targetOf(taskId)
441
+ if (target === undefined) return { ok: false, code: 'no-target', error: `task ${taskId} pins no SSH target` }
442
+ if (target.mode !== 'direct') {
443
+ return { ok: false, code: 'proxy-mode', error: 'a proxy card runs in a local session: start it from the board, not from this tool' }
444
+ }
445
+ const seat = this.seat?.()
446
+ if (seat === undefined) return { ok: false, code: 'board-unavailable', error: 'this board revision serves no action applier' }
447
+ try {
448
+ seat.apply(this.uuid(), { kind: 'run', taskId }, 'ssh')
449
+ } catch (error) {
450
+ return { ok: false, code: 'run-refused', error: error instanceof Error ? error.message : String(error) }
451
+ }
452
+ return { ok: true, taskId, message: 'run requested' }
453
+ }
454
+
455
+ /**
456
+ * Queue one instruction for the card, and drive it into a run.
457
+ *
458
+ * While a run is in flight the instruction waits for the run to settle (there
459
+ * is no channel into a detached remote process). On a settled card it re-enters
460
+ * the launch interceptor through the board's own rerun action, which is what
461
+ * puts the card back in the running column and lets the adapter choose between
462
+ * continuing the session and starting fresh.
463
+ * @param taskId - card to instruct.
464
+ * @param text - the instruction.
465
+ * @param kind - which entry asked.
466
+ * @returns the reply the caller renders.
467
+ */
468
+ async instruct(taskId: string, text: string, kind: 'follow-up' | 'rework'): Promise<SshEngineReply> {
469
+ const task = this.host.tasks.get(taskId)
470
+ if (task === undefined) return { ok: false, code: 'task-not-found', error: `no task with id ${taskId}` }
471
+ if (task.archivedAt !== undefined) return { ok: false, code: 'task-archived', error: `task ${taskId} is archived` }
472
+ const payload = this.payloadOf(taskId)
473
+ if (payload === undefined || payload.target === undefined) {
474
+ return { ok: false, code: 'no-target', error: `task ${taskId} pins no SSH target` }
475
+ }
476
+ if (payload.target.mode !== 'direct') {
477
+ return { ok: false, code: 'proxy-mode', error: 'a proxy card runs in a local session: send follow-ups to that session instead' }
478
+ }
479
+ const trimmed = text.trim()
480
+ if (trimmed === '') return { ok: false, code: 'empty-instruction', error: 'an instruction must not be blank' }
481
+ if (payload.pending !== undefined) {
482
+ return { ok: false, code: 'instruction-already-queued', error: 'an instruction is already queued for this card' }
483
+ }
484
+ const live = liveRunOf(payload)
485
+ // Only snapshot `resumeSessionId` when starting immediately on a settled
486
+ // card; while a run is in flight, leave it unset so `startRun` resolves
487
+ // the fresh session id the in-flight run emits upon settling.
488
+ const previous = live === undefined ? latestSessionId(payload) : undefined
489
+ const pending: SshPendingInstruction = {
490
+ kind,
491
+ text: trimmed,
492
+ queuedAt: this.now(),
493
+ ...(previous === undefined ? {} : { resumeSessionId: previous }),
494
+ }
495
+ const next: HostSshPayload = live === undefined
496
+ ? { ...payload, pending }
497
+ : { ...payload, pending, activeRun: { ...live, followUps: (live.followUps ?? 0) + 1 } }
498
+ if (!this.writePayload(taskId, next)) {
499
+ return { ok: false, code: 'payload-refused', error: 'the board refused the queued instruction' }
500
+ }
501
+ if (live !== undefined) {
502
+ this.publishSummary()
503
+ return { ok: true, taskId, runId: live.runId, phase: live.phase, message: 'queued behind the run in flight' }
504
+ }
505
+ const reentered = this.reenter(taskId, 'ssh-' + kind)
506
+ if (!reentered.ok) {
507
+ // Roll back the queued instruction so a refused rerun never silently
508
+ // hijacks a future regular run of this card.
509
+ const latest = this.payloadOf(taskId)
510
+ if (latest !== undefined && latest.pending?.queuedAt === pending.queuedAt) {
511
+ const rolledBack: HostSshPayload = { ...latest }
512
+ delete rolledBack.pending
513
+ this.writePayload(taskId, rolledBack)
514
+ }
515
+ return reentered
516
+ }
517
+ return { ok: true, taskId, message: kind === 'rework' ? 'rework requested' : 'follow-up requested' }
518
+ }
519
+
520
+ /**
521
+ * Cancel the card's active run and write no verdict.
522
+ * @param taskId - card whose run to stop.
523
+ * @returns the reply the caller renders.
524
+ */
525
+ cancel(taskId: string): SshEngineReply {
526
+ const payload = this.payloadOf(taskId)
527
+ const run = payload?.activeRun
528
+ const target = payload?.target
529
+ if (payload === undefined || run === undefined || target === undefined) {
530
+ return { ok: false, code: 'no-run', error: `task ${taskId} has no remote run` }
531
+ }
532
+ if (isTerminalRunPhase(run.phase)) return { ok: false, code: 'no-run', error: `the run of task ${taskId} already settled` }
533
+ // A run stopped from the card surface leaves the card where it can be
534
+ // picked up again, which is the same place a card dragged out of the running
535
+ // column lands: the todo column, with no verdict written.
536
+ void this.stopRun(taskId, payload, target, run, { restore: true }).catch(error => { this.log('the cancel request failed', error) })
537
+ return { ok: true, taskId, runId: run.runId, phase: 'cancelled', message: 'cancel requested' }
538
+ }
539
+
540
+ /**
541
+ * Re-read remote state now instead of waiting for the next tick.
542
+ * @param taskId - one card, or undefined for every card this mount follows.
543
+ * @returns the reply the caller renders.
544
+ */
545
+ async refresh(taskId?: string, runId?: string, offset?: number): Promise<SshEngineReply> {
546
+ if (runId !== undefined && taskId === undefined) {
547
+ return { ok: false, code: 'task-required', error: 'a run is named inside its card: pass the taskId with the runId' }
548
+ }
549
+ if (taskId !== undefined) {
550
+ if (runId !== undefined && findRun(this.payloadOf(taskId), runId) === undefined) {
551
+ return { ok: false, code: 'unknown-run', error: `task ${taskId} has no run ${runId}` }
552
+ }
553
+ // A viewer that just opened (or reopened) asks for this card, and can
554
+ // also page forward through settled logs past the 8 KiB window budget by
555
+ // passing `offset`.
556
+ await this.replayLog(taskId, runId, offset ?? 0)
557
+ const job = this.jobs.get(taskId)
558
+ if (offset === undefined && job !== undefined && !this.polling && !this.settling.has(taskId)) {
559
+ await this.pollJob(job)
560
+ }
561
+ this.publishSummary()
562
+ return { ok: true, taskId, message: 'refreshed' }
563
+ }
564
+ await this.poll()
565
+ for (const alias of this.aliasesInFlight()) await this.pump(alias)
566
+ this.publishSummary()
567
+ return { ok: true, taskId: '', message: 'refreshed every followed card' }
568
+ }
569
+
570
+ /**
571
+ * Re-read one bounded page of one card's log from `offset` into the pending window.
572
+ * @param taskId - card whose run log to replay.
573
+ * @param runId - a specific run, when the viewer named one.
574
+ * @param offset - byte offset to replay from (defaults to 0).
575
+ */
576
+ private async replayLog(taskId: string, runId?: string, offset = 0): Promise<void> {
577
+ const payload = this.payloadOf(taskId)
578
+ const target = payload?.target
579
+ if (payload === undefined || target === undefined) return
580
+ const run = (runId === undefined ? undefined : findRun(payload, runId))
581
+ ?? payload.activeRun
582
+ ?? payload.history[payload.history.length - 1]
583
+ if (run === undefined) return
584
+ try {
585
+ const stateDir = await this.remote.stateDir(target.host)
586
+ const page = await this.remote.tail({ alias: target.host, stateDir, runId: run.runId }, offset, LOG_WINDOW_BUDGET_BYTES + 1)
587
+ const hasMore = byteLength(page.text) > LOG_WINDOW_BUDGET_BYTES
588
+ this.logs.replay(taskId, run.runId, offset, page.text, hasMore)
589
+ } catch (error) {
590
+ this.log(`the log of run ${run.runId} could not be replayed`, error)
591
+ }
592
+ }
593
+
594
+ /**
595
+ * Read one page of a run's log.
596
+ *
597
+ * The log is a remote file read by byte offset, never a stored payload: the
598
+ * ledger keeps the account of a run, not its bytes.
599
+ * @param taskId - card whose run's log to read.
600
+ * @param options - run to read (defaults to the active one), offset and page size.
601
+ * @returns the page, or the refusal that says why there is none.
602
+ */
603
+ async readLog(taskId: string, options: { runId?: string; offset?: number; limit?: number } = {}): Promise<SshLogPage> {
604
+ const payload = this.payloadOf(taskId)
605
+ const target = payload?.target
606
+ if (payload === undefined || target === undefined) {
607
+ return { ok: false, code: 'no-target', error: `task ${taskId} pins no SSH target` }
608
+ }
609
+ if (options.runId !== undefined && findRun(payload, options.runId) === undefined) {
610
+ return { ok: false, code: 'unknown-run', error: `task ${taskId} has no run ${options.runId}` }
611
+ }
612
+ const runId = options.runId
613
+ ?? payload.activeRun?.runId
614
+ ?? payload.history[payload.history.length - 1]?.runId
615
+ if (runId === undefined) return { ok: false, code: 'no-run', error: `task ${taskId} has never run remotely` }
616
+ const offset = options.offset !== undefined && Number.isFinite(options.offset) && options.offset >= 0
617
+ ? Math.trunc(options.offset)
618
+ : 0
619
+ const limit = options.limit !== undefined && Number.isFinite(options.limit) && options.limit > 0
620
+ ? Math.min(Math.trunc(options.limit), 128 * 1024)
621
+ : 64 * 1024
622
+ try {
623
+ const stateDir = await this.remote.stateDir(target.host)
624
+ const page = await this.remote.tail({ alias: target.host, stateDir, runId }, offset, limit + 1)
625
+ const taken = takeWithinBudget(page.text, limit)
626
+ const bytes = offset + taken.bytes
627
+ return {
628
+ ok: true,
629
+ taskId,
630
+ runId,
631
+ offset,
632
+ nextOffset: bytes,
633
+ bytes,
634
+ eof: byteLength(page.text) <= limit,
635
+ text: taken.text,
636
+ }
637
+ } catch (error) {
638
+ return { ok: false, code: 'log-unavailable', error: error instanceof Error ? error.message : String(error) }
639
+ }
640
+ }
641
+
642
+ /** The document this extension publishes into the board snapshot. */
643
+ summary(): Record<string, unknown> {
644
+ return this.buildSummary().document
645
+ }
646
+
647
+ /**
648
+ * Build the published document and the log windows it carries.
649
+ *
650
+ * The window section is the one unbounded part of this document, so it is
651
+ * bounded here: SshLogWindows caps one card's window and the section as a
652
+ * whole, and a document that still came out over the body budget drops the
653
+ * section (every window then waits for the next publish rather than being
654
+ * lost or overrunning the board's ceiling).
655
+ * @returns the document and the cards whose window it delivered.
656
+ */
657
+ private buildSummary(): { document: Record<string, unknown>; delivered: string[] } {
658
+ const settings = this.settings()
659
+ let running = 0
660
+ let queued = 0
661
+ let targets = 0
662
+ const runs: Array<Record<string, unknown>> = []
663
+ let linked: readonly { task: TaskRecord; payload: Record<string, unknown> }[] = []
664
+ try {
665
+ linked = this.host.tasks.linked() as readonly { task: TaskRecord; payload: Record<string, unknown> }[]
666
+ } catch {
667
+ linked = []
668
+ }
669
+ for (const entry of linked) {
670
+ const payload = readHostPayload(entry.payload)
671
+ if (payload?.target === undefined) continue
672
+ targets += 1
673
+ const run = payload.activeRun
674
+ if (run?.phase === 'running') running += 1
675
+ if (run?.phase === 'queued') queued += 1
676
+ if (run !== undefined && runs.length < 20) {
677
+ const untracked = this.untracked.get(entry.task.id)
678
+ const files = untracked !== undefined && untracked.runId === run.runId ? untracked.files : undefined
679
+ runs.push({
680
+ taskId: entry.task.id,
681
+ runId: run.runId,
682
+ phase: run.phase,
683
+ host: payload.target.host,
684
+ ...(run.bytes === undefined ? {} : { bytes: run.bytes }),
685
+ ...(files === undefined ? {} : { untrackedFiles: files }),
686
+ })
687
+ }
688
+ }
689
+ const delivery = this.logs.take()
690
+ const document: Record<string, unknown> = {
691
+ defaults: {
692
+ host: settings.defaultHost,
693
+ agent: settings.defaultAgent,
694
+ mode: settings.defaultMode,
695
+ perHostCap: settings.perHostCap,
696
+ },
697
+ targets,
698
+ running,
699
+ queued,
700
+ runs,
701
+ hosts: this.hosts().slice(0, 50).map(host => ({ alias: host.alias, host: host.host, user: host.user })),
702
+ ...(Object.keys(delivery.logs).length === 0 ? {} : { logs: delivery.logs }),
703
+ }
704
+ if (byteLength(JSON.stringify(document)) > PUBLISH_BODY_LIMIT_BYTES) {
705
+ delete document.logs
706
+ return { document, delivered: [] }
707
+ }
708
+ return { document, delivered: delivery.delivered }
709
+ }
710
+
711
+ // --- launch interception -----------------------------------------------------
712
+
713
+ /**
714
+ * The board's launch gate for one card.
715
+ *
716
+ * Synchronous by contract: the run it opens is recorded here and started on
717
+ * the next microtask, because the ledger commits the running column after this
718
+ * handler returns and a payload write made inside it would be overwritten.
719
+ */
720
+ private intercept(task: TaskRecord, _context: TaskBoardLaunchContext): TaskBoardLaunchDecision | undefined {
721
+ if (this.disposed || !this.enabled()) return undefined
722
+ const payload = readHostPayload(task.integrations?.[SSH_INTEGRATION_KEY])
723
+ const target = payload?.target
724
+ if (payload === undefined || target === undefined) return undefined
725
+ const seat = this.seat?.()
726
+ if (target.mode === 'proxy') return { kind: 'local', promptPreamble: proxyPreamble(task, target) }
727
+ if (this.host.launch === undefined || seat === undefined) {
728
+ // Fail closed: never return `undefined` (which would silently launch a
729
+ // remote-pinned direct card as a local session on this machine).
730
+ this.log(`task ${task.id} pins a remote host but this board revision serves no launch interception or action applier, so it cannot run remotely`)
731
+ return { kind: 'external' }
732
+ }
733
+ void this.openRun(task.id, target.host).catch(error => { this.log(`the remote run of task ${task.id} could not be opened`, error) })
734
+ return { kind: 'external' }
735
+ }
736
+
737
+ /** Queue one run for a card the board just decided to hand over. */
738
+ private async openRun(taskId: string, alias: string): Promise<void> {
739
+ // The ledger commits the running column after the handler returns: writing
740
+ // the payload before that commit would be overwritten by it.
741
+ await Promise.resolve()
742
+ if (this.disposed) return
743
+ const task = this.host.tasks.get(taskId)
744
+ if (task === undefined || task.archivedAt !== undefined || task.status !== 'running') return
745
+ const payload = this.payloadOf(taskId)
746
+ if (payload?.target === undefined) return
747
+ const live = liveRunOf(payload)
748
+ if (live !== undefined) return
749
+ const run: SshRunRecord = { runId: this.newRunId(), phase: 'queued', startedAt: this.now() }
750
+ this.rememberRun(taskId, alias, run.runId, payload.target)
751
+ if (!this.writePayload(taskId, { ...payload, activeRun: run })) return
752
+ await this.pump(alias)
753
+ this.publishSummary()
754
+ }
755
+
756
+ /** Record a run id against a card so card deletion cleans up every remote artifact. */
757
+ private rememberRun(taskId: string, alias: string, runId: string, target?: SshTarget): void {
758
+ const existing = this.known.get(taskId)
759
+ if (existing !== undefined) {
760
+ existing.alias = alias
761
+ if (target !== undefined) existing.target = target
762
+ existing.runIds.add(runId)
763
+ return
764
+ }
765
+ this.known.set(taskId, {
766
+ alias,
767
+ ...(target === undefined ? {} : { target }),
768
+ runIds: new Set([runId]),
769
+ })
770
+ }
771
+
772
+ /** Previous git worktree run id to reuse for a follow-up / rework, when available. */
773
+ private priorWorktreeRunId(payload: HostSshPayload): string | undefined {
774
+ for (let index = payload.history.length - 1; index >= 0; index -= 1) {
775
+ const record = payload.history[index]
776
+ if (record === undefined) continue
777
+ if (record.branch !== undefined && record.branch.startsWith('dsh-task/')) {
778
+ return record.branch.slice('dsh-task/'.length)
779
+ }
780
+ if (record.phase === 'succeeded' || record.phase === 'failed') {
781
+ return record.runId
782
+ }
783
+ }
784
+ return undefined
785
+ }
786
+
787
+ // --- admission ---------------------------------------------------------------
788
+
789
+ /** The aliases this mount currently has work for. */
790
+ private aliasesInFlight(): string[] {
791
+ const aliases = new Set<string>()
792
+ for (const entry of this.linkedEntries()) {
793
+ const target = entry.payload?.target
794
+ if (target === undefined) continue
795
+ if (liveRunOf(entry.payload as HostSshPayload) === undefined) continue
796
+ aliases.add(target.host)
797
+ }
798
+ return [...aliases]
799
+ }
800
+
801
+ /** Every linked card with the payload this package understands. */
802
+ private linkedEntries(): Array<{ task: TaskRecord; payload: HostSshPayload | undefined }> {
803
+ let linked: readonly { task: TaskRecord; payload: Record<string, unknown> }[] = []
804
+ try {
805
+ linked = this.host.tasks.linked() as readonly { task: TaskRecord; payload: Record<string, unknown> }[]
806
+ } catch (error) {
807
+ this.log('the linked cards could not be read', error)
808
+ return []
809
+ }
810
+ return linked.map(entry => ({ task: entry.task, payload: readHostPayload(entry.payload) }))
811
+ }
812
+
813
+ /** Admit queued runs on one host until its ceiling is reached. */
814
+ private async pump(alias: string): Promise<void> {
815
+ if (this.disposed || !this.enabled()) return
816
+ if (this.pumping.has(alias)) {
817
+ this.pumpAgain.add(alias)
818
+ return
819
+ }
820
+ this.pumping.add(alias)
821
+ try {
822
+ do {
823
+ this.pumpAgain.delete(alias)
824
+ await this.admit(alias)
825
+ } while (this.pumpAgain.has(alias) && !this.disposed)
826
+ } finally {
827
+ this.pumping.delete(alias)
828
+ }
829
+ }
830
+
831
+ /** One admission pass over one host. */
832
+ private async admit(alias: string): Promise<void> {
833
+ const cap = this.settings().perHostCap
834
+ const queued: SshQueueEntry[] = []
835
+ let running = 0
836
+ for (const entry of this.linkedEntries()) {
837
+ const target = entry.payload?.target
838
+ const run = entry.payload?.activeRun
839
+ if (target === undefined || run === undefined || target.host !== alias) continue
840
+ this.rememberRun(entry.task.id, alias, run.runId, target)
841
+ if (run.phase === 'running') {
842
+ running += 1
843
+ this.logs.adopt(entry.task.id, run.runId, run.bytes ?? 0)
844
+ if (!this.jobs.has(entry.task.id)) {
845
+ this.jobs.set(entry.task.id, {
846
+ taskId: entry.task.id,
847
+ runId: run.runId,
848
+ alias,
849
+ target,
850
+ workspaceRunId: run.runId,
851
+ abort: new AbortController(),
852
+ failures: 0,
853
+ degraded: false,
854
+ starting: false,
855
+ })
856
+ }
857
+ continue
858
+ }
859
+ if (run.phase === 'queued') queued.push({ taskId: entry.task.id, runId: run.runId, startedAt: run.startedAt })
860
+ }
861
+ const admission = admitRuns(queued, running, cap)
862
+ for (const entry of admission.start) {
863
+ void this.startRun(alias, entry.taskId, entry.runId).catch(error => {
864
+ this.log(`the run ${entry.runId} of task ${entry.taskId} could not be started`, error)
865
+ })
866
+ }
867
+ }
868
+
869
+ /** Prepare and start one admitted run. */
870
+ private async startRun(alias: string, taskId: string, runId: string): Promise<void> {
871
+ if (this.disposed || !this.enabled()) return
872
+ const task = this.host.tasks.get(taskId)
873
+ const payload = this.payloadOf(taskId)
874
+ const run = payload?.activeRun
875
+ const target = payload?.target
876
+ if (task === undefined || task.archivedAt !== undefined || task.status !== 'running') return
877
+ if (payload === undefined || run === undefined || target === undefined) return
878
+ if (run.runId !== runId || run.phase !== 'queued') return
879
+ const settings = this.settings()
880
+ const pending = payload.pending
881
+ const reusedWorktree = pending !== undefined && target.workspace.kind === 'git'
882
+ ? this.priorWorktreeRunId(payload)
883
+ : undefined
884
+ const workspaceRunId = reusedWorktree ?? runId
885
+ const abort = new AbortController()
886
+ const job: SshJob = {
887
+ taskId,
888
+ runId,
889
+ alias,
890
+ target,
891
+ workspaceRunId,
892
+ abort,
893
+ failures: 0,
894
+ degraded: false,
895
+ starting: true,
896
+ }
897
+ this.jobs.set(taskId, job)
898
+ this.rememberRun(taskId, alias, runId, target)
899
+ this.logs.adopt(taskId, runId, run.bytes ?? 0)
900
+ // The slot is taken before any remote work: a concurrent admission sees a
901
+ // running run instead of starting the same card twice.
902
+ this.writePayload(taskId, withActiveRun(payload, { ...run, phase: 'running' }))
903
+ const templates = agentTemplates(target.agent, settings)
904
+ const resumeSession = pending === undefined ? undefined : pending.resumeSessionId ?? latestSessionId(payload)
905
+ const resumed = pending !== undefined && resumeSession !== undefined && agentResumeSupported(target.agent.kind, templates)
906
+ job.degraded = pending !== undefined && !resumed
907
+ const isCancelledOrSuperseded = (): boolean => (
908
+ this.disposed
909
+ || abort.signal.aborted
910
+ || this.cancelRequested(alias, runId)
911
+ || this.payloadOf(taskId)?.activeRun?.runId !== runId
912
+ )
913
+ try {
914
+ const stateDir = await this.remote.stateDir(alias)
915
+ if (isCancelledOrSuperseded()) { this.jobs.delete(taskId); return }
916
+ await this.remote.installLauncher({ alias, stateDir })
917
+ if (isCancelledOrSuperseded()) { this.jobs.delete(taskId); return }
918
+ const prepared = await this.prepareWorkspace(target, runId, {
919
+ signal: abort.signal,
920
+ ...(reusedWorktree === undefined ? {} : { reuseWorktreeRunId: reusedWorktree }),
921
+ })
922
+ if (isCancelledOrSuperseded()) { this.jobs.delete(taskId); return }
923
+ if (prepared.untrackedFiles !== undefined) {
924
+ this.untracked.set(taskId, { runId, files: prepared.untrackedFiles })
925
+ }
926
+ const promptFile = runFilePath(stateDir, runId, 'prompt.txt')
927
+ const input: SshAgentRunInput = {
928
+ agent: target.agent.kind,
929
+ promptFile,
930
+ cwd: prepared.cwd,
931
+ ...(resumed && resumeSession !== undefined ? { resumeSessionId: resumeSession } : {}),
932
+ }
933
+ const command = agentCommandLine(input, templates)
934
+ const prompt = runPrompt(task, pending, this.previousSummary(payload), resumed)
935
+ await this.remote.writeRunFiles({ alias, stateDir, runId }, {
936
+ prompt,
937
+ command,
938
+ cwd: prepared.cwd,
939
+ spec: {
940
+ runId,
941
+ taskId,
942
+ host: alias,
943
+ mode: target.mode,
944
+ agent: target.agent.kind,
945
+ workspace: target.workspace.kind,
946
+ workspaceRunId,
947
+ resumed,
948
+ degraded: job.degraded,
949
+ startedAt: run.startedAt,
950
+ },
951
+ })
952
+ if (isCancelledOrSuperseded()) {
953
+ this.jobs.delete(taskId)
954
+ return
955
+ }
956
+ let status = await this.remote.start({ alias, stateDir, runId })
957
+ // From here the remote side owns the verdict: the run directory exists, so
958
+ // a poll's "no such run" is a real disappearance.
959
+ job.starting = false
960
+ if (isCancelledOrSuperseded()) {
961
+ // Cancel arrived right as `remote.start` launched the agent: terminate
962
+ // the newly spawned process immediately so no unattended orphan survives.
963
+ this.jobs.delete(taskId)
964
+ try {
965
+ await this.remote.cancel({ alias, stateDir, runId })
966
+ } catch (cancelError) {
967
+ this.log(`late cancel of run ${runId} on ${alias} failed`, cancelError)
968
+ }
969
+ return
970
+ }
971
+ if (status.state !== 'running' && status.state !== 'exited') {
972
+ try {
973
+ status = await this.remote.status({ alias, stateDir, runId })
974
+ } catch (error) {
975
+ this.log(`the state of run ${runId} could not be confirmed after an inconclusive start`, error)
976
+ }
977
+ }
978
+ const current = this.payloadOf(taskId)
979
+ if (isCancelledOrSuperseded() || current?.activeRun?.runId !== runId) {
980
+ this.jobs.delete(taskId)
981
+ try {
982
+ await this.remote.cancel({ alias, stateDir, runId })
983
+ } catch { /* best-effort */ }
984
+ return
985
+ }
986
+ if (status.state === 'running' || status.state === 'exited') {
987
+ this.writePayload(taskId, {
988
+ ...current,
989
+ activeRun: { ...(current.activeRun as SshRunRecord), phase: 'running', ...(status.bytes === undefined ? {} : { bytes: status.bytes }) },
990
+ pending: undefined,
991
+ })
992
+ } else {
993
+ await this.settle(taskId, job, status)
994
+ }
995
+ } catch (error) {
996
+ if (isCancelledOrSuperseded()) {
997
+ this.jobs.delete(taskId)
998
+ return
999
+ }
1000
+ this.log(`the run ${runId} of task ${taskId} could not be prepared on ${alias}`, error)
1001
+ await this.settle(taskId, job, { state: 'lost' }, error)
1002
+ }
1003
+ this.publishSummary()
1004
+ }
1005
+
1006
+ /**
1007
+ * Resolve the run's working directory through its placement strategy.
1008
+ *
1009
+ * The strategy may also report how much of the local work it could not send —
1010
+ * a bundle carries commits, not the untracked working tree — and that note is
1011
+ * kept rather than dropped: the card publishes it while the run is going and
1012
+ * the verdict says it out loud.
1013
+ * @param target - the target the card pins.
1014
+ * @param runId - run being prepared.
1015
+ * @param options - cancellation signal and optional worktree reuse id.
1016
+ * @returns the absolute remote directory and the untracked-file note, when any.
1017
+ */
1018
+ private async prepareWorkspace(
1019
+ target: SshTarget,
1020
+ runId: string,
1021
+ options: { signal?: AbortSignal; reuseWorktreeRunId?: string } = {},
1022
+ ): Promise<{ cwd: string; untrackedFiles?: number }> {
1023
+ const strategy = this.strategyFor(target)
1024
+ const prepared = await strategy.prepare(await this.workspaceRun(target, runId, options))
1025
+ if (typeof prepared.cwd !== 'string' || !prepared.cwd.startsWith('/')) {
1026
+ throw new Error(`the ${target.workspace.kind} workspace strategy returned no absolute working directory`)
1027
+ }
1028
+ const untrackedFiles = readUntrackedFiles(prepared)
1029
+ return untrackedFiles === undefined ? { cwd: prepared.cwd } : { cwd: prepared.cwd, untrackedFiles }
1030
+ }
1031
+
1032
+ /** The strategy one target's workspace runs through, or a diagnosable refusal. */
1033
+ private strategyFor(target: SshTarget): SshWorkspaceStrategy {
1034
+ const strategy = this.workspaces?.(target.workspace)
1035
+ if (strategy === undefined) {
1036
+ throw new Error(`this deployment serves no workspace strategy for "${target.workspace.kind}", so the run has nowhere to work`)
1037
+ }
1038
+ return strategy
1039
+ }
1040
+
1041
+ /** Everything a placement strategy needs about one run. */
1042
+ private async workspaceRun(
1043
+ target: SshTarget,
1044
+ runId: string,
1045
+ options: { signal?: AbortSignal; reuseWorktreeRunId?: string } = {},
1046
+ ): Promise<SshWorkspaceRun> {
1047
+ const run: SshWorkspaceRun = {
1048
+ runId,
1049
+ host: target.host,
1050
+ stateDir: await this.remote.stateDir(target.host),
1051
+ ssh: this.ssh,
1052
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
1053
+ ...(options.reuseWorktreeRunId === undefined ? {} : { reuseWorktreeRunId: options.reuseWorktreeRunId }),
1054
+ }
1055
+ if (target.workspace.kind === 'git') {
1056
+ const source = target.workspace.source
1057
+ run.source = source
1058
+ if (source.kind === 'workspace') {
1059
+ const repository = this.localRepository?.(source.workspaceId)
1060
+ if (repository !== undefined && repository !== '') run.localRepository = repository
1061
+ }
1062
+ }
1063
+ return run
1064
+ }
1065
+
1066
+ // --- polling -----------------------------------------------------------------
1067
+
1068
+ /** One poll pass over every run this process follows. */
1069
+ private async poll(): Promise<void> {
1070
+ // The switch is read here as well as in the registration: a deployment whose
1071
+ // settings reach this instance without unloading it must still stop talking
1072
+ // to its hosts the moment the provider is switched off.
1073
+ if (this.disposed || this.polling || !this.enabled()) return
1074
+ this.polling = true
1075
+ try {
1076
+ for (const job of [...this.jobs.values()]) {
1077
+ if (this.disposed) return
1078
+ await this.pollJob(job)
1079
+ }
1080
+ } finally {
1081
+ this.polling = false
1082
+ this.publishSummary()
1083
+ }
1084
+ }
1085
+
1086
+ /** Read one run's remote state and act on it. */
1087
+ private async pollJob(job: SshJob): Promise<void> {
1088
+ if (this.settling.has(job.taskId)) return
1089
+ const task = this.host.tasks.get(job.taskId)
1090
+ const payload = task === undefined ? undefined : this.payloadOf(job.taskId)
1091
+ const run = payload?.activeRun
1092
+ const target = job.target
1093
+ if (task === undefined || payload === undefined || run === undefined || run.runId !== job.runId) {
1094
+ this.jobs.delete(job.taskId)
1095
+ return
1096
+ }
1097
+ let status: LauncherStatus
1098
+ try {
1099
+ const stateDir = await this.remote.stateDir(job.alias)
1100
+ status = await this.remote.status({ alias: job.alias, stateDir, runId: run.runId })
1101
+ } catch (error) {
1102
+ job.failures += 1
1103
+ this.log(`the state of run ${run.runId} could not be read (${String(job.failures)} in a row)`, error)
1104
+ if (job.failures >= LOST_AFTER_FAILURES) await this.settle(job.taskId, job, { state: 'lost' })
1105
+ return
1106
+ }
1107
+ job.failures = 0
1108
+ if (job.starting && (status.state === 'missing' || status.state === 'lost')) {
1109
+ // The start is still preparing this run: the remote directory it is about
1110
+ // to write is absent by definition, and the start's own answer settles
1111
+ // the card when it has one.
1112
+ return
1113
+ }
1114
+ if (status.state === 'running') {
1115
+ const bytes = status.bytes ?? run.bytes
1116
+ if (bytes !== undefined && bytes !== run.bytes) {
1117
+ const current = this.payloadOf(job.taskId)
1118
+ if (current?.activeRun?.runId === run.runId) this.writePayload(job.taskId, withActiveRun(current, { ...run, bytes }))
1119
+ }
1120
+ await this.readLogIncrement(job.taskId, target, run, bytes ?? 0)
1121
+ return
1122
+ }
1123
+ if (status.state === 'unknown') {
1124
+ job.failures += 1
1125
+ this.log(`the launcher answered run ${run.runId} with something this build does not read`)
1126
+ if (job.failures >= LOST_AFTER_FAILURES) await this.settle(job.taskId, job, { state: 'lost' })
1127
+ return
1128
+ }
1129
+ await this.settle(job.taskId, job, status)
1130
+ }
1131
+
1132
+ /**
1133
+ * Read whatever the run's log gained since the last read and hold it for the
1134
+ * next publish.
1135
+ *
1136
+ * Bounded to one window budget per poll so a multi-megabyte burst never hits
1137
+ * `dsh-ssh`'s 2 MiB stdout cap.
1138
+ * @param taskId - card the run belongs to.
1139
+ * @param target - the target the card pins.
1140
+ * @param run - the run in flight.
1141
+ * @param remoteBytes - log size the launcher just reported.
1142
+ */
1143
+ private async readLogIncrement(taskId: string, target: SshTarget, run: SshRunRecord, remoteBytes: number): Promise<void> {
1144
+ const cursor = this.logs.cursor(taskId, run.runId) ?? run.bytes ?? 0
1145
+ if (remoteBytes <= cursor) return
1146
+ try {
1147
+ const stateDir = await this.remote.stateDir(target.host)
1148
+ const page = await this.remote.tail({ alias: target.host, stateDir, runId: run.runId }, cursor, LOG_WINDOW_BUDGET_BYTES)
1149
+ if (page.text !== '') this.logs.push(taskId, run.runId, cursor, page.text, remoteBytes)
1150
+ } catch (error) {
1151
+ this.log(`the log of run ${run.runId} could not be read`, error)
1152
+ }
1153
+ }
1154
+
1155
+ // --- settlement --------------------------------------------------------------
1156
+
1157
+ /**
1158
+ * Close one run: read what it produced, put its verdict on the card exactly
1159
+ * once, and hand the card's next instruction (if any) back to the launch gate.
1160
+ */
1161
+ private async settle(taskId: string, job: SshJob, status: LauncherStatus, failure?: unknown): Promise<void> {
1162
+ if (this.settling.has(taskId)) return
1163
+ this.jobs.delete(taskId)
1164
+ this.settling.add(taskId)
1165
+ try {
1166
+ const task = this.host.tasks.get(taskId)
1167
+ const payload = this.payloadOf(taskId)
1168
+ const run = payload?.activeRun
1169
+ const target = job.target
1170
+ const runAlias = job.alias
1171
+ if (task === undefined || payload === undefined || run === undefined || run.runId !== job.runId) return
1172
+ let cancelled = this.cancelRequested(runAlias, run.runId) || status.state === 'cancelled'
1173
+ let text = ''
1174
+ let tailOffset = 0
1175
+ let bytes = status.bytes ?? run.bytes ?? 0
1176
+ try {
1177
+ const stateDir = await this.remote.stateDir(runAlias)
1178
+ // Read only the trailing PARSE_WINDOW bytes so logs exceeding dsh-ssh's
1179
+ // 2 MiB output cap never lose their closing final/result JSONL event.
1180
+ tailOffset = Math.max(0, bytes - PARSE_WINDOW)
1181
+ const page = await this.remote.tail({ alias: runAlias, stateDir, runId: run.runId }, tailOffset, PARSE_WINDOW)
1182
+ text = page.text
1183
+ bytes = Math.max(bytes, page.bytes)
1184
+ // Advance the pending browser log window contiguously past its cursor.
1185
+ const cursor = this.logs.cursor(taskId, run.runId) ?? 0
1186
+ if (bytes > cursor) {
1187
+ if (cursor >= tailOffset && text !== '') {
1188
+ this.logs.push(taskId, run.runId, cursor, sliceFromByte(text, cursor - tailOffset), bytes)
1189
+ } else {
1190
+ try {
1191
+ const inc = await this.remote.tail({ alias: runAlias, stateDir, runId: run.runId }, cursor, LOG_WINDOW_BUDGET_BYTES)
1192
+ if (inc.text !== '') this.logs.push(taskId, run.runId, cursor, inc.text, bytes)
1193
+ } catch { /* best-effort window fill */ }
1194
+ }
1195
+ }
1196
+ } catch (error) {
1197
+ this.log(`the log of run ${run.runId} could not be read`, error)
1198
+ }
1199
+ const parsed = readAgentOutput({ agent: target.agent.kind, promptFile: '', cwd: '' }, parseWindow(text))
1200
+ // Re-check cancellation before collecting workspace (cancel may have arrived while reading logs).
1201
+ cancelled = cancelled || this.cancelRequested(runAlias, run.runId) || this.disposed
1202
+ const collection = cancelled
1203
+ ? {}
1204
+ : await this.collectWorkspace(target, run.runId, job.workspaceRunId)
1205
+ // Re-check cancellation, task status and ownership AFTER all awaits so a
1206
+ // cancel, manual column move, archive, or replacement run that arrived
1207
+ // during slow git push/bundle download is never overwritten with a verdict.
1208
+ cancelled = cancelled || this.cancelRequested(runAlias, run.runId)
1209
+ if (this.disposed) return
1210
+ const taskAfterAwait = this.host.tasks.get(taskId)
1211
+ const currentAfterAwait = this.payloadOf(taskId)
1212
+ if (taskAfterAwait === undefined || currentAfterAwait === undefined || currentAfterAwait.activeRun?.runId !== run.runId) return
1213
+ if (cancelled || taskAfterAwait.archivedAt !== undefined || taskAfterAwait.status !== 'running') {
1214
+ if (!cancelled) {
1215
+ const stopped: SshRunRecord = {
1216
+ runId: run.runId,
1217
+ phase: 'cancelled',
1218
+ startedAt: run.startedAt,
1219
+ finishedAt: this.now(),
1220
+ ...(bytes > 0 ? { bytes } : {}),
1221
+ ...(status.exitCode === undefined ? {} : { exitCode: status.exitCode }),
1222
+ }
1223
+ const nextCancelled = withSettledRun(currentAfterAwait, stopped)
1224
+ delete nextCancelled.pending
1225
+ this.writePayload(taskId, nextCancelled)
1226
+ }
1227
+ return
1228
+ }
1229
+
1230
+ const collectionError = collection.error
1231
+ const basePhase = this.phaseOf(cancelled, status, parsed.outcome)
1232
+ const phase: SshRunPhase = collectionError !== undefined && basePhase === 'succeeded' ? 'failed' : basePhase
1233
+ const rawSummary = parsed.outcome?.ok === true ? bound(parsed.outcome.text, SSH_SUMMARY_MAX_LENGTH) : undefined
1234
+ const summary = rawSummary !== undefined && rawSummary !== '' ? rawSummary : undefined
1235
+ let rawError: string | undefined
1236
+ if (failure !== undefined) {
1237
+ rawError = bound(failure instanceof Error ? failure.message : String(failure), SSH_ERROR_MAX_LENGTH)
1238
+ } else if (collectionError !== undefined) {
1239
+ rawError = bound(collectionError, SSH_ERROR_MAX_LENGTH)
1240
+ } else if ((parsed.outcome !== undefined && !parsed.outcome.ok) || phase === 'failed') {
1241
+ // When a remote run exits non-zero, fetch bounded stderr.log so CLI
1242
+ // startup errors (missing binary, bad flag, auth failure) surface on the card.
1243
+ let stderrHint = ''
1244
+ if (status.exitCode !== undefined && status.exitCode !== 0) {
1245
+ try {
1246
+ const stateDir = await this.remote.stateDir(runAlias)
1247
+ stderrHint = await this.remote.stderr({ alias: runAlias, stateDir, runId: run.runId }, 512)
1248
+ } catch { /* best-effort */ }
1249
+ }
1250
+ const baseMessage = parsed.outcome !== undefined && !parsed.outcome.ok
1251
+ ? parsed.outcome.error
1252
+ : `the remote agent exited with code ${String(status.exitCode ?? 'none')}`
1253
+ const detail = stderrHint !== ''
1254
+ ? `${baseMessage} (exit ${String(status.exitCode)}: ${stderrHint})`
1255
+ : baseMessage
1256
+ rawError = bound(detail, SSH_ERROR_MAX_LENGTH)
1257
+ } else if (status.state === 'lost' || status.state === 'missing') {
1258
+ rawError = 'the remote run disappeared: its process and its exit record were both gone'
1259
+ }
1260
+ const errorText = rawError !== undefined && rawError !== '' ? rawError : undefined
1261
+ const sessionId = parsed.sessionId !== undefined && parsed.sessionId !== '' ? parsed.sessionId : undefined
1262
+ const branch = collection.branch !== undefined && collection.branch !== '' ? collection.branch : undefined
1263
+ const settled: SshRunRecord = {
1264
+ runId: run.runId,
1265
+ phase,
1266
+ startedAt: run.startedAt,
1267
+ finishedAt: this.now(),
1268
+ bytes,
1269
+ ...(status.exitCode === undefined ? {} : { exitCode: status.exitCode }),
1270
+ ...(sessionId === undefined ? {} : { sessionId }),
1271
+ ...(branch === undefined ? {} : { branch }),
1272
+ ...(run.followUps === undefined ? {} : { followUps: run.followUps }),
1273
+ ...(summary === undefined ? {} : { summary }),
1274
+ ...(errorText === undefined ? {} : { error: errorText }),
1275
+ }
1276
+ const untracked = this.untracked.get(taskId)
1277
+ const note = untrackedNote(untracked !== undefined && untracked.runId === run.runId ? untracked.files : undefined)
1278
+ this.recordOutcome(task, settled, job.degraded, note)
1279
+ this.untracked.delete(taskId)
1280
+ const current = this.payloadOf(taskId)
1281
+ if (current !== undefined) this.writePayload(taskId, withSettledRun(current, settled))
1282
+ if (current?.pending !== undefined) this.reenter(taskId, 'ssh-follow-up')
1283
+ await this.pump(runAlias)
1284
+ } finally {
1285
+ this.settling.delete(taskId)
1286
+ this.publishSummary()
1287
+ }
1288
+ }
1289
+
1290
+ /** The phase one settled run reaches. */
1291
+ private phaseOf(cancelled: boolean, status: LauncherStatus, outcome: { ok: boolean } | undefined): SshRunPhase {
1292
+ if (cancelled) return 'cancelled'
1293
+ if (status.state === 'lost' || status.state === 'missing' || status.state === 'not-running' || status.state === 'unknown') return 'lost'
1294
+ if (outcome !== undefined && !outcome.ok) return 'failed'
1295
+ if (status.state === 'exited' && status.exitCode === 0) return 'succeeded'
1296
+ return 'failed'
1297
+ }
1298
+
1299
+ /**
1300
+ * Put one settled run's verdict on the card, exactly once.
1301
+ *
1302
+ * The verdict travels in the one free-text field an external record has, so
1303
+ * everything that belongs with it is composed here: the degradation marker when
1304
+ * the run was a fresh one, what the agent reported, and the workspace note when
1305
+ * local files stayed behind. The note is reserved room before the agent's own
1306
+ * text is cut, so a long summary can never push it out of the record.
1307
+ */
1308
+ private recordOutcome(task: TaskRecord, run: SshRunRecord, degraded: boolean, note = ''): void {
1309
+ if (run.phase === 'cancelled') return
1310
+ if (alreadyRecorded(task, run.runId)) return
1311
+ const seat = this.seat?.()
1312
+ if (seat === undefined) {
1313
+ this.log(`the verdict of run ${run.runId} has nowhere to go: this board revision serves no action applier`)
1314
+ return
1315
+ }
1316
+ const marker = degraded ? SSH_DEGRADED_SUMMARY_MARKER + ' ' : ''
1317
+ const room = Math.max(0, SSH_SUMMARY_MAX_LENGTH - marker.length - (note === '' ? 0 : note.length + 1))
1318
+ const text = run.phase === 'succeeded' ? (run.summary ?? run.error) : (run.error ?? run.summary)
1319
+ const body = text === undefined ? '' : bound(text, room)
1320
+ const composed = [marker + body, note].filter(part => part !== '').join(' ')
1321
+ const summary = composed === '' ? undefined : bound(composed, SSH_SUMMARY_MAX_LENGTH)
1322
+ try {
1323
+ seat.apply(this.uuid(), {
1324
+ kind: 'record-external-outcome',
1325
+ taskId: task.id,
1326
+ result: run.phase === 'succeeded' ? 'succeeded' : 'failed',
1327
+ initiatedBy: SSH_INITIATOR_PREFIX + run.runId,
1328
+ ...(summary === undefined ? {} : { summary }),
1329
+ }, 'ssh')
1330
+ } catch (error) {
1331
+ this.log(`the board refused the verdict of run ${run.runId}`, error)
1332
+ }
1333
+ }
1334
+
1335
+ /** Bring back whatever the run's workspace strategy produced, surfacing collection failures explicitly. */
1336
+ private async collectWorkspace(
1337
+ target: SshTarget,
1338
+ runId: string,
1339
+ workspaceRunId: string = runId,
1340
+ ): Promise<{ branch?: string; error?: string }> {
1341
+ const strategy = this.workspaces?.(target.workspace)
1342
+ if (strategy === undefined) return {}
1343
+ try {
1344
+ const collection: SshWorkspaceCollection = await strategy.collect(
1345
+ await this.workspaceRun(target, runId, {
1346
+ ...(workspaceRunId === runId ? {} : { reuseWorktreeRunId: workspaceRunId }),
1347
+ }),
1348
+ )
1349
+ return collection.branch === undefined ? {} : { branch: collection.branch }
1350
+ } catch (error) {
1351
+ const reason = error instanceof Error ? error.message : String(error)
1352
+ this.log(`the result of run ${runId} could not be collected`, error)
1353
+ const branchHint = target.workspace.kind === 'git' ? ` (remote branch dsh-task/${workspaceRunId} on ${target.host})` : ''
1354
+ return { error: `workspace collection failed${branchHint}: ${reason}` }
1355
+ }
1356
+ }
1357
+
1358
+ /** The summary the card's previous run reported, for a run that cannot resume. */
1359
+ private previousSummary(payload: HostSshPayload): string | undefined {
1360
+ for (let index = payload.history.length - 1; index >= 0; index -= 1) {
1361
+ const record = payload.history[index]
1362
+ const text = record?.summary ?? record?.error
1363
+ if (text !== undefined && text !== '') return text
1364
+ }
1365
+ return undefined
1366
+ }
1367
+
1368
+ // --- cancellation and deletion ----------------------------------------------
1369
+
1370
+ /**
1371
+ * A card that left the running column while its run is live is a cancel
1372
+ * request: the remote process is stopped and no verdict is written, because
1373
+ * the person moved the card, the person decides what the card says.
1374
+ */
1375
+ private async onStatusChanged(event: TaskBoardStatusChangedEvent): Promise<void> {
1376
+ if (this.disposed || event.previous !== 'running') return
1377
+ const task = this.host.tasks.get(event.taskId)
1378
+ if (task === undefined) return
1379
+ const payload = this.payloadOf(event.taskId)
1380
+ const run = payload?.activeRun
1381
+ const target = payload?.target
1382
+ if (payload === undefined || run === undefined || target === undefined) return
1383
+ if (isTerminalRunPhase(run.phase)) return
1384
+ if (alreadyRecorded(task, run.runId)) return
1385
+ // The person already chose the column, so this path never moves the card.
1386
+ await this.stopRun(event.taskId, payload, target, run, { restore: false })
1387
+ }
1388
+
1389
+ /**
1390
+ * Cancel one live run, drop any instruction it owed, and write no verdict.
1391
+ *
1392
+ * A card the provider itself stopped would otherwise sit in the running column
1393
+ * with nothing left to observe it, and the detail view offers no cancel button
1394
+ * for a settled run: the restore flag is what puts it back where a person can
1395
+ * run it again.
1396
+ */
1397
+ private async stopRun(
1398
+ taskId: string,
1399
+ payload: HostSshPayload,
1400
+ target: SshTarget,
1401
+ run: SshRunRecord,
1402
+ options: { restore: boolean },
1403
+ ): Promise<void> {
1404
+ const activeJob = this.jobs.get(taskId)
1405
+ activeJob?.abort.abort()
1406
+ this.jobs.delete(taskId)
1407
+ const cancelAlias = activeJob?.alias ?? target.host
1408
+ this.cancelRequests.add(cancelAlias + '/' + run.runId)
1409
+ const cancelled: SshRunRecord = {
1410
+ runId: run.runId,
1411
+ phase: 'cancelled',
1412
+ startedAt: run.startedAt,
1413
+ finishedAt: this.now(),
1414
+ ...(run.exitCode === undefined ? {} : { exitCode: run.exitCode }),
1415
+ ...(run.bytes === undefined ? {} : { bytes: run.bytes }),
1416
+ ...(run.sessionId === undefined ? {} : { sessionId: run.sessionId }),
1417
+ }
1418
+ const next = withSettledRun(payload, cancelled)
1419
+ delete next.pending
1420
+ this.writePayload(taskId, next)
1421
+ if (run.phase === 'running') {
1422
+ try {
1423
+ const stateDir = await this.remote.stateDir(cancelAlias)
1424
+ await this.remote.cancel({ alias: cancelAlias, stateDir, runId: run.runId })
1425
+ } catch (error) {
1426
+ this.log(`the remote run ${run.runId} could not be cancelled`, error)
1427
+ }
1428
+ }
1429
+ if (options.restore) this.restoreToTodo(taskId, run.runId)
1430
+ // The slot this run held is free again: whoever waited for it is served now
1431
+ // rather than on the next tick.
1432
+ await this.pump(cancelAlias)
1433
+ this.publishSummary()
1434
+ }
1435
+
1436
+ /**
1437
+ * Put a card the provider stopped back in the todo column.
1438
+ *
1439
+ * Only acts when the card is STILL in the running column with no newer live
1440
+ * run: if the operator already moved the card or started a fresh run while
1441
+ * `remote.cancel` waited out SIGTERM, leaving it alone prevents overwriting
1442
+ * the manual move or cancelling the newer run.
1443
+ * @param taskId - card to move.
1444
+ * @param runId - run that was stopped, recorded as the initiating party.
1445
+ */
1446
+ private restoreToTodo(taskId: string, runId: string): void {
1447
+ const task = this.host.tasks.get(taskId)
1448
+ if (task === undefined || task.archivedAt !== undefined || task.status !== 'running') return
1449
+ const latest = this.payloadOf(taskId)
1450
+ if (latest !== undefined && liveRunOf(latest) !== undefined) return
1451
+ try {
1452
+ this.host.tasks.setStatus(taskId, 'todo', SSH_INITIATOR_PREFIX + runId)
1453
+ } catch (error) {
1454
+ this.log(`task ${taskId} could not be put back in the todo column after its run was cancelled`, error)
1455
+ }
1456
+ }
1457
+
1458
+ /** A deleted card takes all its remote run directories and git worktrees with it. */
1459
+ private async onTaskDeleted(event: TaskBoardTaskDeletedEvent): Promise<void> {
1460
+ if (this.disposed) return
1461
+ const job = this.jobs.get(event.taskId)
1462
+ job?.abort.abort()
1463
+ this.jobs.delete(event.taskId)
1464
+ this.logs.remove(event.taskId)
1465
+ this.untracked.delete(event.taskId)
1466
+ const known = this.known.get(event.taskId)
1467
+ this.known.delete(event.taskId)
1468
+ const alias = known?.alias ?? job?.alias
1469
+ const target = known?.target ?? job?.target
1470
+ const runIds = new Set<string>(known?.runIds ?? [])
1471
+ if (job !== undefined) {
1472
+ runIds.add(job.runId)
1473
+ runIds.add(job.workspaceRunId)
1474
+ }
1475
+ if (alias === undefined || runIds.size === 0) return
1476
+ try {
1477
+ const stateDir = await this.remote.stateDir(alias)
1478
+ const strategy = target !== undefined && target.workspace.kind === 'git' ? this.workspaces?.(target.workspace) : undefined
1479
+ for (const runId of runIds) {
1480
+ try {
1481
+ await this.remote.cancel({ alias, stateDir, runId })
1482
+ } catch (error) {
1483
+ this.log(`the run ${runId} of the deleted task ${event.taskId} could not be cancelled`, error)
1484
+ }
1485
+ try {
1486
+ await this.remote.removeRun({ alias, stateDir, runId })
1487
+ } catch (error) {
1488
+ this.log(`the remote run directory ${runId} of the deleted task ${event.taskId} could not be removed`, error)
1489
+ }
1490
+ if (strategy?.cleanup !== undefined && target !== undefined) {
1491
+ try {
1492
+ await strategy.cleanup(await this.workspaceRun(target, runId))
1493
+ } catch (error) {
1494
+ this.log(`the remote workspace ${runId} of the deleted task ${event.taskId} could not be removed`, error)
1495
+ }
1496
+ }
1497
+ }
1498
+ // A deleted card frees its slot like any other settlement.
1499
+ await this.pump(alias)
1500
+ } catch (error) {
1501
+ this.log(`the remote run directory of the deleted task ${event.taskId} could not be removed`, error)
1502
+ }
1503
+ }
1504
+
1505
+ /** Put a card's waiting instruction back through the board's own rerun action. */
1506
+ private reenter(taskId: string, initiator: string): SshEngineReply {
1507
+ const seat = this.seat?.()
1508
+ if (seat === undefined) return { ok: false, code: 'board-unavailable', error: 'this board revision serves no action applier' }
1509
+ try {
1510
+ seat.apply(this.uuid(), { kind: 'rerun', taskId }, initiator)
1511
+ return { ok: true, taskId, message: 'run requested' }
1512
+ } catch (error) {
1513
+ const message = error instanceof Error ? error.message : String(error)
1514
+ this.log(`task ${taskId} could not be sent back into its intercepting run`, error)
1515
+ return { ok: false, code: 'rerun-refused', error: message }
1516
+ }
1517
+ }
1518
+
1519
+ // --- reconciliation ----------------------------------------------------------
1520
+
1521
+ /**
1522
+ * Pick up what the previous process left behind: a queued run is served in
1523
+ * its place in the queue, a running one is polled at once (that is how a run
1524
+ * that finished while this Host was down is recorded, once), and a run whose
1525
+ * verdict never reached the board is recorded before anything else.
1526
+ */
1527
+ private async reconcile(): Promise<void> {
1528
+ if (this.disposed) return
1529
+ const aliases = new Set<string>()
1530
+ for (const entry of this.linkedEntries()) {
1531
+ const target = entry.payload?.target
1532
+ if (entry.payload === undefined || target === undefined) continue
1533
+ for (const historic of entry.payload.history) {
1534
+ this.rememberRun(entry.task.id, target.host, historic.runId, target)
1535
+ }
1536
+ const run = entry.payload.activeRun
1537
+ if (run === undefined) continue
1538
+ aliases.add(target.host)
1539
+ this.rememberRun(entry.task.id, target.host, run.runId, target)
1540
+ if (run.phase === 'queued') continue
1541
+ if (!isTerminalRunPhase(run.phase)) {
1542
+ this.jobs.set(entry.task.id, {
1543
+ taskId: entry.task.id,
1544
+ runId: run.runId,
1545
+ alias: target.host,
1546
+ target,
1547
+ workspaceRunId: run.runId,
1548
+ abort: new AbortController(),
1549
+ failures: 0,
1550
+ degraded: false,
1551
+ starting: false,
1552
+ })
1553
+ this.logs.adopt(entry.task.id, run.runId, run.bytes ?? 0)
1554
+ continue
1555
+ }
1556
+ // A verdict written before a crash but never moved into the history: it is
1557
+ // recorded here (idempotently) and the payload is folded afterwards.
1558
+ this.recordOutcome(entry.task, run, false)
1559
+ this.writePayload(entry.task.id, withSettledRun(entry.payload, run))
1560
+ }
1561
+ await this.poll()
1562
+ for (const alias of aliases) await this.pump(alias)
1563
+ }
1564
+
1565
+ // --- shared plumbing ---------------------------------------------------------
1566
+
1567
+ /** Write one card's payload, tolerating a card that vanished under us. */
1568
+ private writePayload(taskId: string, next: HostSshPayload): boolean {
1569
+ try {
1570
+ this.host.integration.write(taskId, writeHostPayload(next, this.now()))
1571
+ return true
1572
+ } catch (error) {
1573
+ this.log(`the payload of task ${taskId} was refused`, error)
1574
+ return false
1575
+ }
1576
+ }
1577
+
1578
+ /** Publish (or refresh) this extension's summary in the board snapshot. */
1579
+ private publishSummary(): void {
1580
+ if (this.disposed) return
1581
+ const { document, delivered } = this.buildSummary()
1582
+ try {
1583
+ this.host.publish(document)
1584
+ } catch (error) {
1585
+ // A refused publish is not a lost window: nothing was delivered, so the
1586
+ // next publish carries it again.
1587
+ this.log('the summary was refused', error)
1588
+ return
1589
+ }
1590
+ this.logs.markDelivered(delivered)
1591
+ }
1592
+
1593
+ /** A run id the remote launcher accepts, ordered by the instant it was requested. */
1594
+ private newRunId(): string {
1595
+ return 'run-' + this.now().toString(36) + '-' + this.uuid().replace(/[^A-Za-z0-9]/g, '').slice(0, 12)
1596
+ }
1597
+
1598
+ /** Whether a person asked for this run to stop. */
1599
+ private cancelRequested(alias: string, runId: string): boolean {
1600
+ return this.cancelRequests.has(alias + '/' + runId)
1601
+ }
1602
+ }