tui.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /**
  2. * `dsh` default surface — the interactive TUI coding agent. Boots the shipped
  3. * tui-agent config (or the `--config` override) with the personal overlay
  4. * from the Harness home (`~/.dsh`): its `.env` fills environment gaps (precedence:
  5. * ambient environment, then the invoking directory's `.env`, then the personal one)
  6. * and its `config.yaml` patches the booted tree. The workspace is the invoking
  7. * directory: sessions, relative paths, and workspace instructions resolve from
  8. * the cwd, so `dsh` acts on whatever project it is launched in. After boot, the
  9. * agent's system prompt is told the path to this harness checkout so it can find
  10. * its own source.
  11. * @module @deepseek-ai/dsh/tui
  12. */
  13. import { fileURLToPath } from 'node:url'
  14. import {
  15. addHarnessSourceSection,
  16. boot,
  17. installFailLoud,
  18. loadEnv,
  19. loadPersonalPatches,
  20. RESUME_SESSION_ID_KEY,
  21. resolveConfigPath,
  22. } from '@deepseek-ai/dsh-app-boot'
  23. import { resolveDshHome } from '@deepseek-ai/dsh-paths'
  24. import type { Context } from 'cordis'
  25. import type { TuiResumeHost } from '@deepseek-ai/dsh-tui'
  26. const NAME = 'dsh'
  27. // Both the source tree (apps/cli/src) and the bundled bin (apps/cli/lib) sit
  28. // one directory under apps/cli, so the shipped default config resolves with
  29. // the same relative hop from either artifact.
  30. const DEFAULT_CONFIG = fileURLToPath(new URL('../../../examples/tui-agent/cordis.yml', import.meta.url))
  31. // The harness checkout root: three hops up from apps/cli/{src,lib}, resolved
  32. // from this bin's location so it holds however `dsh` is launched (a PATH
  33. // symlink, an arbitrary cwd). The agent is told where its own source lives.
  34. const SOURCE_ROOT = fileURLToPath(new URL('../../..', import.meta.url))
  35. /* v8 ignore start -- composition over the unit-tested dsh-app-boot helpers;
  36. the tui-agent PTY smoke drives this path end to end, personal overlay included */
  37. /**
  38. * Run the interactive TUI from the invoking directory.
  39. * @param config - a config path to boot instead of the shipped default, or
  40. * `undefined` for the default; already parsed from `--config`.
  41. * @param resumeSessionId - a persisted session id to resume, or `undefined`;
  42. * already parsed and non-empty-validated from `--resume`. It is provided on the
  43. * boot context under {@link RESUME_SESSION_ID_KEY}, which the shipped config
  44. * reads through `!!js` to rehydrate that session.
  45. */
  46. export async function runTui(config: string | undefined, resumeSessionId: string | undefined): Promise<void> {
  47. // Refuse pipes BEFORE booting: a compose-time throw inside the Loader tree
  48. // is logged per-entry rather than rethrown, so a piped launch would
  49. // otherwise settle into an idle UI-less process instead of exiting nonzero.
  50. if (!process.stdin.isTTY || !process.stdout.isTTY) {
  51. process.stderr.write(
  52. `${NAME}: the TUI requires stdin and stdout to be interactive TTYs; use \`${NAME} -p "task"\` for pipes and automation\n`,
  53. )
  54. process.exit(1)
  55. }
  56. installFailLoud(NAME)
  57. // The bin already loaded the invoking directory's .env; the personal .env
  58. // only fills what is still unset (process.loadEnvFile never overrides).
  59. loadEnv(NAME, resolveDshHome())
  60. // The in-place `/resume` handoff re-execs `dsh` with a normalized `--resume`
  61. // flag, so the resumed process rehydrates through this same intake. The host
  62. // is offered only when Node exposes `process.execve` and knows its own entry.
  63. const entry = process.argv[1]
  64. const execve = process.execve?.bind(process)
  65. const app: { current?: Context } = {}
  66. const resumeHost: TuiResumeHost | undefined = entry === undefined || execve === undefined ? undefined : {
  67. async handoff(sessionId): Promise<never> {
  68. const current = app.current
  69. if (current === undefined) throw new Error(`${NAME}: app boot has not completed`)
  70. // Rebuild argv from the parsed config plus the selected id: TUI mode's
  71. // only arguments are `--config <path>` and `--resume <id>`.
  72. const nextArgv = [
  73. process.execPath,
  74. ...process.execArgv,
  75. entry,
  76. `--resume=${sessionId}`,
  77. ...config !== undefined ? ['--config', config] : [],
  78. ]
  79. try {
  80. await current.fiber.dispose()
  81. execve(process.execPath, nextArgv, process.env)
  82. throw new Error('process replacement returned unexpectedly')
  83. } catch (error) {
  84. process.stderr.write(`${NAME}: resume handoff failed after terminal release: ${String(error)}\n`)
  85. process.exit(1)
  86. }
  87. },
  88. }
  89. const ctx = await boot(
  90. NAME,
  91. resolveConfigPath(config ?? DEFAULT_CONFIG, undefined),
  92. loadPersonalPatches(NAME),
  93. (hostCtx) => {
  94. // Inject the resume id (or undefined) so the shipped config's `!!js`
  95. // reads it as a bare identifier; then offer the in-place handoff host.
  96. hostCtx.provide(RESUME_SESSION_ID_KEY, resumeSessionId)
  97. if (resumeHost !== undefined) hostCtx.provide('tuiResumeHost', resumeHost)
  98. },
  99. )
  100. app.current = ctx
  101. addHarnessSourceSection(ctx, SOURCE_ROOT)
  102. }
  103. /* v8 ignore stop */