tui.ts 5.5 KB

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