index.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. /**
  2. * Model-facing `pwsh` tool over the `ctx.bash` executor seam. Intended for
  3. * Windows compositions where a PowerShell executor (e.g.
  4. * `@deepseek-ai/dsh-pwsh-local`) backs `ctx.bash`; the tool contract is
  5. * PowerShell-dialect: native `C:\...` paths and `$env:NAME` variables.
  6. *
  7. * Behavior mirrors `dsh-tool-bash` call-for-call minus the sandbox surface:
  8. * foreground and `run_in_background` execution (background handles register
  9. * with the generic `ctx.tasks` runtime), the managed `DSH_*` environment
  10. * through the shared `bash-env` registry, and the bash marker/truncation
  11. * rendering story. UI presentation mirrors the bash tool's too: a completed
  12. * foreground call is a terminal card with the parsed exit-status pill, using
  13. * the shared exit-status parse from `@deepseek-ai/dsh-bash`.
  14. *
  15. * @module @deepseek-ai/dsh-tool-pwsh
  16. */
  17. import { isAbsolute, resolve as resolvePath } from 'node:path'
  18. import type { Context } from 'cordis'
  19. import z from 'schemastery'
  20. import { defineTool, TOOL_ABORTED } from '@deepseek-ai/dsh-tools'
  21. import type { GenericCallView, TerminalCallView, ToolResult, ToolResultView } from '@deepseek-ai/dsh-tools'
  22. import { HarnessError } from '@deepseek-ai/dsh-llm'
  23. import type { Agent } from '@deepseek-ai/dsh-agent'
  24. import type {} from '@deepseek-ai/dsh-system-prompt'
  25. import type {} from '@deepseek-ai/dsh-tasks'
  26. import type {} from '@deepseek-ai/dsh-bash-env'
  27. import type { BashRunResult } from '@deepseek-ai/dsh-bash'
  28. import { parseExitStatus } from '@deepseek-ai/dsh-bash'
  29. import { processOutcome } from './background.ts'
  30. import { renderPwshProcessRead, renderPwshResult } from './render.ts'
  31. declare module '@deepseek-ai/dsh-tasks' {
  32. interface TaskKindMap {
  33. pwsh: 'pwsh'
  34. }
  35. }
  36. export const name = 'tool-pwsh'
  37. export const inject = ['tools', 'bash', 'systemPrompt', 'bashEnv']
  38. /** Configuration for the pwsh tool. */
  39. export interface Config {
  40. /** Expose `run_in_background` (default true); disabled calls are also rejected. */
  41. enableRunInBackground?: boolean
  42. }
  43. /** Runtime configuration schema for the pwsh tool plugin. */
  44. export const Config: z<Config> = z.object({
  45. enableRunInBackground: z.boolean().default(true),
  46. })
  47. /** Parsed tool args; execute validates value constraints absent from ParameterSchemaSpec. */
  48. interface PwshToolArgs {
  49. command: string
  50. description: string
  51. timeoutMs?: number
  52. workdir?: string
  53. run_in_background?: boolean
  54. }
  55. /** The canonical foreground result of one pwsh call (the `output.schema` value shape). */
  56. interface PwshForegroundResult {
  57. kind: 'foreground'
  58. exitCode: number | null
  59. signal: NodeJS.Signals | null
  60. timedOut: boolean
  61. aborted: boolean
  62. timeoutMs: number
  63. stdout: { text: string; truncated: boolean; spillPath?: string }
  64. stderr: { text: string; truncated: boolean; spillPath?: string }
  65. }
  66. /* jscpd:ignore-start -- minimal mirror of dsh-tool-bash's validation and execute plumbing (Agent Note). */
  67. function validatePwshArgs(args: PwshToolArgs): void {
  68. if (args.command.trim().length === 0) {
  69. throw new Error('invalid command: expected a non-empty string')
  70. }
  71. if (args.description.trim().length === 0) {
  72. throw new Error('invalid description: expected a non-empty string')
  73. }
  74. if (args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) {
  75. throw new Error(`invalid timeoutMs: expected a positive number, got ${JSON.stringify(args.timeoutMs)}`)
  76. }
  77. }
  78. /* jscpd:ignore-end */
  79. function pwshDescription(backgroundEnabled: boolean): string {
  80. const background = backgroundEnabled
  81. ? 'Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`.'
  82. : 'Background execution is not available; long-running commands must finish within the timeout.'
  83. return 'Execute a PowerShell command (`pwsh -Command`) and return its stdout/stderr. '
  84. + 'Each call runs in a fresh pwsh process: no state (cwd, variables, functions) persists between calls — '
  85. + 'pass `workdir` instead of using `cd`. Paths use native Windows form (`C:\\...`); read environment '
  86. + 'variables with `$env:NAME`. Non-zero exits are reported as `[exit code: N]`. '
  87. + 'Current harness environment facts are exposed through managed `$env:DSH_*` variables; inspect them when needed. '
  88. + 'Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. '
  89. + 'On Windows a force-killed command settles as `[exit code: 1]` without a signal marker — treat it as an interruption, not a command failure. '
  90. + background
  91. }
  92. /**
  93. * Resolve an explicit workdir first, making a relative one session-workspace-relative;
  94. * otherwise use the session header cwd and leave executor defaulting as the fallback.
  95. */
  96. function resolveWorkdir(modelWorkdir: string | undefined, exec: { agent?: Agent }): string | undefined {
  97. const headerCwd = exec.agent?.session.header.cwd
  98. if (modelWorkdir === undefined) return headerCwd
  99. if (headerCwd !== undefined && !isAbsolute(modelWorkdir)) {
  100. return resolvePath(headerCwd, modelWorkdir)
  101. }
  102. return modelWorkdir
  103. }
  104. /** Detach the executor DTO from readonly seam interfaces into plain JSON data. */
  105. function canonicalPwshResult(result: BashRunResult): PwshForegroundResult {
  106. const output = (stream: BashRunResult['stdout']) => ({
  107. text: stream.text,
  108. truncated: stream.truncated,
  109. ...stream.spillPath !== undefined ? { spillPath: stream.spillPath } : {},
  110. })
  111. return {
  112. kind: 'foreground',
  113. exitCode: result.exitCode,
  114. signal: result.signal,
  115. timedOut: result.timedOut,
  116. aborted: result.aborted,
  117. timeoutMs: result.timeoutMs,
  118. /* jscpd:ignore-start -- the canonical projection and background-handle shape mirror dsh-tool-bash's by design (Agent Note). */
  119. stdout: output(result.stdout),
  120. stderr: output(result.stderr),
  121. }
  122. }
  123. /** Canonical background-handle properties shared by the pwsh output union. */
  124. const BACKGROUND_OUTPUT_PROPERTIES = {
  125. kind: { type: 'string', required: true, const: 'background' },
  126. taskId: { type: 'string', required: true },
  127. } as const
  128. /* jscpd:ignore-end */
  129. export function apply(ctx: Context, config: Config = {}): void {
  130. const backgroundEnabled = config.enableRunInBackground ?? true
  131. ctx.systemPrompt.section({
  132. name: 'tool:pwsh',
  133. order: 105,
  134. text: 'Non-zero exits are reported as `[exit code: N]` markers; investigate failures before moving on. '
  135. + '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.',
  136. })
  137. ctx.tools.register(defineTool({
  138. name: 'pwsh',
  139. description: pwshDescription(backgroundEnabled),
  140. parameters: {
  141. command: { type: 'string', required: true, description: 'The PowerShell command to execute.' },
  142. description: {
  143. type: 'string',
  144. required: true,
  145. description: 'Clear, concise description of what this command does in active voice, '
  146. + '5-10 words (shown in the UI). Examples: "ls" → "List files in current directory"; '
  147. + '"git status" → "Show working tree status"; "Get-Process" → "List running processes".',
  148. },
  149. timeoutMs: { type: 'number', description: 'Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry.' },
  150. workdir: { type: 'string', description: 'Working directory for this command. Defaults to the session workspace; a relative path is resolved against it.' },
  151. ...backgroundEnabled ? {
  152. run_in_background: { type: 'boolean' as const, description: 'Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies.' },
  153. } : {},
  154. },
  155. output: {
  156. // The foreground result wire shape mirrors dsh-tool-bash's by contract —
  157. // consumers of one must accept the other (see the pwsh-tool-and-executor
  158. // Agent Note).
  159. /* jscpd:ignore-start -- deliberate result-schema symmetry with dsh-tool-bash. */
  160. schema: {
  161. oneOf: [
  162. {
  163. type: 'object',
  164. additionalProperties: false,
  165. properties: BACKGROUND_OUTPUT_PROPERTIES,
  166. },
  167. {
  168. type: 'object',
  169. additionalProperties: false,
  170. properties: {
  171. kind: { type: 'string', required: true, const: 'foreground' },
  172. exitCode: { required: true, oneOf: [{ type: 'integer' }, { type: 'null' }] },
  173. signal: { required: true, oneOf: [{ type: 'string' }, { type: 'null' }] },
  174. timedOut: { type: 'boolean', required: true },
  175. aborted: { type: 'boolean', required: true },
  176. timeoutMs: { type: 'number', required: true },
  177. stdout: {
  178. type: 'object',
  179. additionalProperties: false,
  180. required: true,
  181. properties: {
  182. text: { type: 'string', required: true },
  183. truncated: { type: 'boolean', required: true },
  184. spillPath: { type: 'string' },
  185. },
  186. },
  187. stderr: {
  188. type: 'object',
  189. additionalProperties: false,
  190. required: true,
  191. properties: {
  192. text: { type: 'string', required: true },
  193. truncated: { type: 'boolean', required: true },
  194. spillPath: { type: 'string' },
  195. },
  196. },
  197. },
  198. },
  199. ],
  200. },
  201. /* jscpd:ignore-end */
  202. render: (_args, value) => [{
  203. type: 'text',
  204. text: value.kind === 'background'
  205. ? `started background task ${value.taskId}`
  206. : renderPwshResult(value),
  207. }],
  208. },
  209. /* jscpd:ignore-start -- the execute path mirrors dsh-tool-bash's by design (see the pwsh-tool-and-executor Agent Note). */
  210. async execute(args: PwshToolArgs, exec) {
  211. validatePwshArgs(args)
  212. const workdir = resolveWorkdir(args.workdir, exec)
  213. const request = {
  214. command: args.command,
  215. ...workdir !== undefined ? { workdir } : {},
  216. ...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {},
  217. dshEnv: ctx.bashEnv.collect(exec),
  218. }
  219. if (args.run_in_background === true) {
  220. // Undeclared keys are allowed, so schema omission also needs enforcement.
  221. if (!backgroundEnabled) {
  222. throw new Error('run_in_background is disabled for this deployment (enableRunInBackground: false)')
  223. }
  224. const tasks = ctx.get('tasks')
  225. if (tasks === undefined) {
  226. throw new Error('background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks')
  227. }
  228. // The caller owns cancellation until ctx.tasks commits detached ownership.
  229. /* v8 ignore start -- the bash twin's branch is exercised by its sandbox-approval mid-call abort;
  230. pwsh has no approval surface, and the tool registry's pre-dispatch abort check intercepts
  231. already-aborted signals first, so this mirror-only guard has no reachable trigger. */
  232. if (exec.signal.aborted) {
  233. const error = new HarnessError('tool call aborted', TOOL_ABORTED)
  234. error.name = 'AbortError'
  235. throw error
  236. }
  237. /* v8 ignore end */
  238. // Task preflight finishes before the starter can spawn a process.
  239. const id = tasks.start({
  240. kind: 'pwsh',
  241. label: args.command,
  242. ...exec.agent ? { owner: exec.agent } : {},
  243. run: () => {
  244. const proc = ctx.bash.start(ctx.bash.resolve(request))
  245. return {
  246. cancel: () => void proc.kill(),
  247. done: proc.done.then(() => processOutcome(proc)),
  248. readOutput: () => renderPwshProcessRead(proc.readOutput()),
  249. }
  250. },
  251. })
  252. return { kind: 'background' as const, taskId: id }
  253. }
  254. const result = await ctx.bash.run(ctx.bash.resolve({
  255. ...request,
  256. signal: exec.signal,
  257. }))
  258. if (result.aborted) {
  259. const error = new HarnessError('tool call aborted', TOOL_ABORTED)
  260. error.name = 'AbortError'
  261. throw error
  262. }
  263. return canonicalPwshResult(result)
  264. },
  265. /* jscpd:ignore-end */
  266. /* jscpd:ignore-start -- the background call card mirrors presentBashCall's by design (Agent Note). */
  267. presentCall: (args: PwshToolArgs): TerminalCallView | GenericCallView => {
  268. // Background acknowledgements carry no terminal exit status; the generic
  269. // card mirrors the bash tool's background presentation.
  270. if (args.run_in_background === true) {
  271. return {
  272. card: 'generic',
  273. title: args.command,
  274. kind: 'execute',
  275. rawInput: args.command,
  276. content: [{ type: 'text', text: args.description }],
  277. }
  278. }
  279. return {
  280. card: 'terminal',
  281. title: args.command,
  282. description: args.description,
  283. ...args.workdir !== undefined ? { cwd: args.workdir } : {},
  284. }
  285. },
  286. /* jscpd:ignore-end */
  287. /* jscpd:ignore-start -- the completed-result presentation mirrors presentBashResult's by design (Agent Note). */
  288. presentResult: (args: unknown, result: ToolResult): ToolResultView | undefined => {
  289. const block = result.content.length === 1 ? result.content[0] : undefined
  290. if (block === undefined || block.type !== 'text') return undefined
  291. const raw = block.text
  292. const isBackground = typeof args === 'object' && args !== null && (args as { run_in_background?: unknown }).run_in_background === true
  293. // Background acknowledgements and errors have no terminal exit status.
  294. if (isBackground || result.isError) {
  295. return { card: 'generic', content: [{ type: 'text', text: `\`\`\`console\n${raw.replace(/\n+$/, '')}\n\`\`\`` }] }
  296. }
  297. // The exit marker becomes the card's exit pill, so it leaves the output body.
  298. const { body, ...exit } = parseExitStatus(raw)
  299. return { card: 'terminal', output: body, ...exit }
  300. },
  301. /* jscpd:ignore-end */
  302. }))
  303. }