dsh-remote-vs 0.13.0 → 0.15.1

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/README.en.md +455 -443
  2. package/README.md +408 -396
  3. package/lib/client.js +8062 -2651
  4. package/lib/index.js +1058 -288
  5. package/lib/p2-router-fs.js +1 -1
  6. package/lib/p2-router-refs.js +89 -10
  7. package/lib/p2-router-spill.js +73 -1
  8. package/lib/p2-router-subprocess.js +18 -6
  9. package/lib/spill-retention-BwKEWrl5.js +115 -0
  10. package/lib/{ssh-proc-arI5lm4W.js → ssh-proc-VKWn_LZC.js} +17 -0
  11. package/lib/types/archive.d.ts +1 -1
  12. package/lib/types/changes/recorder.d.ts +34 -2
  13. package/lib/types/client/CodeEditor.d.ts +12 -0
  14. package/lib/types/client/ConnectionStatus.d.ts +17 -0
  15. package/lib/types/client/DirectoryFlow.d.ts +2 -0
  16. package/lib/types/client/DoctorPanel.d.ts +25 -0
  17. package/lib/types/client/QuickOpen.d.ts +17 -0
  18. package/lib/types/client/RemoteExplorer.d.ts +192 -1
  19. package/lib/types/client/RemoteRoot.d.ts +17 -0
  20. package/lib/types/client/SearchView.d.ts +55 -0
  21. package/lib/types/client/TerminalView.d.ts +38 -0
  22. package/lib/types/client/WorkspaceWizard.d.ts +17 -0
  23. package/lib/types/client/api.d.ts +54 -4
  24. package/lib/types/client/changes/undo-affordance.d.ts +16 -0
  25. package/lib/types/client/changes/undo-context.d.ts +14 -18
  26. package/lib/types/client/changes/undo-target.d.ts +78 -0
  27. package/lib/types/client/connection.d.ts +111 -0
  28. package/lib/types/client/doctor.d.ts +122 -0
  29. package/lib/types/client/download.d.ts +35 -5
  30. package/lib/types/client/downloads.d.ts +18 -1
  31. package/lib/types/client/file-open-probe.d.ts +64 -0
  32. package/lib/types/client/i18n.d.ts +1 -1
  33. package/lib/types/client/quickopen-model.d.ts +332 -0
  34. package/lib/types/client/scm/DiffView.d.ts +34 -0
  35. package/lib/types/client/scm/actions.d.ts +18 -0
  36. package/lib/types/client/scm/diff-model.d.ts +17 -1
  37. package/lib/types/client/scm/git-cache.d.ts +10 -2
  38. package/lib/types/client/scm/read-queue.d.ts +2 -1
  39. package/lib/types/client/scm/stage-queue.d.ts +13 -0
  40. package/lib/types/client/scm/status-map.d.ts +3 -1
  41. package/lib/types/client/store.d.ts +114 -5
  42. package/lib/types/client/vsc/FindWidget.d.ts +7 -0
  43. package/lib/types/client/vsc/save-shortcut.d.ts +57 -0
  44. package/lib/types/deploy.d.ts +44 -2
  45. package/lib/types/git-format.d.ts +15 -0
  46. package/lib/types/http.d.ts +44 -0
  47. package/lib/types/p2/file-refs.d.ts +39 -2
  48. package/lib/types/p2/helper-rpc.d.ts +26 -0
  49. package/lib/types/p2/router-spill.d.ts +19 -0
  50. package/lib/types/p2/router-subprocess.d.ts +2 -0
  51. package/lib/types/p2/spill-retention.d.ts +74 -0
  52. package/lib/types/p2/worlds.d.ts +11 -0
  53. package/lib/types/pool.d.ts +73 -11
  54. package/lib/types/protocol.d.ts +63 -0
  55. package/lib/types/routes.d.ts +18 -0
  56. package/lib/types/sftp.d.ts +114 -8
  57. package/lib/types/store.d.ts +34 -0
  58. package/lib/types/timeouts.d.ts +14 -0
  59. package/lib/{worlds-C6Xha1mQ.js → worlds-Be1YE2Ot.js} +727 -78
  60. package/package.json +1 -1
  61. package/src/archive.ts +41 -9
  62. package/src/changes/recorder.ts +227 -31
  63. package/src/changes/status.ts +37 -1
  64. package/src/client/CodeEditor.tsx +84 -2
  65. package/src/client/ConnectionStatus.tsx +130 -0
  66. package/src/client/DirectoryFlow.tsx +40 -5
  67. package/src/client/DoctorPanel.tsx +202 -0
  68. package/src/client/DownloadDock.tsx +13 -25
  69. package/src/client/EditorPane.tsx +291 -7
  70. package/src/client/HostsView.tsx +17 -8
  71. package/src/client/QuickOpen.tsx +371 -0
  72. package/src/client/RemoteDirectoryPicker.tsx +54 -3
  73. package/src/client/RemoteExplorer.tsx +879 -160
  74. package/src/client/RemoteRoot.tsx +178 -1
  75. package/src/client/SearchView.tsx +180 -6
  76. package/src/client/SettingsHosts.tsx +1 -1
  77. package/src/client/TerminalView.tsx +174 -9
  78. package/src/client/WorkspaceWizard.tsx +110 -16
  79. package/src/client/WorkspacesView.tsx +22 -6
  80. package/src/client/api.ts +197 -11
  81. package/src/client/changes/ChangesDock.tsx +35 -8
  82. package/src/client/changes/undo-affordance.ts +33 -0
  83. package/src/client/changes/undo-context.ts +14 -18
  84. package/src/client/changes/undo-target.ts +139 -0
  85. package/src/client/connection.ts +264 -0
  86. package/src/client/doctor.ts +441 -0
  87. package/src/client/download.ts +148 -12
  88. package/src/client/downloads.ts +43 -2
  89. package/src/client/file-open-probe.ts +83 -0
  90. package/src/client/i18n.ts +244 -0
  91. package/src/client/index.tsx +5 -2
  92. package/src/client/quickopen-model.ts +778 -0
  93. package/src/client/remote-file-open.ts +21 -33
  94. package/src/client/scm/DiffView.tsx +116 -6
  95. package/src/client/scm/ScmPanel.tsx +19 -0
  96. package/src/client/scm/actions.ts +34 -2
  97. package/src/client/scm/diff-model.ts +33 -37
  98. package/src/client/scm/git-cache.ts +61 -4
  99. package/src/client/scm/read-queue.ts +33 -2
  100. package/src/client/scm/stage-queue.ts +72 -1
  101. package/src/client/scm/status-map.ts +22 -1
  102. package/src/client/store.tsx +704 -21
  103. package/src/client/vsc/FindWidget.tsx +20 -0
  104. package/src/client/vsc/kit.tsx +115 -6
  105. package/src/client/vsc/reveal-line.ts +33 -14
  106. package/src/client/vsc/save-shortcut.ts +131 -0
  107. package/src/client/vsc/vsc.css +419 -0
  108. package/src/deploy.ts +185 -33
  109. package/src/git-format.ts +136 -22
  110. package/src/git-ops.ts +14 -6
  111. package/src/http.ts +80 -12
  112. package/src/importers.ts +80 -21
  113. package/src/index.ts +21 -1
  114. package/src/p2/file-refs.ts +112 -10
  115. package/src/p2/helper-rpc.ts +73 -36
  116. package/src/p2/router-spill.ts +96 -1
  117. package/src/p2/router-subprocess.ts +18 -5
  118. package/src/p2/spill-retention.ts +134 -0
  119. package/src/p2/ssh-proc.ts +22 -0
  120. package/src/p2/worlds.ts +24 -0
  121. package/src/pool.ts +329 -47
  122. package/src/protocol.ts +66 -0
  123. package/src/routes.ts +251 -43
  124. package/src/sftp.ts +486 -26
  125. package/src/store.ts +207 -85
  126. package/src/terminal.ts +38 -2
  127. package/src/timeouts.ts +14 -0
  128. package/src/tools.ts +14 -5
package/src/store.ts CHANGED
@@ -2,9 +2,9 @@
2
2
  * Durable store for dsh-remote-vs: hosts + workspace bindings in
3
3
  * $DSH_HOME/dsh-remote.json (0600, atomic tmp+rename writes).
4
4
  */
5
- import { existsSync, statSync, openSync, readFileSync, renameSync, writeSync, closeSync } from 'node:fs'
5
+ import { existsSync, statSync, openSync, readFileSync, renameSync, writeSync, closeSync, fsyncSync, mkdirSync } from 'node:fs'
6
6
  import { randomUUID } from 'node:crypto'
7
- import { join } from 'node:path'
7
+ import { dirname, join } from 'node:path'
8
8
  import { aliasRoot, keysDir, storePath } from './paths.ts'
9
9
  import type {
10
10
  RemoteDeployState,
@@ -45,6 +45,28 @@ function assertAlias(alias: unknown): asserts alias is string {
45
45
  }
46
46
  }
47
47
 
48
+ /**
49
+ * Replays one read-modify-write before giving up. Two processes sharing
50
+ * `$DSH_HOME` (desktop + `dsh web`) can each land an edit between the other's
51
+ * read and write; a single retry almost always settles it, and the third attempt
52
+ * fails loud instead of silently dropping someone's change.
53
+ */
54
+ const MUTATION_ATTEMPTS = 3
55
+
56
+ /**
57
+ * Validate the SHAPE of an `auth` patch before it is merged.
58
+ *
59
+ * `update()` used to treat anything whose `kind` was not `'key'` as a password
60
+ * patch: `{kind:'garbage'}` silently kept the stored password (HTTP 200), and
61
+ * `auth: null` threw an engine TypeError. The merge below (and `normalize()`)
62
+ * must only ever see the two declared kinds, with a real object to read from.
63
+ */
64
+ function assertAuthPatch(auth: unknown): asserts auth is HostPayload['auth'] {
65
+ if (typeof auth !== 'object' || auth === null) throw new Error('auth must be an object')
66
+ const kind = (auth as { kind?: unknown }).kind
67
+ if (kind !== 'key' && kind !== 'password') throw new Error('auth.kind must be key or password')
68
+ }
69
+
48
70
  /** Payload accepted by create/update (secrets included, host-side only). */
49
71
  export interface HostPayload {
50
72
  alias: string
@@ -139,15 +161,75 @@ export class RemoteStore {
139
161
  // one is picked up by that same re-read, which re-arms the fast path.
140
162
  this.stamp = undefined
141
163
  const payload = JSON.stringify(this.doc, null, 2)
164
+ const dir = dirname(this.file)
165
+ // A fresh $DSH_HOME may not exist yet: the first host/workspace write must
166
+ // not fail with ENOENT.
167
+ mkdirSync(dir, { recursive: true })
142
168
  const tmp = `${this.file}.${process.pid}.tmp`
143
169
  // 0600 from creation (Windows: best effort, mode is advisory there).
144
170
  const fd = openSync(tmp, 'w', 0o600)
145
171
  try {
146
172
  writeSync(fd, payload)
173
+ // Flush the bytes BEFORE the rename: a power loss/blue screen must not
174
+ // leave the store empty or half written (the next boot refuses to load
175
+ // that). Best effort — an OS refusing fsync must not fail the save.
176
+ try {
177
+ fsyncSync(fd)
178
+ } catch {
179
+ // Durability is improved, not guaranteed.
180
+ }
147
181
  } finally {
148
182
  closeSync(fd)
149
183
  }
150
184
  renameSync(tmp, this.file)
185
+ // Make the rename itself durable (POSIX directory fsync). Windows cannot
186
+ // open a directory for fsync, so it keeps the file-level flush above.
187
+ if (process.platform !== 'win32') {
188
+ let dirFd: number | undefined
189
+ try {
190
+ dirFd = openSync(dir, 'r')
191
+ fsyncSync(dirFd)
192
+ } catch {
193
+ // Best effort.
194
+ } finally {
195
+ if (dirFd !== undefined) {
196
+ try {
197
+ closeSync(dirFd)
198
+ } catch {
199
+ // Ignore.
200
+ }
201
+ }
202
+ }
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Re-read, mutate, then write only while the file has not changed underneath.
208
+ *
209
+ * Every mutation here rewrites the WHOLE document, so a plain
210
+ * read-modify-write let the last writer win: desktop and `dsh web` share
211
+ * `$DSH_HOME/dsh-remote.json` by design, and one side's host edit could
212
+ * disappear without any error. Re-reading at the start plus a stamp re-check
213
+ * right before the write turns that into a replay on fresh content.
214
+ *
215
+ * `apply` must only touch `this.doc` and return a value (no I/O, no logging):
216
+ * a conflicting attempt is executed again against the reloaded document.
217
+ * The final rename window is still unguarded (a real lock needs blocking I/O);
218
+ * this narrows the lost-update window from a whole user edit to microseconds.
219
+ */
220
+ private mutate<T>(apply: (doc: StoreDoc) => T): T {
221
+ for (let attempt = 0; attempt < MUTATION_ATTEMPTS; attempt += 1) {
222
+ this.reload()
223
+ const base: FileStamp = this.stamp ?? null
224
+ const before = JSON.stringify(this.doc)
225
+ const result = apply(this.doc)
226
+ // Nothing changed (e.g. deleting an unknown alias): do not rewrite the file.
227
+ if (JSON.stringify(this.doc) === before) return result
228
+ if (!sameStamp(base, this.stampOf() ?? null)) continue
229
+ this.save()
230
+ return result
231
+ }
232
+ throw new Error(`${this.file}: another process keeps editing the store; retry the operation`)
151
233
  }
152
234
 
153
235
  // ------------------------------------------------------------- hosts
@@ -173,69 +255,94 @@ export class RemoteStore {
173
255
 
174
256
  create(payload: HostPayload): RemoteHostEntry {
175
257
  assertAlias(payload.alias)
176
- if (this.get(payload.alias) !== undefined) throw new Error(`alias already exists: ${payload.alias}`)
177
- const entry = this.normalize(payload, undefined)
178
- this.doc.hosts.push(entry)
179
- this.save()
180
- return entry
258
+ return this.mutate(() => {
259
+ if (this.doc.hosts.some(host => host.alias === payload.alias)) {
260
+ throw new Error(`alias already exists: ${payload.alias}`)
261
+ }
262
+ const entry = this.normalize(payload, undefined)
263
+ this.doc.hosts.push(entry)
264
+ return entry
265
+ })
181
266
  }
182
267
 
183
268
  update(alias: string, patch: Partial<Omit<HostPayload, 'alias'>>): RemoteHostEntry {
184
- const current = this.require(alias)
185
- // Empty auth materials mean "keep the stored one" (the browser never
186
- // echoes secrets back, so an untouched field arrives empty/omitted).
187
- let auth = patch.auth ?? current.auth
188
- if (patch.auth !== undefined) {
189
- if (patch.auth.kind === 'key') {
190
- const keyPath = (patch.auth.keyPath ?? '').trim()
191
- auth = {
192
- kind: 'key',
193
- keyPath: keyPath !== ''
194
- ? keyPath
195
- : current.auth.kind === 'key'
196
- ? (current.auth.keyPath as string)
197
- : '',
198
- ...(patch.auth.passphrase !== undefined
199
- ? { passphrase: patch.auth.passphrase }
200
- : current.auth.kind === 'key' && current.auth.passphrase !== undefined
201
- ? { passphrase: current.auth.passphrase }
202
- : {}),
203
- }
204
- } else {
205
- const password = patch.auth.password ?? ''
206
- auth = {
207
- kind: 'password',
208
- password: password !== ''
209
- ? password
210
- : current.auth.kind === 'password'
211
- ? (current.auth.password as string)
212
- : '',
269
+ // The HTTP route casts an arbitrary JSON body here, so the SHAPE has to be
270
+ // checked before the merge: otherwise an unknown `auth.kind` silently became
271
+ // a password patch (and `auth: null` threw an engine TypeError).
272
+ if (patch.auth !== undefined) assertAuthPatch(patch.auth)
273
+ return this.mutate(() => {
274
+ const index = this.doc.hosts.findIndex(h => h.alias === alias)
275
+ if (index < 0) throw new Error(`unknown host alias: ${alias}`)
276
+ const current = this.doc.hosts[index] as RemoteHostEntry
277
+ // Empty auth materials mean "keep the stored one" (the browser never
278
+ // echoes secrets back, so an untouched field arrives empty/omitted).
279
+ let auth = patch.auth ?? current.auth
280
+ if (patch.auth !== undefined) {
281
+ if (patch.auth.kind === 'key') {
282
+ const keyPath = (patch.auth.keyPath ?? '').trim()
283
+ auth = {
284
+ kind: 'key',
285
+ keyPath: keyPath !== ''
286
+ ? keyPath
287
+ : current.auth.kind === 'key'
288
+ ? (current.auth.keyPath as string)
289
+ : '',
290
+ ...(patch.auth.passphrase !== undefined
291
+ ? { passphrase: patch.auth.passphrase }
292
+ : current.auth.kind === 'key' && current.auth.passphrase !== undefined
293
+ ? { passphrase: current.auth.passphrase }
294
+ : {}),
295
+ }
296
+ } else {
297
+ const password = patch.auth.password ?? ''
298
+ auth = {
299
+ kind: 'password',
300
+ password: password !== ''
301
+ ? password
302
+ : current.auth.kind === 'password'
303
+ ? (current.auth.password as string)
304
+ : '',
305
+ }
213
306
  }
214
307
  }
215
- }
216
- const merged: HostPayload = {
217
- alias,
218
- host: patch.host ?? current.host,
219
- port: patch.port ?? current.port,
220
- user: patch.user ?? current.user,
221
- auth,
222
- description: patch.description ?? current.description,
223
- tags: patch.tags ?? current.tags,
224
- }
225
- const next = this.normalize(merged, current)
226
- const index = this.doc.hosts.findIndex(h => h.alias === alias)
227
- this.doc.hosts[index] = next
228
- this.save()
229
- return next
308
+ const merged: HostPayload = {
309
+ alias,
310
+ host: patch.host ?? current.host,
311
+ port: patch.port ?? current.port,
312
+ user: patch.user ?? current.user,
313
+ auth,
314
+ description: patch.description ?? current.description,
315
+ tags: patch.tags ?? current.tags,
316
+ }
317
+ const next = this.normalize(merged, current)
318
+ this.doc.hosts[index] = next
319
+ return next
320
+ })
230
321
  }
231
322
 
323
+ /**
324
+ * Delete one host AND its workspace bindings.
325
+ *
326
+ * The cascade has to keep the tombstone contract (see `removeWorkspace`): a
327
+ * binding that disappears while its alias dir stays on disk is no longer
328
+ * routed, but DSH's workspace registry still lists that dir, so a session
329
+ * rooted there would quietly execute LOCALLY against an empty folder instead
330
+ * of failing closed. Every cascaded binding is therefore tombstoned in the
331
+ * SAME atomic write as the removal — there is no on-disk state where the
332
+ * binding is gone but its tombstone is missing.
333
+ */
232
334
  remove(alias: string): boolean {
233
- const before = this.doc.hosts.length
234
- this.doc.hosts = this.doc.hosts.filter(h => h.alias !== alias)
235
- this.doc.workspaces = this.doc.workspaces.filter(w => w.alias !== alias)
236
- if (this.doc.hosts.length === before) return false
237
- this.save()
238
- return true
335
+ return this.mutate(() => {
336
+ const hosts = this.doc.hosts.filter(h => h.alias !== alias)
337
+ // Unknown alias: do not mutate (and do not record tombstones for nothing).
338
+ if (hosts.length === this.doc.hosts.length) return false
339
+ this.doc.hosts = hosts
340
+ for (const binding of this.doc.workspaces) {
341
+ if (binding.alias === alias) this.recordTombstone(join(aliasRoot(), binding.id))
342
+ }
343
+ this.doc.workspaces = this.doc.workspaces.filter(w => w.alias !== alias)
344
+ return true
345
+ })
239
346
  }
240
347
 
241
348
  private normalize(payload: HostPayload, current: RemoteHostEntry | undefined): RemoteHostEntry {
@@ -306,10 +413,12 @@ export class RemoteStore {
306
413
  }
307
414
 
308
415
  setDeploy(alias: string, state: RemoteDeployState): void {
309
- const entry = this.require(alias)
310
- entry.deploy = state
311
- entry.updatedAt = Date.now()
312
- this.save()
416
+ this.mutate(() => {
417
+ const entry = this.doc.hosts.find(h => h.alias === alias)
418
+ if (entry === undefined) throw new Error(`unknown host alias: ${alias}`)
419
+ entry.deploy = state
420
+ entry.updatedAt = Date.now()
421
+ })
313
422
  }
314
423
 
315
424
  // -------------------------------------------------------- workspaces
@@ -321,40 +430,53 @@ export class RemoteStore {
321
430
 
322
431
  createWorkspace(payload: WorkspacePayload): RemoteWorkspaceBinding {
323
432
  if (typeof payload.name !== 'string' || payload.name.trim() === '') throw new Error('name must be a non-empty string')
324
- this.require(payload.alias)
325
433
  if (typeof payload.remotePath !== 'string' || !payload.remotePath.startsWith('/')) {
326
434
  throw new Error('remotePath must be an absolute POSIX path')
327
435
  }
328
- const binding: RemoteWorkspaceBinding = {
329
- id: randomUUID().slice(0, 8),
330
- name: payload.name.trim(),
331
- alias: payload.alias,
332
- remotePath: payload.remotePath,
333
- createdAt: Date.now(),
334
- }
335
- this.doc.workspaces.push(binding)
336
- this.save()
337
- return binding
436
+ return this.mutate(() => {
437
+ if (!this.doc.hosts.some(host => host.alias === payload.alias)) {
438
+ throw new Error(`unknown host alias: ${payload.alias}`)
439
+ }
440
+ const binding: RemoteWorkspaceBinding = {
441
+ id: randomUUID().slice(0, 8),
442
+ name: payload.name.trim(),
443
+ alias: payload.alias,
444
+ remotePath: payload.remotePath,
445
+ createdAt: Date.now(),
446
+ }
447
+ this.doc.workspaces.push(binding)
448
+ return binding
449
+ })
338
450
  }
339
451
 
340
452
  removeWorkspace(id: string): boolean {
341
- this.reload()
342
- const victim = this.doc.workspaces.find(w => w.id === id)
343
- if (victim === undefined) return false
344
- // Tombstone the alias BEFORE dropping the binding (history stays readable,
345
- // new tool calls fail closed instead of silently running locally).
346
- this.addTombstone(join(aliasRoot(), id))
347
- this.doc.workspaces = this.doc.workspaces.filter(w => w.id !== id)
348
- this.save()
349
- return true
453
+ return this.mutate(() => {
454
+ const victim = this.doc.workspaces.find(w => w.id === id)
455
+ if (victim === undefined) return false
456
+ // Tombstone the alias BEFORE dropping the binding (history stays readable,
457
+ // new tool calls fail closed instead of silently running locally).
458
+ this.recordTombstone(join(aliasRoot(), id))
459
+ this.doc.workspaces = this.doc.workspaces.filter(w => w.id !== id)
460
+ return true
461
+ })
462
+ }
463
+
464
+ /**
465
+ * Record one tombstone without writing (idempotent).
466
+ *
467
+ * The caller owns `save()` so a change covering several bindings lands in ONE
468
+ * atomic write: a crash between two writes must never leave a binding removed
469
+ * while its tombstone is still missing.
470
+ */
471
+ private recordTombstone(aliasPath: string): void {
472
+ if (!this.doc.tombstones.includes(aliasPath)) this.doc.tombstones.push(aliasPath)
350
473
  }
351
474
 
352
475
  /** Record a removed alias path (idempotent). */
353
476
  addTombstone(aliasPath: string): void {
354
- if (!this.doc.tombstones.includes(aliasPath)) {
355
- this.doc.tombstones.push(aliasPath)
356
- this.save()
357
- }
477
+ this.mutate(() => {
478
+ this.recordTombstone(aliasPath)
479
+ })
358
480
  }
359
481
 
360
482
  listTombstones(): string[] {
package/src/terminal.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  * detaches (reattach by id). Frames are JSON text (see protocol.ts).
4
4
  */
5
5
  import { randomUUID } from 'node:crypto'
6
+ import { StringDecoder } from 'node:string_decoder'
6
7
  import type { WebSocket } from 'ws'
7
8
  import type { ClientChannel } from 'ssh2'
8
9
  import type { RemotePool } from './pool.ts'
@@ -21,6 +22,14 @@ interface Session {
21
22
  paused: boolean
22
23
  /** Fires once the last socket has been gone for EMPTY_SOCKET_TTL_MS. */
23
24
  reap: ReturnType<typeof setTimeout> | undefined
25
+ /**
26
+ * One decoder per stream: an SSH data chunk can end in the middle of a UTF-8
27
+ * character (a CJK glyph is 3 bytes, an emoji 4), and `chunk.toString('utf8')`
28
+ * would turn both halves into U+FFFD. `pool.ts` decodes exec output with the
29
+ * same API for exactly this reason.
30
+ */
31
+ outDecoder: StringDecoder
32
+ errDecoder: StringDecoder
24
33
  }
25
34
 
26
35
  /**
@@ -65,6 +74,14 @@ const OUT_LOW_WATER = 1 * 1024 * 1024
65
74
  */
66
75
  export const TERMINAL_MAX_FRAME_BYTES = 1024 * 1024
67
76
 
77
+ /**
78
+ * `WebSocket.OPEN` (RFC 6455 readyState 1).
79
+ *
80
+ * Used to detect a socket that closed while a shell was still being opened: the
81
+ * library never replays a `close` event to a listener attached afterwards.
82
+ */
83
+ const WS_OPEN = 1
84
+
68
85
  export class TerminalSessionRegistry {
69
86
  private readonly sessions = new Map<string, Session>()
70
87
 
@@ -95,17 +112,26 @@ export class TerminalSessionRegistry {
95
112
  pending: 0,
96
113
  paused: false,
97
114
  reap: undefined,
115
+ outDecoder: new StringDecoder('utf8'),
116
+ errDecoder: new StringDecoder('utf8'),
98
117
  }
99
118
  this.sessions.set(id, session)
100
119
  channel.on('data', (chunk: Buffer) => {
101
- this.broadcast(session, { t: 'out', d: chunk.toString('utf8') })
120
+ const text = session.outDecoder.write(chunk)
121
+ if (text !== '') this.broadcast(session, { t: 'out', d: text })
102
122
  })
103
123
  channel.stderr.on('data', (chunk: Buffer) => {
104
- this.broadcast(session, { t: 'out', d: chunk.toString('utf8') })
124
+ const text = session.errDecoder.write(chunk)
125
+ if (text !== '') this.broadcast(session, { t: 'out', d: text })
105
126
  })
106
127
  channel.on('close', (code: number | null) => {
107
128
  session.alive = false
108
129
  session.exitCode = code
130
+ // Flush the decoder-held tail BEFORE the exit frame: a command's last
131
+ // character may still be sitting in the decoder when the channel closes.
132
+ for (const tail of [session.outDecoder.end(), session.errDecoder.end()]) {
133
+ if (tail !== '') this.broadcast(session, { t: 'out', d: tail })
134
+ }
109
135
  this.broadcast(session, { t: 'exit', code })
110
136
  for (const socket of session.sockets) {
111
137
  try {
@@ -222,6 +248,16 @@ export class TerminalSessionRegistry {
222
248
  }
223
249
  ws.on('close', detach)
224
250
  ws.on('error', detach)
251
+ /**
252
+ * The socket may have closed while `pool.shell()` was still dialing: a cold
253
+ * connection takes seconds, and a page reload (or a closed tab) during it
254
+ * happens well before those listeners exist. EventEmitter does not replay
255
+ * events, so without this the socket would sit in `sockets` forever, no
256
+ * detach would ever run, no reap would ever arm — and the session, its PTY
257
+ * and the pooled connection's hold would leak for the life of the process.
258
+ * `readyState` is the only way to observe "already gone" from here.
259
+ */
260
+ if (ws.readyState !== WS_OPEN) detach()
225
261
  }
226
262
 
227
263
  /** Keep the shell for a while (reload can reattach), then close it for good. */
package/src/timeouts.ts CHANGED
@@ -18,6 +18,20 @@
18
18
  */
19
19
  import type { RemoteTimeouts } from './protocol.ts'
20
20
 
21
+ /**
22
+ * An operation that ran out of its wall-clock budget.
23
+ *
24
+ * Tagged on purpose: callers have to tell "the remote never answered" from a real
25
+ * remote failure (a missing path must not cost the session), and matching on the
26
+ * message text would silently stop working the moment the template changed.
27
+ *
28
+ * It lives in this module because "a budget ran out" is a timeout fact, not a
29
+ * pool or an SFTP fact: both halves need the same type to keep the distinction
30
+ * (the Host decides not to paint the link red, and the client must not downgrade
31
+ * the editor to read-only for it).
32
+ */
33
+ export class DeadlineError extends Error {}
34
+
21
35
  /** Smallest accepted timeout: below this, local work would start failing. */
22
36
  export const MIN_TIMEOUT_MS = 1_000
23
37
 
package/src/tools.ts CHANGED
@@ -9,6 +9,7 @@ import type { RemotePool } from './pool.ts'
9
9
  import { RemoteFiles } from './sftp.ts'
10
10
  import type { RemoteStore } from './store.ts'
11
11
  import type { RemoteExecResult, RemoteHostSummary } from './protocol.ts'
12
+ import { clampExecTimeout, MAX_TIMEOUT_MS } from './timeouts.ts'
12
13
 
13
14
  function text(value: string): ContentBlock[] {
14
15
  return [{ type: 'text', text: value }]
@@ -169,7 +170,7 @@ export function remoteExecTool(deps: RemoteToolsDeps): ReturnType<typeof defineT
169
170
  parameters: {
170
171
  alias: { type: 'string', description: 'Host alias from remote_hosts.' },
171
172
  command: { type: 'string', description: 'Shell command to run on the remote host.' },
172
- timeoutMs: { type: 'number', description: 'Timeout in ms (default 60000, max 600000).' },
173
+ timeoutMs: { type: 'number', description: `Timeout in ms (default 60000, max ${MAX_TIMEOUT_MS}).` },
173
174
  },
174
175
  output: {
175
176
  schema: {
@@ -188,9 +189,9 @@ export function remoteExecTool(deps: RemoteToolsDeps): ReturnType<typeof defineT
188
189
  render: (_args, value: AgentExecOut) => text(renderExec({ ...value, exitCode: value.exitCode ?? null })),
189
190
  },
190
191
  async execute(args) {
191
- const timeoutMs = typeof args.timeoutMs === 'number' && Number.isFinite(args.timeoutMs)
192
- ? Math.min(Math.max(Math.floor(args.timeoutMs), 1000), 600_000)
193
- : undefined
192
+ // One clamp for every exec surface: the HTTP routes use the same helper,
193
+ // so the agent tool cannot drift below/above the Host's own limit.
194
+ const timeoutMs = clampExecTimeout(args.timeoutMs)
194
195
  const result = await deps.pool.exec(
195
196
  args.alias as string,
196
197
  args.command as string,
@@ -314,7 +315,15 @@ export function remoteWriteTool(deps: RemoteToolsDeps): ReturnType<typeof define
314
315
  },
315
316
  async execute(args) {
316
317
  const files = new RemoteFiles(deps.pool)
317
- return files.write(args.alias as string, args.path as string, args.content as string, 'utf8')
318
+ const written = await files.write(args.alias as string, args.path as string, args.content as string, 'utf8')
319
+ /**
320
+ * Exactly the declared shape. `write` also reports the version it left
321
+ * behind (the editor's save guard reads it), but the model has no use for
322
+ * a timestamp and this schema refuses undeclared keys — DSH rejects such a
323
+ * result BEFORE the model ever sees it, which would make this tool
324
+ * uncallable rather than merely verbose.
325
+ */
326
+ return { size: written.size }
318
327
  },
319
328
  })
320
329
  }