@linxin666/dsh-win-bash 0.0.0-stage → 0.4.7

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 (118) hide show
  1. package/LICENSE +202 -0
  2. package/PROVENANCE.md +215 -0
  3. package/README.i18n.yaml +6 -0
  4. package/README.md +257 -2
  5. package/README.zh.md +217 -0
  6. package/cordis.patch.yml +13 -0
  7. package/lib/index.js +2697 -0
  8. package/lib/types/background.d.ts +169 -0
  9. package/lib/types/config.d.ts +130 -0
  10. package/lib/types/gate.d.ts +179 -0
  11. package/lib/types/index.d.ts +104 -0
  12. package/lib/types/protocol.d.ts +90 -0
  13. package/lib/types/pwsh-replacement.d.ts +140 -0
  14. package/lib/types/runtime.d.ts +115 -0
  15. package/lib/types/shell.d.ts +184 -0
  16. package/lib/types/tool.d.ts +108 -0
  17. package/package.json +58 -3
  18. package/runtime/win32-x64/checksums.sha256 +91 -0
  19. package/runtime/win32-x64/etc/bash.bashrc +69 -0
  20. package/runtime/win32-x64/etc/fstab +6 -0
  21. package/runtime/win32-x64/etc/msystem +27 -0
  22. package/runtime/win32-x64/etc/msystem.d/CLANG64 +7 -0
  23. package/runtime/win32-x64/etc/msystem.d/CLANGARM64 +7 -0
  24. package/runtime/win32-x64/etc/msystem.d/MINGW32 +7 -0
  25. package/runtime/win32-x64/etc/msystem.d/MINGW64 +7 -0
  26. package/runtime/win32-x64/etc/msystem.d/MSYS +4 -0
  27. package/runtime/win32-x64/etc/msystem.d/UCRT64 +7 -0
  28. package/runtime/win32-x64/etc/nsswitch.conf +12 -0
  29. package/runtime/win32-x64/etc/package-versions.txt +67 -0
  30. package/runtime/win32-x64/etc/profile +146 -0
  31. package/runtime/win32-x64/etc/profile.d/bash_profile.sh +11 -0
  32. package/runtime/win32-x64/etc/profile.d/lang.sh +19 -0
  33. package/runtime/win32-x64/licenses/GPL-2.0.txt +338 -0
  34. package/runtime/win32-x64/licenses/GPL-3.0.txt +674 -0
  35. package/runtime/win32-x64/licenses/LGPL-2.1.txt +501 -0
  36. package/runtime/win32-x64/licenses/LGPL-3.0.txt +165 -0
  37. package/runtime/win32-x64/licenses/expat-COPYING.txt +21 -0
  38. package/runtime/win32-x64/licenses/gcc-libs-RUNTIME.LIBRARY.EXCEPTION.txt +73 -0
  39. package/runtime/win32-x64/licenses/gettext-runtime-COPYING.LIB.txt +501 -0
  40. package/runtime/win32-x64/licenses/gettext-runtime-COPYING.txt +13 -0
  41. package/runtime/win32-x64/licenses/git-for-windows-LICENSE.txt +360 -0
  42. package/runtime/win32-x64/licenses/heimdal-LICENSE.txt +33 -0
  43. package/runtime/win32-x64/licenses/libcbor-LICENSE.md +21 -0
  44. package/runtime/win32-x64/licenses/libffi-LICENSE.txt +21 -0
  45. package/runtime/win32-x64/licenses/libfido2-LICENSE.txt +26 -0
  46. package/runtime/win32-x64/licenses/libiconv-COPYING.LIB.txt +501 -0
  47. package/runtime/win32-x64/licenses/libiconv-COPYING.txt +674 -0
  48. package/runtime/win32-x64/licenses/libopenssl-LICENSE.txt +177 -0
  49. package/runtime/win32-x64/licenses/libpcre-LICENCE.txt +93 -0
  50. package/runtime/win32-x64/licenses/libsqlite-LICENSE +25 -0
  51. package/runtime/win32-x64/licenses/ncurses-LICENSE +29 -0
  52. package/runtime/win32-x64/licenses/openssh-LICENCE.txt +412 -0
  53. package/runtime/win32-x64/licenses/zlib-LICENSE +22 -0
  54. package/runtime/win32-x64/usr/bin/awk.exe +0 -0
  55. package/runtime/win32-x64/usr/bin/b2sum.exe +0 -0
  56. package/runtime/win32-x64/usr/bin/basename.exe +0 -0
  57. package/runtime/win32-x64/usr/bin/basenc.exe +0 -0
  58. package/runtime/win32-x64/usr/bin/bash.exe +0 -0
  59. package/runtime/win32-x64/usr/bin/cat.exe +0 -0
  60. package/runtime/win32-x64/usr/bin/cmp.exe +0 -0
  61. package/runtime/win32-x64/usr/bin/comm.exe +0 -0
  62. package/runtime/win32-x64/usr/bin/cp.exe +0 -0
  63. package/runtime/win32-x64/usr/bin/cut.exe +0 -0
  64. package/runtime/win32-x64/usr/bin/dash.exe +0 -0
  65. package/runtime/win32-x64/usr/bin/date.exe +0 -0
  66. package/runtime/win32-x64/usr/bin/diff.exe +0 -0
  67. package/runtime/win32-x64/usr/bin/diff3.exe +0 -0
  68. package/runtime/win32-x64/usr/bin/dirname.exe +0 -0
  69. package/runtime/win32-x64/usr/bin/echo.exe +0 -0
  70. package/runtime/win32-x64/usr/bin/env.exe +0 -0
  71. package/runtime/win32-x64/usr/bin/expr.exe +0 -0
  72. package/runtime/win32-x64/usr/bin/false.exe +0 -0
  73. package/runtime/win32-x64/usr/bin/find.exe +0 -0
  74. package/runtime/win32-x64/usr/bin/grep.exe +0 -0
  75. package/runtime/win32-x64/usr/bin/head.exe +0 -0
  76. package/runtime/win32-x64/usr/bin/ls.exe +0 -0
  77. package/runtime/win32-x64/usr/bin/mkdir.exe +0 -0
  78. package/runtime/win32-x64/usr/bin/mktemp.exe +0 -0
  79. package/runtime/win32-x64/usr/bin/msys-2.0.dll +0 -0
  80. package/runtime/win32-x64/usr/bin/msys-gcc_s-seh-1.dll +0 -0
  81. package/runtime/win32-x64/usr/bin/msys-gmp-10.dll +0 -0
  82. package/runtime/win32-x64/usr/bin/msys-iconv-2.dll +0 -0
  83. package/runtime/win32-x64/usr/bin/msys-intl-8.dll +0 -0
  84. package/runtime/win32-x64/usr/bin/msys-mpfr-6.dll +0 -0
  85. package/runtime/win32-x64/usr/bin/msys-ncursesw6.dll +0 -0
  86. package/runtime/win32-x64/usr/bin/msys-pcre-1.dll +0 -0
  87. package/runtime/win32-x64/usr/bin/msys-readline8.dll +0 -0
  88. package/runtime/win32-x64/usr/bin/mv.exe +0 -0
  89. package/runtime/win32-x64/usr/bin/pathchk.exe +0 -0
  90. package/runtime/win32-x64/usr/bin/printf.exe +0 -0
  91. package/runtime/win32-x64/usr/bin/pwd.exe +0 -0
  92. package/runtime/win32-x64/usr/bin/readlink.exe +0 -0
  93. package/runtime/win32-x64/usr/bin/rm.exe +0 -0
  94. package/runtime/win32-x64/usr/bin/rmdir.exe +0 -0
  95. package/runtime/win32-x64/usr/bin/sdiff.exe +0 -0
  96. package/runtime/win32-x64/usr/bin/sed.exe +0 -0
  97. package/runtime/win32-x64/usr/bin/seq.exe +0 -0
  98. package/runtime/win32-x64/usr/bin/sh.exe +0 -0
  99. package/runtime/win32-x64/usr/bin/sleep.exe +0 -0
  100. package/runtime/win32-x64/usr/bin/sort.exe +0 -0
  101. package/runtime/win32-x64/usr/bin/tail.exe +0 -0
  102. package/runtime/win32-x64/usr/bin/test.exe +0 -0
  103. package/runtime/win32-x64/usr/bin/touch.exe +0 -0
  104. package/runtime/win32-x64/usr/bin/tr.exe +0 -0
  105. package/runtime/win32-x64/usr/bin/true.exe +0 -0
  106. package/runtime/win32-x64/usr/bin/uname.exe +0 -0
  107. package/runtime/win32-x64/usr/bin/uniq.exe +0 -0
  108. package/runtime/win32-x64/usr/bin/wc.exe +0 -0
  109. package/runtime/win32-x64/usr/bin/xargs.exe +0 -0
  110. package/src/background.ts +270 -0
  111. package/src/config.ts +209 -0
  112. package/src/gate.ts +308 -0
  113. package/src/index.ts +277 -0
  114. package/src/protocol.ts +130 -0
  115. package/src/pwsh-replacement.ts +435 -0
  116. package/src/runtime.ts +240 -0
  117. package/src/shell.ts +630 -0
  118. package/src/tool.ts +417 -0
package/src/tool.ts ADDED
@@ -0,0 +1,417 @@
1
+ /**
2
+ * The model-facing win_bash tool.
3
+ *
4
+ * Named win_bash and not bash on purpose: the host already mounts its own
5
+ * bash-family tools (bash, pwsh), and a name collision would either be a
6
+ * duplicate-registration failure or, worse, silently replace the host's tool.
7
+ * This tool is additional capability, not a replacement.
8
+ *
9
+ * Permission: the sandbox-policy service is read for the CALLING SESSION, since
10
+ * a session's own mode log outranks the deployment default. A session in a
11
+ * restricted mode is refused outright rather than confined — see
12
+ * {@link assertUnconfined} for the measured reason.
13
+ * @module @linxin666/dsh-win-bash/tool
14
+ */
15
+
16
+ import type { Context } from '@deepseek-ai/cordis'
17
+ import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox'
18
+ import { defineTool } from '@deepseek-ai/dsh-tools'
19
+ import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
20
+ import type { JobRegistryLike } from './background.ts'
21
+ import { BACKGROUND_STDERR_BYTES, BACKGROUND_STDOUT_BYTES, startBackgroundJob } from './background.ts'
22
+ import type { WinBashConfig } from './config.ts'
23
+ import { shellArgv, shellEnvironment, shellTempDir, type ShellRegistry } from './shell.ts'
24
+
25
+ /** The registered tool name. Deliberately not bash. */
26
+ export const WIN_BASH_TOOL = 'win_bash'
27
+
28
+ /** Every sandbox mode a session may run under. */
29
+ const SANDBOX_MODES: readonly SandboxMode[] = ['read-only', 'workspace-write', 'danger-full-access']
30
+
31
+ /** The only mode this tool runs under; every other mode is refused. */
32
+ const SUPPORTED_MODE: SandboxMode = 'danger-full-access'
33
+
34
+ /** The policy read this tool consumes from the sandbox-policy service. */
35
+ interface PolicyResolver {
36
+ resolve(request?: { session?: unknown, mode?: SandboxMode }): SandboxExecutionPolicy
37
+ }
38
+
39
+ /**
40
+ * Refuse every session mode but danger-full-access.
41
+ *
42
+ * WHY REFUSAL RATHER THAN CONFINEMENT. A restricted session would have to spawn
43
+ * this payload through the sandbox provider's confine step, and the pinned MSYS2
44
+ * bash cannot start that way. Measured on win32 x64 (Windows 10.0.26200) against
45
+ * the real restricted-token runner: bash.exe, sh.exe, dash.exe and echo.exe all
46
+ * die BEFORE main with
47
+ * NtCreateDirectoryObject(\BaseNamedObjects\msys-2.0S5-<hash>): 0xC0000022
48
+ * (exit 3221225794 / 0xC0000142), and system Git for Windows fails identically
49
+ * ('couldn't create signal pipe, Win32 error 5'). cmd.exe, node.exe and
50
+ * powershell.exe run confined on that same runner, so the runner is sound and
51
+ * the limitation belongs to the MSYS runtime.
52
+ *
53
+ * So confinement here cannot produce a working shell, and a shell whose every
54
+ * command dies before main is worse than an honest refusal: it would report a
55
+ * boundary that never actually held any command. The refusal names the other
56
+ * shells, which ARE confined, so the caller is not left without a route.
57
+ * @param policy - the session's effective policy.
58
+ * @throws when the session runs under any other mode.
59
+ */
60
+ function assertUnconfined(policy: SandboxExecutionPolicy): void {
61
+ if (policy.mode === SUPPORTED_MODE) return
62
+ throw new Error(
63
+ 'SANDBOX_UNSUPPORTED: win_bash runs only under ' + SUPPORTED_MODE + ', and this session is in ' + policy.mode
64
+ + ' mode. The pinned MSYS2 bash cannot start under a restricted token (it dies before main with'
65
+ + ' NtCreateDirectoryObject 0xC0000022), so no bash command can run inside that boundary.'
66
+ + ' Run the command with the host pwsh tool instead: it is the native shell for this platform, it IS confined, and it'
67
+ + ' stays on this session surface whenever win_bash cannot serve the session. win_bash is the preferred shell, not the'
68
+ + ' only one. Switching this session to ' + SUPPORTED_MODE + ' brings win_bash back.',
69
+ )
70
+ }
71
+
72
+ /** One agent session's working directory, read structurally. */
73
+ function sessionCwd(agent: unknown): string | undefined {
74
+ const session = (agent as { session?: { header?: { cwd?: unknown } } } | undefined)?.session
75
+ const cwd = session?.header?.cwd
76
+ return typeof cwd === 'string' && cwd !== '' ? cwd : undefined
77
+ }
78
+
79
+ /**
80
+ * Single-quote one value for the shell, escaping embedded single quotes.
81
+ * @param value - the raw value.
82
+ * @returns a POSIX single-quoted literal.
83
+ */
84
+ export function shellQuote(value: string): string {
85
+ return "'" + value.split("'").join("'\\''") + "'"
86
+ }
87
+
88
+ /**
89
+ * Normalize a Windows path into the spelling MSYS accepts without escaping:
90
+ * a backslash is also the shell's escape character, so a path handed to cd is
91
+ * converted to forward slashes before it is quoted.
92
+ * @param path - the caller-supplied working directory.
93
+ * @returns the same path with backslashes replaced.
94
+ */
95
+ export function normalizeWorkdir(path: string): string {
96
+ return path.split('\\').join('/')
97
+ }
98
+
99
+ /**
100
+ * Clamp a per-call deadline to the configured ceiling.
101
+ * @param requested - the model's timeoutMs, if any.
102
+ * @param configured - the plugin's configured default and ceiling.
103
+ * @returns the effective deadline in milliseconds.
104
+ * @throws when the requested value is not a positive whole number.
105
+ */
106
+ export function clampTimeout(requested: number | undefined, configured: number): number {
107
+ if (requested === undefined) return configured
108
+ if (!Number.isSafeInteger(requested) || requested <= 0) {
109
+ throw new Error('win_bash: timeoutMs must be a positive whole number of milliseconds.')
110
+ }
111
+ return Math.min(requested, configured)
112
+ }
113
+
114
+ /** The truncation facts a rendered result reports to the model. */
115
+ export interface RenderFacts {
116
+ /** Visible stdout, already cut to its byte budget. */
117
+ stdout: string
118
+ /** Visible stderr, already cut to its byte budget. */
119
+ stderr: string
120
+ /** The command's exit status. */
121
+ exitCode: number
122
+ /** True when visible stdout hit its byte budget. */
123
+ stdoutTruncated?: boolean
124
+ /** True when visible stderr hit its byte budget. */
125
+ stderrTruncated?: boolean
126
+ /** True when the retained stdout lost its head. */
127
+ stdoutLostHead?: boolean
128
+ /** True when the retained stderr lost its head. */
129
+ stderrLostHead?: boolean
130
+ /** True when the frame watch window dropped the middle of stdout. */
131
+ frameOverflow?: boolean
132
+ /** Host path of the complete stdout, when the provider spilled it. */
133
+ stdoutSpillPath?: string
134
+ /** Host path of the complete stderr, when the provider spilled it. */
135
+ stderrSpillPath?: string
136
+ }
137
+
138
+ /** UTF-8 byte length of a string. */
139
+ function byteLength(text: string): number {
140
+ return Buffer.byteLength(text, 'utf8')
141
+ }
142
+
143
+ /**
144
+ * The line that tells the model its view of one stream is incomplete.
145
+ *
146
+ * WHY THIS IS NOT DECORATION. The visible text is the TAIL of the stream: the
147
+ * head was already cut to fit the byte budget, so the first thing the model
148
+ * reads can be the middle of a line with nothing marking the cut. Without this
149
+ * line a partial result is indistinguishable from a short one, and a model
150
+ * reading a truncated listing draws conclusions from data it never saw.
151
+ * @param stream - stream label.
152
+ * @param visible - the bytes actually shown.
153
+ * @param flags - which cuts happened.
154
+ * @param spillPath - complete-stream file, when the provider kept one.
155
+ * @returns the notice, or undefined when that stream was shown in full.
156
+ */
157
+ export function truncationNotice(
158
+ stream: 'stdout' | 'stderr',
159
+ visible: string,
160
+ flags: { truncated: boolean, lostHead: boolean, overflow: boolean },
161
+ spillPath?: string,
162
+ ): string | undefined {
163
+ if (!flags.truncated && !flags.lostHead && !flags.overflow) return undefined
164
+ const parts = [
165
+ '[win_bash: ' + stream + ' was truncated, only the last ' + byteLength(visible).toString() + ' bytes are shown',
166
+ ]
167
+ if (flags.lostHead || flags.truncated) parts.push('; the beginning was dropped')
168
+ if (flags.overflow) parts.push('; a middle window was dropped by the frame watch limit')
169
+ if (spillPath !== undefined) parts.push('. The complete stream is at ' + spillPath)
170
+ parts.push(']')
171
+ return parts.join('')
172
+ }
173
+
174
+ /** Render one result the way the host's own shell tools render theirs. */
175
+ export function renderResult(value: RenderFacts): string {
176
+ let body = value.stdout
177
+ if (value.stderr !== '') {
178
+ if (body !== '' && !body.endsWith('\n')) body += '\n'
179
+ body += '[stderr]\n' + value.stderr
180
+ }
181
+ if (body === '') body = '(no output)'
182
+ const parts = [body]
183
+ // The truncation notices come FIRST, before the exit line: a model that reads
184
+ // only the head of a long result still learns that the output was cut, which
185
+ // is the one fact it cannot recover from the text.
186
+ const outNotice = truncationNotice('stdout', value.stdout, {
187
+ truncated: value.stdoutTruncated === true,
188
+ lostHead: value.stdoutLostHead === true,
189
+ overflow: value.frameOverflow === true,
190
+ }, value.stdoutSpillPath)
191
+ if (outNotice !== undefined) parts.push(outNotice)
192
+ const errNotice = truncationNotice('stderr', value.stderr, {
193
+ truncated: value.stderrTruncated === true,
194
+ lostHead: value.stderrLostHead === true,
195
+ overflow: false,
196
+ }, value.stderrSpillPath)
197
+ if (errNotice !== undefined) parts.push(errNotice)
198
+ if (value.exitCode !== 0) parts.push('[exit code: ' + value.exitCode.toString() + ']')
199
+ return parts.join('\n')
200
+ }
201
+
202
+ /**
203
+ * The deployment's background job registry, read without letting a refused
204
+ * lookup escape: a cordis service proxy throws for a name it cannot resolve,
205
+ * and "this deployment composes no job registry" is an ordinary state here,
206
+ * not an error.
207
+ * @param ctx - the plugin context.
208
+ * @returns the registry, or undefined when this deployment has none.
209
+ */
210
+ export function readJobRegistry(ctx: Context): JobRegistryLike | undefined {
211
+ let candidate: unknown
212
+ try {
213
+ candidate = ctx.get('jobs')
214
+ } catch {
215
+ return undefined
216
+ }
217
+ if (candidate === null || typeof candidate !== 'object') return undefined
218
+ if (typeof (candidate as { start?: unknown }).start !== 'function') return undefined
219
+ return candidate as JobRegistryLike
220
+ }
221
+
222
+ /**
223
+ * The calling session's effective policy, or undefined when the service is absent.
224
+ *
225
+ * The SESSION goes into the request on purpose: the service resolves a session's
226
+ * own mode log before the deployment default, so a read without it answers for
227
+ * the deployment and would let a session the user restricted run here.
228
+ * @param ctx - the plugin context.
229
+ * @param agent - the calling agent, carrying the session whose mode applies.
230
+ * @returns the policy, or undefined when no service is composed.
231
+ * @throws when the service answers with a policy this tool cannot read.
232
+ */
233
+ function resolvePolicy(ctx: Context, agent: unknown): SandboxExecutionPolicy | undefined {
234
+ const service = ctx.get('sandboxPolicy') as PolicyResolver | undefined
235
+ if (service === undefined || typeof service.resolve !== 'function') return undefined
236
+ const session = (agent as { session?: unknown } | undefined)?.session
237
+ const policy = service.resolve(session === undefined ? {} : { session })
238
+ if (!SANDBOX_MODES.includes(policy.mode) || typeof policy.workspaceRoot !== 'string') {
239
+ throw new Error('win_bash: the sandbox policy service returned an invalid policy; no command was started.')
240
+ }
241
+ return policy
242
+ }
243
+
244
+ /**
245
+ * Build the win_bash tool bound to one payload and one shell registry.
246
+ * @param ctx - host context carrying the optional sandbox and job services.
247
+ * @param config - the resolved plugin configuration.
248
+ * @param runtime - absolute shell and payload paths.
249
+ * @param shells - the registry owning this plugin instance's shells.
250
+ * @returns the tool definition, ready for the tools registry.
251
+ */
252
+ export function buildWinBashTool(
253
+ ctx: Context,
254
+ config: WinBashConfig,
255
+ runtime: { bash: string, bin: string },
256
+ shells: ShellRegistry,
257
+ ): ToolDefinition {
258
+ // The background surface follows the registry, read once at build time: the
259
+ // entry registers the foreground-only variant when this deployment composes
260
+ // no job registry, so run_in_background is not advertised where it could
261
+ // never be honoured.
262
+ const jobs = config.enableRunInBackground ? readJobRegistry(ctx) : undefined
263
+ return defineTool({
264
+ name: WIN_BASH_TOOL,
265
+ description: config.description,
266
+ parameters: {
267
+ command: {
268
+ type: 'string',
269
+ required: true,
270
+ description:
271
+ "The bash command to run in this session's persistent shell. Any number of lines; the working directory and exported variables from earlier win_bash calls are still in effect.",
272
+ },
273
+ workdir: {
274
+ type: 'string',
275
+ description:
276
+ "Working directory for this command. Omitted keeps the shell's current directory, which is the session workspace until a command cds elsewhere. A relative path resolves against that directory.",
277
+ },
278
+ timeoutMs: {
279
+ type: 'integer',
280
+ description:
281
+ 'Wall-clock limit for this command in milliseconds (default '
282
+ + config.timeoutMs.toString()
283
+ + '). On expiry the shell is stopped and the next call starts a fresh one.',
284
+ },
285
+ ...jobs === undefined ? {} : {
286
+ run_in_background: {
287
+ type: 'boolean' as const,
288
+ description:
289
+ 'Run in a separate pinned bash process and return a job id immediately; collect it with job_output and stop it with job_kill. '
290
+ + 'No timeout applies, the persistent shell is not used, and this process survives this call.',
291
+ },
292
+ },
293
+ },
294
+ output: {
295
+ schema: {
296
+ type: 'object',
297
+ additionalProperties: false,
298
+ properties: {
299
+ stdout: { type: 'string', required: true },
300
+ stderr: { type: 'string', required: true },
301
+ exitCode: { type: 'integer', required: true },
302
+ // The truncation facts ./shell.ts already computes. They are declared
303
+ // here because an undeclared output member is not part of the
304
+ // canonical value the model's rendering is projected from.
305
+ stdoutTruncated: { type: 'boolean' },
306
+ stderrTruncated: { type: 'boolean' },
307
+ stdoutLostHead: { type: 'boolean' },
308
+ stderrLostHead: { type: 'boolean' },
309
+ frameOverflow: { type: 'boolean' },
310
+ stdoutSpillPath: { type: 'string' },
311
+ stderrSpillPath: { type: 'string' },
312
+ jobId: { type: 'string' },
313
+ },
314
+ },
315
+ render: (_args, value) => [{
316
+ type: 'text' as const,
317
+ text: value.jobId === undefined
318
+ ? renderResult(value)
319
+ : 'started background job ' + value.jobId
320
+ + ' (collect it with job_output, stop it with job_kill)',
321
+ }],
322
+ },
323
+ async execute(args, exec) {
324
+ const agent = exec.agent
325
+ if (agent === undefined) {
326
+ throw new Error('win_bash needs an owning agent session: the persistent shell belongs to the session that calls it.')
327
+ }
328
+ const cwd = sessionCwd(agent)
329
+ if (cwd === undefined) {
330
+ throw new Error('win_bash needs a calling session with a working directory.')
331
+ }
332
+ const policy = resolvePolicy(ctx, agent)
333
+ if (policy === undefined) {
334
+ throw new Error(
335
+ 'win_bash: the deployment serves no sandbox policy service, so this command has no authoritative permission mode'
336
+ + ' and will not run. Use the host pwsh tool instead: it is the native shell for this platform and remains available'
337
+ + ' whenever win_bash cannot serve a call.',
338
+ )
339
+ }
340
+ // Before anything is spawned or registered: a restricted session is told
341
+ // so, rather than handed a shell that dies before running its command.
342
+ assertUnconfined(policy)
343
+ const timeoutMs = clampTimeout(args.timeoutMs, config.timeoutMs)
344
+ const command = args.workdir === undefined || args.workdir === ''
345
+ ? args.command
346
+ : 'cd ' + shellQuote(normalizeWorkdir(args.workdir)) + ' && ' + args.command
347
+
348
+ // A background job owns its own pinned process. It must be refused
349
+ // BEFORE any decision to run it in the foreground: silently running the
350
+ // command in this session's persistent shell would hang the caller for
351
+ // the command's whole lifetime and then die with that shell, which is
352
+ // the opposite of what was asked for.
353
+ if (args.run_in_background === true) {
354
+ if (!config.enableRunInBackground) {
355
+ throw new Error(
356
+ 'win_bash: run_in_background is disabled for this deployment (enableRunInBackground: false),'
357
+ + ' so this call was not started.',
358
+ )
359
+ }
360
+ const registry = readJobRegistry(ctx)
361
+ if (registry === undefined) {
362
+ throw new Error(
363
+ 'BACKGROUND_UNAVAILABLE: this deployment composes no background job registry (ctx.jobs), so win_bash cannot'
364
+ + ' register a background command. This call was not run in the foreground instead. Run it without'
365
+ + ' run_in_background, or start it in the background with the host pwsh tool, which is the native shell for'
366
+ + ' this platform and stays available whenever win_bash cannot serve a call.',
367
+ )
368
+ }
369
+ const jobId = startBackgroundJob({
370
+ subprocess: ctx.subprocess,
371
+ jobs: registry,
372
+ owner: agent.id,
373
+ script: command,
374
+ argv: shellArgv(runtime),
375
+ cwd,
376
+ env: shellEnvironment(runtime, shellTempDir()),
377
+ label: args.command,
378
+ stdoutBytes: BACKGROUND_STDOUT_BYTES,
379
+ stderrBytes: BACKGROUND_STDERR_BYTES,
380
+ })
381
+ return { stdout: '', stderr: '', exitCode: 0, jobId }
382
+ }
383
+
384
+ const result = await shells.run(agent, runtime, cwd, command, {
385
+ stdoutBytes: config.maxStdoutBytes,
386
+ stderrBytes: config.maxStderrBytes,
387
+ timeoutMs,
388
+ signal: exec.signal,
389
+ })
390
+ return {
391
+ stdout: result.stdout,
392
+ stderr: result.stderr,
393
+ exitCode: result.exitCode,
394
+ stdoutTruncated: result.stdoutTruncated,
395
+ stderrTruncated: result.stderrTruncated,
396
+ stdoutLostHead: result.stdoutLostHead,
397
+ stderrLostHead: result.stderrLostHead,
398
+ frameOverflow: result.frameOverflow,
399
+ ...(result.stdoutSpillPath === undefined ? {} : { stdoutSpillPath: result.stdoutSpillPath }),
400
+ ...(result.stderrSpillPath === undefined ? {} : { stderrSpillPath: result.stderrSpillPath }),
401
+ }
402
+ },
403
+ presentCall: (args) => args.run_in_background === true
404
+ ? {
405
+ card: 'generic' as const,
406
+ title: args.command,
407
+ kind: 'execute' as const,
408
+ rawInput: args.command,
409
+ content: [{ type: 'text' as const, text: 'background command (win_bash)' }],
410
+ }
411
+ : {
412
+ card: 'terminal' as const,
413
+ title: args.command,
414
+ description: 'persistent bash (win_bash)',
415
+ },
416
+ })
417
+ }