agent.host.spec.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { Context } from '@deepseek-ai/cordis'
  5. import AgentRegistry from '@deepseek-ai/dsh-agent'
  6. import type { Agent } from '@deepseek-ai/dsh-agent'
  7. import { agentPresetProjectionDefinition } from '@deepseek-ai/dsh-agent-presets'
  8. import SessionStore, { SESSION_FORMAT_VERSION, SessionLogOffset, SessionId } from '@deepseek-ai/dsh-session'
  9. import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session'
  10. import type { SessionObservation } from '@deepseek-ai/dsh-session-query'
  11. import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
  12. import { afterEach, describe, expect, it, vi } from 'vitest'
  13. import {
  14. ApiSessionAgentController,
  15. ApiSessionCwdConflict,
  16. ApiSessionNotFound,
  17. ApiSessionSubagentOwnership,
  18. inspectApiSession,
  19. } from '../src/agent.ts'
  20. import { installModelSelectionProjection } from '../src/model-selection-projection.ts'
  21. import { installSessionReadTestServices, testSessionPersistence } from './test-remote.ts'
  22. const roots: Context[] = []
  23. /** Session cwd roots created per test, removed after their context settles. */
  24. const tempDirs: string[] = []
  25. afterEach(async () => {
  26. await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose()))
  27. for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true })
  28. })
  29. async function harness(): Promise<{ ctx: Context; agents: ApiSessionAgentController }> {
  30. const ctx = new Context()
  31. roots.push(ctx)
  32. await ctx.plugin(TypertRegistry)
  33. await ctx.plugin(SessionStore)
  34. await ctx.plugin(AgentRegistry)
  35. installSessionReadTestServices(ctx)
  36. ctx.sessionProjections.register(agentPresetProjectionDefinition)
  37. installModelSelectionProjection(ctx)
  38. ctx.provide('agentDefaultModel', {
  39. currentSelection: () => ({ provider: 'fixture', model: 'fixture-model' }),
  40. saveSelection: () => Promise.resolve(),
  41. } as never)
  42. return { ctx, agents: new ApiSessionAgentController(ctx) }
  43. }
  44. function header(id: string, cwd: string | null = '/workspace'): SessionHeader {
  45. return {
  46. version: SESSION_FORMAT_VERSION,
  47. id: SessionId(id),
  48. createdAt: 1,
  49. isSeeded: false,
  50. ...(cwd === null ? {} : { cwd }),
  51. }
  52. }
  53. function providePersistence(ctx: Context, persistence: Record<string, unknown>): () => void {
  54. return ctx.provide('sessionPersistence', testSessionPersistence(ctx, persistence) as never)
  55. }
  56. function agent(ctx: Context, meta: SessionHeader): Agent {
  57. const session = ctx.sessions.create(meta.id, { meta })
  58. return { id: meta.id, session, status: 'idle', ctx } as Agent
  59. }
  60. function unpublishedAgent(ctx: Context, meta: SessionHeader): Agent {
  61. return {
  62. id: meta.id,
  63. session: { id: meta.id, header: meta, events: [] },
  64. status: 'idle',
  65. ctx,
  66. } as unknown as Agent
  67. }
  68. describe('ApiSession identity failures', () => {
  69. it('describes cwd conflicts with and without a recorded cwd', () => {
  70. expect(new ApiSessionCwdConflict(SessionId('missing-cwd'), '/wanted', undefined).message)
  71. .toContain('records no cwd')
  72. expect(new ApiSessionCwdConflict(SessionId('wrong-cwd'), '/wanted', '/existing').message)
  73. .toContain('belongs to "/existing"')
  74. })
  75. it('maps absent and cwd-less point observations to not found', async () => {
  76. const ctx = new Context()
  77. roots.push(ctx)
  78. await ctx.plugin(SessionStore)
  79. installSessionReadTestServices(ctx)
  80. await expect(inspectApiSession(ctx, SessionId('missing')))
  81. .rejects.toBeInstanceOf(ApiSessionNotFound)
  82. const inspect = vi.fn(() => Promise.resolve(undefined))
  83. const stat = vi.fn(() => Promise.resolve(undefined))
  84. const disposeMissing = providePersistence(ctx, {
  85. list: () => Promise.resolve([]),
  86. stat,
  87. inspect,
  88. })
  89. await expect(inspectApiSession(ctx, SessionId('missing'))).rejects.toBeInstanceOf(ApiSessionNotFound)
  90. // Absence is decided by the stat preflight; the log itself is never opened.
  91. expect(stat).toHaveBeenCalledOnce()
  92. expect(inspect).not.toHaveBeenCalled()
  93. disposeMissing()
  94. const listed = header('cwd-less-catalog', null)
  95. const disposeListed = providePersistence(ctx, {
  96. list: () => Promise.resolve([listed]),
  97. inspect: () => Promise.resolve({ meta: listed, events: [] }),
  98. })
  99. await expect(inspectApiSession(ctx, listed.id)).rejects.toBeInstanceOf(ApiSessionNotFound)
  100. disposeListed()
  101. const catalog = header('cwd-less-inspect')
  102. const inspected = header('cwd-less-inspect', null)
  103. providePersistence(ctx, {
  104. list: () => Promise.resolve([catalog]),
  105. inspect: () => Promise.resolve({ meta: inspected, events: [] }),
  106. })
  107. await expect(inspectApiSession(ctx, catalog.id)).rejects.toBeInstanceOf(ApiSessionNotFound)
  108. })
  109. it('forwards an explicit inspection signal', async () => {
  110. const ctx = new Context()
  111. roots.push(ctx)
  112. await ctx.plugin(SessionStore)
  113. installSessionReadTestServices(ctx)
  114. const meta = header('signalled-inspection')
  115. const inspect = vi.fn(() => Promise.resolve({ meta, inheritedEventCount: SessionLogOffset(0), events: [] }))
  116. providePersistence(ctx, {
  117. list: () => Promise.resolve([meta]),
  118. inspect,
  119. })
  120. const signal = new AbortController().signal
  121. await expect(inspectApiSession(ctx, meta.id, signal)).resolves.toEqual({ meta, inheritedEventCount: SessionLogOffset(0), events: [] })
  122. expect(inspect).toHaveBeenCalledWith(meta.id, signal)
  123. })
  124. })
  125. describe('ApiSession Agent lookup and recovery', () => {
  126. it('resumes directly from a retained observation and rejects an invalid observed header', async () => {
  127. const { ctx, agents } = await harness()
  128. const meta = header('observed-resume')
  129. const resumed = unpublishedAgent(ctx, meta)
  130. const resume = vi.spyOn(ctx.agents, 'resume').mockResolvedValue({
  131. agent: resumed,
  132. dispose: () => Promise.resolve(),
  133. })
  134. const observed = {
  135. source: 'prepared',
  136. header: meta,
  137. events: [],
  138. cursor: -1,
  139. projections: { asOfSeq: -1, values: {} },
  140. retain: vi.fn(),
  141. [Symbol.dispose]: vi.fn(),
  142. } as unknown as SessionObservation
  143. await expect(agents.resolveObservedAgent(observed)).resolves.toEqual({ agent: resumed })
  144. expect(resume).toHaveBeenCalledWith(expect.objectContaining({ resumeSessionId: meta.id }))
  145. const invalid = {
  146. ...observed,
  147. header: header('observed-without-cwd', null),
  148. } as SessionObservation
  149. await expect(agents.resolveObservedAgent(invalid)).resolves.toMatchObject({
  150. error: { code: 'session/not-found' },
  151. })
  152. })
  153. it('projects live Agent contexts and maps missing cold identities through Typert lookup failures', async () => {
  154. const { ctx } = await harness()
  155. const live = agent(ctx, header('live'))
  156. ctx.agents.register(live)
  157. providePersistence(ctx, {
  158. list: () => Promise.resolve([]),
  159. inspect: vi.fn(),
  160. })
  161. const host = ctx.typert.contexts.getHost('agent')
  162. if (host === undefined) throw new Error('Agent Context resolver was not registered')
  163. await expect(host.resolve(live.id)).resolves.toBe(live.ctx)
  164. await expect(host.resolve(SessionId('missing'))).rejects.toMatchObject({ code: 'session/not-found' })
  165. })
  166. it('returns raced ordinary Agents and ownership failures after resume throws', async () => {
  167. const ordinary = await harness()
  168. const ordinaryMeta = header('ordinary-race')
  169. providePersistence(ordinary.ctx, {
  170. list: () => Promise.resolve([ordinaryMeta]),
  171. inspect: () => Promise.resolve({ meta: ordinaryMeta, events: [] }),
  172. })
  173. const winner = agent(ordinary.ctx, ordinaryMeta)
  174. vi.spyOn(ordinary.ctx.agents, 'resume').mockImplementation(async () => {
  175. ordinary.ctx.agents.register(winner)
  176. throw new Error('raced publication')
  177. })
  178. await expect(ordinary.agents.resolveAgent(ordinaryMeta.id)).resolves.toEqual({ agent: winner })
  179. const child = await harness()
  180. const childMeta = header('child-race')
  181. providePersistence(child.ctx, {
  182. list: () => Promise.resolve([childMeta]),
  183. inspect: () => Promise.resolve({ meta: childMeta, events: [] }),
  184. })
  185. vi.spyOn(child.ctx.agents, 'resume').mockImplementation(async () => {
  186. child.ctx.sessions.create(childMeta.id, {
  187. meta: { ...childMeta, parentSession: SessionId('parent'), origin: 'subagent' },
  188. })
  189. throw new Error('raced child publication')
  190. })
  191. await expect(child.agents.resolveAgent(childMeta.id)).resolves.toMatchObject({
  192. error: { code: 'session/agent-busy' },
  193. })
  194. })
  195. it('reports not-found and ordinary resume failures without fabricating an Agent', async () => {
  196. const missing = await harness()
  197. providePersistence(missing.ctx, {
  198. list: () => Promise.resolve([]),
  199. inspect: vi.fn(),
  200. })
  201. await expect(missing.agents.resolveAgent(SessionId('missing'))).resolves.toMatchObject({
  202. error: { code: 'session/not-found' },
  203. })
  204. const failed = await harness()
  205. const meta = header('failed')
  206. providePersistence(failed.ctx, {
  207. list: () => Promise.resolve([meta]),
  208. inspect: () => Promise.resolve({ meta, events: [] }),
  209. })
  210. vi.spyOn(failed.ctx.agents, 'resume').mockRejectedValue(new Error('factory unavailable'))
  211. await expect(failed.agents.resolveAgent(meta.id)).resolves.toMatchObject({
  212. error: { code: 'gateway/internal', message: expect.stringContaining('factory unavailable') as string },
  213. })
  214. })
  215. it('requires projected observations before activation', async () => {
  216. const { agents } = await harness()
  217. const meta = header('unprojected-observation')
  218. const observed = {
  219. source: 'prepared',
  220. header: meta,
  221. events: [],
  222. cursor: -1,
  223. retain: vi.fn(),
  224. [Symbol.dispose]: vi.fn(),
  225. } as unknown as SessionObservation
  226. expect(() => agents.presetForObservation(observed)).toThrow(
  227. 'Agent activation requires a projected Session observation',
  228. )
  229. })
  230. })
  231. describe('ApiSession model selection', () => {
  232. it('requires the model-selection projection', async () => {
  233. const { ctx, agents } = await harness()
  234. const live = agent(ctx, header('missing-model-projection'))
  235. vi.spyOn(ctx.sessionProjections, 'stateOf').mockReturnValue(undefined)
  236. expect(() => agents.selectionFor(live)).toThrow('required modelSelection projection')
  237. })
  238. it('reads a reasoning-free request and consumes only the exact pending selection', async () => {
  239. const { ctx, agents } = await harness()
  240. const logged = agent(ctx, header('logged-model'))
  241. logged.session.append('request/header', {
  242. header: { config: { provider: 'logged-provider', model: 'logged-model' } },
  243. reason: 'initial',
  244. })
  245. expect(agents.selectionFor(logged).current).toEqual({
  246. provider: 'logged-provider',
  247. model: 'logged-model',
  248. })
  249. const pending = agent(ctx, header('pending-model'))
  250. const selection = agents.selectionFor(pending)
  251. agents.selectForNextRequest(pending, {
  252. provider: 'selected-provider',
  253. model: 'selected-model',
  254. reasoningEffort: 'high' as never,
  255. })
  256. expect(selection.current).toMatchObject({
  257. provider: 'selected-provider', model: 'selected-model', reasoningEffort: 'high',
  258. })
  259. expect(agents.consumeSelection(pending, 'other-provider', 'selected-model', 'high')).toBe(false)
  260. expect(agents.consumeSelection(pending, 'selected-provider', 'other-model', 'high')).toBe(false)
  261. expect(agents.consumeSelection(pending, 'selected-provider', 'selected-model', 'low')).toBe(false)
  262. expect(agents.consumeSelection(pending, 'selected-provider', 'selected-model', 'high')).toBe(true)
  263. expect(selection.current).toEqual({ provider: 'fixture', model: 'fixture-model' })
  264. const untouched = agent(ctx, header('uninstalled-model'))
  265. expect(agents.consumeSelection(untouched, 'fixture', 'fixture-model', undefined)).toBe(false)
  266. })
  267. })
  268. describe('ApiSession create or adoption', () => {
  269. it('shares one in-flight creation between concurrent callers', async () => {
  270. const { ctx, agents } = await harness()
  271. const cwd = mkdtempSync(join(tmpdir(), 'dsh-session-controller-concurrent-'))
  272. tempDirs.push(cwd)
  273. const meta = header('concurrent-create', cwd)
  274. const created = unpublishedAgent(ctx, meta)
  275. let release!: () => void
  276. const gate = new Promise<void>((resolve) => { release = resolve })
  277. const create = vi.spyOn(ctx.agents, 'create').mockImplementation(async () => {
  278. await gate
  279. return { agent: created, dispose: () => Promise.resolve() }
  280. })
  281. const first = agents.ensureSession(meta.id, cwd, false)
  282. const second = agents.ensureSession(meta.id, cwd, false)
  283. release()
  284. await expect(Promise.all([first, second])).resolves.toEqual([created, created])
  285. expect(create).toHaveBeenCalledOnce()
  286. })
  287. it('accepts a raced ordinary creation and rejects a raced attached child', async () => {
  288. const ordinary = await harness()
  289. const cwd = mkdtempSync(join(tmpdir(), 'dsh-session-controller-create-'))
  290. tempDirs.push(cwd)
  291. const ordinaryMeta = header('create-race', cwd)
  292. const winner = agent(ordinary.ctx, ordinaryMeta)
  293. vi.spyOn(ordinary.ctx.agents, 'create').mockImplementation(async () => {
  294. ordinary.ctx.agents.register(winner)
  295. throw new Error('raced creation')
  296. })
  297. await expect(ordinary.agents.ensureSession(ordinaryMeta.id, cwd, false))
  298. .resolves.toBe(winner)
  299. const child = await harness()
  300. const childCwd = mkdtempSync(join(tmpdir(), 'dsh-session-controller-child-'))
  301. tempDirs.push(childCwd)
  302. const childId = SessionId('create-child-race')
  303. vi.spyOn(child.ctx.agents, 'create').mockImplementation(async () => {
  304. child.ctx.sessions.create(childId, {
  305. meta: { cwd: childCwd, parentSession: SessionId('parent'), origin: 'subagent' },
  306. })
  307. throw new Error('raced child creation')
  308. })
  309. await expect(child.agents.ensureSession(childId, childCwd, false))
  310. .rejects.toBeInstanceOf(ApiSessionSubagentOwnership)
  311. })
  312. it('validates ownership and cwd on the Agent returned by creation', async () => {
  313. const child = await harness()
  314. const childCwd = mkdtempSync(join(tmpdir(), 'dsh-session-controller-returned-child-'))
  315. tempDirs.push(childCwd)
  316. const childMeta = {
  317. ...header('returned-child', childCwd),
  318. parentSession: SessionId('parent'),
  319. origin: 'subagent' as const,
  320. }
  321. const childAgent = unpublishedAgent(child.ctx, childMeta)
  322. vi.spyOn(child.ctx.agents, 'create').mockResolvedValue({
  323. agent: childAgent,
  324. dispose: () => Promise.resolve(),
  325. })
  326. await expect(child.agents.ensureSession(childMeta.id, childCwd, false))
  327. .rejects.toBeInstanceOf(ApiSessionSubagentOwnership)
  328. const wrong = await harness()
  329. const requestedCwd = mkdtempSync(join(tmpdir(), 'dsh-session-controller-wrong-cwd-'))
  330. tempDirs.push(requestedCwd)
  331. const wrongAgent = unpublishedAgent(wrong.ctx, header('wrong-returned-cwd', '/other'))
  332. vi.spyOn(wrong.ctx.agents, 'create').mockResolvedValue({
  333. agent: wrongAgent,
  334. dispose: () => Promise.resolve(),
  335. })
  336. await expect(wrong.agents.ensureSession(wrongAgent.id, requestedCwd, false))
  337. .rejects.toBeInstanceOf(ApiSessionCwdConflict)
  338. })
  339. it('resumes a matching persisted identity and preserves its selected preset', async () => {
  340. const { ctx, agents } = await harness()
  341. const meta = { ...header('stored'), agentPreset: 'minimal' }
  342. const events = [{
  343. type: 'agent-preset/selected',
  344. seq: 0,
  345. time: 1,
  346. data: { agentPreset: 'minimal' },
  347. }] as SessionEvent[]
  348. providePersistence(ctx, {
  349. list: () => Promise.resolve([meta]),
  350. inspect: () => Promise.resolve({ meta, events }),
  351. })
  352. ctx.provide('agentPresets', {
  353. resolve: (id?: string) => Promise.resolve({ id: id ?? 'minimal' }),
  354. mount: () => Promise.resolve(),
  355. } as never)
  356. const resumed = {
  357. id: meta.id,
  358. session: {
  359. id: meta.id,
  360. header: meta,
  361. snapshotEvents: () => events,
  362. eventAt: (seq: number) => events[seq],
  363. seq: events.length,
  364. },
  365. status: 'idle',
  366. ctx,
  367. } as unknown as Agent
  368. const resume = vi.spyOn(ctx.agents, 'resume').mockResolvedValue({
  369. agent: resumed,
  370. dispose: () => Promise.resolve(),
  371. })
  372. await expect(agents.ensureSession(meta.id, '/workspace', true, 'minimal')).resolves.toBe(resumed)
  373. expect(resume).toHaveBeenCalledWith(expect.objectContaining({ resumeSessionId: meta.id }))
  374. })
  375. it('rejects an ownership race before resume and a persisted cwd conflict', async () => {
  376. const child = await harness()
  377. const childMeta = header('resume-child-race')
  378. providePersistence(child.ctx, {
  379. list: () => Promise.resolve([childMeta]),
  380. inspect: () => Promise.resolve({ meta: childMeta, events: [] }),
  381. })
  382. child.ctx.provide('agentPresets', {
  383. resolve: () => {
  384. child.ctx.sessions.create(childMeta.id, {
  385. meta: { ...childMeta, parentSession: SessionId('parent'), origin: 'subagent' },
  386. })
  387. return Promise.resolve({ id: 'standard' })
  388. },
  389. mount: () => Promise.resolve(),
  390. } as never)
  391. await expect(child.agents.resolveAgent(childMeta.id)).resolves.toMatchObject({
  392. error: { code: 'session/agent-busy' },
  393. })
  394. const conflict = await harness()
  395. const stored = header('stored-cwd-conflict', '/stored')
  396. providePersistence(conflict.ctx, {
  397. list: () => Promise.resolve([stored]),
  398. inspect: () => Promise.resolve({ meta: stored, events: [] }),
  399. })
  400. await expect(conflict.agents.ensureSession(stored.id, '/requested', true))
  401. .rejects.toBeInstanceOf(ApiSessionCwdConflict)
  402. })
  403. it('surfaces directory creation failure and rejects setup without a scoped Agent', async () => {
  404. const { agents } = await harness()
  405. const parent = mkdtempSync(join(tmpdir(), 'dsh-session-controller-file-'))
  406. tempDirs.push(parent)
  407. const file = join(parent, 'file')
  408. writeFileSync(file, 'not a directory')
  409. await expect(agents.ensureSession(SessionId('mkdir-failure'), join(file, 'child'), false))
  410. .rejects.toThrow('failed to ensure project directory')
  411. const composition = await agents.composeAgent(undefined)
  412. expect(() => composition.setup(new Context())).toThrow('Agent setup has no scoped Agent')
  413. })
  414. })