@linxin666/dsh-win-bash 0.0.0-stage → 0.4.8
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.
- package/LICENSE +202 -0
- package/PROVENANCE.md +215 -0
- package/README.i18n.yaml +6 -0
- package/README.md +264 -2
- package/README.zh.md +221 -0
- package/cordis.patch.yml +13 -0
- package/lib/index.js +2756 -0
- package/lib/types/background.d.ts +169 -0
- package/lib/types/config.d.ts +130 -0
- package/lib/types/gate.d.ts +179 -0
- package/lib/types/index.d.ts +104 -0
- package/lib/types/protocol.d.ts +90 -0
- package/lib/types/pwsh-replacement.d.ts +140 -0
- package/lib/types/runtime.d.ts +115 -0
- package/lib/types/shell.d.ts +184 -0
- package/lib/types/tool.d.ts +123 -0
- package/package.json +58 -3
- package/runtime/win32-x64/checksums.sha256 +91 -0
- package/runtime/win32-x64/etc/bash.bashrc +69 -0
- package/runtime/win32-x64/etc/fstab +6 -0
- package/runtime/win32-x64/etc/msystem +27 -0
- package/runtime/win32-x64/etc/msystem.d/CLANG64 +7 -0
- package/runtime/win32-x64/etc/msystem.d/CLANGARM64 +7 -0
- package/runtime/win32-x64/etc/msystem.d/MINGW32 +7 -0
- package/runtime/win32-x64/etc/msystem.d/MINGW64 +7 -0
- package/runtime/win32-x64/etc/msystem.d/MSYS +4 -0
- package/runtime/win32-x64/etc/msystem.d/UCRT64 +7 -0
- package/runtime/win32-x64/etc/nsswitch.conf +12 -0
- package/runtime/win32-x64/etc/package-versions.txt +67 -0
- package/runtime/win32-x64/etc/profile +146 -0
- package/runtime/win32-x64/etc/profile.d/bash_profile.sh +11 -0
- package/runtime/win32-x64/etc/profile.d/lang.sh +19 -0
- package/runtime/win32-x64/licenses/GPL-2.0.txt +338 -0
- package/runtime/win32-x64/licenses/GPL-3.0.txt +674 -0
- package/runtime/win32-x64/licenses/LGPL-2.1.txt +501 -0
- package/runtime/win32-x64/licenses/LGPL-3.0.txt +165 -0
- package/runtime/win32-x64/licenses/expat-COPYING.txt +21 -0
- package/runtime/win32-x64/licenses/gcc-libs-RUNTIME.LIBRARY.EXCEPTION.txt +73 -0
- package/runtime/win32-x64/licenses/gettext-runtime-COPYING.LIB.txt +501 -0
- package/runtime/win32-x64/licenses/gettext-runtime-COPYING.txt +13 -0
- package/runtime/win32-x64/licenses/git-for-windows-LICENSE.txt +360 -0
- package/runtime/win32-x64/licenses/heimdal-LICENSE.txt +33 -0
- package/runtime/win32-x64/licenses/libcbor-LICENSE.md +21 -0
- package/runtime/win32-x64/licenses/libffi-LICENSE.txt +21 -0
- package/runtime/win32-x64/licenses/libfido2-LICENSE.txt +26 -0
- package/runtime/win32-x64/licenses/libiconv-COPYING.LIB.txt +501 -0
- package/runtime/win32-x64/licenses/libiconv-COPYING.txt +674 -0
- package/runtime/win32-x64/licenses/libopenssl-LICENSE.txt +177 -0
- package/runtime/win32-x64/licenses/libpcre-LICENCE.txt +93 -0
- package/runtime/win32-x64/licenses/libsqlite-LICENSE +25 -0
- package/runtime/win32-x64/licenses/ncurses-LICENSE +29 -0
- package/runtime/win32-x64/licenses/openssh-LICENCE.txt +412 -0
- package/runtime/win32-x64/licenses/zlib-LICENSE +22 -0
- package/runtime/win32-x64/usr/bin/awk.exe +0 -0
- package/runtime/win32-x64/usr/bin/b2sum.exe +0 -0
- package/runtime/win32-x64/usr/bin/basename.exe +0 -0
- package/runtime/win32-x64/usr/bin/basenc.exe +0 -0
- package/runtime/win32-x64/usr/bin/bash.exe +0 -0
- package/runtime/win32-x64/usr/bin/cat.exe +0 -0
- package/runtime/win32-x64/usr/bin/cmp.exe +0 -0
- package/runtime/win32-x64/usr/bin/comm.exe +0 -0
- package/runtime/win32-x64/usr/bin/cp.exe +0 -0
- package/runtime/win32-x64/usr/bin/cut.exe +0 -0
- package/runtime/win32-x64/usr/bin/dash.exe +0 -0
- package/runtime/win32-x64/usr/bin/date.exe +0 -0
- package/runtime/win32-x64/usr/bin/diff.exe +0 -0
- package/runtime/win32-x64/usr/bin/diff3.exe +0 -0
- package/runtime/win32-x64/usr/bin/dirname.exe +0 -0
- package/runtime/win32-x64/usr/bin/echo.exe +0 -0
- package/runtime/win32-x64/usr/bin/env.exe +0 -0
- package/runtime/win32-x64/usr/bin/expr.exe +0 -0
- package/runtime/win32-x64/usr/bin/false.exe +0 -0
- package/runtime/win32-x64/usr/bin/find.exe +0 -0
- package/runtime/win32-x64/usr/bin/grep.exe +0 -0
- package/runtime/win32-x64/usr/bin/head.exe +0 -0
- package/runtime/win32-x64/usr/bin/ls.exe +0 -0
- package/runtime/win32-x64/usr/bin/mkdir.exe +0 -0
- package/runtime/win32-x64/usr/bin/mktemp.exe +0 -0
- package/runtime/win32-x64/usr/bin/msys-2.0.dll +0 -0
- package/runtime/win32-x64/usr/bin/msys-gcc_s-seh-1.dll +0 -0
- package/runtime/win32-x64/usr/bin/msys-gmp-10.dll +0 -0
- package/runtime/win32-x64/usr/bin/msys-iconv-2.dll +0 -0
- package/runtime/win32-x64/usr/bin/msys-intl-8.dll +0 -0
- package/runtime/win32-x64/usr/bin/msys-mpfr-6.dll +0 -0
- package/runtime/win32-x64/usr/bin/msys-ncursesw6.dll +0 -0
- package/runtime/win32-x64/usr/bin/msys-pcre-1.dll +0 -0
- package/runtime/win32-x64/usr/bin/msys-readline8.dll +0 -0
- package/runtime/win32-x64/usr/bin/mv.exe +0 -0
- package/runtime/win32-x64/usr/bin/pathchk.exe +0 -0
- package/runtime/win32-x64/usr/bin/printf.exe +0 -0
- package/runtime/win32-x64/usr/bin/pwd.exe +0 -0
- package/runtime/win32-x64/usr/bin/readlink.exe +0 -0
- package/runtime/win32-x64/usr/bin/rm.exe +0 -0
- package/runtime/win32-x64/usr/bin/rmdir.exe +0 -0
- package/runtime/win32-x64/usr/bin/sdiff.exe +0 -0
- package/runtime/win32-x64/usr/bin/sed.exe +0 -0
- package/runtime/win32-x64/usr/bin/seq.exe +0 -0
- package/runtime/win32-x64/usr/bin/sh.exe +0 -0
- package/runtime/win32-x64/usr/bin/sleep.exe +0 -0
- package/runtime/win32-x64/usr/bin/sort.exe +0 -0
- package/runtime/win32-x64/usr/bin/tail.exe +0 -0
- package/runtime/win32-x64/usr/bin/test.exe +0 -0
- package/runtime/win32-x64/usr/bin/touch.exe +0 -0
- package/runtime/win32-x64/usr/bin/tr.exe +0 -0
- package/runtime/win32-x64/usr/bin/true.exe +0 -0
- package/runtime/win32-x64/usr/bin/uname.exe +0 -0
- package/runtime/win32-x64/usr/bin/uniq.exe +0 -0
- package/runtime/win32-x64/usr/bin/wc.exe +0 -0
- package/runtime/win32-x64/usr/bin/xargs.exe +0 -0
- package/src/background.ts +270 -0
- package/src/config.ts +209 -0
- package/src/gate.ts +308 -0
- package/src/index.ts +277 -0
- package/src/protocol.ts +130 -0
- package/src/pwsh-replacement.ts +435 -0
- package/src/runtime.ts +240 -0
- package/src/shell.ts +630 -0
- package/src/tool.ts +481 -0
package/src/shell.ts
ADDED
|
@@ -0,0 +1,630 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One persistent bash process per calling agent, driven over piped stdio.
|
|
3
|
+
*
|
|
4
|
+
* Why pipes and not the host's terminal seam: this tool needs a persistent
|
|
5
|
+
* SHELL, not a terminal emulator. What must survive across calls is the shell
|
|
6
|
+
* process state (its current directory, exported variables, functions and
|
|
7
|
+
* aliases) plus exact stdout/stderr bytes and an exact exit code — all of
|
|
8
|
+
* which the subprocess seam's collected streams give directly. A PTY would add
|
|
9
|
+
* echoing and escape sequences this tool would then have to strip again, and
|
|
10
|
+
* would not change the state model.
|
|
11
|
+
*
|
|
12
|
+
* Recovery policy: a shell that exits, wedges or fails its handshake is torn
|
|
13
|
+
* down and the CURRENT call fails with a specific message; the NEXT call
|
|
14
|
+
* starts a fresh shell. State loss is reported rather than hidden, because a
|
|
15
|
+
* silent fresh shell would run the model's next command in the wrong directory
|
|
16
|
+
* with no signal that the previous call's cd/export vanished.
|
|
17
|
+
* @module @linxin666/dsh-win-bash/shell
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { randomUUID } from 'node:crypto'
|
|
21
|
+
import { mkdirSync } from 'node:fs'
|
|
22
|
+
import { tmpdir } from 'node:os'
|
|
23
|
+
import { join } from 'node:path'
|
|
24
|
+
import type { SubprocessHandle, SubprocessRuntime } from '@deepseek-ai/dsh-subprocess'
|
|
25
|
+
import { buildFrame, markerFor, parseFrame, type FrameMarker, type FrameOutcome } from './protocol.ts'
|
|
26
|
+
|
|
27
|
+
/** Command stdout budget, in bytes, for one call. */
|
|
28
|
+
export const DEFAULT_MAX_STDOUT_BYTES = 128 * 1024
|
|
29
|
+
|
|
30
|
+
/** Command stderr budget, in bytes, for one call. */
|
|
31
|
+
export const DEFAULT_MAX_STDERR_BYTES = 32 * 1024
|
|
32
|
+
|
|
33
|
+
/** Spill-file byte cap per stream, so a runaway command cannot fill the disk. */
|
|
34
|
+
export const DEFAULT_SPILL_BYTES = 8 * 1024 * 1024
|
|
35
|
+
|
|
36
|
+
/** Grace period handed to the subprocess seam for range teardown. */
|
|
37
|
+
export const GRACE_MS = 5000
|
|
38
|
+
|
|
39
|
+
/** Ceiling on the bytes buffered while looking for a frame's end marker. */
|
|
40
|
+
export const FRAME_WATCH_BYTES = 4 * 1024 * 1024
|
|
41
|
+
|
|
42
|
+
/** In-memory capture ceiling for one shell's stderr, in bytes. */
|
|
43
|
+
export const SHELL_STDERR_CAPTURE_BYTES = 256 * 1024
|
|
44
|
+
|
|
45
|
+
/** Poll cadence while waiting for a frame to complete. */
|
|
46
|
+
const POLL_INTERVAL_MS = 15
|
|
47
|
+
|
|
48
|
+
/** How long a freshly spawned shell gets to answer its startup handshake. */
|
|
49
|
+
const HANDSHAKE_TIMEOUT_MS = 15_000
|
|
50
|
+
|
|
51
|
+
/** Exit status reported for a call the tool itself gave up on. */
|
|
52
|
+
export const TIMEOUT_EXIT_CODE = 124
|
|
53
|
+
|
|
54
|
+
/** Environment variable names carrying the per-shell private temp directory. */
|
|
55
|
+
export const TEMP_ENV_KEYS = ['TMPDIR', 'TMP', 'TEMP'] as const
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The argv of one pinned shell: the payload's own bash by absolute path, no rc
|
|
59
|
+
* file and no profile, reading its commands from stdin. This tool never
|
|
60
|
+
* consults PATH, and every shell it starts — the session's persistent one and
|
|
61
|
+
* every background job — is built from this one function so the two can never
|
|
62
|
+
* drift into different shells.
|
|
63
|
+
* @param runtime - the verified payload paths.
|
|
64
|
+
* @returns the argv to spawn.
|
|
65
|
+
*/
|
|
66
|
+
export function shellArgv(runtime: { bash: string }): string[] {
|
|
67
|
+
return [runtime.bash, '--norc', '--noprofile', '-s']
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The environment contract every pinned shell starts with.
|
|
72
|
+
* @param runtime - the verified payload paths.
|
|
73
|
+
* @param temp - the private temp directory that shell owns.
|
|
74
|
+
* @param base - the ambient environment the PATH is appended to.
|
|
75
|
+
* @returns the entries this tool sets explicitly.
|
|
76
|
+
*/
|
|
77
|
+
export function shellEnvironment(
|
|
78
|
+
runtime: { bin: string },
|
|
79
|
+
temp: string,
|
|
80
|
+
base: NodeJS.ProcessEnv = process.env,
|
|
81
|
+
): NodeJS.ProcessEnv {
|
|
82
|
+
return {
|
|
83
|
+
// The vendored usr/bin goes FIRST on PATH: the payload's own userland
|
|
84
|
+
// is what commands resolve to, and no host Git for Windows, WSL or
|
|
85
|
+
// per-user shim later in the inherited PATH can shadow it.
|
|
86
|
+
PATH: runtime.bin + (process.platform === 'win32' ? ';' : ':') + (base.PATH ?? ''),
|
|
87
|
+
// The payload resolves /tmp from its own etc/fstab usertemp entry,
|
|
88
|
+
// which follows these three names. Pinning them keeps bash's whole
|
|
89
|
+
// mkstemp family inside one private directory per shell instead of
|
|
90
|
+
// the machine's shared temp root.
|
|
91
|
+
TMPDIR: temp,
|
|
92
|
+
TMP: temp,
|
|
93
|
+
TEMP: temp,
|
|
94
|
+
// The MSYS2 personality the payload was built from, which
|
|
95
|
+
// profile.d/msystem reads.
|
|
96
|
+
MSYSTEM: 'MSYS',
|
|
97
|
+
// No terminal is attached, so coreutils would otherwise colour output
|
|
98
|
+
// and pad it into columns based on an inherited TERM guess.
|
|
99
|
+
TERM: 'dumb',
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Create one shell process's private temp directory.
|
|
105
|
+
* @returns the absolute directory, created if absent.
|
|
106
|
+
*/
|
|
107
|
+
export function shellTempDir(): string {
|
|
108
|
+
const temp = join(tmpdir(), 'dsh-win-bash-' + process.pid.toString() + '-' + randomUUID().slice(0, 8))
|
|
109
|
+
mkdirSync(temp, { recursive: true })
|
|
110
|
+
return temp
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** One command's complete result, as the tool consumes it. */
|
|
114
|
+
export interface ShellResult {
|
|
115
|
+
/** The command's stdout, bounded to the visible budget. */
|
|
116
|
+
readonly stdout: string
|
|
117
|
+
/** The command's stderr, bounded to the visible budget. */
|
|
118
|
+
readonly stderr: string
|
|
119
|
+
/** The command's exit status. */
|
|
120
|
+
readonly exitCode: number
|
|
121
|
+
/** True when visible stdout hit its byte budget. */
|
|
122
|
+
readonly stdoutTruncated: boolean
|
|
123
|
+
/** True when visible stderr hit its byte budget. */
|
|
124
|
+
readonly stderrTruncated: boolean
|
|
125
|
+
/** True when the retained stdout lost its head (marker or budget). */
|
|
126
|
+
readonly stdoutLostHead: boolean
|
|
127
|
+
/** True when the retained stderr lost its head. */
|
|
128
|
+
readonly stderrLostHead: boolean
|
|
129
|
+
/** The complete stdout, when it was truncated and the provider spilled it. */
|
|
130
|
+
readonly stdoutSpillPath?: string
|
|
131
|
+
/** The complete stderr, when it was truncated and the provider spilled it. */
|
|
132
|
+
readonly stderrSpillPath?: string
|
|
133
|
+
/** True when stdout overflowed the frame window, so the middle was dropped. */
|
|
134
|
+
readonly frameOverflow: boolean
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The fallback every failure here points at.
|
|
139
|
+
*
|
|
140
|
+
* win_bash is the PREFERRED shell on Windows, not the only one: whenever it
|
|
141
|
+
* cannot serve a call the native shell tool takes over, and a failure that did
|
|
142
|
+
* not say so would leave the model retrying a shell that is not coming back
|
|
143
|
+
* instead of switching to the one that works.
|
|
144
|
+
*/
|
|
145
|
+
export const NATIVE_FALLBACK_HINT = ' Use the host pwsh tool instead: it is the native shell for this platform'
|
|
146
|
+
+ ' and remains available whenever win_bash cannot serve a call.'
|
|
147
|
+
|
|
148
|
+
/** Failure raised when the shell cannot serve a call. */
|
|
149
|
+
export class ShellUnavailableError extends Error {
|
|
150
|
+
/** Stable machine-readable reason. */
|
|
151
|
+
readonly code: string
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* @param code - stable reason code.
|
|
155
|
+
* @param message - explanation safe to show the model.
|
|
156
|
+
*/
|
|
157
|
+
constructor(code: string, message: string) {
|
|
158
|
+
super(message)
|
|
159
|
+
this.name = 'ShellUnavailableError'
|
|
160
|
+
this.code = code
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** One live shell process and the facts the framing needs. */
|
|
165
|
+
interface LiveShell {
|
|
166
|
+
/** The spawned process handle. */
|
|
167
|
+
readonly handle: SubprocessHandle
|
|
168
|
+
/** Set once the handle's outcome settles, so a dead shell is never reused. */
|
|
169
|
+
exited: boolean
|
|
170
|
+
/**
|
|
171
|
+
* The process's own exit facts once it settled. A command that runs 'exit N'
|
|
172
|
+
* ends the SHELL, and the shell's status IS that command's status, so the
|
|
173
|
+
* tool can still report a real exit code instead of an error.
|
|
174
|
+
*/
|
|
175
|
+
exitCode: number | null
|
|
176
|
+
/**
|
|
177
|
+
* Whole-stream byte offsets every earlier call on this process consumed,
|
|
178
|
+
* ONE PER STREAM. Collected readers are whole-stream and non-consuming, so
|
|
179
|
+
* each call must resume from here or it would re-parse the previous calls'
|
|
180
|
+
* frames. The two counters are independent: stdout and stderr are separate
|
|
181
|
+
* byte streams with unrelated lengths, and using one shared counter would
|
|
182
|
+
* start the shorter stream past its own data.
|
|
183
|
+
*/
|
|
184
|
+
cursor: ShellCursor
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Per-stream resume offsets for one live shell. */
|
|
188
|
+
interface ShellCursor {
|
|
189
|
+
/** Bytes of stdout already consumed by earlier calls. */
|
|
190
|
+
stdout: number
|
|
191
|
+
/** Bytes of stderr already consumed by earlier calls. */
|
|
192
|
+
stderr: number
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Budgets and deadline for one {@link ShellRegistry.run} call. */
|
|
196
|
+
export interface RunBudget {
|
|
197
|
+
/** Visible stdout byte budget. */
|
|
198
|
+
readonly stdoutBytes: number
|
|
199
|
+
/** Visible stderr byte budget. */
|
|
200
|
+
readonly stderrBytes: number
|
|
201
|
+
/** Whole-call deadline in milliseconds. */
|
|
202
|
+
readonly timeoutMs: number
|
|
203
|
+
/** Caller cancellation. */
|
|
204
|
+
readonly signal?: AbortSignal | undefined
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** One bounded accumulator fed by an offset-based collected reader. */
|
|
208
|
+
class StreamTail {
|
|
209
|
+
private buffer = ''
|
|
210
|
+
/** Whole-stream offset already consumed from the provider's reader. */
|
|
211
|
+
private offset = 0
|
|
212
|
+
private overflowed = false
|
|
213
|
+
private spilled = false
|
|
214
|
+
private spill: string | undefined
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* @param label - which collected reader this accumulator drains.
|
|
218
|
+
* @param from - whole-stream offset already consumed by earlier calls on
|
|
219
|
+
* the same process. Collected readers are whole-stream and non-consuming,
|
|
220
|
+
* so without this a call would re-read every previous frame.
|
|
221
|
+
*/
|
|
222
|
+
constructor(private readonly label: 'stdout' | 'stderr', from = 0) {
|
|
223
|
+
this.offset = from
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Everything retained so far. */
|
|
227
|
+
text(): string {
|
|
228
|
+
return this.buffer
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Whether the retained window dropped bytes (a lossy read or a trim). */
|
|
232
|
+
lost(): boolean {
|
|
233
|
+
return this.overflowed
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Whether anything visible was cut, which is what a spill file is for. */
|
|
237
|
+
wasCut(): boolean {
|
|
238
|
+
return this.spilled
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Spill file holding the complete stream, once the provider made one. */
|
|
242
|
+
spillPath(): string | undefined {
|
|
243
|
+
return this.spill
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Cut the visible text down to its last budget bytes, recording that the
|
|
248
|
+
* stream was cut so the caller can point at the spill file for the rest.
|
|
249
|
+
* @param budget - the visible byte budget.
|
|
250
|
+
* @returns the visible text and whether it was cut.
|
|
251
|
+
*/
|
|
252
|
+
visible(budget: number): { text: string, truncated: boolean } {
|
|
253
|
+
const result = tailBytes(this.buffer, budget)
|
|
254
|
+
if (result.truncated) this.spilled = true
|
|
255
|
+
return result
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Record that this stream's visible text was cut somewhere upstream. */
|
|
259
|
+
markCut(): void {
|
|
260
|
+
this.spilled = true
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Whole-stream byte offset already consumed. */
|
|
264
|
+
consumed(): number {
|
|
265
|
+
return this.offset
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Drain new bytes from one handle's collected readers.
|
|
270
|
+
* @param handle - the live shell's handle.
|
|
271
|
+
* @param watchBytes - how many bytes may be buffered before the head drops.
|
|
272
|
+
*/
|
|
273
|
+
drain(handle: SubprocessHandle, watchBytes: number): void {
|
|
274
|
+
const reader = this.label === 'stdout' ? handle.collected.stdout : handle.collected.stderr
|
|
275
|
+
if (reader === undefined) return
|
|
276
|
+
const read = reader.readFrom(this.offset)
|
|
277
|
+
this.offset = read.nextOffset
|
|
278
|
+
if (read.lossy) this.overflowed = true
|
|
279
|
+
if (read.spillPath !== undefined) this.spill = read.spillPath
|
|
280
|
+
if (read.text === '') return
|
|
281
|
+
this.buffer += read.text
|
|
282
|
+
while (byteLength(this.buffer) > watchBytes) {
|
|
283
|
+
this.overflowed = true
|
|
284
|
+
this.buffer = this.buffer.slice(Math.ceil(this.buffer.length / 4))
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** UTF-8 byte length of a string. */
|
|
290
|
+
function byteLength(text: string): number {
|
|
291
|
+
return Buffer.byteLength(text, 'utf8')
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Keep the LAST budget bytes of a string, reporting whether it dropped any.
|
|
296
|
+
* @param text - the full text.
|
|
297
|
+
* @param budget - the visible byte budget.
|
|
298
|
+
* @returns the visible text and whether it was cut.
|
|
299
|
+
*/
|
|
300
|
+
export function tailBytes(text: string, budget: number): { text: string, truncated: boolean } {
|
|
301
|
+
if (byteLength(text) <= budget) return { text, truncated: false }
|
|
302
|
+
// Cut from the front on a byte basis. A multi-byte character split by the
|
|
303
|
+
// cut would decode to U+FFFD, which is dropped so the result stays clean
|
|
304
|
+
// text rather than carrying a replacement character nobody wrote.
|
|
305
|
+
const bytes = Buffer.from(text, 'utf8')
|
|
306
|
+
const tail = bytes.subarray(bytes.length - budget).toString('utf8')
|
|
307
|
+
return { text: tail.startsWith('\uFFFD') ? tail.slice(1) : tail, truncated: true }
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* The persistent shells of one plugin instance, keyed by calling agent.
|
|
312
|
+
*
|
|
313
|
+
* The keys are the live agent objects and the map is plain, so an agent's
|
|
314
|
+
* shell is dropped by that agent's own disposal hook rather than by a weak
|
|
315
|
+
* reference that decides for itself when to act.
|
|
316
|
+
*/
|
|
317
|
+
export class ShellRegistry {
|
|
318
|
+
private readonly shells = new Map<object, LiveShell>()
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* @param subprocess - the host's managed subprocess seam.
|
|
322
|
+
* @param now - clock, injected so tests run without real waiting.
|
|
323
|
+
*/
|
|
324
|
+
constructor(
|
|
325
|
+
private readonly subprocess: SubprocessRuntime,
|
|
326
|
+
private readonly now: () => number = () => Date.now(),
|
|
327
|
+
) {}
|
|
328
|
+
|
|
329
|
+
/** Live shell count, for teardown assertions. */
|
|
330
|
+
get size(): number {
|
|
331
|
+
return this.shells.size
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** Whether the given owner currently holds a live shell. */
|
|
335
|
+
has(owner: object): boolean {
|
|
336
|
+
const shell = this.shells.get(owner)
|
|
337
|
+
return shell !== undefined && !shell.exited
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Run one command in the owner's persistent shell, starting it on first use.
|
|
342
|
+
* @param owner - the calling agent (the shell lifetime key).
|
|
343
|
+
* @param runtime - absolute shell and payload paths.
|
|
344
|
+
* @param cwd - the session workspace a newly started shell begins in.
|
|
345
|
+
* @param command - the command to run.
|
|
346
|
+
* @param budget - output budgets and the call deadline.
|
|
347
|
+
* @returns the command's complete result.
|
|
348
|
+
*/
|
|
349
|
+
async run(
|
|
350
|
+
owner: object,
|
|
351
|
+
runtime: { bash: string, bin: string },
|
|
352
|
+
cwd: string,
|
|
353
|
+
command: string,
|
|
354
|
+
budget: RunBudget,
|
|
355
|
+
): Promise<ShellResult> {
|
|
356
|
+
const shell = await this.ensure(owner, runtime, cwd, budget.signal)
|
|
357
|
+
const marker = markerFor(randomUUID())
|
|
358
|
+
const stdout = new StreamTail('stdout', shell.cursor.stdout)
|
|
359
|
+
const stderr = new StreamTail('stderr', shell.cursor.stderr)
|
|
360
|
+
shell.handle.stdin?.write(buildFrame(command, marker))
|
|
361
|
+
const deadline = this.now() + budget.timeoutMs
|
|
362
|
+
let sawBegin = false
|
|
363
|
+
// Resume offsets advance on EVERY return path, so the next call on this
|
|
364
|
+
// process starts after this frame instead of re-parsing it.
|
|
365
|
+
const resume = (): void => {
|
|
366
|
+
shell.cursor.stdout = stdout.consumed()
|
|
367
|
+
shell.cursor.stderr = stderr.consumed()
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
for (;;) {
|
|
371
|
+
if (budget.signal?.aborted === true) {
|
|
372
|
+
resume()
|
|
373
|
+
await this.dispose(owner, 'the tool call was aborted')
|
|
374
|
+
throw new ShellUnavailableError(
|
|
375
|
+
'aborted',
|
|
376
|
+
'The win_bash call was aborted and its persistent shell was stopped. The next call starts a fresh shell, '
|
|
377
|
+
+ 'so shell state changed before this call was aborted is gone.',
|
|
378
|
+
)
|
|
379
|
+
}
|
|
380
|
+
const frame = readFrame(shell, stdout, stderr, marker, sawBegin)
|
|
381
|
+
// Latch the begin marker: a command whose output exceeds the watch window
|
|
382
|
+
// loses its head, and the end marker must still be recognized then.
|
|
383
|
+
sawBegin ||= frame.text.includes(marker.begin)
|
|
384
|
+
if (frame.outcome !== undefined) {
|
|
385
|
+
const result = complete(frame.outcome, stdout, stderr, budget)
|
|
386
|
+
resume()
|
|
387
|
+
return result
|
|
388
|
+
}
|
|
389
|
+
if (shell.exited) {
|
|
390
|
+
// A drained-but-unframed exit means the command ended the SHELL (an
|
|
391
|
+
// explicit 'exit N', or a runtime failure). When the process reported
|
|
392
|
+
// its own status, that status IS this command's status, so the call
|
|
393
|
+
// answers with a real exit code plus a note that the shell is gone and
|
|
394
|
+
// the next call starts fresh. Without a status there is nothing honest
|
|
395
|
+
// to report but the teardown itself.
|
|
396
|
+
resume()
|
|
397
|
+
this.shells.delete(owner)
|
|
398
|
+
const partial = tailBytes(recoverPartial(frame.text, marker), budget.stdoutBytes)
|
|
399
|
+
if (shell.exitCode === null) {
|
|
400
|
+
throw new ShellUnavailableError(
|
|
401
|
+
'shell-exited',
|
|
402
|
+
'The persistent bash shell exited without reporting a status, so this command did not complete. '
|
|
403
|
+
+ 'The next win_bash call starts a fresh shell in the session workspace with a new current directory and environment.',
|
|
404
|
+
)
|
|
405
|
+
}
|
|
406
|
+
const visibleErr = stderr.visible(budget.stderrBytes)
|
|
407
|
+
const note = '[the command ended the persistent bash process; the next win_bash call starts a fresh shell]'
|
|
408
|
+
return {
|
|
409
|
+
stdout: partial.text,
|
|
410
|
+
stderr: visibleErr.text === '' ? note : visibleErr.text + '\n' + note,
|
|
411
|
+
exitCode: shell.exitCode,
|
|
412
|
+
stdoutTruncated: partial.truncated,
|
|
413
|
+
stderrTruncated: visibleErr.truncated,
|
|
414
|
+
stdoutLostHead: stdout.lost() || partial.truncated,
|
|
415
|
+
stderrLostHead: stderr.lost() || visibleErr.truncated,
|
|
416
|
+
frameOverflow: stdout.lost(),
|
|
417
|
+
...(stdout.wasCut() && stdout.spillPath() !== undefined ? { stdoutSpillPath: stdout.spillPath() } : {}),
|
|
418
|
+
...(stderr.wasCut() && stderr.spillPath() !== undefined ? { stderrSpillPath: stderr.spillPath() } : {}),
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
if (this.now() > deadline) {
|
|
422
|
+
await this.dispose(owner, 'the command exceeded its time budget')
|
|
423
|
+
const visibleErr = stderr.visible(budget.stderrBytes)
|
|
424
|
+
const note = '[timed out after ' + budget.timeoutMs.toString()
|
|
425
|
+
+ 'ms; the persistent shell was stopped, so the next win_bash call starts a fresh shell]'
|
|
426
|
+
const partial = tailBytes(recoverPartial(frame.text, marker), budget.stdoutBytes)
|
|
427
|
+
if (partial.truncated) stdout.markCut()
|
|
428
|
+
resume()
|
|
429
|
+
return {
|
|
430
|
+
stdout: partial.text,
|
|
431
|
+
stderr: visibleErr.text === '' ? note : visibleErr.text + '\n' + note,
|
|
432
|
+
exitCode: TIMEOUT_EXIT_CODE,
|
|
433
|
+
stdoutTruncated: partial.truncated,
|
|
434
|
+
stderrTruncated: visibleErr.truncated,
|
|
435
|
+
stdoutLostHead: stdout.lost() || partial.truncated,
|
|
436
|
+
stderrLostHead: stderr.lost() || visibleErr.truncated,
|
|
437
|
+
frameOverflow: stdout.lost(),
|
|
438
|
+
...(stdout.wasCut() && stdout.spillPath() !== undefined ? { stdoutSpillPath: stdout.spillPath() } : {}),
|
|
439
|
+
...(stderr.wasCut() && stderr.spillPath() !== undefined ? { stderrSpillPath: stderr.spillPath() } : {}),
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
await new Promise<void>(resolve => { setTimeout(resolve, POLL_INTERVAL_MS) })
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* Get the owner's live shell, starting one when absent.
|
|
448
|
+
* @param owner - calling agent identity.
|
|
449
|
+
* @param runtime - absolute shell and payload paths.
|
|
450
|
+
* @param cwd - the session workspace a new shell starts in.
|
|
451
|
+
* @param signal - cancellation while the shell starts.
|
|
452
|
+
* @returns the live shell record.
|
|
453
|
+
*/
|
|
454
|
+
private async ensure(
|
|
455
|
+
owner: object,
|
|
456
|
+
runtime: { bash: string, bin: string },
|
|
457
|
+
cwd: string,
|
|
458
|
+
signal?: AbortSignal,
|
|
459
|
+
): Promise<LiveShell> {
|
|
460
|
+
const existing = this.shells.get(owner)
|
|
461
|
+
if (existing !== undefined && !existing.exited) return existing
|
|
462
|
+
if (existing !== undefined) this.shells.delete(owner)
|
|
463
|
+
const handle = this.subprocess.spawn({
|
|
464
|
+
argv: shellArgv(runtime),
|
|
465
|
+
cwd,
|
|
466
|
+
stdio: {
|
|
467
|
+
stdin: 'pipe',
|
|
468
|
+
stdout: { maxBytes: FRAME_WATCH_BYTES, spill: { maxBytes: DEFAULT_SPILL_BYTES } },
|
|
469
|
+
stderr: { maxBytes: SHELL_STDERR_CAPTURE_BYTES, spill: { maxBytes: DEFAULT_SPILL_BYTES } },
|
|
470
|
+
},
|
|
471
|
+
graceMs: GRACE_MS,
|
|
472
|
+
env: shellEnvironment(runtime, shellTempDir()),
|
|
473
|
+
})
|
|
474
|
+
const shell: LiveShell = { handle, exited: false, cursor: { stdout: 0, stderr: 0 }, exitCode: null }
|
|
475
|
+
const markExited = (outcome: { exitCode: number | null }): void => {
|
|
476
|
+
shell.exitCode = outcome.exitCode
|
|
477
|
+
shell.exited = true
|
|
478
|
+
}
|
|
479
|
+
void handle.done.then(markExited, () => { shell.exited = true })
|
|
480
|
+
this.shells.set(owner, shell)
|
|
481
|
+
await this.handshake(shell, signal)
|
|
482
|
+
return shell
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Confirm a fresh shell answers before the first real command runs, so a
|
|
487
|
+
* payload that cannot start surfaces as one clear failure instead of as a
|
|
488
|
+
* mysterious empty result on the model's command.
|
|
489
|
+
*/
|
|
490
|
+
private async handshake(shell: LiveShell, signal?: AbortSignal): Promise<void> {
|
|
491
|
+
const marker = markerFor(randomUUID())
|
|
492
|
+
const stdout = new StreamTail('stdout', shell.cursor.stdout)
|
|
493
|
+
shell.handle.stdin?.write(buildFrame('printf %s "$BASH_VERSION"', marker))
|
|
494
|
+
const deadline = this.now() + HANDSHAKE_TIMEOUT_MS
|
|
495
|
+
for (;;) {
|
|
496
|
+
if (shell.exited) {
|
|
497
|
+
throw new ShellUnavailableError(
|
|
498
|
+
'shell-exited',
|
|
499
|
+
'The vendored bash exited during startup, so win_bash cannot run commands in this session.' + NATIVE_FALLBACK_HINT,
|
|
500
|
+
)
|
|
501
|
+
}
|
|
502
|
+
if (signal?.aborted === true) {
|
|
503
|
+
throw new ShellUnavailableError('aborted', 'The win_bash call was aborted while the persistent shell was starting.')
|
|
504
|
+
}
|
|
505
|
+
stdout.drain(shell.handle, 256 * 1024)
|
|
506
|
+
const outcome = parseFrame(stdout.text(), marker, true)
|
|
507
|
+
if (outcome !== undefined) {
|
|
508
|
+
if (outcome.exitCode !== 0 || !/^\d+(\.\d+)?/.test(outcome.stdout)) {
|
|
509
|
+
throw new ShellUnavailableError(
|
|
510
|
+
'handshake-failed',
|
|
511
|
+
'The vendored bash did not report a version (exit ' + outcome.exitCode.toString() + ').' + NATIVE_FALLBACK_HINT,
|
|
512
|
+
)
|
|
513
|
+
}
|
|
514
|
+
// The handshake's own bytes are consumed here too: the first real
|
|
515
|
+
// command must resume past the version frame, not re-parse it.
|
|
516
|
+
shell.cursor.stdout = stdout.consumed()
|
|
517
|
+
return
|
|
518
|
+
}
|
|
519
|
+
if (this.now() > deadline) {
|
|
520
|
+
throw new ShellUnavailableError(
|
|
521
|
+
'handshake-timeout',
|
|
522
|
+
'The vendored bash did not answer its startup handshake in time.' + NATIVE_FALLBACK_HINT,
|
|
523
|
+
)
|
|
524
|
+
}
|
|
525
|
+
await new Promise<void>(resolve => { setTimeout(resolve, POLL_INTERVAL_MS) })
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/**
|
|
530
|
+
* Stop one owner's shell and forget it. Termination goes through the seam's
|
|
531
|
+
* managed-process range, so a background job the command left behind is torn
|
|
532
|
+
* down with the shell rather than surviving the plugin.
|
|
533
|
+
* @param owner - calling agent identity.
|
|
534
|
+
* @param reason - recorded by the provider for diagnostics.
|
|
535
|
+
*/
|
|
536
|
+
async dispose(owner: object, reason: string): Promise<void> {
|
|
537
|
+
const shell = this.shells.get(owner)
|
|
538
|
+
if (shell === undefined) return
|
|
539
|
+
this.shells.delete(owner)
|
|
540
|
+
await terminate(shell, reason)
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/** Stop every shell this registry owns; used on plugin unload. */
|
|
544
|
+
async disposeAll(reason: string): Promise<void> {
|
|
545
|
+
const shells = [...this.shells.values()]
|
|
546
|
+
this.shells.clear()
|
|
547
|
+
await Promise.allSettled(shells.map(shell => terminate(shell, reason)))
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/** One frame read attempt: the parsed outcome and the raw stdout it came from. */
|
|
552
|
+
interface FrameRead {
|
|
553
|
+
/** The parsed frame, once both markers and the status digits arrived. */
|
|
554
|
+
readonly outcome: FrameOutcome | undefined
|
|
555
|
+
/** Raw accumulated stdout, used to recover a partial result on timeout. */
|
|
556
|
+
readonly text: string
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* Drain both streams once and try to parse the call's frame.
|
|
561
|
+
*
|
|
562
|
+
* Draining and parsing are one step on purpose: a caller that drained without
|
|
563
|
+
* parsing left the accumulator holding a frame it never consumed, and the next
|
|
564
|
+
* call then re-read that stale text as its own result.
|
|
565
|
+
* @param shell - the live shell.
|
|
566
|
+
* @param stdout - the stdout accumulator.
|
|
567
|
+
* @param stderr - the stderr accumulator.
|
|
568
|
+
* @param marker - the call's markers.
|
|
569
|
+
* @param sawBegin - whether the begin marker was already observed.
|
|
570
|
+
* @returns the parsed outcome (once complete) and the raw stdout.
|
|
571
|
+
*/
|
|
572
|
+
function readFrame(
|
|
573
|
+
shell: LiveShell,
|
|
574
|
+
stdout: StreamTail,
|
|
575
|
+
stderr: StreamTail,
|
|
576
|
+
marker: FrameMarker,
|
|
577
|
+
sawBegin: boolean,
|
|
578
|
+
): FrameRead {
|
|
579
|
+
stdout.drain(shell.handle, FRAME_WATCH_BYTES)
|
|
580
|
+
stderr.drain(shell.handle, FRAME_WATCH_BYTES)
|
|
581
|
+
const text = stdout.text()
|
|
582
|
+
return {
|
|
583
|
+
outcome: text.includes(marker.end) ? parseFrame(text, marker, sawBegin) : undefined,
|
|
584
|
+
text,
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/**
|
|
589
|
+
* Assemble the tool-visible result from a completed frame.
|
|
590
|
+
*
|
|
591
|
+
* The stdout comes from the PARSED FRAME, not from the raw accumulator: the
|
|
592
|
+
* accumulator still holds the markers and every earlier byte of the stream,
|
|
593
|
+
* so reading it directly would hand the model the framing as its output.
|
|
594
|
+
*/
|
|
595
|
+
function complete(outcome: FrameOutcome, stdout: StreamTail, stderr: StreamTail, budget: RunBudget): ShellResult {
|
|
596
|
+
const visibleOut = tailBytes(outcome.stdout, budget.stdoutBytes)
|
|
597
|
+
if (visibleOut.truncated) stdout.markCut()
|
|
598
|
+
const visibleErr = stderr.visible(budget.stderrBytes)
|
|
599
|
+
const outDropped = outcome.lostPrefix || stdout.lost() || visibleOut.truncated
|
|
600
|
+
return {
|
|
601
|
+
stdout: visibleOut.text,
|
|
602
|
+
stderr: visibleErr.text,
|
|
603
|
+
exitCode: outcome.exitCode,
|
|
604
|
+
stdoutTruncated: outDropped,
|
|
605
|
+
stderrTruncated: visibleErr.truncated,
|
|
606
|
+
stdoutLostHead: outDropped,
|
|
607
|
+
stderrLostHead: stderr.lost() || visibleErr.truncated,
|
|
608
|
+
frameOverflow: stdout.lost(),
|
|
609
|
+
...(stdout.wasCut() && stdout.spillPath() !== undefined ? { stdoutSpillPath: stdout.spillPath() } : {}),
|
|
610
|
+
...(stderr.wasCut() && stderr.spillPath() !== undefined ? { stderrSpillPath: stderr.spillPath() } : {}),
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/** Whatever stdout is recoverable after a timeout, with the begin marker cut. */
|
|
615
|
+
function recoverPartial(text: string, marker: FrameMarker): string {
|
|
616
|
+
const begin = text.lastIndexOf(marker.begin)
|
|
617
|
+
return begin < 0 ? text : text.slice(begin + marker.begin.length).replace(/^\n/, '')
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/** Signal and await one shell's managed range, never letting teardown throw. */
|
|
621
|
+
async function terminate(shell: LiveShell, reason: string): Promise<void> {
|
|
622
|
+
void reason
|
|
623
|
+
try {
|
|
624
|
+
shell.handle.terminate()
|
|
625
|
+
await shell.handle.waitForExit()
|
|
626
|
+
} catch {
|
|
627
|
+
// A provider that can no longer observe its range must not block teardown:
|
|
628
|
+
// the process was signalled and the registry entry is already gone.
|
|
629
|
+
}
|
|
630
|
+
}
|