@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,313 @@
1
+ /**
2
+ * The remote launcher, as text.
3
+ *
4
+ * One POSIX `sh` script, installed once per dsh-ssh host and re-entered for
5
+ * every verb; the state directory it works in is derived at run time, so this
6
+ * text carries no per-host value. It is a line array rather than a template
7
+ * literal so the shell quoting below stays literal: nothing in this file is
8
+ * interpolated by the bundler.
9
+ *
10
+ * @module dsh-task-board-ssh/core/launcher-script
11
+ */
12
+
13
+ /** Remote launcher source; the POSIX `sh` program the provider installs. */
14
+ export const LAUNCHER_SCRIPT: string = [
15
+ "#!/bin/sh",
16
+ "# Remote launcher for the task board SSH provider. POSIX sh only: no bash, no",
17
+ "# tmux and no systemd, because none of the three is guaranteed on a host the",
18
+ "# provider reaches over dsh-ssh.",
19
+ "#",
20
+ "# Verbs: start <runId>, status <runId>, tail <runId> <offset> [limit], stderr <runId> [limit], cancel <runId>.",
21
+ "# __exec is internal: the detached wrapper re-enters this file with it.",
22
+ "#",
23
+ "# State lives under $TASK_BOARD_SSH_STATE (default $HOME/.dsh/task-board-ssh),",
24
+ "# one directory per run under runs/<runId>/. The provider writes spec.json,",
25
+ "# cmd.sh, cwd and prompt.txt there; this script writes stdout.log, stderr.log,",
26
+ "# pid, exit and cancelled. It never parses spec.json: the command line it runs",
27
+ "# is cmd.sh, already quoted by the provider.",
28
+ "#",
29
+ "# Every verb prints one line of key=value pairs on stdout (tail/stderr print raw",
30
+ "# bytes), so the caller parses without a JSON reader on this side.",
31
+ "set -f",
32
+ "",
33
+ "STATE=${TASK_BOARD_SSH_STATE:-$HOME/.dsh/task-board-ssh}",
34
+ "RUNS=$STATE/runs",
35
+ "",
36
+ "die() {",
37
+ " printf '%s\\n' \"$1\" >&2",
38
+ " exit \"$2\"",
39
+ "}",
40
+ "",
41
+ "sleep_tick() {",
42
+ " sleep 0.05 2>/dev/null || sleep 1",
43
+ "}",
44
+ "",
45
+ "valid_run_id() {",
46
+ " case $1 in",
47
+ " ''|.|..) return 1 ;;",
48
+ " *[!A-Za-z0-9._-]*) return 1 ;;",
49
+ " esac",
50
+ " return 0",
51
+ "}",
52
+ "",
53
+ "alive() {",
54
+ " case $1 in",
55
+ " ''|*[!0-9]*) return 1 ;;",
56
+ " esac",
57
+ " kill -0 \"$1\" 2>/dev/null",
58
+ "}",
59
+ "",
60
+ "read_pid() {",
61
+ " [ -f \"$1/pid\" ] || return 1",
62
+ " cat \"$1/pid\"",
63
+ "}",
64
+ "",
65
+ "log_bytes() {",
66
+ " if [ -f \"$1/stdout.log\" ]; then",
67
+ " wc -c < \"$1/stdout.log\" | tr -d ' '",
68
+ " else",
69
+ " printf 0",
70
+ " fi",
71
+ "}",
72
+ "",
73
+ "print_status() {",
74
+ " dir=$1",
75
+ " bytes=$(log_bytes \"$dir\")",
76
+ " if [ -f \"$dir/exit\" ]; then",
77
+ " code=$(cat \"$dir/exit\")",
78
+ " if [ -f \"$dir/cancelled\" ]; then",
79
+ " printf 'state=cancelled exit=%s bytes=%s\\n' \"$code\" \"$bytes\"",
80
+ " else",
81
+ " printf 'state=exited exit=%s bytes=%s\\n' \"$code\" \"$bytes\"",
82
+ " fi",
83
+ " return 0",
84
+ " fi",
85
+ " pid=$(read_pid \"$dir\" 2>/dev/null || printf '')",
86
+ " if alive \"$pid\"; then",
87
+ " printf 'state=running pid=%s bytes=%s\\n' \"$pid\" \"$bytes\"",
88
+ " else",
89
+ " printf 'state=lost bytes=%s\\n' \"$bytes\"",
90
+ " fi",
91
+ "}",
92
+ "",
93
+ "record_exit() {",
94
+ " printf '%s\\n' \"$1\" > \"$dir/exit\"",
95
+ "}",
96
+ "",
97
+ "run_exec() {",
98
+ " dir=$1",
99
+ " trap 'record_exit 143; exit 143' TERM",
100
+ " trap 'record_exit 130; exit 130' INT",
101
+ " trap 'record_exit 129; exit 129' HUP",
102
+ " printf '%s\\n' \"$$\" > \"$dir/pid\"",
103
+ " if [ -f \"$dir/cancelled\" ]; then",
104
+ " record_exit 143",
105
+ " exit 143",
106
+ " fi",
107
+ " cwd=$dir",
108
+ " if [ -f \"$dir/cwd\" ]; then",
109
+ " cwd=$(cat \"$dir/cwd\")",
110
+ " fi",
111
+ " cd \"$cwd\" 2>/dev/null || { record_exit 125; exit 125; }",
112
+ " sh \"$dir/cmd.sh\" < /dev/null",
113
+ " code=$?",
114
+ " record_exit \"$code\"",
115
+ " exit \"$code\"",
116
+ "}",
117
+ "",
118
+ "wait_for_pid() {",
119
+ " i=0",
120
+ " while [ ! -s \"$1/pid\" ] && [ ! -f \"$1/exit\" ]; do",
121
+ " i=$((i + 1))",
122
+ " if [ \"$i\" -gt 200 ]; then",
123
+ " return 1",
124
+ " fi",
125
+ " sleep_tick",
126
+ " done",
127
+ " return 0",
128
+ "}",
129
+ "",
130
+ "report_running() {",
131
+ " printf 'state=running pid=%s bytes=%s started=%s\\n' \"$1\" \"$(log_bytes \"$2\")\" \"$3\"",
132
+ "}",
133
+ "",
134
+ "run_start() {",
135
+ " run_id=$1",
136
+ " dir=$RUNS/$run_id",
137
+ " mkdir -p \"$dir\" || die 'cannot create the run directory' 74",
138
+ " # A run that already recorded its exit is finished: start never reopens it.",
139
+ " if [ -f \"$dir/exit\" ]; then",
140
+ " print_status \"$dir\"",
141
+ " return 0",
142
+ " fi",
143
+ " if [ -f \"$dir/cancelled\" ]; then",
144
+ " record_exit 143",
145
+ " print_status \"$dir\"",
146
+ " return 0",
147
+ " fi",
148
+ " pid=$(read_pid \"$dir\" 2>/dev/null || printf '')",
149
+ " if alive \"$pid\"; then",
150
+ " report_running \"$pid\" \"$dir\" 0",
151
+ " return 0",
152
+ " fi",
153
+ " # The lock closes the window between the liveness check and the recorded",
154
+ " # pid, so two starts of one runId never produce two agents. Re-checking",
155
+ " # inside the lock prevents a racing/replayed starter from truncating logs",
156
+ " # or spawning a duplicate once the first starter releases its lock.",
157
+ " if mkdir \"$dir/lock\" 2>/dev/null; then",
158
+ " trap 'rmdir \"$dir/lock\" 2>/dev/null' EXIT",
159
+ " if [ -f \"$dir/exit\" ]; then",
160
+ " print_status \"$dir\"",
161
+ " return 0",
162
+ " fi",
163
+ " if [ -f \"$dir/cancelled\" ]; then",
164
+ " record_exit 143",
165
+ " print_status \"$dir\"",
166
+ " return 0",
167
+ " fi",
168
+ " pid=$(read_pid \"$dir\" 2>/dev/null || printf '')",
169
+ " if alive \"$pid\"; then",
170
+ " report_running \"$pid\" \"$dir\" 0",
171
+ " return 0",
172
+ " fi",
173
+ " rm -f \"$dir/exit\" \"$dir/pid\"",
174
+ " : > \"$dir/stdout.log\"",
175
+ " : > \"$dir/stderr.log\"",
176
+ " if command -v setsid >/dev/null 2>&1; then",
177
+ " setsid nohup sh \"$0\" __exec \"$dir\" >> \"$dir/stdout.log\" 2>> \"$dir/stderr.log\" < /dev/null &",
178
+ " else",
179
+ " nohup sh \"$0\" __exec \"$dir\" >> \"$dir/stdout.log\" 2>> \"$dir/stderr.log\" < /dev/null &",
180
+ " fi",
181
+ " wait_for_pid \"$dir\"",
182
+ " if [ -f \"$dir/exit\" ]; then",
183
+ " print_status \"$dir\"",
184
+ " return 0",
185
+ " fi",
186
+ " pid=$(read_pid \"$dir\" 2>/dev/null || printf '')",
187
+ " if alive \"$pid\"; then",
188
+ " report_running \"$pid\" \"$dir\" 1",
189
+ " return 0",
190
+ " fi",
191
+ " printf 'state=lost started=0\\n'",
192
+ " return 0",
193
+ " fi",
194
+ " wait_for_pid \"$dir\"",
195
+ " if [ -f \"$dir/exit\" ]; then",
196
+ " print_status \"$dir\"",
197
+ " return 0",
198
+ " fi",
199
+ " pid=$(read_pid \"$dir\" 2>/dev/null || printf '')",
200
+ " if alive \"$pid\"; then",
201
+ " report_running \"$pid\" \"$dir\" 0",
202
+ " return 0",
203
+ " fi",
204
+ " printf 'state=lost started=0\\n'",
205
+ "}",
206
+ "",
207
+ "run_status() {",
208
+ " dir=$RUNS/$1",
209
+ " if [ ! -d \"$dir\" ]; then",
210
+ " printf 'state=missing\\n'",
211
+ " return 0",
212
+ " fi",
213
+ " print_status \"$dir\"",
214
+ "}",
215
+ "",
216
+ "run_tail() {",
217
+ " dir=$RUNS/$1",
218
+ " offset=$2",
219
+ " limit=${3:-}",
220
+ " case $offset in",
221
+ " ''|*[!0-9]*) die 'offset must be a byte count' 65 ;;",
222
+ " esac",
223
+ " if [ -n \"$limit\" ]; then",
224
+ " case $limit in",
225
+ " *[!0-9]*) die 'limit must be a byte count' 65 ;;",
226
+ " esac",
227
+ " fi",
228
+ " if [ ! -f \"$dir/stdout.log\" ]; then",
229
+ " return 0",
230
+ " fi",
231
+ " if [ -n \"$limit\" ]; then",
232
+ " tail -c +$((offset + 1)) \"$dir/stdout.log\" | head -c \"$limit\"",
233
+ " else",
234
+ " tail -c +$((offset + 1)) \"$dir/stdout.log\"",
235
+ " fi",
236
+ "}",
237
+ "",
238
+ "run_stderr() {",
239
+ " dir=$RUNS/$1",
240
+ " limit=${2:-4096}",
241
+ " case $limit in",
242
+ " ''|*[!0-9]*) die 'limit must be a byte count' 65 ;;",
243
+ " esac",
244
+ " if [ ! -f \"$dir/stderr.log\" ]; then",
245
+ " return 0",
246
+ " fi",
247
+ " tail -c \"$limit\" \"$dir/stderr.log\"",
248
+ "}",
249
+ "",
250
+ "run_cancel() {",
251
+ " dir=$RUNS/$1",
252
+ " if [ ! -d \"$dir\" ]; then",
253
+ " printf 'state=missing\\n'",
254
+ " return 0",
255
+ " fi",
256
+ " # Mark cancellation before checking pid so a racing start or __exec sees it",
257
+ " # and aborts cleanly without breaking an active start lock.",
258
+ " : > \"$dir/cancelled\"",
259
+ " pid=$(read_pid \"$dir\" 2>/dev/null || printf '')",
260
+ " if ! alive \"$pid\"; then",
261
+ " if [ -f \"$dir/exit\" ]; then",
262
+ " print_status \"$dir\"",
263
+ " return 0",
264
+ " fi",
265
+ " printf 'state=not-running\\n'",
266
+ " return 0",
267
+ " fi",
268
+ " kill -s TERM -- \"-$pid\" 2>/dev/null || kill -s TERM \"$pid\" 2>/dev/null",
269
+ " i=0",
270
+ " while alive \"$pid\"; do",
271
+ " i=$((i + 1))",
272
+ " if [ \"$i\" -gt 100 ]; then",
273
+ " kill -s KILL -- \"-$pid\" 2>/dev/null || kill -s KILL \"$pid\" 2>/dev/null",
274
+ " if [ ! -f \"$dir/exit\" ]; then",
275
+ " printf '%s\\n' 137 > \"$dir/exit\"",
276
+ " fi",
277
+ " break",
278
+ " fi",
279
+ " sleep_tick",
280
+ " done",
281
+ " if [ ! -f \"$dir/exit\" ]; then",
282
+ " printf '%s\\n' 143 > \"$dir/exit\"",
283
+ " fi",
284
+ " printf 'state=cancelled pid=%s\\n' \"$pid\"",
285
+ "}",
286
+ "",
287
+ "verb=${1:-}",
288
+ "run_id=${2:-}",
289
+ "case $verb in",
290
+ " start|status|tail|stderr|cancel)",
291
+ " valid_run_id \"$run_id\" || die 'run id must be letters, digits, dots, underscores or hyphens' 65",
292
+ " ;;",
293
+ " __exec)",
294
+ " dir=${2:-}",
295
+ " [ -n \"$dir\" ] || die 'missing run directory' 64",
296
+ " run_exec \"$dir\"",
297
+ " exit 0",
298
+ " ;;",
299
+ " *)",
300
+ " printf 'usage: %s start|status|tail|stderr|cancel <runId> [offset] [limit]\\n' \"$0\" >&2",
301
+ " exit 64",
302
+ " ;;",
303
+ "esac",
304
+ "",
305
+ "case $verb in",
306
+ " start) run_start \"$run_id\" ;;",
307
+ " status) run_status \"$run_id\" ;;",
308
+ " tail) run_tail \"$run_id\" \"${3:-0}\" \"${4:-}\" ;;",
309
+ " stderr) run_stderr \"$run_id\" \"${3:-4096}\" ;;",
310
+ " cancel) run_cancel \"$run_id\" ;;",
311
+ "esac",
312
+ "",
313
+ ].join('\n')
@@ -0,0 +1,283 @@
1
+ /**
2
+ * The launcher's command construction and its output grammar.
3
+ *
4
+ * The remote side is one POSIX `sh` script ({@link LAUNCHER_SCRIPT}) installed
5
+ * once per host. This module builds every command the provider sends it, writes
6
+ * a run's files, and reads the one status line each verb answers, so nothing on
7
+ * this side concatenates a path or a run id into a command by hand.
8
+ *
9
+ * @module dsh-task-board-ssh/core/launcher
10
+ */
11
+ import type { SshAgentCommand } from './adapters/types.ts'
12
+ import { LAUNCHER_SCRIPT } from './launcher-script.ts'
13
+ import { shellEnsureDir, shellJoin, shellQuote, shellWriteFile } from './shell.ts'
14
+
15
+ /** Verbs the installed script accepts. */
16
+ export const LAUNCHER_VERBS = ['start', 'status', 'tail', 'stderr', 'cancel'] as const
17
+
18
+ /** One launcher verb. */
19
+ export type LauncherVerb = (typeof LAUNCHER_VERBS)[number]
20
+
21
+ /**
22
+ * State directory the provider owns on a host, relative to the remote `$HOME`.
23
+ * The provider resolves the absolute path once per host and passes it in, so no
24
+ * command depends on the remote shell expanding a tilde.
25
+ */
26
+ export const REMOTE_STATE_SUFFIX = '.dsh/task-board-ssh'
27
+
28
+ /** Every file a run directory holds, in the order the provider writes them. */
29
+ export const RUN_FILE_NAMES = [
30
+ 'spec.json',
31
+ 'prompt.txt',
32
+ 'cmd.sh',
33
+ 'cwd',
34
+ 'stdout.log',
35
+ 'stderr.log',
36
+ 'pid',
37
+ 'exit',
38
+ 'session',
39
+ 'cancelled',
40
+ ] as const
41
+
42
+ /** One file inside a run directory. */
43
+ export type RunFileName = (typeof RUN_FILE_NAMES)[number]
44
+
45
+ /** Run id grammar the script enforces, restated here so a bad id never leaves the host. */
46
+ const RUN_ID_RE = /^[A-Za-z0-9._-]{1,128}$/
47
+
48
+ /**
49
+ * Resolve the absolute state directory for a host's home directory.
50
+ * @param home - absolute remote home directory.
51
+ * @returns the state directory the provider installs the launcher under.
52
+ */
53
+ export function stateDirForHome(home: string): string {
54
+ return `${home.replace(/\/+$/, '')}/${REMOTE_STATE_SUFFIX}`
55
+ }
56
+
57
+ /**
58
+ * Short content digest of a launcher script, used in its file name.
59
+ *
60
+ * A digest rather than a version number: an installed script is replaced
61
+ * exactly when its text changes, so a host that already runs the current one is
62
+ * left alone. FNV-1a over UTF-16 code units is enough for a file name and keeps
63
+ * this module free of a platform crypto dependency.
64
+ * @param script - launcher source; defaults to the shipped script.
65
+ * @returns eight lower-case hex digits.
66
+ */
67
+ export function launcherScriptHash(script: string = LAUNCHER_SCRIPT): string {
68
+ let hash = 0x811c9dc5
69
+ for (let index = 0; index < script.length; index += 1) {
70
+ hash ^= script.charCodeAt(index)
71
+ hash = Math.imul(hash, 0x01000193) >>> 0
72
+ }
73
+ return hash.toString(16).padStart(8, '0')
74
+ }
75
+
76
+ /**
77
+ * Absolute remote path of the installed launcher.
78
+ * @param stateDir - absolute state directory.
79
+ * @param hash - script digest; defaults to the shipped script's.
80
+ * @returns `<stateDir>/runner-<hash>.sh`.
81
+ */
82
+ export function launcherScriptPath(stateDir: string, hash: string = launcherScriptHash()): string {
83
+ return `${stateDir}/runner-${hash}.sh`
84
+ }
85
+
86
+ /**
87
+ * Refuse a run id the remote script would refuse.
88
+ * @param runId - candidate id.
89
+ * @returns whether it matches the script's grammar.
90
+ */
91
+ export function isRunId(runId: string): boolean {
92
+ return runId !== '.' && runId !== '..' && RUN_ID_RE.test(runId)
93
+ }
94
+
95
+ /**
96
+ * Absolute remote directory of one run.
97
+ * @param stateDir - absolute state directory.
98
+ * @param runId - run identifier.
99
+ * @returns `<stateDir>/runs/<runId>`.
100
+ */
101
+ export function runDirectory(stateDir: string, runId: string): string {
102
+ if (!isRunId(runId)) throw new RangeError(`invalid run id: ${runId}`)
103
+ return `${stateDir}/runs/${runId}`
104
+ }
105
+
106
+ /**
107
+ * Absolute remote path of one run file.
108
+ * @param stateDir - absolute state directory.
109
+ * @param runId - run identifier.
110
+ * @param name - which file.
111
+ * @returns its absolute path.
112
+ */
113
+ export function runFilePath(stateDir: string, runId: string, name: RunFileName): string {
114
+ return `${runDirectory(stateDir, runId)}/${name}`
115
+ }
116
+
117
+ /** Suffix of the staging file one install writes before it replaces the launcher. */
118
+ const LAUNCHER_STAGING_SUFFIX = '.install'
119
+
120
+ /**
121
+ * Build the command that installs (or refreshes) the launcher on a host.
122
+ *
123
+ * The write lands on a staging file that is then renamed over the launcher, so
124
+ * the command is safe to replay while the host is using the script: `mv` within
125
+ * one directory is a rename(2), so a wrapper already executing the previous
126
+ * file keeps reading the bytes it opened. Writing the launcher path directly
127
+ * would truncate the script a live `__exec` wrapper is still reading, and a
128
+ * POSIX sh that reaches that truncation ends the run without writing its exit
129
+ * code.
130
+ * @param stateDir - absolute state directory.
131
+ * @param script - launcher source; defaults to the shipped script.
132
+ * @returns one shell command that is safe to replay.
133
+ */
134
+ export function buildLauncherInstallCommand(stateDir: string, script: string = LAUNCHER_SCRIPT): string {
135
+ const path = launcherScriptPath(stateDir, launcherScriptHash(script))
136
+ // Per-shell PID suffix prevents concurrent installs on the same host
137
+ // (default perHostCap = 2) from deleting or racing on one shared staging file.
138
+ const stagingExpr = `${shellQuote(path + LAUNCHER_STAGING_SUFFIX + '.')}$$`
139
+ return [
140
+ shellEnsureDir(stateDir),
141
+ `printf '%s' ${shellQuote(script)} > ${stagingExpr}`,
142
+ `chmod 700 ${stagingExpr}`,
143
+ `mv -f ${stagingExpr} ${shellQuote(path)}`,
144
+ ].join(' && ')
145
+ }
146
+
147
+ /**
148
+ * Build the command that invokes one verb.
149
+ * @param input - state directory, verb, run id and optional byte bounds.
150
+ * @returns one shell command.
151
+ */
152
+ export function buildLauncherCommand(input: {
153
+ /** Absolute state directory. */
154
+ stateDir: string
155
+ /** Verb to invoke. */
156
+ verb: LauncherVerb
157
+ /** Run the verb addresses. */
158
+ runId: string
159
+ /** Byte offset for `tail`; ignored by every other verb. */
160
+ offset?: number
161
+ /** Maximum byte count for `tail` or `stderr`; omitted reads to EOF / default. */
162
+ limit?: number
163
+ }): string {
164
+ if (!isRunId(input.runId)) throw new RangeError(`invalid run id: ${input.runId}`)
165
+ const scriptPath = launcherScriptPath(input.stateDir)
166
+ const words = ['sh', scriptPath, input.verb, input.runId]
167
+ if (input.verb === 'tail') {
168
+ const offset = input.offset ?? 0
169
+ if (!Number.isInteger(offset) || offset < 0) throw new RangeError(`invalid byte offset: ${String(offset)}`)
170
+ words.push(String(offset))
171
+ if (input.limit !== undefined) {
172
+ if (!Number.isInteger(input.limit) || input.limit <= 0) throw new RangeError(`invalid byte limit: ${String(input.limit)}`)
173
+ words.push(String(input.limit))
174
+ }
175
+ } else if (input.verb === 'stderr' && input.limit !== undefined) {
176
+ if (!Number.isInteger(input.limit) || input.limit <= 0) throw new RangeError(`invalid byte limit: ${String(input.limit)}`)
177
+ words.push(String(input.limit))
178
+ }
179
+ return `TASK_BOARD_SSH_STATE=${shellQuote(input.stateDir)} ${shellJoin(words)}`
180
+ }
181
+
182
+ /** The command body a run executes, as `cmd.sh` holds it. */
183
+ export function agentScript(command: SshAgentCommand): string {
184
+ // `run_exec` already runs `sh "$dir/cmd.sh" < /dev/null`, so templates
185
+ // without an adapter-managed `stdinFile` stay verbatim (preserving user
186
+ // redirections like `cmd < {prompt_file}` and pipelines like `cat ... | cmd`).
187
+ if (command.stdinFile === undefined) return command.command
188
+ return `${command.command} < ${shellQuote(command.stdinFile)}`
189
+ }
190
+
191
+ /**
192
+ * Build the commands that write one run's files before `start`.
193
+ *
194
+ * The provider writes the run directory, the prompt, the agent command, the
195
+ * working directory and the spec; the launcher writes only the files it owns
196
+ * (logs, pid, exit, cancelled), so neither side overwrites the other's state.
197
+ * @param input - state directory, run id and the run's content.
198
+ * @returns one shell command per write, in order.
199
+ */
200
+ export function buildRunFileCommands(input: {
201
+ /** Absolute state directory. */
202
+ stateDir: string
203
+ /** Run identifier. */
204
+ runId: string
205
+ /** Prompt text the agent reads. */
206
+ prompt: string
207
+ /** Command line the run executes. */
208
+ command: SshAgentCommand
209
+ /** Absolute remote directory the run works in. */
210
+ cwd: string
211
+ /** Opaque spec the provider keeps for its own reconciliation. */
212
+ spec: unknown
213
+ }): string[] {
214
+ const directory = runDirectory(input.stateDir, input.runId)
215
+ return [
216
+ shellEnsureDir(directory),
217
+ shellWriteFile(runFilePath(input.stateDir, input.runId, 'prompt.txt'), input.prompt),
218
+ shellWriteFile(runFilePath(input.stateDir, input.runId, 'cmd.sh'), agentScript(input.command)),
219
+ shellWriteFile(runFilePath(input.stateDir, input.runId, 'cwd'), input.cwd),
220
+ shellWriteFile(runFilePath(input.stateDir, input.runId, 'spec.json'), JSON.stringify(input.spec)),
221
+ ]
222
+ }
223
+
224
+ /** State one verb reported. */
225
+ export type LauncherRunState = 'running' | 'exited' | 'cancelled' | 'lost' | 'missing' | 'not-running' | 'unknown'
226
+
227
+ /** One parsed status line. */
228
+ export interface LauncherStatus {
229
+ /** State the launcher reported. */
230
+ state: LauncherRunState
231
+ /** Process group id the run owns, while it is running. */
232
+ pid?: number
233
+ /** Exit code the run recorded, once it settled. */
234
+ exitCode?: number
235
+ /** Bytes of `stdout.log` the launcher has seen. */
236
+ bytes?: number
237
+ /** Whether `start` spawned the agent on this call. */
238
+ started?: boolean
239
+ }
240
+
241
+ /** States a verb may report, as the grammar's vocabulary. */
242
+ const LAUNCHER_STATES: readonly LauncherRunState[] = [
243
+ 'running',
244
+ 'exited',
245
+ 'cancelled',
246
+ 'lost',
247
+ 'missing',
248
+ 'not-running',
249
+ ]
250
+
251
+ /**
252
+ * Read a verb's status line.
253
+ *
254
+ * The grammar is `key=value` pairs separated by spaces, one line. Anything
255
+ * else parses as `unknown` with the raw text preserved, because a shell that
256
+ * printed something unexpected is a fact the caller should record, not an
257
+ * exception.
258
+ * @param output - captured stdout of a `status` or `start` invocation.
259
+ * @returns the parsed state.
260
+ */
261
+ export function parseLauncherStatus(output: string): LauncherStatus {
262
+ const line = output.trim().split('\n').find(text => text.trim().length > 0) ?? ''
263
+ const fields = new Map<string, string>()
264
+ for (const token of line.split(/\s+/)) {
265
+ const separator = token.indexOf('=')
266
+ if (separator <= 0) continue
267
+ fields.set(token.slice(0, separator), token.slice(separator + 1))
268
+ }
269
+ const state = fields.get('state')
270
+ if (state === undefined || !(LAUNCHER_STATES as readonly string[]).includes(state)) {
271
+ return { state: 'unknown' }
272
+ }
273
+ const status: LauncherStatus = { state: state as LauncherRunState }
274
+ const pid = Number(fields.get('pid'))
275
+ if (Number.isInteger(pid) && pid > 0) status.pid = pid
276
+ const exitCode = Number(fields.get('exit'))
277
+ if (fields.has('exit') && Number.isInteger(exitCode)) status.exitCode = exitCode
278
+ const bytes = Number(fields.get('bytes'))
279
+ if (fields.has('bytes') && Number.isInteger(bytes)) status.bytes = bytes
280
+ if (fields.get('started') === '1') status.started = true
281
+ if (fields.get('started') === '0') status.started = false
282
+ return status
283
+ }