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

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