@deepseek-ai/dsh-tool-pwsh 0.2.2-alpha.3 → 0.2.2-rc.2

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/src/index.ts ADDED
@@ -0,0 +1,643 @@
1
+ /**
2
+ * Model-facing PowerShell Consumer of the `ctx.shell` capability seam. Intended for
3
+ * Windows compositions where a PowerShell executor (e.g.
4
+ * `@deepseek-ai/dsh-pwsh-local`) backs `ctx.shell`; the tool contract is
5
+ * PowerShell-dialect: native `C:\...` paths and `$env:NAME` variables.
6
+ *
7
+ * Behavior mirrors `dsh-tool-bash` call-for-call: foreground and
8
+ * `run_in_background` execution (with a job registry composed, every call
9
+ * registers its process with `ctx.jobs` as it starts, and a foreground call
10
+ * waits on its job until the timeout passes), the managed `DSH_*` environment through the
11
+ * shared `shell-env` registry, the per-call sandbox policy resolution (the
12
+ * calling session's mode and cwd travel to the confining executor), the
13
+ * sandbox-denial rendering with the same-turn escalation surface
14
+ * (`sandbox_permissions` + `justification` resolved through
15
+ * `ctx.approval`), and the bash marker/truncation rendering story. UI
16
+ * presentation mirrors the bash tool's too: a completed foreground call is
17
+ * a terminal card with the parsed exit-status pill, using the shared
18
+ * exit-status parse from `@deepseek-ai/dsh-shell`.
19
+ *
20
+ * @module @deepseek-ai/dsh-tool-pwsh
21
+ */
22
+
23
+ import { isAbsolute, resolve as resolvePath } from 'node:path'
24
+ import type {} from '@deepseek-ai/dsh-working-directory'
25
+ import { FiberState } from '@deepseek-ai/cordis'
26
+ import type { Context } from '@deepseek-ai/cordis'
27
+ import z from '@deepseek-ai/schemastery'
28
+ import { defineTool, TOOL_ABORTED, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools'
29
+ import type { GenericCallView, TerminalCallView, ToolDefinition, ToolExecution, ToolResult, ToolResultView } from '@deepseek-ai/dsh-tools'
30
+ import { HarnessError } from '@deepseek-ai/dsh-llm'
31
+ import { JobError } from '@deepseek-ai/dsh-jobs'
32
+ import type { JobId, JobRegistry, JobView } from '@deepseek-ai/dsh-jobs'
33
+ import type {} from '@deepseek-ai/dsh-shell-env'
34
+ import type {} from '@deepseek-ai/dsh-user-approval'
35
+ import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox'
36
+ import { ESCALATION_TARGETS, SandboxEscalationError, approveEscalation, sandboxPermissionsDescription, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox'
37
+ import { subprocessSpawnFailure } from '@deepseek-ai/dsh-subprocess'
38
+ import type { SandboxPolicyService } from '@deepseek-ai/dsh-sandbox-policy'
39
+ import type { ShellExecRequest, ShellExecSpec, ShellExecution, ShellRunResult } from '@deepseek-ai/dsh-shell'
40
+ import { parseExitStatus } from '@deepseek-ai/dsh-shell'
41
+ import { processJob, processOutcome, processSources, ringDelta } from './background.ts'
42
+ import type { ProcessJobHooks } from './background.ts'
43
+ import { renderPwshJobRead, renderPwshPromoted, renderPwshResult } from './render.ts'
44
+ import type { RenderablePwshResult } from './render.ts'
45
+
46
+ declare module '@deepseek-ai/dsh-jobs' {
47
+ interface JobKindMap {
48
+ pwsh: 'pwsh'
49
+ }
50
+ }
51
+
52
+ export const name = 'tool-pwsh'
53
+ export const inject = ['tools', 'shell', 'systemPrompt', 'shellEnv', 'workingDirectory']
54
+
55
+ /* jscpd:ignore-start -- the pwsh Config mirrors tool-bash's by design, like render/background. */
56
+ /** Configuration for the pwsh tool. */
57
+ export interface Config {
58
+ /**
59
+ * Expose `run_in_background` while a job registry is composed (default
60
+ * true); disabled calls are also rejected. Without a registry the tool is
61
+ * foreground-only regardless.
62
+ */
63
+ enableRunInBackground?: boolean
64
+ /**
65
+ * Keep a foreground command that reaches its timeout running as a
66
+ * background job instead of killing it (default true). Applies only while
67
+ * background execution is available: with `enableRunInBackground` false or
68
+ * no job registry, the executor's deadline kills the command. A foreground
69
+ * command the registry refuses at its start (admission or a missing
70
+ * controller) also runs under the deadline kill.
71
+ */
72
+ promoteOnTimeout?: boolean
73
+ }
74
+
75
+ /** Runtime configuration schema for the pwsh tool plugin. */
76
+ export const Config: z<Config> = z.object({
77
+ enableRunInBackground: z.boolean().default(true),
78
+ promoteOnTimeout: z.boolean().default(true),
79
+ })
80
+ /* jscpd:ignore-end */
81
+
82
+ /** Parsed tool args; execute validates value constraints absent from ParameterSchemaSpec. */
83
+ interface PwshToolArgs {
84
+ command: string
85
+ description: string
86
+ timeoutMs?: number
87
+ workdir?: string
88
+ run_in_background?: boolean
89
+ sandbox_permissions?: string
90
+ justification?: string
91
+ }
92
+
93
+ /** The canonical foreground result of one pwsh call (the `output.schema` value shape). */
94
+ interface PwshForegroundResult {
95
+ cwd: string
96
+ kind: 'foreground'
97
+ exitCode: number | null
98
+ signal: NodeJS.Signals | null
99
+ timedOut: boolean
100
+ aborted: boolean
101
+ /** The reason the command was stopped from outside this call, such as a human kill of its job. */
102
+ stopped?: string
103
+ timeoutMs: number
104
+ stdout: { text: string; truncated: boolean; spillPath?: string }
105
+ stderr: { text: string; truncated: boolean; spillPath?: string }
106
+ sandbox?: { mode: string; denied: boolean; enforcement?: string; runnerFailed?: boolean }
107
+ }
108
+
109
+ /* jscpd:ignore-start -- minimal mirror of dsh-tool-bash's validation and execute plumbing (Agent Note). */
110
+ function validatePwshArgs(args: PwshToolArgs): void {
111
+ if (args.command.trim().length === 0) {
112
+ throw new ToolArgsError(['invalid command: expected a non-empty string'])
113
+ }
114
+ if (args.description.trim().length === 0) {
115
+ throw new ToolArgsError(['invalid description: expected a non-empty string'])
116
+ }
117
+ if (args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) {
118
+ throw new ToolArgsError([`invalid timeoutMs: expected a positive number, got ${JSON.stringify(args.timeoutMs)}`])
119
+ }
120
+ validateEscalationArgs(args.sandbox_permissions, args.justification)
121
+ }
122
+ /* jscpd:ignore-end */
123
+
124
+ function pwshDescription(windowsSandbox: boolean): string {
125
+ const base = 'Execute a PowerShell command (`pwsh -Command`) and return its stdout/stderr. '
126
+ + 'Each call runs in a fresh pwsh process; pass `workdir` instead of using `cd`. Paths use native Windows form (`C:\\...`); read environment '
127
+ + 'variables with `$env:NAME`. '
128
+ + 'Managed `$env:DSH_*` variables expose current harness environment facts. '
129
+ + 'Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. '
130
+ + 'On Windows a force-killed command settles as `[exit code: 1]` without a signal marker — treat it as an interruption, not a command failure. '
131
+ + 'Provide `description` before `command` in the arguments. '
132
+ + 'Before any delete or move, verify that the resolved absolute target path is the intended one; never run it against a computed path you have not checked. '
133
+ + 'Do not assign to automatic variables such as `$HOME`; variable names are case-insensitive, so `$home` is the same read-only variable. '
134
+ + 'Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]`, a policy denial: do not retry another way.'
135
+ if (!windowsSandbox) return base
136
+ // The language-mode and named-pipe contracts below are Windows-restricted-token
137
+ // behavior, but the gate is 'any confining executor is mounted'
138
+ // (escalation fields advertised). Every shipped composition pairing tool-pwsh
139
+ // with a confining executor is win32-only, so the gate is equivalent. A POSIX
140
+ // pwsh-sandbox composition must gate both sentences on the platform instead
141
+ // (tracked in the pwsh-tool-and-executor Agent Note).
142
+ return base + ' Under the Windows sandbox, read-only pwsh runs in PowerShell ConstrainedLanguage mode, while '
143
+ + 'workspace-write stays in FullLanguage unless host policy says otherwise. In read-only, prefer cmdlets and core types (`[string]`, `[datetime]`, `[regex]`, `[guid]`); '
144
+ + '.NET static calls (`[System.IO.*]::`, `[math]::`), `Add-Type`, COM objects, and reflection fail '
145
+ + 'with "only core types" errors. `-f` formatting, property access, and core cmdlets work. '
146
+ + 'In both confined modes, programs cannot open named pipes, so a command that captures another '
147
+ + 'program\'s output through piped stdio (Node.js `child_process.spawn`/`exec` with the default '
148
+ + '`stdio: \'pipe\'`) fails with EPERM, while `stdio: \'inherit\'` and `stdio: \'ignore\'` spawns '
149
+ + 'work and PowerShell\'s own pipelines are unaffected. That EPERM is the documented boundary: '
150
+ + 'do not retry the command another way — escalate the exact command once or restructure it to '
151
+ + 'avoid capturing output.'
152
+ }
153
+
154
+ /** Resolve a relative per-call override against the Session's current directory. */
155
+ function resolveWorkdir(modelWorkdir: string | undefined, sessionCwd: string | undefined): string | undefined {
156
+ if (modelWorkdir === undefined) return sessionCwd
157
+ if (sessionCwd !== undefined && !isAbsolute(modelWorkdir)) {
158
+ return resolvePath(sessionCwd, modelWorkdir)
159
+ }
160
+ return modelWorkdir
161
+ }
162
+
163
+ /** Detach the executor DTO from readonly Service Definition types into plain JSON data. */
164
+ function canonicalPwshResult(result: ShellRunResult, cwd: string): PwshForegroundResult {
165
+ const output = (stream: ShellRunResult['stdout']) => ({
166
+ text: stream.text,
167
+ truncated: stream.truncated,
168
+ ...stream.spillPath !== undefined ? { spillPath: stream.spillPath } : {},
169
+ })
170
+ return {
171
+ cwd,
172
+ kind: 'foreground',
173
+ exitCode: result.exitCode,
174
+ signal: result.signal,
175
+ timedOut: result.timedOut,
176
+ aborted: result.aborted,
177
+ timeoutMs: result.timeoutMs,
178
+ /* jscpd:ignore-start -- the canonical projection and background-handle shape mirror dsh-tool-bash's by design (Agent Note). */
179
+ stdout: output(result.stdout),
180
+ stderr: output(result.stderr),
181
+ ...result.sandbox !== undefined ? {
182
+ sandbox: {
183
+ mode: result.sandbox.mode,
184
+ denied: result.sandbox.denied,
185
+ ...result.sandbox.enforcement !== undefined ? { enforcement: result.sandbox.enforcement } : {},
186
+ ...result.sandbox.runnerFailed !== undefined ? { runnerFailed: result.sandbox.runnerFailed } : {},
187
+ },
188
+ } : {},
189
+ }
190
+ }
191
+
192
+ /** The structured abort the foreground paths throw when the caller cancels the call. */
193
+ function toolAborted(): HarnessError {
194
+ const error = new HarnessError('tool call aborted', TOOL_ABORTED)
195
+ error.name = 'AbortError'
196
+ return error
197
+ }
198
+
199
+ /**
200
+ * Report a launch or preparation rejection as this tool's failure. This
201
+ * call's cancellation reason stays as thrown so the registry records it as
202
+ * aborted; a platform spawn error is classified as a subprocess spawn failure
203
+ * with the original as `cause`; any other value, including a coded error,
204
+ * keeps its own identity.
205
+ */
206
+ function launchFailure(error: unknown, signal: AbortSignal): unknown {
207
+ return signal.aborted && error === signal.reason ? error : subprocessSpawnFailure(error, 'pwsh')
208
+ }
209
+
210
+ /** A registered command: its id, the process once the starter spawned it, and the reason an outside kill gave. */
211
+ interface StartedJob {
212
+ readonly id: JobId
213
+ readonly process: () => ShellExecution | undefined
214
+ readonly stopped: () => string | undefined
215
+ /** The original error of a registration whose preparation failed before the process published. */
216
+ readonly failure: () => { error: unknown } | undefined
217
+ }
218
+
219
+ /** Canonical background-handle properties shared by the pwsh output union. */
220
+ const BACKGROUND_OUTPUT_PROPERTIES = {
221
+ kind: { type: 'string', required: true, const: 'background' },
222
+ jobId: { type: 'string', required: true },
223
+ cwd: { type: 'string', required: true },
224
+ } as const
225
+ /* jscpd:ignore-end */
226
+
227
+ /* jscpd:ignore-start -- deliberate mirror of dsh-tool-bash's apply() preamble (pwsh-tool-and-executor Agent Note). */
228
+ export function apply(ctx: Context, config: Config = {}): void {
229
+ const backgroundEnabled = config.enableRunInBackground ?? true
230
+ // Keeping a timed-out command needs the whole background surface: the job
231
+ // tools to collect and stop it, and the registry itself at execution time.
232
+ const promoteOnTimeout = (config.promoteOnTimeout ?? true) && backgroundEnabled
233
+ const defaultMode = ctx.shell.sandboxMode
234
+ const escalationModes: readonly SandboxMode[] = defaultMode === undefined ? [] : ESCALATION_TARGETS
235
+ const sandboxPolicy: SandboxPolicyService | undefined = defaultMode === undefined ? undefined : ctx.get('sandboxPolicy')
236
+ if (defaultMode !== undefined && sandboxPolicy === undefined) {
237
+ throw new Error('tool-pwsh: the mounted bash executor confines but ctx.sandboxPolicy is missing')
238
+ }
239
+ /* jscpd:ignore-end */
240
+ /** Resolve the complete standing policy for this call when a confining executor is mounted. */
241
+ const resolveSandboxPolicy = (exec: ToolExecution): SandboxExecutionPolicy | undefined =>
242
+ sandboxPolicy?.resolve(exec.agent === undefined ? {} : { session: exec.agent.session })
243
+
244
+ /* jscpd:ignore-start -- deliberate mirror of dsh-tool-bash's escalation resolver (pwsh-tool-and-executor Agent Note). */
245
+ /**
246
+ * Resolve a sandbox-escalation request through `ctx.approval` BEFORE
247
+ * anything executes, delegating the shared fail-closed sequence (strict
248
+ * widening, channel resolution, outcome mapping) to
249
+ * {@link approveEscalation}. This tool contributes only the composition
250
+ * guard (the fields are unadvertised without a sandboxing executor, yet
251
+ * schema validation checks advertised keys only, so an unadvertised
252
+ * `sandbox_permissions` still reaches execute) and the approval
253
+ * ingredients. The shared policy resolver is required whenever the
254
+ * executor advertises confinement, so a split composition fails at
255
+ * tool-plugin load.
256
+ */
257
+ const approvePwshEscalation = (
258
+ mode: string,
259
+ justification: string,
260
+ exec: ToolExecution,
261
+ standingPolicy: SandboxExecutionPolicy | undefined,
262
+ ): Promise<SandboxMode> => {
263
+ if (escalationModes.length === 0) {
264
+ throw new SandboxEscalationError(
265
+ 'sandbox_permissions is not available in this composition (no sandboxing executor to escalate)',
266
+ 'SANDBOX_ESCALATION_UNAVAILABLE',
267
+ )
268
+ }
269
+ const effectiveMode = (standingPolicy as SandboxExecutionPolicy).mode
270
+ return approveEscalation(
271
+ { requestedMode: mode, justification, effectiveMode, subject: 'command' },
272
+ {
273
+ approver: ctx.get('approval'),
274
+ agent: exec.agent,
275
+ callId: exec.callId,
276
+ toolName: 'pwsh',
277
+ signal: exec.signal,
278
+ },
279
+ )
280
+ }
281
+ /* jscpd:ignore-end */
282
+
283
+ ctx.systemPrompt.section({
284
+ name: 'tool:pwsh',
285
+ order: ctx.systemPrompt.getSectionOrder('TOOL_PWSH'),
286
+ text: 'Non-zero exits are reported as `[exit code: N]` markers; investigate failures before moving on. '
287
+ + 'On Windows a killed process settles as `[exit code: 1]` without a signal marker; treat a bare exit 1 after an interruption as a termination, not a command failure.',
288
+ })
289
+
290
+ /**
291
+ * One registration of the `pwsh` tool. With a registry, every call
292
+ * registers its process as a job at its start; without one the tool is
293
+ * foreground-only and the executor's deadline kills the command.
294
+ */
295
+ const pwshTool = (jobs: JobRegistry | undefined): ToolDefinition => {
296
+ const background = jobs !== undefined
297
+ const promote = background && promoteOnTimeout
298
+ /* jscpd:ignore-start -- the job start and wait mirror dsh-tool-bash's by design (pwsh-tool-and-executor Agent Note). */
299
+ /** Register the command as a job; the process spawns inside the starter, after admission. */
300
+ const startJob = (registry: JobRegistry, args: PwshToolArgs, exec: ToolExecution, spec: ShellExecSpec): StartedJob => {
301
+ let proc: ShellExecution | undefined
302
+ let stopped: string | undefined
303
+ let hooks: ProcessJobHooks | undefined
304
+ const id = registry.start({
305
+ kind: 'pwsh',
306
+ label: args.command,
307
+ toolCall: { callId: exec.callId, rootCallId: exec.rootCallId },
308
+ ...exec.agent ? { owner: exec.agent.id } : {},
309
+ output: processSources(() => proc),
310
+ run: () => {
311
+ const job = processJob(
312
+ async (signal) => {
313
+ proc = await ctx.shell.execute({ ...spec, signal })
314
+ return proc
315
+ },
316
+ started => processOutcome(started, escalationModes),
317
+ )
318
+ hooks = job
319
+ return {
320
+ done: job.done,
321
+ // A kill from outside this call (the human's, a parallel job_kill)
322
+ // reaches the process here; its reason is what the model reads.
323
+ cancel: (reason) => {
324
+ stopped = reason
325
+ job.cancel(reason)
326
+ },
327
+ }
328
+ },
329
+ })
330
+ return { id, process: () => proc, stopped: () => stopped, failure: () => hooks?.failure() }
331
+ }
332
+ /** Wait on a registered foreground command until it settles or the timeout passes. */
333
+ const waitOnJob = async (registry: JobRegistry, attached: StartedJob, exec: ToolExecution, spec: ShellExecSpec) => {
334
+ const owner = exec.agent?.id
335
+ const timeoutMs = spec.timeoutMs
336
+ /**
337
+ * Stop the job on this call's own account and stay on it until it
338
+ * settles, so the settlement is `awaited` and no completion notice
339
+ * follows a result this call already carries; the record then leaves
340
+ * with the call, as the model never saw the id.
341
+ */
342
+ const stop = async (reason: string): Promise<JobView> => {
343
+ registry.kill(attached.id, owner, reason)
344
+ const settled = await registry.wait(attached.id, timeoutMs, owner)
345
+ if (settled.status !== 'running' && settled.status !== 'stopping') registry.remove(attached.id, owner)
346
+ return settled
347
+ }
348
+ let view: JobView
349
+ try {
350
+ view = await registry.wait(attached.id, timeoutMs, owner, exec.signal)
351
+ } catch {
352
+ // A wait on the caller's own live job rejects only for the caller's
353
+ // abort: the model's call is over, so the command goes with it, as
354
+ // under the deadline kill.
355
+ await stop('tool call aborted')
356
+ throw toolAborted()
357
+ }
358
+ if ((view.status === 'running' || view.status === 'stopping') && attached.process() === undefined) {
359
+ // The wait expired while preparation still ran: nothing is running
360
+ // to keep, so this is the deadline's preparation timeout, with the
361
+ // settled empty result the executor's own deadline would have given.
362
+ await stop('timed out during preparation')
363
+ return {
364
+ kind: 'foreground' as const,
365
+ cwd: spec.workdir,
366
+ exitCode: null,
367
+ signal: null,
368
+ timedOut: true,
369
+ aborted: false,
370
+ timeoutMs,
371
+ stdout: { text: '', truncated: false },
372
+ stderr: { text: '', truncated: false },
373
+ ...spec.sandboxPolicy !== undefined ? { sandbox: { mode: spec.sandboxPolicy.mode, denied: false } } : {},
374
+ }
375
+ }
376
+ if (view.status === 'running' || view.status === 'stopping') {
377
+ // The wait timed out: the job keeps running. One consuming read seeds
378
+ // the result with the output so far, so `job_output` continues exactly
379
+ // where this result stops.
380
+ const read = registry.read(attached.id, owner)
381
+ return {
382
+ kind: 'promoted' as const,
383
+ cwd: spec.workdir,
384
+ jobId: attached.id,
385
+ timeoutMs,
386
+ output: renderPwshJobRead(
387
+ ringDelta(read.chunks), read.lossy, read.job.output.spillPaths ?? [], attached.process()?.sandbox, escalationModes,
388
+ ),
389
+ }
390
+ }
391
+ // Settled while the call waited: the model never saw the id, so the
392
+ // record leaves the registry with this result. The process handle keeps
393
+ // the split streams and classification the foreground result needs.
394
+ registry.remove(attached.id, owner)
395
+ const process = attached.process()
396
+ // No process was published: the starter failed before the spawn. The
397
+ // original error keeps its class and code, exactly as the foreground
398
+ // projection would have rejected; a kill before the spawn has only its detail.
399
+ if (process === undefined) {
400
+ const failure = attached.failure()
401
+ throw failure === undefined ? new Error(view.detail) : launchFailure(failure.error, exec.signal)
402
+ }
403
+ const result = await process.result().catch((error: unknown) => { throw launchFailure(error, exec.signal) })
404
+ const stopped = attached.stopped()
405
+ return { ...canonicalPwshResult(result, spec.workdir), ...stopped !== undefined ? { stopped } : {} }
406
+ }
407
+ /* jscpd:ignore-end */
408
+ return defineTool({
409
+ name: 'pwsh',
410
+ description: pwshDescription(escalationModes.length > 0),
411
+ /* jscpd:ignore-start -- deliberate mirror of dsh-tool-bash's parameter surface (pwsh-tool-and-executor Agent Note). */
412
+ parameters: {
413
+ description: {
414
+ type: 'string',
415
+ required: true,
416
+ description: 'Clear, concise description of what this command does in active voice, '
417
+ + '5-10 words (shown in the UI). Examples: "ls" → "List files in current directory"; '
418
+ + '"git status" → "Show working tree status"; "Get-Process" → "List running processes".',
419
+ },
420
+ command: { type: 'string', required: true, description: 'The PowerShell command to execute.' },
421
+ timeoutMs: {
422
+ type: 'number',
423
+ description: promote
424
+ ? 'Timeout in milliseconds. The executor applies its configured default and cap; on expiry the command moves to the background as a job instead of being killed.'
425
+ : 'Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry.',
426
+ },
427
+ workdir: { type: 'string', description: 'Working directory for this command. Defaults to the session workspace; a relative path is resolved against it.' },
428
+ ...background ? {
429
+ run_in_background: { type: 'boolean' as const, description: 'Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies.' },
430
+ } : {},
431
+ ...escalationModes.length > 0 ? {
432
+ sandbox_permissions: {
433
+ type: 'string' as const,
434
+ enum: [...escalationModes],
435
+ description: sandboxPermissionsDescription('command'),
436
+ },
437
+ justification: {
438
+ type: 'string' as const,
439
+ description: 'Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access. '
440
+ + 'Use the language of the user’s current request.',
441
+ },
442
+ } : {},
443
+ },
444
+ /* jscpd:ignore-end */
445
+ output: {
446
+ // The foreground result wire shape mirrors dsh-tool-bash's by contract —
447
+ // consumers of one must accept the other (see the pwsh-tool-and-executor
448
+ // Agent Note).
449
+ /* jscpd:ignore-start -- deliberate result-schema symmetry with dsh-tool-bash. */
450
+ schema: {
451
+ oneOf: [
452
+ {
453
+ type: 'object',
454
+ additionalProperties: false,
455
+ properties: BACKGROUND_OUTPUT_PROPERTIES,
456
+ },
457
+ {
458
+ type: 'object',
459
+ additionalProperties: false,
460
+ properties: {
461
+ kind: { type: 'string', required: true, const: 'promoted' },
462
+ cwd: { type: 'string', required: true },
463
+ jobId: { type: 'string', required: true },
464
+ timeoutMs: { type: 'number', required: true },
465
+ output: { type: 'string', required: true },
466
+ },
467
+ },
468
+ {
469
+ type: 'object',
470
+ additionalProperties: false,
471
+ properties: {
472
+ kind: { type: 'string', required: true, const: 'foreground' },
473
+ cwd: { type: 'string', required: true },
474
+ exitCode: { required: true, oneOf: [{ type: 'integer' }, { type: 'null' }] },
475
+ signal: { required: true, oneOf: [{ type: 'string' }, { type: 'null' }] },
476
+ timedOut: { type: 'boolean', required: true },
477
+ aborted: { type: 'boolean', required: true },
478
+ stopped: { type: 'string' },
479
+ timeoutMs: { type: 'number', required: true },
480
+ stdout: {
481
+ type: 'object',
482
+ additionalProperties: false,
483
+ required: true,
484
+ properties: {
485
+ text: { type: 'string', required: true },
486
+ truncated: { type: 'boolean', required: true },
487
+ spillPath: { type: 'string' },
488
+ },
489
+ },
490
+ stderr: {
491
+ type: 'object',
492
+ additionalProperties: false,
493
+ required: true,
494
+ properties: {
495
+ text: { type: 'string', required: true },
496
+ truncated: { type: 'boolean', required: true },
497
+ spillPath: { type: 'string' },
498
+ },
499
+ },
500
+ sandbox: {
501
+ type: 'object',
502
+ additionalProperties: false,
503
+ properties: {
504
+ mode: { type: 'string', required: true },
505
+ denied: { type: 'boolean', required: true },
506
+ enforcement: { type: 'string' },
507
+ runnerFailed: { type: 'boolean' },
508
+ },
509
+ },
510
+ },
511
+ },
512
+ ],
513
+ },
514
+ /* jscpd:ignore-end */
515
+ render: (_args, value) => [{
516
+ type: 'text',
517
+ text: value.kind === 'background'
518
+ ? `started background job ${value.jobId}`
519
+ : value.kind === 'promoted'
520
+ ? renderPwshPromoted(value)
521
+ : renderPwshResult(value as RenderablePwshResult, escalationModes),
522
+ }],
523
+ presentationMeta: (_args, value) => ({ cwd: value.cwd }),
524
+ },
525
+ /* jscpd:ignore-start -- the execute path mirrors dsh-tool-bash's by design (see the pwsh-tool-and-executor Agent Note). */
526
+ async execute(args: PwshToolArgs, exec) {
527
+ validatePwshArgs(args)
528
+ // Description is display metadata; workdir defaults to the caller's session.
529
+ const standingPolicy = resolveSandboxPolicy(exec)
530
+ const approvedMode = args.sandbox_permissions !== undefined && args.justification !== undefined
531
+ ? await approvePwshEscalation(args.sandbox_permissions, args.justification, exec, standingPolicy)
532
+ : undefined
533
+ const policy = approvedMode === undefined
534
+ ? standingPolicy
535
+ : { ...(standingPolicy as SandboxExecutionPolicy), mode: approvedMode }
536
+ const cwd = exec.agent === undefined ? undefined : await ctx.workingDirectory.ensure(exec.agent, exec.signal)
537
+ const workdir = resolveWorkdir(args.workdir, cwd)
538
+ const request: ShellExecRequest = {
539
+ command: args.command,
540
+ ...workdir !== undefined ? { workdir } : {},
541
+ ...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {},
542
+ dshEnv: ctx.shellEnv.collect(exec),
543
+ ...policy !== undefined ? { sandboxPolicy: policy } : {},
544
+ }
545
+ if (args.run_in_background === true) {
546
+ // Undeclared keys are allowed, so schema omission also needs enforcement.
547
+ if (!backgroundEnabled) {
548
+ throw new JobError('run_in_background is disabled for this deployment (enableRunInBackground: false)', 'JOB_BACKGROUND_DISABLED')
549
+ }
550
+ if (jobs === undefined) {
551
+ throw new ToolContextUnavailableError('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs')
552
+ }
553
+ // The caller owns cancellation until ctx.jobs commits detached ownership.
554
+ if (exec.signal.aborted) throw toolAborted()
555
+ const spec = ctx.shell.resolve({ ...request, onExpiry: 'none' })
556
+ return { kind: 'background' as const, jobId: startJob(jobs, args, exec, spec).id, cwd: spec.workdir }
557
+ }
558
+ // A foreground call is a job the tool waits on, so the command is
559
+ // visible and killable from the moment it starts and outlives the wait
560
+ // when the timeout passes. Admission refused at the start (the owner's
561
+ // job limit, no controller) runs the command under the deadline kill
562
+ // instead, exactly as a composition without a registry does.
563
+ if (jobs !== undefined && promote) {
564
+ const spec = ctx.shell.resolve({ ...request, onExpiry: 'none' })
565
+ let attached: StartedJob | undefined
566
+ try {
567
+ attached = startJob(jobs, args, exec, spec)
568
+ } catch (error) {
569
+ ctx.logger.warn(`pwsh: job registration refused, running in the foreground with the timeout kill instead: ${String(error)}`)
570
+ }
571
+ if (attached !== undefined) return waitOnJob(jobs, attached, exec, spec)
572
+ }
573
+ const spec = ctx.shell.resolve({ ...request, signal: exec.signal })
574
+ let result: ShellRunResult
575
+ try {
576
+ result = await (await ctx.shell.execute(spec)).result()
577
+ } catch (error) {
578
+ throw launchFailure(error, exec.signal)
579
+ }
580
+ if (result.aborted) throw toolAborted()
581
+ return canonicalPwshResult(result, spec.workdir)
582
+ },
583
+ /* jscpd:ignore-end */
584
+ /* jscpd:ignore-start -- the background call card mirrors presentBashCall's by design (Agent Note). */
585
+ presentCall: (args: PwshToolArgs): TerminalCallView | GenericCallView => {
586
+ // Background acknowledgements carry no terminal exit status; the generic
587
+ // card mirrors the bash tool's background presentation.
588
+ if (args.run_in_background === true) {
589
+ return {
590
+ card: 'generic',
591
+ title: args.command,
592
+ kind: 'execute',
593
+ rawInput: args.command,
594
+ content: [{ type: 'text', text: args.description }],
595
+ }
596
+ }
597
+ return {
598
+ card: 'terminal',
599
+ title: args.command,
600
+ description: args.description,
601
+ ...args.workdir !== undefined ? { cwd: args.workdir } : {},
602
+ }
603
+ },
604
+ /* jscpd:ignore-end */
605
+ /* jscpd:ignore-start -- the completed-result presentation mirrors presentBashResult's by design (Agent Note). */
606
+ presentResult: (args: unknown, result: ToolResult): ToolResultView | undefined => {
607
+ const block = result.content.length === 1 ? result.content[0] : undefined
608
+ if (block === undefined || block.type !== 'text') return undefined
609
+ const raw = block.text
610
+ const isBackground = typeof args === 'object' && args !== null && (args as { run_in_background?: unknown }).run_in_background === true
611
+ const isPromoted = (result as { value?: { kind?: unknown } }).value?.kind === 'promoted'
612
+ // Background acknowledgements, promotions, and errors have no terminal exit status.
613
+ if (isBackground || isPromoted || result.isError) {
614
+ return { card: 'generic', content: [{ type: 'text', text: `\`\`\`console\n${raw.replace(/\n+$/, '')}\n\`\`\`` }] }
615
+ }
616
+ // The exit marker becomes the card's exit pill, so it leaves the output body.
617
+ const { body, ...exit } = parseExitStatus(raw)
618
+ return { card: 'terminal', output: body, ...exit }
619
+ },
620
+ /* jscpd:ignore-end */
621
+ })
622
+ }
623
+
624
+ // The background surface follows the registry. The foreground-only variant
625
+ // registers now unless a registry is already composed, the job-backed
626
+ // variant replaces it for as long as `ctx.jobs` is present, and the
627
+ // foreground-only one returns when the registry unloads while this plugin
628
+ // stays. Both registrations belong to this plugin's own fiber.
629
+ if (!backgroundEnabled) {
630
+ ctx.tools.register(pwshTool(undefined))
631
+ return
632
+ }
633
+ let foregroundOnly = ctx.get('jobs') === undefined ? ctx.tools.register(pwshTool(undefined)) : undefined
634
+ ctx.inject(['jobs'], (jobCtx) => {
635
+ foregroundOnly?.()
636
+ foregroundOnly = undefined
637
+ const unregister = ctx.tools.register(pwshTool(jobCtx.jobs))
638
+ jobCtx.effect(() => () => {
639
+ unregister()
640
+ if (ctx.fiber.state === FiberState.ACTIVE) foregroundOnly = ctx.tools.register(pwshTool(undefined))
641
+ })
642
+ })
643
+ }