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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +85 -2
  4. package/README.zh.md +86 -0
  5. package/cordis.patch.yml +15 -0
  6. package/icon.svg +5 -0
  7. package/lib/client.js +4429 -0
  8. package/lib/index.js +6100 -0
  9. package/lib/types/client/PluginSettingsCard.d.ts +255 -0
  10. package/lib/types/client/RangeBubble.d.ts +46 -0
  11. package/lib/types/client/SegmentGroup.d.ts +28 -0
  12. package/lib/types/client/index.d.ts +100 -0
  13. package/lib/types/client/locales.d.ts +125 -0
  14. package/lib/types/client/seat-props.d.ts +53 -0
  15. package/lib/types/client/settings-entry-form.d.ts +49 -0
  16. package/lib/types/client/settings-form.d.ts +237 -0
  17. package/lib/types/client/ssh/card-decoration.d.ts +23 -0
  18. package/lib/types/client/ssh/compose-section.d.ts +7 -0
  19. package/lib/types/client/ssh/detail-section.d.ts +7 -0
  20. package/lib/types/client/ssh/extension.d.ts +54 -0
  21. package/lib/types/client/ssh/log-buffer.d.ts +128 -0
  22. package/lib/types/client/ssh/log-view.d.ts +37 -0
  23. package/lib/types/client/ssh/model.d.ts +130 -0
  24. package/lib/types/client/ssh/settings-section.d.ts +134 -0
  25. package/lib/types/client/ssh/summary.d.ts +160 -0
  26. package/lib/types/client/ssh/target-form.d.ts +60 -0
  27. package/lib/types/core/action.d.ts +89 -0
  28. package/lib/types/core/adapters/claude.d.ts +15 -0
  29. package/lib/types/core/adapters/codex.d.ts +15 -0
  30. package/lib/types/core/adapters/custom.d.ts +29 -0
  31. package/lib/types/core/adapters/dsh.d.ts +21 -0
  32. package/lib/types/core/adapters/index.d.ts +25 -0
  33. package/lib/types/core/adapters/types.d.ts +76 -0
  34. package/lib/types/core/contract.d.ts +445 -0
  35. package/lib/types/core/launcher-script.d.ts +13 -0
  36. package/lib/types/core/launcher.d.ts +153 -0
  37. package/lib/types/core/ledger.d.ts +123 -0
  38. package/lib/types/core/shell.d.ts +61 -0
  39. package/lib/types/core/target.d.ts +143 -0
  40. package/lib/types/core/task-record.d.ts +63 -0
  41. package/lib/types/core/workspace.d.ts +74 -0
  42. package/lib/types/host/board.d.ts +71 -0
  43. package/lib/types/host/engine.d.ts +418 -0
  44. package/lib/types/host/extension.d.ts +59 -0
  45. package/lib/types/host/logs.d.ts +135 -0
  46. package/lib/types/host/payload.d.ts +75 -0
  47. package/lib/types/host/prompt.d.ts +44 -0
  48. package/lib/types/host/queue.d.ts +53 -0
  49. package/lib/types/host/remote.d.ts +120 -0
  50. package/lib/types/host/settings.d.ts +149 -0
  51. package/lib/types/host/timers.d.ts +20 -0
  52. package/lib/types/host/tools.d.ts +15 -0
  53. package/lib/types/host/workspace/errors.d.ts +29 -0
  54. package/lib/types/host/workspace/git.d.ts +108 -0
  55. package/lib/types/host/workspace/in-place.d.ts +36 -0
  56. package/lib/types/host/workspace/index.d.ts +28 -0
  57. package/lib/types/host/workspace/layout.d.ts +62 -0
  58. package/lib/types/host/workspace/local-git.d.ts +72 -0
  59. package/lib/types/host/workspace/remote-git.d.ts +111 -0
  60. package/lib/types/host/workspace/remote.d.ts +85 -0
  61. package/lib/types/host/workspace/types.d.ts +28 -0
  62. package/lib/types/host/workspace-seam.d.ts +100 -0
  63. package/lib/types/index.d.ts +97 -0
  64. package/lib/types/mount-once.d.ts +55 -0
  65. package/locale/en.json +6 -0
  66. package/locale/zh.json +6 -0
  67. package/package.json +89 -3
  68. package/src/client/PluginSettingsCard.tsx +838 -0
  69. package/src/client/RangeBubble.tsx +164 -0
  70. package/src/client/SegmentGroup.tsx +93 -0
  71. package/src/client/css-modules.d.ts +5 -0
  72. package/src/client/index.ts +195 -0
  73. package/src/client/locales.ts +257 -0
  74. package/src/client/seat-props.ts +58 -0
  75. package/src/client/settings-card.module.css +821 -0
  76. package/src/client/settings-entry-form.ts +141 -0
  77. package/src/client/settings-form.ts +529 -0
  78. package/src/client/ssh/card-decoration.tsx +55 -0
  79. package/src/client/ssh/compose-section.tsx +147 -0
  80. package/src/client/ssh/detail-section.tsx +345 -0
  81. package/src/client/ssh/extension.ts +271 -0
  82. package/src/client/ssh/log-buffer.ts +224 -0
  83. package/src/client/ssh/log-view.tsx +149 -0
  84. package/src/client/ssh/model.ts +299 -0
  85. package/src/client/ssh/settings-section.tsx +401 -0
  86. package/src/client/ssh/summary.ts +388 -0
  87. package/src/client/ssh/target-form.tsx +380 -0
  88. package/src/client/ssh.module.css +617 -0
  89. package/src/core/action.ts +270 -0
  90. package/src/core/adapters/claude.ts +64 -0
  91. package/src/core/adapters/codex.ts +83 -0
  92. package/src/core/adapters/custom.ts +88 -0
  93. package/src/core/adapters/dsh.ts +87 -0
  94. package/src/core/adapters/index.ts +74 -0
  95. package/src/core/adapters/types.ts +95 -0
  96. package/src/core/contract.ts +510 -0
  97. package/src/core/launcher-script.ts +313 -0
  98. package/src/core/launcher.ts +283 -0
  99. package/src/core/ledger.ts +372 -0
  100. package/src/core/shell.ts +77 -0
  101. package/src/core/target.ts +413 -0
  102. package/src/core/task-record.ts +65 -0
  103. package/src/core/workspace.ts +78 -0
  104. package/src/host/board.ts +103 -0
  105. package/src/host/engine.ts +1602 -0
  106. package/src/host/extension.ts +304 -0
  107. package/src/host/logs.ts +297 -0
  108. package/src/host/payload.ts +134 -0
  109. package/src/host/prompt.ts +89 -0
  110. package/src/host/queue.ts +73 -0
  111. package/src/host/remote.ts +328 -0
  112. package/src/host/settings.ts +294 -0
  113. package/src/host/timers.ts +33 -0
  114. package/src/host/tools.ts +259 -0
  115. package/src/host/workspace/errors.ts +43 -0
  116. package/src/host/workspace/git.ts +305 -0
  117. package/src/host/workspace/in-place.ts +58 -0
  118. package/src/host/workspace/index.ts +37 -0
  119. package/src/host/workspace/layout.ts +122 -0
  120. package/src/host/workspace/local-git.ts +164 -0
  121. package/src/host/workspace/remote-git.ts +244 -0
  122. package/src/host/workspace/remote.ts +181 -0
  123. package/src/host/workspace/types.ts +34 -0
  124. package/src/host/workspace-seam.ts +132 -0
  125. package/src/index.ts +243 -0
  126. package/src/mount-once.ts +142 -0
@@ -0,0 +1,304 @@
1
+ /**
2
+ * The SSH provider assembled as one task-board extension.
3
+ *
4
+ * Everything SSH-specific lives behind this factory: the board admits it through
5
+ * the cordis `taskBoard` service, hands it the capability face, and never learns
6
+ * what the provider does with it. The factory imports no board internals — only
7
+ * the same-shape contract in `../core/contract.ts` — and it probes the two seams
8
+ * a board revision may or may not serve (`launch.intercept` and the in-process
9
+ * action seat) instead of assuming them, so a board that serves neither still
10
+ * mounts this extension: its tools answer, its polls stop, and the reason is
11
+ * logged rather than thrown at the board.
12
+ *
13
+ * @module dsh-task-board-ssh/host/extension
14
+ */
15
+ import { parseSshActionRequest, type SshActionReply } from '../core/action.ts'
16
+ import {
17
+ TASK_BOARD_API_VERSION,
18
+ type DshSshService,
19
+ type TaskBoardExtension,
20
+ type TaskBoardExtensionActionRequest,
21
+ type TaskBoardExtensionHost,
22
+ } from '../core/contract.ts'
23
+ import { SSH_AGENT_KINDS, type SshAgentKind, type SshExecutionMode } from '../core/target.ts'
24
+ import type { BoardActionSeat } from './board.ts'
25
+ import { SshRunEngine, type SshEngineReply, type SshLogPage } from './engine.ts'
26
+ import {
27
+ SshSettingsError,
28
+ type SshProviderSettings,
29
+ type SshSettingsPatch,
30
+ type SshSettingsWriter,
31
+ } from './settings.ts'
32
+ import type { HostTimerFace } from './timers.ts'
33
+ import { buildSshTools } from './tools.ts'
34
+ import type { SshWorkspaceStrategyResolver } from './workspace-seam.ts'
35
+
36
+ /** Extension id this provider registers under, and the key of its ledger payload. */
37
+ export const SSH_EXTENSION_ID = 'ssh'
38
+
39
+ /**
40
+ * Actions this package handles on top of the frozen card protocol.
41
+ *
42
+ * The six card actions are the board's own vocabulary and are parsed by
43
+ * `src/core/action.ts`. These three are host-half additions a settings card or a
44
+ * log viewer drives: the log pager (a remote file read by offset, never a new
45
+ * HTTP route) and the configuration read/write pair, whose write goes through the
46
+ * extension's single write path and therefore through `ctx.settings.mutate`.
47
+ */
48
+ export const SSH_HOST_ACTIONS = {
49
+ /** Read one page of a run's log by byte offset. */
50
+ readLog: 'read-log',
51
+ /** Read the extension's effective settings. */
52
+ setupStatus: 'setup-status',
53
+ /** Write the extension's settings through the one write path. */
54
+ setupSave: 'setup-save',
55
+ } as const
56
+
57
+ /** Everything the extension needs from its mount. */
58
+ export interface SshExtensionOptions {
59
+ /** The `dshSsh` forwarder every remote operation goes through. */
60
+ ssh: DshSshService
61
+ /** Live configuration, read at use time. */
62
+ settings: () => SshProviderSettings
63
+ /** The one configuration write path. */
64
+ settingsWriter: SshSettingsWriter
65
+ /** Timer seat the poll cadence runs on. */
66
+ timers: HostTimerFace
67
+ /** The board's in-process action seat, resolved per call so a late one is honoured. */
68
+ seat?: () => BoardActionSeat | undefined
69
+ /** Placement strategies, when this deployment serves any. */
70
+ workspaces?: SshWorkspaceStrategyResolver
71
+ /** Resolve a local workspace id to the repository root a git run bundles. */
72
+ localRepository?: (workspaceId: string) => string | undefined
73
+ /** Clock (ms epoch). */
74
+ now?: () => number
75
+ /** Identifier source for request ids and run ids. */
76
+ uuid?: () => string
77
+ /** Poll cadence, in milliseconds. */
78
+ pollIntervalMs?: number
79
+ /** Ceiling for one remote command, in milliseconds. */
80
+ commandTimeoutMs?: number
81
+ /** Where a refusal or a failed remote call is reported. */
82
+ log?: (message: string, detail?: unknown) => void
83
+ /** Register a hook invoked whenever volatile settings change while mounted. */
84
+ onSettingsHook?: (notify: (() => void) | undefined) => void
85
+ }
86
+
87
+ /** The message of anything thrown below. */
88
+ function messageOf(error: unknown): string {
89
+ return error instanceof Error ? error.message : String(error)
90
+ }
91
+
92
+ /** Read one plain object off an untyped payload. */
93
+ function recordOf(value: unknown): Record<string, unknown> {
94
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : {}
95
+ }
96
+
97
+ /** Read one bounded non-negative integer option. */
98
+ function optionalNumber(value: unknown): number | undefined {
99
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.trunc(value) : undefined
100
+ }
101
+
102
+ /** Read the log pager's options out of an action payload. */
103
+ function readLogOptions(payload: Record<string, unknown>): { runId?: string; offset?: number; limit?: number } {
104
+ const options: { runId?: string; offset?: number; limit?: number } = {}
105
+ if (typeof payload.runId === 'string' && payload.runId !== '') options.runId = payload.runId
106
+ const offset = optionalNumber(payload.offset)
107
+ if (offset !== undefined) options.offset = offset
108
+ const limit = optionalNumber(payload.limit)
109
+ if (limit !== undefined) options.limit = limit
110
+ return options
111
+ }
112
+
113
+ /** One validated settings patch, or the reason it was refused. */
114
+ type SettingsPatchResult = { ok: true; patch: SshSettingsPatch } | { ok: false; error: string }
115
+
116
+ /** Read one settings patch out of an action payload, refusing a malformed field. */
117
+ function readSettingsPatch(payload: Record<string, unknown>): SettingsPatchResult {
118
+ const patch: SshSettingsPatch = {}
119
+ if (payload.enabled !== undefined) {
120
+ if (typeof payload.enabled !== 'boolean') return { ok: false, error: 'enabled must be a boolean' }
121
+ patch.enabled = payload.enabled
122
+ }
123
+ if (payload.defaultHost !== undefined) {
124
+ if (typeof payload.defaultHost !== 'string') return { ok: false, error: 'defaultHost must be a string' }
125
+ patch.defaultHost = payload.defaultHost
126
+ }
127
+ if (payload.defaultAgent !== undefined) {
128
+ if (!(SSH_AGENT_KINDS as readonly string[]).includes(String(payload.defaultAgent))) {
129
+ return { ok: false, error: `defaultAgent must be one of: ${SSH_AGENT_KINDS.join(', ')}` }
130
+ }
131
+ patch.defaultAgent = String(payload.defaultAgent) as SshAgentKind
132
+ }
133
+ if (payload.defaultMode !== undefined) {
134
+ if (payload.defaultMode !== 'direct' && payload.defaultMode !== 'proxy') {
135
+ return { ok: false, error: 'defaultMode must be "direct" or "proxy"' }
136
+ }
137
+ patch.defaultMode = payload.defaultMode as SshExecutionMode
138
+ }
139
+ if (payload.perHostCap !== undefined) {
140
+ if (typeof payload.perHostCap !== 'number' || !Number.isFinite(payload.perHostCap)) {
141
+ return { ok: false, error: 'perHostCap must be a number' }
142
+ }
143
+ patch.perHostCap = payload.perHostCap
144
+ }
145
+ if (payload.agentCommands !== undefined) {
146
+ if (!Array.isArray(payload.agentCommands)) return { ok: false, error: 'agentCommands must be an array' }
147
+ const rows: Array<{ kind: SshAgentKind; command: string; resumeCommand?: string }> = []
148
+ for (const entry of payload.agentCommands) {
149
+ const row = recordOf(entry)
150
+ const kind = (SSH_AGENT_KINDS as readonly string[]).includes(String(row.kind)) ? String(row.kind) as SshAgentKind : undefined
151
+ if (kind === undefined) return { ok: false, error: `an agentCommands row names an unknown agent: ${String(row.kind)}` }
152
+ if (typeof row.command !== 'string') return { ok: false, error: 'an agentCommands row needs a command template' }
153
+ rows.push({
154
+ kind,
155
+ command: row.command,
156
+ ...(typeof row.resumeCommand === 'string' ? { resumeCommand: row.resumeCommand } : {}),
157
+ })
158
+ }
159
+ patch.agentCommands = rows
160
+ }
161
+ return { ok: true, patch }
162
+ }
163
+
164
+ /** Route one action to the engine and the settings writer. */
165
+ async function routeAction(
166
+ request: TaskBoardExtensionActionRequest,
167
+ engine: SshRunEngine | undefined,
168
+ writer: SshSettingsWriter,
169
+ ): Promise<unknown> {
170
+ const payload = recordOf(request.payload)
171
+ switch (request.action) {
172
+ case SSH_HOST_ACTIONS.readLog: {
173
+ if (engine === undefined) return { ok: false, error: 'the SSH extension is not running' }
174
+ if (typeof request.taskId !== 'string' || request.taskId === '') return { ok: false, error: 'read-log needs a taskId' }
175
+ const page: SshLogPage = await engine.readLog(request.taskId, readLogOptions(payload))
176
+ return page
177
+ }
178
+ case SSH_HOST_ACTIONS.setupStatus: {
179
+ return {
180
+ ok: true,
181
+ writable: writer.available(),
182
+ settings: engine === undefined ? null : engine.summary().defaults,
183
+ }
184
+ }
185
+ case SSH_HOST_ACTIONS.setupSave: {
186
+ const parsed = readSettingsPatch(payload)
187
+ if (!parsed.ok) return { ok: false, error: parsed.error }
188
+ try {
189
+ const result = await writer.save(parsed.patch)
190
+ return { ok: true, entry: result.entry, fields: result.fields }
191
+ } catch (error) {
192
+ return {
193
+ ok: false,
194
+ code: error instanceof SshSettingsError ? error.code : 'settings-write-failed',
195
+ error: messageOf(error),
196
+ }
197
+ }
198
+ }
199
+ default:
200
+ break
201
+ }
202
+ if (engine === undefined) return { ok: false, error: 'the SSH extension is not running' }
203
+ const parsed = parseSshActionRequest(request)
204
+ if (!parsed.ok) {
205
+ const reply: SshActionReply = { ok: false, error: 'the request was refused', issues: parsed.errors }
206
+ return reply
207
+ }
208
+ const action = parsed.value
209
+ let reply: SshEngineReply
210
+ switch (action.action) {
211
+ case 'run':
212
+ reply = engine.runNow(action.taskId)
213
+ break
214
+ case 'cancel':
215
+ reply = engine.cancel(action.taskId)
216
+ break
217
+ case 'follow-up':
218
+ reply = await engine.instruct(action.taskId, action.text, 'follow-up')
219
+ break
220
+ case 'rework':
221
+ reply = await engine.instruct(action.taskId, action.instructions, 'rework')
222
+ break
223
+ case 'set-target':
224
+ reply = engine.setTarget(action.taskId, action.target)
225
+ break
226
+ default:
227
+ // The detail view names the run (and optional byte offset for paging past
228
+ // one window) whose log it wants, so a settled run can be read in full.
229
+ reply = await engine.refresh(action.taskId, action.runId, action.offset)
230
+ break
231
+ }
232
+ const answer: SshActionReply = reply.ok
233
+ ? {
234
+ ok: true,
235
+ taskId: reply.taskId,
236
+ ...(reply.runId === undefined ? {} : { runId: reply.runId }),
237
+ ...(reply.message === undefined ? {} : { message: reply.message }),
238
+ }
239
+ : { ok: false, error: reply.error }
240
+ return answer
241
+ }
242
+
243
+ /**
244
+ * Build the SSH provider extension.
245
+ * @param options - the mount's faces, settings and clock.
246
+ * @returns the extension the board registers.
247
+ */
248
+ export function createSshExtension(options: SshExtensionOptions): TaskBoardExtension {
249
+ let engine: SshRunEngine | undefined
250
+ const toolDisposers: Array<() => void> = []
251
+ const log = options.log ?? ((message: string, detail?: unknown) => {
252
+ if (detail === undefined) console.error('[dsh-task-board-ssh] ' + message)
253
+ else console.error('[dsh-task-board-ssh] ' + message, detail)
254
+ })
255
+
256
+ return {
257
+ id: SSH_EXTENSION_ID,
258
+ apiVersion: TASK_BOARD_API_VERSION,
259
+ enabled: () => options.settings().enabled,
260
+ start(host: TaskBoardExtensionHost): void {
261
+ const live = new SshRunEngine({
262
+ host,
263
+ ssh: options.ssh,
264
+ timers: options.timers,
265
+ settings: options.settings,
266
+ ...(options.seat === undefined ? {} : { seat: options.seat }),
267
+ ...(options.workspaces === undefined ? {} : { workspaces: options.workspaces }),
268
+ ...(options.localRepository === undefined ? {} : { localRepository: options.localRepository }),
269
+ ...(options.now === undefined ? {} : { now: options.now }),
270
+ ...(options.uuid === undefined ? {} : { uuid: options.uuid }),
271
+ ...(options.pollIntervalMs === undefined ? {} : { pollIntervalMs: options.pollIntervalMs }),
272
+ ...(options.commandTimeoutMs === undefined ? {} : { commandTimeoutMs: options.commandTimeoutMs }),
273
+ log,
274
+ })
275
+ engine = live
276
+ options.onSettingsHook?.(() => { live.onSettingsUpdated() })
277
+ live.start()
278
+ for (const tool of buildSshTools(live)) {
279
+ try {
280
+ toolDisposers.push(host.registerTool(tool))
281
+ } catch (error) {
282
+ // A missing tool registry costs the three tools, not the provider.
283
+ log(`the tool ${tool.name} could not register`, error)
284
+ }
285
+ }
286
+ try {
287
+ host.publish(live.summary())
288
+ } catch (error) {
289
+ log('the initial summary was refused', error)
290
+ }
291
+ },
292
+ stop(): void {
293
+ options.onSettingsHook?.(undefined)
294
+ for (const dispose of toolDisposers.splice(0)) {
295
+ try { dispose() } catch { /* best-effort */ }
296
+ }
297
+ engine?.stop()
298
+ engine = undefined
299
+ },
300
+ async handleAction(request: TaskBoardExtensionActionRequest): Promise<unknown> {
301
+ return await routeAction(request, engine, options.settingsWriter)
302
+ },
303
+ }
304
+ }
@@ -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
+ }