stdio-agent.spec.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import { describe, it, expect } from 'vitest'
  2. import { mkdtemp } from 'node:fs/promises'
  3. import { join } from 'node:path'
  4. import { tmpdir } from 'node:os'
  5. import { Context } from 'cordis'
  6. import Loader from '@cordisjs/plugin-loader'
  7. import { AgentId, agentEvents, type Agent } from '@deepseek-ai/dsh-agent'
  8. import type { Message } from '@deepseek-ai/dsh-llm'
  9. import { TOOL_ORDER_REST } from '@deepseek-ai/dsh-system-prompt'
  10. import * as stdioAgent from '../src/index.ts'
  11. /**
  12. * Unit coverage for app composition and config forwarding: console logger, pre-created main agent,
  13. * agent-core spine, JSONL backend, and readline UI. HMR is a Loader-only leaf concern covered by the
  14. * keyless echo smoke; this tier pins the export shape because an inject-less app could otherwise
  15. * survive namespace collapse while silently losing its schema.
  16. */
  17. async function mount(config: stdioAgent.Config, withBash = false): Promise<Context> {
  18. const ctx = new Context()
  19. if (withBash) ctx.provide('bash', { sandboxMode: undefined })
  20. await ctx.plugin(stdioAgent, config)
  21. // The app mounts its children inside apply() (not awaited there); let their
  22. // fibers settle so the spine services + the pre-created agent are ready.
  23. await new Promise(resolve => setTimeout(resolve, 80))
  24. return ctx
  25. }
  26. async function isolatedSkillsConfig(catalogDescriptionMaxLength?: number): Promise<NonNullable<stdioAgent.Config['skills']>> {
  27. const home = await mkdtemp(join(tmpdir(), 'dsh-stdio-demo-skills-'))
  28. return {
  29. local: { dshHome: join(home, '.dsh'), agentsHome: join(home, '.agents') },
  30. ...catalogDescriptionMaxLength !== undefined ? { tool: { catalogDescriptionMaxLength } } : {},
  31. }
  32. }
  33. async function composePrefix(ctx: Context): Promise<Message[]> {
  34. const agent = { session: { header: { cwd: '/tmp' } } } as unknown as Agent
  35. const empty: Message[] = []
  36. return await agentEvents(ctx, agent).waterfall(
  37. 'agent/session-prefix', empty, new AbortController().signal,
  38. () => Promise.resolve(empty),
  39. )
  40. }
  41. async function withIsolatedSkillHomes<T>(run: () => Promise<T>): Promise<T> {
  42. const oldDshHome = process.env.DSH_HOME
  43. const oldAgentsHome = process.env.DSH_AGENTS_HOME
  44. const home = await mkdtemp(join(tmpdir(), 'dsh-stdio-demo-default-skills-'))
  45. process.env.DSH_HOME = join(home, '.dsh')
  46. process.env.DSH_AGENTS_HOME = join(home, '.agents')
  47. try {
  48. return await run()
  49. } finally {
  50. if (oldDshHome === undefined) {
  51. delete process.env.DSH_HOME
  52. } else {
  53. process.env.DSH_HOME = oldDshHome
  54. }
  55. if (oldAgentsHome === undefined) {
  56. delete process.env.DSH_AGENTS_HOME
  57. } else {
  58. process.env.DSH_AGENTS_HOME = oldAgentsHome
  59. }
  60. }
  61. }
  62. describe('dsh-stdio-demo app', () => {
  63. it('composes the spine + front-door cluster and pre-creates the main agent', async () => {
  64. const ctx = await mount({ model: 'mock', persona: 'hi', persistenceRoot: '/tmp/dsh-stdio-demo-spec', skills: await isolatedSkillsConfig() })
  65. // The spine services (brought up by the agent-core bundle) are all present.
  66. expect(ctx.get('agents')).toBeDefined()
  67. expect(ctx.get('agentLoop')).toBeDefined()
  68. expect(ctx.get('sessionPersistence')).toBeDefined()
  69. expect(ctx.get('userInteraction')).toBeDefined()
  70. expect(ctx.get('tools')?.get('ask_user_question')).toBeDefined()
  71. // The pre-created `main` agent the UI drives.
  72. const agent = ctx.get('agents')?.get(AgentId('main'))
  73. expect(agent).toBeDefined()
  74. expect(agent?.session.header.cwd).toBe(process.cwd())
  75. await ctx.fiber.dispose()
  76. })
  77. it('defaults persistenceRoot and welcome when omitted', async () => {
  78. // Direct apply (NOT via ctx.plugin, which validates+defaults the config
  79. // first) so the runtime `?? './.sessions'` / `?? 'ready.'` fallbacks on
  80. // apply()'s last two lines are the ones that fire — covering a
  81. // schema-bypassing direct-mount caller.
  82. const ctx = new Context()
  83. // No persona: covers the omitted-persona forwarding branch too.
  84. stdioAgent.apply(ctx, { model: 'mock', skills: await isolatedSkillsConfig() })
  85. await new Promise(resolve => setTimeout(resolve, 80))
  86. expect(ctx.get('sessionPersistence')).toBeDefined()
  87. expect(ctx.get('agents')?.get(AgentId('main'))).toBeDefined()
  88. await ctx.fiber.dispose()
  89. })
  90. it('uses default skill config when apply is called directly without skills', async () => {
  91. await withIsolatedSkillHomes(async () => {
  92. const ctx = new Context()
  93. stdioAgent.apply(ctx, { model: 'mock' })
  94. await new Promise(resolve => setTimeout(resolve, 80))
  95. expect(ctx.skills).toBeDefined()
  96. expect(await ctx.skills.list()).toEqual([])
  97. await ctx.fiber.dispose()
  98. })
  99. })
  100. it('forwards resumeSessionId onto the pre-created agent when set', async () => {
  101. // A resume id defers agent creation until persistence loads; with no backing
  102. // session the resume is contained + logged, so no `main` agent registers —
  103. // the branch that maps resumeSessionId through is what this covers.
  104. const ctx = await mount({
  105. model: 'mock',
  106. persona: 'hi',
  107. persistenceRoot: '/tmp/dsh-stdio-demo-spec-resume',
  108. resumeSessionId: 'no-such-session',
  109. skills: await isolatedSkillsConfig(),
  110. })
  111. expect(ctx.get('agents')?.get(AgentId('main'))).toBeUndefined()
  112. await ctx.fiber.dispose()
  113. })
  114. it('forwards skill config into agent-core', async () => {
  115. const ctx = await mount({ model: 'mock', persona: 'hi', skills: await isolatedSkillsConfig(6) })
  116. ctx.skills.register({ name: 'stdio-skill', description: 'Stdio skill', source: 'runtime', content: 'body' })
  117. expect(JSON.stringify(await composePrefix(ctx))).toContain('- `stdio-skill`: Std...')
  118. await ctx.fiber.dispose()
  119. })
  120. it('forwards bundled tool config into agent-core', async () => {
  121. const ctx = await mount({
  122. model: 'mock',
  123. toolBash: { enableRunInBackground: false },
  124. toolTasks: { waitTimeoutMs: 7, maxWaitTimeoutMs: 11 },
  125. skills: await isolatedSkillsConfig(),
  126. }, true)
  127. const bash = ctx.tools.schemas().find(tool => tool.name === 'bash')
  128. expect(Object.keys((bash!.parameters as { properties: Record<string, unknown> }).properties))
  129. .not.toContain('run_in_background')
  130. await ctx.fiber.dispose()
  131. })
  132. it('exposes its name and Config schema', () => {
  133. expect(stdioAgent.name).toBe('stdio-demo')
  134. expect(stdioAgent.Config).toBeDefined()
  135. })
  136. it('forwards toolOrder through agent-core to the system-prompt assembly', async () => {
  137. const ctx = await mount({
  138. model: 'mock',
  139. toolOrder: ['zulu', TOOL_ORDER_REST],
  140. persistenceRoot: '/tmp/dsh-stdio-demo-spec-tool-order',
  141. })
  142. // The bundle's own bash tools pend on the absent `ctx.bash` executor in
  143. // this providerless mount, so register two plain tools to order.
  144. for (const name of ['alpha', 'zulu']) {
  145. ctx.get('tools')!.register({
  146. name,
  147. description: name,
  148. parameters: {},
  149. execute: async () => [],
  150. })
  151. }
  152. const assembly = await ctx.get('systemPrompt')!.assemble()
  153. expect(assembly.tools.map(tool => tool.name)).toEqual(['zulu', 'alpha', 'ask_user_question', 'skill', 'task_kill', 'task_list', 'task_output'])
  154. await ctx.fiber.dispose()
  155. })
  156. it('has the namespace-plugin export shape (no stray default) so the Loader keeps name/Config/apply', () => {
  157. // A default export would make `unwrapExports` collapse this inject-less namespace and silently
  158. // drop `name`/`Config` while the app still boots. Guard the postmortem-0001 shape directly.
  159. expect('default' in stdioAgent).toBe(false)
  160. expect(typeof stdioAgent.apply).toBe('function')
  161. const loader = Object.create(Loader.prototype) as Loader
  162. const unwrapped = loader.unwrapExports(stdioAgent) as Record<string, unknown>
  163. expect(unwrapped).toBe(stdioAgent)
  164. expect(unwrapped.name).toBe('stdio-demo')
  165. expect(unwrapped.Config).toBeDefined()
  166. expect(typeof unwrapped.apply).toBe('function')
  167. })
  168. })