index.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. /**
  2. * Out-of-process ACP subagent backend. Each child has its own process, session, model, and
  3. * tools, so it shares no Cordis context and advertises no parent-enforced start capabilities;
  4. * the ONE thing it reads off `request.parent` is the session's workspace cwd (see
  5. * {@link resolveCwd}). This plugin uses named exports only; a default would hide its
  6. * loader metadata (see `docs/postmortem/0001-acp-default-export-drops-inject.md`).
  7. * @module @deepseek-ai/dsh-subagent-acp
  8. */
  9. import { accessSync, constants, statSync } from 'node:fs'
  10. import { isAbsolute, resolve } from 'node:path'
  11. import type { Context } from 'cordis'
  12. import z from 'schemastery'
  13. import type { SubagentCapabilities, SubagentProvider, SubagentStartRequest } from '@deepseek-ai/dsh-subagent'
  14. import { type AcpRunSpec, DEFAULT_DISPOSE_EOF_GRACE_MS, DEFAULT_DISPOSE_GRACE_MS, type PermissionPolicy, startAcpRun } from './run.ts'
  15. export const name = 'subagent-acp'
  16. export const inject = ['subagents', 'subprocess']
  17. /** Config: how to spawn and drive the child ACP agent process. */
  18. export interface Config {
  19. /** Provider name on `ctx.subagents` (default `acp`). */
  20. providerName: string
  21. /** The executable to spawn for each run (the child ACP agent). */
  22. command: string
  23. /** Arguments passed to {@link command}. */
  24. args: string[]
  25. /**
  26. * Working directory override for the child process and its ACP session.
  27. * Must be non-empty; a relative path resolves against the harness launch
  28. * directory at load, and the result must be an existing directory. When
  29. * omitted, each child inherits its delegating parent session's cwd — and
  30. * starting one from a parent session that has no cwd fails.
  31. */
  32. cwd?: string
  33. /**
  34. * How to auto-answer the child's `session/request_permission` prompts:
  35. * `reject` (default — decline every prompt) or `allow` (approve via the first
  36. * allow-shaped option). The first cut surfaces no prompt to a human.
  37. */
  38. permission: PermissionPolicy
  39. /**
  40. * Extra environment variables for the child process — e.g. the child
  41. * harness's own `DEEPSEEK_API_KEY`. Forwarded on top of a credential-scrubbed
  42. * copy of the parent env, so an explicit key here reaches the child while
  43. * ambient secrets do not leak implicitly.
  44. */
  45. env: Record<string, string>
  46. /**
  47. * Grace period (ms) for the child's EOF-driven quiesce on dispose — its
  48. * window to flush persistence and tear down its own nested subprocesses
  49. * before the parent escalates to a signal.
  50. */
  51. disposeEofGraceMs?: number
  52. /** Termination confirmation window (ms), including forced exit on every platform. */
  53. disposeGraceMs?: number
  54. }
  55. export const Config: z<Config> = z.object({
  56. providerName: z.string().default('acp'),
  57. command: z.string().required(),
  58. args: z.array(z.string()).default([]),
  59. cwd: z.string(),
  60. permission: z.union(['allow', 'reject'] as const).default('reject'),
  61. env: z.dict(z.string()).default({}),
  62. disposeEofGraceMs: z.number().default(DEFAULT_DISPOSE_EOF_GRACE_MS),
  63. disposeGraceMs: z.number().default(DEFAULT_DISPOSE_GRACE_MS),
  64. })
  65. /** A dispose grace must be a positive finite number (it bounds the teardown wait). */
  66. function assertPositiveFinite(name: string, value: number): void {
  67. if (!Number.isFinite(value) || value <= 0) {
  68. throw new Error(`subagent-acp: ${name} must be a positive finite number`)
  69. }
  70. }
  71. /** The shape after schemastery applied the defaults (cwd has none). */
  72. type ResolvedConfig = Required<Omit<Config, 'cwd'>> & Pick<Config, 'cwd'>
  73. /**
  74. * Whether `path` names an existing directory the harness can ENTER. The
  75. * search-permission probe matters: `statSync().isDirectory()` is true for a
  76. * mode-600 directory, but a subprocess cwd needs `X_OK` or spawn fails EACCES.
  77. */
  78. function isDirectory(path: string): boolean {
  79. try {
  80. if (!statSync(path).isDirectory()) return false
  81. accessSync(path, constants.X_OK)
  82. return true
  83. } catch {
  84. // statSync/accessSync throw only filesystem access errors here
  85. // (ENOENT/EACCES/ENOTDIR/…), and every one of them means the path cannot
  86. // serve as the child's cwd.
  87. return false
  88. }
  89. }
  90. /**
  91. * Assert `cwd` can actually host the child: absolute (it doubles as the ACP
  92. * session workspace, and a relative path would be re-anchored to the server
  93. * process's launch directory) and an existing directory (fail here, before the
  94. * process boundary, instead of as an ambiguous spawn ENOENT).
  95. * @param label - which source supplied the value, for the diagnostic.
  96. * @param cwd - the candidate working directory.
  97. * @returns `cwd`, validated.
  98. */
  99. function assertUsableCwd(label: string, cwd: string): string {
  100. if (!isAbsolute(cwd)) {
  101. throw new Error(`subagent-acp: ${label} must be an absolute path: ${cwd}`)
  102. }
  103. if (!isDirectory(cwd)) {
  104. throw new Error(`subagent-acp: ${label} is not an accessible directory: ${cwd}`)
  105. }
  106. return cwd
  107. }
  108. /**
  109. * Resolve the child's working directory: the deployment `cwd` override when
  110. * configured (already validated at load), else the parent session's workspace
  111. * cwd (validated here, its earliest resolvable point). Fails loud when neither
  112. * exists — falling back to the harness process cwd would silently bind the
  113. * child to the server's launch directory instead of the delegating session's
  114. * workspace (one server process serves many sessions, each with its own cwd).
  115. */
  116. function resolveCwd(configured: string | undefined, request: SubagentStartRequest): string {
  117. if (configured !== undefined) return configured
  118. const parentCwd = request.parent.session.header.cwd
  119. if (parentCwd === undefined) {
  120. throw new Error('subagent-acp: no working directory for the child — configure `cwd` or delegate from a parent session that has one')
  121. }
  122. return assertUsableCwd('parent session cwd', parentCwd)
  123. }
  124. /**
  125. * The ACP provider. Advertises NO start-time capabilities: an out-of-process
  126. * child cannot honor `outputSchema`/`maxDepth`/`toolFilter` (the service rejects
  127. * a request needing any of them before `start` runs).
  128. */
  129. class AcpProvider implements SubagentProvider {
  130. readonly capabilities: SubagentCapabilities = { outputSchema: false, depthLimit: false, toolFilter: false, persona: false }
  131. // Context contract: an out-of-process ACP child starts fresh — no parent conversation crosses the process boundary.
  132. readonly inheritsParentContext = false
  133. constructor(readonly name: string, private readonly ctx: Context, private readonly config: ResolvedConfig) {}
  134. start(request: SubagentStartRequest) {
  135. const spec: AcpRunSpec = {
  136. command: this.config.command,
  137. args: this.config.args,
  138. cwd: resolveCwd(this.config.cwd, request),
  139. permission: this.config.permission,
  140. env: this.config.env,
  141. disposeEofGraceMs: this.config.disposeEofGraceMs,
  142. disposeGraceMs: this.config.disposeGraceMs,
  143. spawn: spec => this.ctx.subprocess.spawn(spec),
  144. onError: (error, stopReason) => {
  145. // The seam forbids `result` rejecting, so a child-level failure is
  146. // flattened to a stop reason — preserve it here rather than losing it.
  147. this.ctx.logger.warn(`subagent-acp "${this.name}": child run failed (${stopReason}): ${error.message}`)
  148. },
  149. }
  150. return startAcpRun(request, spec)
  151. }
  152. }
  153. export function apply(ctx: Context, config: Config): void {
  154. // schemastery (Config) has already filled every defaulted field.
  155. const resolved = config as ResolvedConfig
  156. assertPositiveFinite('disposeEofGraceMs', resolved.disposeEofGraceMs)
  157. assertPositiveFinite('disposeGraceMs', resolved.disposeGraceMs)
  158. // `path.resolve('')` is the process cwd — an empty string would silently
  159. // reintroduce the launch-directory fallback this resolution removed.
  160. if (resolved.cwd === '') {
  161. throw new Error('subagent-acp: config cwd must not be empty — omit the key to inherit the parent session cwd')
  162. }
  163. // Interpret a relative configured cwd against the harness launch directory
  164. // ONCE, at load, and fail a misconfigured directory here — not per start.
  165. const validated: ResolvedConfig = resolved.cwd === undefined
  166. ? resolved
  167. : { ...resolved, cwd: assertUsableCwd('config cwd', resolve(resolved.cwd)) }
  168. ctx.subagents.registerProvider(new AcpProvider(validated.providerName, ctx, validated))
  169. }