@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,297 @@
1
+ /**
2
+ * The log windows this extension publishes into the board snapshot.
3
+ *
4
+ * A card's log is a file on the remote host, never part of the card: the ledger
5
+ * payload is bounded at 64 KiB and an agent's stream is unbounded, so the bytes
6
+ * travel one way only — read by byte offset over the dshSsh face, and delivered
7
+ * to the browser through the extension's published summary, which the board
8
+ * hands the client mirror as-is.
9
+ *
10
+ * The browser has no other byte channel: a dispatched action answers a boolean,
11
+ * so the log viewer decodes the windows below. Every window names the exact byte
12
+ * interval its text covers, [baseOffset, endOffset), so a decoder appends it
13
+ * without guessing, and a window that could not carry everything waiting is
14
+ * marked truncated instead of dropping the rest: the next publish carries the
15
+ * continuation, starting exactly where the previous one stopped.
16
+ *
17
+ * Windows are per card and in memory. Nothing here is ever written into a card's
18
+ * payload.
19
+ *
20
+ * @module dsh-task-board-ssh/host/logs
21
+ */
22
+
23
+ /** Largest window one card carries in a single publish, in bytes. */
24
+ export const LOG_WINDOW_BUDGET_BYTES = 8 * 1024
25
+
26
+ /** Largest window section one publish carries across all cards, in bytes. */
27
+ export const PUBLISH_LOG_BUDGET_BYTES = 32 * 1024
28
+
29
+ /**
30
+ * Budget for the whole published summary, in bytes of its JSON serialization.
31
+ *
32
+ * The board validates a published summary with the same predicate it applies to
33
+ * any extension payload, so the hard ceiling is TASK_BOARD_PAYLOAD_LIMIT_BYTES
34
+ * (64 KiB). This budget stays well under it, which leaves room for the host
35
+ * list, the defaults and the runs the same summary carries.
36
+ */
37
+ export const PUBLISH_BODY_LIMIT_BYTES = 48 * 1024
38
+
39
+ /** One window a browser decodes at a known byte interval. */
40
+ export interface SshLogWindow {
41
+ /** Run the text belongs to. */
42
+ runId: string
43
+ /** Byte offset of the first delivered byte. */
44
+ baseOffset: number
45
+ /** Byte offset just past the last delivered byte. */
46
+ endOffset: number
47
+ /** The delivered bytes, as text. */
48
+ text: string
49
+ /** Whether more bytes are waiting after `endOffset` (carried in a later publish/page). */
50
+ truncated?: boolean
51
+ /** Explicit continuation signal distinguishing trailing unread bytes from skipped leading bytes. */
52
+ hasMore?: boolean
53
+ }
54
+
55
+ /** What one card's window currently holds. */
56
+ interface WindowState {
57
+ /** Run the window belongs to. */
58
+ runId: string
59
+ /** Byte offset of the first byte in the pending text. */
60
+ base: number
61
+ /** Byte offset just past the last byte in the pending text. */
62
+ end: number
63
+ /** Bytes read but not yet published. */
64
+ text: string
65
+ /** Whether unread bytes remain after the end. */
66
+ truncated: boolean
67
+ /** Offset the next read for this run starts at. */
68
+ cursor: number
69
+ }
70
+
71
+ /** Byte length of a text. */
72
+ export function byteLength(text: string): number {
73
+ return new TextEncoder().encode(text).length
74
+ }
75
+
76
+ /**
77
+ * The longest prefix of a text that fits a byte budget, never splitting a
78
+ * character (which would make the delivered byte count lie).
79
+ * @param text - the text to cut.
80
+ * @param budget - largest prefix, in UTF-8 bytes.
81
+ * @returns the prefix and its byte length.
82
+ */
83
+ export function takeWithinBudget(text: string, budget: number): { text: string; bytes: number } {
84
+ const encoder = new TextEncoder()
85
+ const total = encoder.encode(text).length
86
+ if (total <= budget) return { text, bytes: total }
87
+ let bytes = 0
88
+ let index = 0
89
+ for (const character of text) {
90
+ const size = encoder.encode(character).length
91
+ if (bytes + size > budget) break
92
+ bytes += size
93
+ index += character.length
94
+ }
95
+ return { text: text.slice(0, index), bytes }
96
+ }
97
+
98
+ /**
99
+ * The part of a text that starts at one UTF-8 byte offset.
100
+ * @param text - the whole text.
101
+ * @param from - byte offset to start at.
102
+ * @returns the remainder.
103
+ */
104
+ export function sliceFromByte(text: string, from: number): string {
105
+ if (from <= 0) return text
106
+ const encoder = new TextEncoder()
107
+ let bytes = 0
108
+ let index = 0
109
+ while (index < text.length) {
110
+ const code = text.codePointAt(index) ?? 0
111
+ const character = String.fromCodePoint(code)
112
+ const size = encoder.encode(character).length
113
+ if (bytes + size > from) break
114
+ bytes += size
115
+ index += character.length
116
+ }
117
+ return text.slice(index)
118
+ }
119
+
120
+ /** One publish's window section and the cards it delivered for. */
121
+ export interface SshLogDelivery {
122
+ /** Windows keyed by card id, in the shape the client decodes. */
123
+ logs: Record<string, SshLogWindow>
124
+ /** Cards whose window this publish carried; they are cleared afterwards. */
125
+ delivered: string[]
126
+ }
127
+
128
+ export class SshLogWindows {
129
+ private readonly states = new Map<string, WindowState>()
130
+ private readonly perCardBudget: number
131
+ private readonly perPublishBudget: number
132
+
133
+ constructor(perCardBudget = LOG_WINDOW_BUDGET_BYTES, perPublishBudget = PUBLISH_LOG_BUDGET_BYTES) {
134
+ this.perCardBudget = Math.max(256, perCardBudget)
135
+ this.perPublishBudget = Math.max(this.perCardBudget, perPublishBudget)
136
+ }
137
+
138
+ /** Forget every window (the extension stopped, or a host went away). */
139
+ clear(): void {
140
+ this.states.clear()
141
+ }
142
+
143
+ /** Drop one card's window (called when the card is deleted). */
144
+ remove(taskId: string): void {
145
+ this.states.delete(taskId)
146
+ }
147
+
148
+ /**
149
+ * Start following one run's log from an offset.
150
+ *
151
+ * Adopting a run this process already follows is a no-op, which is what keeps
152
+ * a poll from resetting the offset the card's payload recorded: a Host that
153
+ * comes back does not re-send bytes the browser already holds, and the
154
+ * viewer's own replay is the way to ask for everything from zero.
155
+ * @param taskId - card the run belongs to.
156
+ * @param runId - run whose log is followed.
157
+ * @param startOffset - first byte the next read asks for.
158
+ */
159
+ adopt(taskId: string, runId: string, startOffset: number): void {
160
+ const existing = this.states.get(taskId)
161
+ if (existing !== undefined && existing.runId === runId) return
162
+ this.states.set(taskId, {
163
+ runId,
164
+ base: startOffset,
165
+ end: startOffset,
166
+ text: '',
167
+ truncated: false,
168
+ cursor: startOffset,
169
+ })
170
+ }
171
+
172
+ /** The offset the next read for one card starts at, when it is followed. */
173
+ cursor(taskId: string, runId: string): number | undefined {
174
+ const state = this.states.get(taskId)
175
+ return state !== undefined && state.runId === runId ? state.cursor : undefined
176
+ }
177
+
178
+ /**
179
+ * Add the bytes read for one card to its pending window.
180
+ * @param taskId - card the run belongs to.
181
+ * @param runId - run whose log was read.
182
+ * @param from - byte offset the read started at.
183
+ * @param text - the bytes read from `from`.
184
+ * @param remoteBytes - optional total remote log size when known (detects trailing unread bytes on bounded reads).
185
+ */
186
+ push(taskId: string, runId: string, from: number, text: string, remoteBytes?: number): void {
187
+ const current = this.states.get(taskId)
188
+ if (current === undefined || current.runId !== runId) {
189
+ this.states.set(taskId, { runId, base: from, end: from, text: '', truncated: false, cursor: from })
190
+ }
191
+ const state = this.states.get(taskId)
192
+ if (state === undefined) return
193
+ // Guard against concurrent `poll` + `refresh` reads overlapping the same
194
+ // byte range: slice off bytes already buffered instead of duplicating them.
195
+ let effectiveFrom = from
196
+ let effectiveText = text
197
+ if (effectiveFrom < state.end) {
198
+ const overlap = state.end - effectiveFrom
199
+ effectiveText = sliceFromByte(effectiveText, overlap)
200
+ effectiveFrom = state.end
201
+ }
202
+ const incomingBytes = byteLength(effectiveText)
203
+ const remaining = this.perCardBudget - byteLength(state.text)
204
+ if (remaining <= 0) {
205
+ // The window is full and still waiting to be published: nothing is taken,
206
+ // so the next read asks for exactly the same bytes again.
207
+ state.cursor = state.end
208
+ state.truncated = incomingBytes > 0 || (remoteBytes !== undefined && remoteBytes > state.end)
209
+ return
210
+ }
211
+ const taken = takeWithinBudget(effectiveText, remaining)
212
+ if (taken.text !== '') {
213
+ state.text += taken.text
214
+ state.end = state.base + byteLength(state.text)
215
+ }
216
+ state.cursor = Math.max(state.cursor, effectiveFrom + taken.bytes)
217
+ // Anything the budget could not take is still on the host: the next read
218
+ // starts exactly where this window stopped, so nothing is ever skipped.
219
+ state.truncated = taken.bytes < incomingBytes || (remoteBytes !== undefined && remoteBytes > state.end)
220
+ }
221
+
222
+ /**
223
+ * Replace one card's pending window with a replay from an offset.
224
+ * @param taskId - card the run belongs to.
225
+ * @param runId - run whose log was read.
226
+ * @param from - byte offset the replay starts at (zero for a full replay).
227
+ * @param text - the bytes read from `from`.
228
+ * @param hasMore - optional explicit flag when caller read a bounded window and more bytes exist past it.
229
+ */
230
+ replay(taskId: string, runId: string, from: number, text: string, hasMore = false): void {
231
+ const taken = takeWithinBudget(text, this.perCardBudget)
232
+ const truncated = hasMore || taken.bytes < byteLength(text)
233
+ this.states.set(taskId, {
234
+ runId,
235
+ base: from,
236
+ end: from + taken.bytes,
237
+ text: taken.text,
238
+ truncated,
239
+ cursor: from + taken.bytes,
240
+ })
241
+ }
242
+
243
+ /** How many cards hold an unpublished window. */
244
+ pending(): number {
245
+ let count = 0
246
+ for (const state of this.states.values()) {
247
+ if (state.text !== '' || state.truncated) count += 1
248
+ }
249
+ return count
250
+ }
251
+
252
+ /**
253
+ * The windows one publish carries, bounded across cards.
254
+ *
255
+ * A card whose window does not fit this publish keeps it: the next publish
256
+ * carries it instead of losing it, and the iteration order is stable, so a
257
+ * backlog drains card by card.
258
+ * @returns the window section and the cards it covered.
259
+ */
260
+ take(): SshLogDelivery {
261
+ const logs: Record<string, SshLogWindow> = {}
262
+ const delivered: string[] = []
263
+ let used = 0
264
+ for (const [taskId, state] of this.states) {
265
+ if (state.text === '' && !state.truncated) continue
266
+ const window: SshLogWindow = {
267
+ runId: state.runId,
268
+ baseOffset: state.base,
269
+ endOffset: state.end,
270
+ text: state.text,
271
+ ...(state.truncated ? { truncated: true, hasMore: true } : {}),
272
+ }
273
+ const size = byteLength(JSON.stringify({ [taskId]: window }))
274
+ if (used + size > this.perPublishBudget && delivered.length > 0) continue
275
+ logs[taskId] = window
276
+ delivered.push(taskId)
277
+ used += size
278
+ }
279
+ return { logs, delivered }
280
+ }
281
+
282
+ /**
283
+ * Clear the windows one publish carried, so the next one carries only what
284
+ * arrived since.
285
+ * @param taskIds - cards the publish covered.
286
+ */
287
+ markDelivered(taskIds: readonly string[]): void {
288
+ for (const taskId of taskIds) {
289
+ const state = this.states.get(taskId)
290
+ if (state === undefined) continue
291
+ state.base = state.end
292
+ state.text = ''
293
+ // Bytes still waiting past the delivered end keep the window open.
294
+ state.truncated = state.cursor > state.end
295
+ }
296
+ }
297
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * The host half's reading of the payload it stores on a card.
3
+ *
4
+ * The schema itself belongs to `src/core/ledger.ts` — the target pin, the active
5
+ * run, the bounded history and the one instruction a future run still owes — and
6
+ * the host half adds no member of its own to it. What this module owns is the
7
+ * write: it stamps the document, keeps it under the board's 64 KiB ceiling and
8
+ * makes every member it clears explicit, because the board merges a written
9
+ * payload into the stored one key by key.
10
+ *
11
+ * @module dsh-task-board-ssh/host/payload
12
+ */
13
+ import {
14
+ SSH_INTEGRATION_KEY,
15
+ SSH_LEDGER_VERSION,
16
+ parseSshLedgerPayload,
17
+ trimSshLedgerPayload,
18
+ type SshLedgerPayload,
19
+ } from '../core/ledger.ts'
20
+ import { isTerminalRunPhase, type SshRunRecord } from '../core/target.ts'
21
+
22
+ export { SSH_INTEGRATION_KEY }
23
+ export type { SshPendingInstruction } from '../core/ledger.ts'
24
+
25
+ /** How many settled runs one card keeps here, oldest dropped first. */
26
+ export const HOST_HISTORY_LIMIT = 20
27
+
28
+ /** One card's payload: exactly the frozen document, with nothing added beside it. */
29
+ export type HostSshPayload = Omit<SshLedgerPayload, 'version'>
30
+
31
+ /**
32
+ * Parse one stored payload into what the host half works with.
33
+ * @param raw - the card's `integrations.ssh` value, or undefined when it carries none.
34
+ * @returns the payload, or undefined when the card carries none this build understands.
35
+ */
36
+ export function readHostPayload(raw: unknown): HostSshPayload | undefined {
37
+ const frozen = parseSshLedgerPayload(raw)
38
+ if (!frozen.ok) return undefined
39
+ const { version: _version, ...payload } = frozen.value
40
+ return { ...payload, history: [...payload.history] }
41
+ }
42
+
43
+ /**
44
+ * Serialize one payload for storage, keeping it strictly under the board's ceiling.
45
+ *
46
+ * The frozen trimmer does the budgeting, including the room it reserves for a
47
+ * queued instruction, so the store may drop the oldest history and never the
48
+ * message a person is waiting on.
49
+ * @param next - the payload to store.
50
+ * @param now - clock instant written into the document (ms epoch).
51
+ * @returns the board-ready extension payload.
52
+ */
53
+ export function writeHostPayload(next: HostSshPayload, now: number): Record<string, unknown> {
54
+ const trimmed = trimSshLedgerPayload({ ...next, version: SSH_LEDGER_VERSION, updatedAt: now }, {
55
+ maxHistory: HOST_HISTORY_LIMIT,
56
+ })
57
+ // The board merges a written payload into the stored one key by key, so a
58
+ // member this write clears has to be present as an explicit undefined (the
59
+ // board deletes such a key, and JSON drops it on the way to disk).
60
+ return {
61
+ ...trimmed,
62
+ target: trimmed.target,
63
+ activeRun: trimmed.activeRun,
64
+ pending: trimmed.pending,
65
+ }
66
+ }
67
+
68
+ /**
69
+ * The same payload carrying one run as the run in flight.
70
+ * @param payload - the current payload.
71
+ * @param run - the run to carry.
72
+ * @returns the next payload.
73
+ */
74
+ export function withActiveRun(payload: HostSshPayload, run: SshRunRecord): HostSshPayload {
75
+ return { ...payload, activeRun: run, history: [...payload.history] }
76
+ }
77
+
78
+ /**
79
+ * The same payload with one run settled into the bounded history.
80
+ * @param payload - the current payload.
81
+ * @param run - the settled run.
82
+ * @returns the next payload, the active run cleared.
83
+ */
84
+ export function withSettledRun(payload: HostSshPayload, run: SshRunRecord): HostSshPayload {
85
+ const history = [...payload.history.filter(record => record.runId !== run.runId), run]
86
+ const next: HostSshPayload = {
87
+ ...payload,
88
+ history: history.slice(Math.max(0, history.length - HOST_HISTORY_LIMIT)),
89
+ }
90
+ delete next.activeRun
91
+ return next
92
+ }
93
+
94
+ /**
95
+ * One run of a card's payload by id.
96
+ *
97
+ * A run stays addressable after it settles — the detail view names a historical
98
+ * run to replay its log — so the search covers the run in flight and the whole
99
+ * bounded history.
100
+ * @param payload - the payload to read.
101
+ * @param runId - run to find.
102
+ * @returns the run, or undefined when this card never had it.
103
+ */
104
+ export function findRun(payload: HostSshPayload | undefined, runId: string): SshRunRecord | undefined {
105
+ if (payload === undefined) return undefined
106
+ if (payload.activeRun?.runId === runId) return payload.activeRun
107
+ return payload.history.find(record => record.runId === runId)
108
+ }
109
+
110
+ /**
111
+ * The most recent session this card's runs recorded, which is the one a
112
+ * follow-up would continue.
113
+ * @param payload - the payload to read.
114
+ * @returns the session id, or undefined when no run of this card reported one.
115
+ */
116
+ export function latestSessionId(payload: HostSshPayload): string | undefined {
117
+ const candidates = [...payload.history, ...(payload.activeRun === undefined ? [] : [payload.activeRun])]
118
+ for (let index = candidates.length - 1; index >= 0; index -= 1) {
119
+ const sessionId = candidates[index]?.sessionId
120
+ if (sessionId !== undefined && sessionId !== '') return sessionId
121
+ }
122
+ return undefined
123
+ }
124
+
125
+ /**
126
+ * The run a card is waiting on, when it is still in a phase that schedules work.
127
+ * @param payload - the payload to read.
128
+ * @returns the live run, or undefined when the card waits on nothing.
129
+ */
130
+ export function liveRunOf(payload: HostSshPayload): SshRunRecord | undefined {
131
+ const run = payload.activeRun
132
+ if (run === undefined) return undefined
133
+ return isTerminalRunPhase(run.phase) ? undefined : run
134
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The text one run's prompt carries: the proxy preamble a local session starts
3
+ * with, and the instruction a resumed (or degraded) run reads.
4
+ *
5
+ * These are model-facing strings, so they live here rather than in a locale
6
+ * dictionary, exactly as the board's own tool descriptions do. Nothing in them
7
+ * is rendered to a person.
8
+ *
9
+ * @module dsh-task-board-ssh/host/prompt
10
+ */
11
+ import type { TaskRecord } from '../core/task-record.ts'
12
+ import type { SshTarget } from '../core/target.ts'
13
+ import type { SshPendingInstruction } from './payload.ts'
14
+
15
+ /** The tool family a proxy run has to drive the host with. */
16
+ export const SSH_TOOL_FAMILY = 'ssh_list, ssh_exec, ssh_upload and ssh_download'
17
+
18
+ /** Prefix a recorded summary carries when the instruction started a fresh run. */
19
+ export const SSH_DEGRADED_SUMMARY_MARKER = '[fresh run: this agent cannot resume, so the previous summary was carried in the prompt]'
20
+
21
+ /** Where a proxy run's work happens, in the words the model reads. */
22
+ function proxyPlacement(target: SshTarget): string {
23
+ const workspace = target.workspace
24
+ if (workspace.kind === 'in-place') {
25
+ return `Remote directory: ${workspace.path}`
26
+ }
27
+ const source = workspace.source
28
+ if (source.kind === 'url') {
29
+ const base = source.base === undefined ? '' : ` (base branch ${source.base})`
30
+ return `Repository: ${source.url}${base}. Create a per-run worktree of it on the host before you edit, and leave the result on the host.`
31
+ }
32
+ return `Repository: the workspace repository ${source.workspaceId}. It has to be sent to the host before the run, so ask the user to pin a repository URL instead when one is reachable there.`
33
+ }
34
+
35
+ /**
36
+ * Build the preamble a proxy card's local session opens with.
37
+ *
38
+ * The board injects it ahead of the card body on the same path it injects tag
39
+ * prefixes, so the session reads what this run IS before it reads the task: the
40
+ * work happens on a pinned host through the `ssh_*` tools, and nothing about the
41
+ * card is local.
42
+ * @param task - the card about to run.
43
+ * @param target - the target the card pins.
44
+ * @returns the preamble text.
45
+ */
46
+ export function proxyPreamble(task: TaskRecord, target: SshTarget): string {
47
+ return [
48
+ 'Remote execution target (task board SSH provider, proxy mode).',
49
+ `Host alias: ${target.host}`,
50
+ proxyPlacement(target),
51
+ `Run every command and every file operation for this card on that host through the ssh_* tools of the dsh-ssh plugin (${SSH_TOOL_FAMILY}); read the host list with ssh_list before you start if you are unsure of the alias. The paths above exist on the host, not on this machine, so do not do the work locally and do not assume a local path mirrors a remote one.`,
52
+ `Card: ${task.title} (id ${task.id})`,
53
+ ].join('\n')
54
+ }
55
+
56
+ /**
57
+ * Build the prompt one run reads.
58
+ *
59
+ * A start reads the card's own prompt. A follow-up or a rework that continues the
60
+ * agent's session reads the instruction alone, because the session already holds
61
+ * the work. A degraded follow-up — the agent cannot be resumed — reads what the
62
+ * previous run reported before it reads the instruction, which is the whole
63
+ * reason that path exists.
64
+ * @param task - the card being run.
65
+ * @param pending - the instruction this run carries, when it carries one.
66
+ * @param previousSummary - what the previous run reported, when it is known.
67
+ * @param resumed - whether the run continues the agent's session.
68
+ * @returns the text written to the run's prompt file.
69
+ */
70
+ export function runPrompt(
71
+ task: TaskRecord,
72
+ pending: SshPendingInstruction | undefined,
73
+ previousSummary: string | undefined,
74
+ resumed: boolean,
75
+ ): string {
76
+ if (pending === undefined) return task.prompt
77
+ const heading = pending.kind === 'rework' ? 'Rework instructions for the previous run of this card.' : 'Follow-up for the previous run of this card.'
78
+ if (resumed) return `${heading}\n\n${pending.text}`
79
+ const previous = previousSummary === undefined || previousSummary === ''
80
+ ? 'The previous run reported no summary.'
81
+ : `The previous run reported:\n${previousSummary}`
82
+ return [
83
+ heading,
84
+ 'The agent cannot be resumed in its earlier session, so this is a fresh run that carries what the previous run reported.',
85
+ previous,
86
+ 'Instruction:',
87
+ pending.text,
88
+ ].join('\n\n')
89
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Per-host admission: the concurrency ceiling and the first-in-first-out queue.
3
+ *
4
+ * The queue is not stored anywhere of its own — it is the ordered set of cards
5
+ * whose payload carries a queued run, which is what makes it survive a restart
6
+ * for free: the same cards, read in the same order, produce the same queue.
7
+ * Order is the instant each run was requested, with the run id as the tie-break
8
+ * so two runs requested in the same millisecond still have one order.
9
+ *
10
+ * @module dsh-task-board-ssh/host/queue
11
+ */
12
+
13
+ /** One run waiting for a slot on its host. */
14
+ export interface SshQueueEntry {
15
+ /** Card waiting for the slot. */
16
+ taskId: string
17
+ /** Run the card waits on. */
18
+ runId: string
19
+ /** Instant the run was requested (ms epoch). */
20
+ startedAt: number
21
+ }
22
+
23
+ /** What one admission pass decided. */
24
+ export interface SshAdmission {
25
+ /** Runs that may start now, in queue order. */
26
+ start: SshQueueEntry[]
27
+ /** Runs left waiting, in the order they will be reached. */
28
+ waiting: SshQueueEntry[]
29
+ }
30
+
31
+ /** Default ceiling of concurrent runs on one host. */
32
+ export const DEFAULT_PER_HOST_CAP = 2
33
+
34
+ /** Lowest accepted ceiling; one run at a time is the smallest queue worth naming. */
35
+ export const PER_HOST_CAP_MIN = 1
36
+
37
+ /** Highest accepted ceiling per host. */
38
+ export const PER_HOST_CAP_MAX = 16
39
+
40
+ /**
41
+ * Clamp a configured ceiling into the accepted range.
42
+ * @param value - configured value; anything unusable falls back to the default.
43
+ * @returns an integer between {@link PER_HOST_CAP_MIN} and {@link PER_HOST_CAP_MAX}.
44
+ */
45
+ export function normalizePerHostCap(value: unknown): number {
46
+ if (typeof value !== 'number' || !Number.isFinite(value)) return DEFAULT_PER_HOST_CAP
47
+ return Math.min(PER_HOST_CAP_MAX, Math.max(PER_HOST_CAP_MIN, Math.trunc(value)))
48
+ }
49
+
50
+ /**
51
+ * Order a host's queue the way it will be served.
52
+ * @param entries - every queued run of one host.
53
+ * @returns the same entries, oldest first.
54
+ */
55
+ export function orderQueue(entries: readonly SshQueueEntry[]): SshQueueEntry[] {
56
+ return [...entries].sort((left, right) => {
57
+ if (left.startedAt !== right.startedAt) return left.startedAt - right.startedAt
58
+ return left.runId < right.runId ? -1 : left.runId > right.runId ? 1 : 0
59
+ })
60
+ }
61
+
62
+ /**
63
+ * Decide which queued runs may start now.
64
+ * @param entries - every queued run of one host, in any order.
65
+ * @param running - how many runs of that host already hold a slot.
66
+ * @param cap - the host's ceiling.
67
+ * @returns the runs to start now and the ones still waiting.
68
+ */
69
+ export function admitRuns(entries: readonly SshQueueEntry[], running: number, cap: number): SshAdmission {
70
+ const ordered = orderQueue(entries)
71
+ const free = Math.max(0, normalizePerHostCap(cap) - Math.max(0, Math.trunc(running)))
72
+ return { start: ordered.slice(0, free), waiting: ordered.slice(free) }
73
+ }