@linxin666/dsh-client-ui-task-board-ssh 0.4.20 → 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.
@@ -29,7 +29,7 @@ import {
29
29
  } from '../core/adapters/index.ts'
30
30
  import type { DshSshHost, DshSshService, TaskBoardExtensionHost, TaskBoardLaunchContext, TaskBoardLaunchDecision, TaskBoardStatusChangedEvent, TaskBoardTaskDeletedEvent } from '../core/contract.ts'
31
31
  import { SSH_ERROR_MAX_LENGTH, SSH_SUMMARY_MAX_LENGTH } from '../core/ledger.ts'
32
- import { runFilePath, type LauncherStatus } from '../core/launcher.ts'
32
+ import { REMOTE_STATE_SUFFIX, runFilePath, type LauncherStatus } from '../core/launcher.ts'
33
33
  import { isTerminalRunPhase, type SshAgentKind, type SshAgentTarget, type SshRunPhase, type SshRunRecord, type SshTarget } from '../core/target.ts'
34
34
  import type { TaskRecord } from '../core/task-record.ts'
35
35
  import type { SshWorkspaceCollection, SshWorkspaceRun, SshWorkspaceStrategy } from '../core/workspace.ts'
@@ -50,6 +50,19 @@ import { LOG_WINDOW_BUDGET_BYTES, PUBLISH_BODY_LIMIT_BYTES, SshLogWindows, byteL
50
50
  import { SSH_DEGRADED_SUMMARY_MARKER, proxyPreamble, runPrompt } from './prompt.ts'
51
51
  import { admitRuns, type SshQueueEntry } from './queue.ts'
52
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'
53
66
  import type { SshProviderSettings } from './settings.ts'
54
67
  import type { HostTimerFace } from './timers.ts'
55
68
  import { readUntrackedFiles, untrackedNote, type SshWorkspaceStrategyResolver } from './workspace-seam.ts'
@@ -60,6 +73,9 @@ export const DEFAULT_POLL_INTERVAL_MS = 2_000
60
73
  /** Consecutive unreadable polls after which a run is recorded as lost. */
61
74
  export const LOST_AFTER_FAILURES = 3
62
75
 
76
+ /** Expected run length when no earlier run says better, in milliseconds. */
77
+ export const DEFAULT_ESTIMATED_DURATION_MS = 180_000
78
+
63
79
  /** Longest tail of a run's log this engine parses, in characters. */
64
80
  const PARSE_WINDOW = 256 * 1024
65
81
 
@@ -93,6 +109,8 @@ export interface SshRunEngineOptions {
93
109
  uuid?: () => string
94
110
  /** Poll cadence, in milliseconds. */
95
111
  pollIntervalMs?: number
112
+ /** Wait source for a blocking status call; defaults to a real timer. */
113
+ sleep?: (ms: number) => Promise<void>
96
114
  /** Ceiling for one remote command, in milliseconds. */
97
115
  commandTimeoutMs?: number
98
116
  /** Where a refusal or a failed remote call is reported. */
@@ -169,6 +187,67 @@ export interface SshRunStatusView {
169
187
  pending?: 'follow-up' | 'rework'
170
188
  }
171
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
+
172
251
  /** One page of a run's log. */
173
252
  export type SshLogPage =
174
253
  | { ok: true; taskId: string; runId: string; offset: number; nextOffset: number; bytes: number; eof: boolean; text: string }
@@ -227,6 +306,26 @@ export function agentCommandLine(input: SshAgentRunInput, templates: SshCustomTe
227
306
  return templates === undefined ? buildAgentCommandLine(input) : customAgentCommand(input, templates)
228
307
  }
229
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
+
230
329
  export class SshRunEngine {
231
330
  private readonly host: TaskBoardExtensionHost
232
331
  private readonly ssh: DshSshService
@@ -238,6 +337,9 @@ export class SshRunEngine {
238
337
  private readonly now: () => number
239
338
  private readonly uuid: () => string
240
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 }>()
241
343
  private readonly log: (message: string, detail?: unknown) => void
242
344
  private readonly remote: SshRemote
243
345
  /** Runs this process follows, keyed by card id: a card has at most one. */
@@ -280,6 +382,7 @@ export class SshRunEngine {
280
382
  this.now = options.now ?? (() => Date.now())
281
383
  this.uuid = options.uuid ?? (() => crypto.randomUUID())
282
384
  this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS
385
+ this.sleep = options.sleep ?? (ms => new Promise<void>(resolve => { setTimeout(resolve, ms) }))
283
386
  this.log = options.log ?? ((message, detail) => {
284
387
  if (detail === undefined) console.error('[dsh-task-board-ssh] ' + message)
285
388
  else console.error('[dsh-task-board-ssh] ' + message, detail)
@@ -330,6 +433,7 @@ export class SshRunEngine {
330
433
  this.pumping.clear()
331
434
  this.pumpAgain.clear()
332
435
  this.settling.clear()
436
+ this.reserved.clear()
333
437
  this.untracked.clear()
334
438
  this.logs.clear()
335
439
  this.remote.forget()
@@ -380,6 +484,236 @@ export class SshRunEngine {
380
484
  return this.payloadOf(taskId)?.target
381
485
  }
382
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
+
383
717
  /** One card's remote-run state. */
384
718
  status(taskId: string): SshRunStatusView {
385
719
  const payload = this.payloadOf(taskId)
@@ -430,6 +764,67 @@ export class SshRunEngine {
430
764
  return { ok: true, taskId, message: 'target pinned' }
431
765
  }
432
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
+
433
828
  /**
434
829
  * Start a card's pinned run now, through the board's own run action so the
435
830
  * card reaches the running column the same way the run button puts it there.
@@ -730,6 +1125,19 @@ export class SshRunEngine {
730
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`)
731
1126
  return { kind: 'external' }
732
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() })
733
1141
  void this.openRun(task.id, target.host).catch(error => { this.log(`the remote run of task ${task.id} could not be opened`, error) })
734
1142
  return { kind: 'external' }
735
1143
  }
@@ -741,12 +1149,22 @@ export class SshRunEngine {
741
1149
  await Promise.resolve()
742
1150
  if (this.disposed) return
743
1151
  const task = this.host.tasks.get(taskId)
744
- if (task === undefined || task.archivedAt !== undefined || task.status !== 'running') return
1152
+ if (task === undefined || task.archivedAt !== undefined || task.status !== 'running') {
1153
+ this.reserved.delete(taskId)
1154
+ return
1155
+ }
745
1156
  const payload = this.payloadOf(taskId)
746
- if (payload?.target === undefined) return
1157
+ if (payload?.target === undefined) {
1158
+ this.reserved.delete(taskId)
1159
+ return
1160
+ }
747
1161
  const live = liveRunOf(payload)
748
1162
  if (live !== undefined) return
749
- const run: SshRunRecord = { runId: this.newRunId(), phase: 'queued', startedAt: this.now() }
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 }
750
1168
  this.rememberRun(taskId, alias, run.runId, payload.target)
751
1169
  if (!this.writePayload(taskId, { ...payload, activeRun: run })) return
752
1170
  await this.pump(alias)
@@ -1115,7 +1533,7 @@ export class SshRunEngine {
1115
1533
  const bytes = status.bytes ?? run.bytes
1116
1534
  if (bytes !== undefined && bytes !== run.bytes) {
1117
1535
  const current = this.payloadOf(job.taskId)
1118
- if (current?.activeRun?.runId === run.runId) this.writePayload(job.taskId, withActiveRun(current, { ...run, bytes }))
1536
+ if (current?.activeRun?.runId === run.runId) this.writePayload(job.taskId, withActiveRun(current, { ...run, bytes, lastActivityAt: this.now() }))
1119
1537
  }
1120
1538
  await this.readLogIncrement(job.taskId, target, run, bytes ?? 0)
1121
1539
  return
@@ -1272,6 +1690,9 @@ export class SshRunEngine {
1272
1690
  ...(run.followUps === undefined ? {} : { followUps: run.followUps }),
1273
1691
  ...(summary === undefined ? {} : { summary }),
1274
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) }),
1275
1696
  }
1276
1697
  const untracked = this.untracked.get(taskId)
1277
1698
  const note = untrackedNote(untracked !== undefined && untracked.runId === run.runId ? untracked.files : undefined)
@@ -1315,7 +1736,7 @@ export class SshRunEngine {
1315
1736
  }
1316
1737
  const marker = degraded ? SSH_DEGRADED_SUMMARY_MARKER + ' ' : ''
1317
1738
  const room = Math.max(0, SSH_SUMMARY_MAX_LENGTH - marker.length - (note === '' ? 0 : note.length + 1))
1318
- const text = run.phase === 'succeeded' ? (run.summary ?? run.error) : (run.error ?? run.summary)
1739
+ const text = run.phase === 'succeeded' ? run.summary : (run.error ?? run.summary)
1319
1740
  const body = text === undefined ? '' : bound(text, room)
1320
1741
  const composed = [marker + body, note].filter(part => part !== '').join(' ')
1321
1742
  const summary = composed === '' ? undefined : bound(composed, SSH_SUMMARY_MAX_LENGTH)
@@ -1326,6 +1747,9 @@ export class SshRunEngine {
1326
1747
  result: run.phase === 'succeeded' ? 'succeeded' : 'failed',
1327
1748
  initiatedBy: SSH_INITIATOR_PREFIX + run.runId,
1328
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) }),
1329
1753
  }, 'ssh')
1330
1754
  } catch (error) {
1331
1755
  this.log(`the board refused the verdict of run ${run.runId}`, error)
@@ -21,6 +21,7 @@ import {
21
21
  type TaskBoardExtensionHost,
22
22
  } from '../core/contract.ts'
23
23
  import { SSH_AGENT_KINDS, type SshAgentKind, type SshExecutionMode } from '../core/target.ts'
24
+ import type { TaskRecord } from '../core/task-record.ts'
24
25
  import type { BoardActionSeat } from './board.ts'
25
26
  import { SshRunEngine, type SshEngineReply, type SshLogPage } from './engine.ts'
26
27
  import {
@@ -74,6 +75,8 @@ export interface SshExtensionOptions {
74
75
  now?: () => number
75
76
  /** Identifier source for request ids and run ids. */
76
77
  uuid?: () => string
78
+ /** Wait source of a blocking status call; a real timer when absent. */
79
+ sleep?: (ms: number) => Promise<void>
77
80
  /** Poll cadence, in milliseconds. */
78
81
  pollIntervalMs?: number
79
82
  /** Ceiling for one remote command, in milliseconds. */
@@ -268,6 +271,7 @@ export function createSshExtension(options: SshExtensionOptions): TaskBoardExten
268
271
  ...(options.localRepository === undefined ? {} : { localRepository: options.localRepository }),
269
272
  ...(options.now === undefined ? {} : { now: options.now }),
270
273
  ...(options.uuid === undefined ? {} : { uuid: options.uuid }),
274
+ ...(options.sleep === undefined ? {} : { sleep: options.sleep }),
271
275
  ...(options.pollIntervalMs === undefined ? {} : { pollIntervalMs: options.pollIntervalMs }),
272
276
  ...(options.commandTimeoutMs === undefined ? {} : { commandTimeoutMs: options.commandTimeoutMs }),
273
277
  log,
@@ -297,6 +301,8 @@ export function createSshExtension(options: SshExtensionOptions): TaskBoardExten
297
301
  engine?.stop()
298
302
  engine = undefined
299
303
  },
304
+ describeTask: (task: TaskRecord) => engine?.describeTask(task),
305
+ describeRun: (taskId: string) => engine?.describeRun(taskId),
300
306
  async handleAction(request: TaskBoardExtensionActionRequest): Promise<unknown> {
301
307
  return await routeAction(request, engine, options.settingsWriter)
302
308
  },