tui.ts 5.0 KB

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