session-cold.host.spec.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. /**
  2. * Cold-session and degenerate-composition paths of the Session Controller:
  3. * metadata-only listing, Agent-free history reads, subagent ownership
  4. * isolation, and prompt failure mapping.
  5. */
  6. import { describe, expect, it, vi } from 'vitest'
  7. import { mkdtempSync, writeFileSync } from 'node:fs'
  8. import { tmpdir } from 'node:os'
  9. import { join } from 'node:path'
  10. import { Context } from '@deepseek-ai/cordis'
  11. import SessionStore from '@deepseek-ai/dsh-session'
  12. import AgentRegistry from '@deepseek-ai/dsh-agent'
  13. import { SessionHistoryController } from '@deepseek-ai/dsh-api-session-controller/src/history.ts'
  14. import { subagentIdentityProjectionDefinition } from '@deepseek-ai/dsh-subagent/src/projection.ts'
  15. import { TypertLookupFailure } from '@deepseek-ai/dsh-typert-protocol'
  16. import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
  17. import { createUserMessage, MessageId } from '@deepseek-ai/dsh-llm'
  18. import { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent'
  19. import type { Agent } from '@deepseek-ai/dsh-agent'
  20. import type { Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
  21. import type { SessionPromptRequest, SessionRequestId } from '../src/types.ts'
  22. import {
  23. PersistenceCoordinator,
  24. SessionPersistenceRevision,
  25. type PersistenceBackend,
  26. type StoredPrefix,
  27. } from '@deepseek-ai/dsh-session-persistence'
  28. import { ApiSessionList } from '../src/list.ts'
  29. import {
  30. createSessionTestRemote,
  31. installSessionReadTestServices,
  32. testSessionPersistence,
  33. } from './test-remote.ts'
  34. const sid = (id: string): SessionId => id as SessionId
  35. function request<P>(payload: P): P {
  36. return payload
  37. }
  38. let nextRequestId = 1
  39. function promptRequest(
  40. payload: Omit<SessionPromptRequest, 'requestId'>,
  41. ): SessionPromptRequest {
  42. return {
  43. ...payload,
  44. requestId: `cold-${String(nextRequestId++)}` as SessionRequestId,
  45. }
  46. }
  47. function header(id: string, createdAt: number, extra: Partial<SessionHeader> = {}): SessionHeader {
  48. return { version: 0, id: sid(id), createdAt, cwd: '/proj', ...extra }
  49. }
  50. function providePersistence(ctx: Context, persistence: Record<string, unknown>): () => void {
  51. return ctx.provide('sessionPersistence', testSessionPersistence(ctx, persistence) as never)
  52. }
  53. describe('sessions.list cold merge', () => {
  54. it('fully observes only small possibly-blank artifacts and treats unavailable probes as visible', async () => {
  55. const ctx = new Context()
  56. await ctx.plugin(SessionStore)
  57. const root = mkdtempSync(join(tmpdir(), 'dsh-cold-'))
  58. const smallPath = join(root, 'small.log')
  59. const largePath = join(root, 'large.log')
  60. writeFileSync(smallPath, 'x'.repeat(1024))
  61. writeFileSync(largePath, 'x'.repeat(1025))
  62. const metas = [
  63. header('small-blank', 100),
  64. header('small-conversation', 200),
  65. header('large-unknown', 300),
  66. header('cached-nonblank', 400),
  67. header('locationless', 500, { parentSession: sid('session-parent'), origin: 'subagent' }),
  68. header('vanished', 600),
  69. header('read-failure', 700),
  70. { version: 0, id: sid('missing-cwd'), createdAt: 800 },
  71. ]
  72. const inspect = vi.fn(async (id: SessionId) => {
  73. if (id === sid('small-blank')) {
  74. return {
  75. meta: metas[0]!,
  76. events: [{ type: 'session/end-seed', seq: 0, time: 700, data: {} }] as SessionEvent[],
  77. }
  78. }
  79. if (id === sid('small-conversation')) {
  80. return {
  81. meta: metas[1]!,
  82. events: [
  83. { type: 'turn/start', seq: 0, time: 800, data: { turn: 1 } },
  84. {
  85. type: 'user/message', seq: 1, time: 1200,
  86. data: createUserMessage({ content: [{ type: 'text', text: 'worked' }], source: { kind: 'user' } }),
  87. surfaceOp: 'append',
  88. },
  89. ] as SessionEvent[],
  90. }
  91. }
  92. if (id === sid('read-failure')) throw new Error('simulated read failure')
  93. throw new Error(`unexpected cold read: ${id}`)
  94. })
  95. providePersistence(ctx, {
  96. list: () => Promise.resolve(metas),
  97. locate: (meta: SessionHeader) => {
  98. if (meta.id === sid('large-unknown')) return { kind: 'jsonl', path: largePath }
  99. if (meta.id === sid('locationless')) return undefined
  100. if (meta.id === sid('vanished')) return { kind: 'jsonl', path: join(root, 'vanished.log') }
  101. return { kind: 'jsonl', path: smallPath }
  102. },
  103. inspect,
  104. })
  105. ctx.provide('sessionProjectionCache', {
  106. cachedSnapshot: (meta: SessionHeader) => {
  107. if (meta.id === sid('small-blank')) {
  108. return { asOfSeq: 0, values: { sessionListMetadata: { blank: true, lastPromptAt: null } } }
  109. }
  110. if (meta.id === sid('small-conversation')) {
  111. return { asOfSeq: 0, values: { sessionListMetadata: { blank: true, lastPromptAt: 900 } } }
  112. }
  113. if (meta.id === sid('cached-nonblank')) {
  114. return { asOfSeq: 1, values: { sessionListMetadata: { blank: false, lastPromptAt: 1000 } } }
  115. }
  116. return undefined
  117. },
  118. hydratePrepared: (session: Session, _meta: SessionHeader, events: readonly SessionEvent[]) =>
  119. ctx.sessionProjections.hydrate(session, {}, events, 0),
  120. } as never)
  121. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  122. const response = await remote.list(request({}))
  123. expect(response.ok).toBe(true)
  124. if (!response.ok) throw new Error('unreachable')
  125. const byId = Object.fromEntries(response.value.items.map(item => [item.sessionId, item]))
  126. expect(byId['small-blank']).toMatchObject({ blank: true, updatedAt: 100, running: false })
  127. expect(byId['small-conversation']).toMatchObject({ blank: false, updatedAt: 1200 })
  128. expect(byId['large-unknown']).toMatchObject({ blank: false, updatedAt: 300 })
  129. expect(byId['cached-nonblank']).toMatchObject({ blank: false, updatedAt: 1000 })
  130. expect(byId['locationless']).toMatchObject({
  131. blank: false,
  132. updatedAt: 500,
  133. parentSessionId: 'session-parent',
  134. origin: 'subagent',
  135. })
  136. expect(byId['vanished']).toMatchObject({ blank: false, updatedAt: 600 })
  137. expect(byId['read-failure']).toMatchObject({ blank: false, updatedAt: 700 })
  138. expect(byId['missing-cwd']).toBeUndefined()
  139. expect(inspect).toHaveBeenCalledTimes(3)
  140. expect(inspect.mock.calls.map(([id]) => id)).toEqual(expect.arrayContaining([
  141. sid('small-blank'),
  142. sid('small-conversation'),
  143. sid('read-failure'),
  144. ]))
  145. })
  146. it('can disable bounded cold observations without hiding cold Sessions', async () => {
  147. const ctx = new Context()
  148. await ctx.plugin(SessionStore)
  149. const meta = header('probe-disabled', 100)
  150. const inspect = vi.fn()
  151. providePersistence(ctx, {
  152. list: () => Promise.resolve([meta]),
  153. locate: () => ({ kind: 'jsonl', path: '/not-read' }),
  154. inspect,
  155. })
  156. const remote = createSessionTestRemote(ctx, {
  157. defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
  158. cwd: '/tmp',
  159. coldBlankProbeMaxBytes: 0,
  160. })
  161. const response = await remote.list(request({}))
  162. if (!response.ok) throw new Error('unreachable')
  163. expect(response.value.items).toEqual([
  164. expect.objectContaining({ sessionId: meta.id, blank: false, updatedAt: meta.createdAt }),
  165. ])
  166. expect(inspect).not.toHaveBeenCalled()
  167. })
  168. it('prefers a live row attached during the query without folding its seed', async () => {
  169. const ctx = new Context()
  170. await ctx.plugin(SessionStore)
  171. await ctx.plugin(AgentRegistry)
  172. const meta = header('attached-during-list', 100)
  173. const started = Promise.withResolvers<undefined>()
  174. const release = Promise.withResolvers<undefined>()
  175. providePersistence(ctx, {
  176. list: async () => {
  177. started.resolve(undefined)
  178. await release.promise
  179. return [meta]
  180. },
  181. })
  182. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  183. const listing = remote.list(request({}))
  184. await started.promise
  185. const session = ctx.sessions.create(meta.id, {
  186. seed: [
  187. { type: 'turn/start', seq: 0, time: 200, data: { turn: 1 } },
  188. {
  189. type: 'user/message', seq: 1, time: 300,
  190. data: createUserMessage({ content: [{ type: 'text', text: 'live' }], source: { kind: 'user' } }),
  191. surfaceOp: 'append',
  192. },
  193. ],
  194. meta: {
  195. ...meta.cwd === undefined ? {} : { cwd: meta.cwd },
  196. createdAt: meta.createdAt,
  197. },
  198. })
  199. ctx.agents.register({ id: session.id, session, status: 'running', ctx } as Agent)
  200. release.resolve(undefined)
  201. const response = await listing
  202. if (!response.ok) throw new Error('list failed')
  203. expect(response.value.items).toEqual([
  204. expect.objectContaining({
  205. sessionId: meta.id,
  206. blank: false,
  207. running: true,
  208. updatedAt: 100,
  209. }),
  210. ])
  211. })
  212. it('prefers a Session that attaches during its bounded cold observation', async () => {
  213. const ctx = new Context()
  214. await ctx.plugin(SessionStore)
  215. await ctx.plugin(AgentRegistry)
  216. const root = mkdtempSync(join(tmpdir(), 'dsh-cold-race-'))
  217. const path = join(root, 'small.log')
  218. writeFileSync(path, 'small')
  219. const meta = header('attached-during-probe', 100)
  220. providePersistence(ctx, {
  221. list: () => Promise.resolve([meta]),
  222. locate: () => ({ kind: 'jsonl', path }),
  223. inspect: () => {
  224. const session = ctx.sessions.create(meta.id, {
  225. meta,
  226. seed: [{ type: 'turn/start', seq: 0, time: 200, data: { turn: 1 } }],
  227. })
  228. ctx.agents.register({ id: session.id, session, status: 'running', ctx } as Agent)
  229. return Promise.resolve({ meta, events: [] })
  230. },
  231. })
  232. const remote = createSessionTestRemote(ctx, {
  233. defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp',
  234. })
  235. const response = await remote.list(request({}))
  236. if (!response.ok) throw new Error('list failed')
  237. expect(response.value.items).toEqual([
  238. expect.objectContaining({ sessionId: meta.id, running: true, blank: false }),
  239. ])
  240. await ctx.fiber.dispose()
  241. })
  242. it('propagates a cold location failure instead of returning a partial list', async () => {
  243. const ctx = new Context()
  244. await ctx.plugin(SessionStore)
  245. const meta = header('broken-cache', 100)
  246. providePersistence(ctx, {
  247. list: () => Promise.resolve([meta]),
  248. locate: () => { throw new Error('location failed') },
  249. })
  250. const remote = createSessionTestRemote(ctx, {
  251. defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp',
  252. })
  253. await expect(remote.list(request({}))).resolves.toMatchObject({
  254. ok: false,
  255. error: { message: expect.stringContaining('location failed') as string },
  256. })
  257. await ctx.fiber.dispose()
  258. })
  259. it('supports an unsignalled probe whose observation has no projection registry', async () => {
  260. const ctx = new Context()
  261. await ctx.plugin(SessionStore)
  262. await ctx.plugin(AgentRegistry)
  263. installSessionReadTestServices(ctx)
  264. const root = mkdtempSync(join(tmpdir(), 'dsh-cold-unprojected-'))
  265. const path = join(root, 'small.log')
  266. writeFileSync(path, 'small')
  267. const meta = header('unprojected-small', 100)
  268. ctx.provide('sessionPersistence', {
  269. list: () => Promise.resolve([meta]),
  270. locate: () => ({ kind: 'jsonl', path }),
  271. } as never)
  272. vi.spyOn(ctx.sessionQuery, 'listSessions').mockResolvedValue([{
  273. header: meta, live: false, persisted: true,
  274. }])
  275. vi.spyOn(ctx.sessionQuery, 'observeSession').mockResolvedValue({
  276. source: 'prepared', header: meta, events: [], cursor: -1,
  277. retain: vi.fn(), [Symbol.dispose]: vi.fn(),
  278. })
  279. const list = new ApiSessionList(ctx, 1024)
  280. await expect(list.list()).resolves.toEqual([
  281. expect.objectContaining({ sessionId: meta.id, blank: false }),
  282. ])
  283. await ctx.fiber.dispose()
  284. })
  285. })
  286. describe('attached updatedAt tracks human prompts', () => {
  287. it('ignores pickup and non-prompt work after the latest human message', async () => {
  288. const ctx = new Context()
  289. await ctx.plugin(SessionStore)
  290. await ctx.plugin(AgentRegistry)
  291. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  292. await new Promise(resolve => setTimeout(resolve, 0))
  293. // Old work, resumed just now: the log tail would report the pickup.
  294. const worked = 1_000_000
  295. const resumed = ctx.sessions.create(sid('resumed-untouched'), {
  296. seed: [
  297. { type: 'turn/start', seq: 0, time: worked, data: { turn: 1 } },
  298. {
  299. type: 'user/message', seq: 1, time: worked,
  300. data: createUserMessage({ content: [{ type: 'text', text: 'worked' }], source: { kind: 'user' } }),
  301. surfaceOp: 'append',
  302. },
  303. { type: 'turn/end', seq: 2, time: worked + 1, data: { turn: 1, reason: { kind: 'completed' } } },
  304. ],
  305. meta: { cwd: '/proj', createdAt: 500 },
  306. })
  307. ctx.agents.register({ id: resumed.id, session: resumed, status: 'idle', ctx } as Agent)
  308. const boundary = resumed.events.at(-1)
  309. expect(boundary?.type).toBe('session/end-seed')
  310. expect(boundary?.time).toBeGreaterThan(worked)
  311. const listed = await remote.list(request({}))
  312. if (!listed.ok) throw new Error('list failed')
  313. const summary = listed.value.items.find(item => item.sessionId === 'resumed-untouched')
  314. expect(summary?.updatedAt).toBe(500)
  315. // A lifecycle boundary is not a human update.
  316. resumed.append('turn/start', { turn: 2 })
  317. const afterBoundary = await remote.list(request({}))
  318. if (!afterBoundary.ok) throw new Error('list failed')
  319. expect(afterBoundary.value.items.find(item => item.sessionId === 'resumed-untouched')?.updatedAt)
  320. .toBe(worked)
  321. const prompt = resumed.append('user/message', createUserMessage({
  322. content: [{ type: 'text', text: 'new prompt' }],
  323. source: { kind: 'user' },
  324. }), { surfaceOp: 'append' })
  325. const after = await remote.list(request({}))
  326. if (!after.ok) throw new Error('list failed')
  327. const moved = after.value.items.find(item => item.sessionId === 'resumed-untouched')
  328. expect(moved?.updatedAt).toBe(prompt.time)
  329. })
  330. })
  331. describe('cold history recovery view', () => {
  332. it('shows in-memory interruption repair without activating the session', async () => {
  333. const ctx = new Context()
  334. await ctx.plugin(SessionStore)
  335. const sessionId = sid('session-interrupted')
  336. const meta = header(sessionId, 1000)
  337. const stored: StoredPrefix<never> = {
  338. meta,
  339. events: [{ type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }],
  340. revision: SessionPersistenceRevision('history-recovery-test:1'),
  341. }
  342. const backend: PersistenceBackend<never> = {
  343. name: 'history-recovery-test',
  344. loadStored: id => Promise.resolve(id === sessionId ? structuredClone(stored) : undefined),
  345. readStoredRevision: id => Promise.resolve(
  346. id === sessionId ? SessionPersistenceRevision('history-recovery-test:1') : undefined,
  347. ),
  348. appendBatch: () => Promise.resolve(),
  349. commitRepair: () => Promise.resolve(),
  350. list: () => Promise.resolve([structuredClone(meta)]),
  351. }
  352. const coordinator = new PersistenceCoordinator(ctx, backend)
  353. providePersistence(ctx, {
  354. list: (signal?: AbortSignal) => backend.list(signal),
  355. inspect: (id: SessionId, signal?: AbortSignal) => coordinator.inspect(id, signal),
  356. borrowSession: (id: SessionId, signal?: AbortSignal) => coordinator.borrowSession(id, signal),
  357. locate: () => undefined,
  358. })
  359. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  360. const history = await remote.page({
  361. address: { kind: 'session', sessionId },
  362. throughSeq: 1,
  363. beforeSeq: 2,
  364. maxMessages: 10,
  365. })
  366. if (!history.ok) throw new Error('history failed')
  367. expect(history.value.events.map(entry => entry.event)).toMatchInlineSnapshot(`
  368. [
  369. {
  370. "data": {
  371. "turn": 1,
  372. },
  373. "seq": 0,
  374. "time": 1,
  375. "type": "turn/start",
  376. },
  377. {
  378. "data": {
  379. "reason": {
  380. "kind": "interrupted",
  381. },
  382. "turn": 1,
  383. },
  384. "seq": 1,
  385. "time": 1,
  386. "type": "turn/end",
  387. },
  388. ]
  389. `)
  390. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  391. await ctx.fiber.dispose()
  392. })
  393. })
  394. describe('Remote Agent and Session lookup policy', () => {
  395. it('deduplicates a cold resume across Agent and Session parameters', async () => {
  396. const ctx = new Context()
  397. await ctx.plugin(TypertRegistry)
  398. await ctx.plugin(SessionStore)
  399. await ctx.plugin(AgentRegistry)
  400. const sessionId = sid('session-remote-cold')
  401. const meta = header(sessionId, 1000)
  402. const inspect = vi.fn(() => Promise.resolve({ meta, events: [] as SessionEvent[] }))
  403. providePersistence(ctx, {
  404. list: () => Promise.resolve([meta]),
  405. inspect,
  406. locate: () => undefined,
  407. })
  408. const resumedSession = { id: sessionId, header: meta, events: [] } as unknown as import('@deepseek-ai/dsh-session').Session
  409. const resumedAgent = { id: sessionId, session: resumedSession, status: 'idle', ctx } as Agent
  410. const release = Promise.withResolvers<undefined>()
  411. const resume = vi.spyOn(ctx.agents, 'resume').mockImplementation(async () => {
  412. await release.promise
  413. return { agent: resumedAgent, dispose: () => Promise.resolve() }
  414. })
  415. const defaultAgentLookup = ctx.typert.lookups.get('agent')
  416. const defaultSessionLookup = ctx.typert.lookups.get('session')
  417. createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  418. await vi.waitFor(() => {
  419. expect(ctx.typert.lookups.get('agent')).not.toBe(defaultAgentLookup)
  420. expect(ctx.typert.lookups.get('session')).not.toBe(defaultSessionLookup)
  421. })
  422. const agentLookup = ctx.typert.lookups.get('agent')
  423. const sessionLookup = ctx.typert.lookups.get('session')
  424. if (agentLookup === undefined || sessionLookup === undefined) throw new Error('core lookup providers were not mounted')
  425. const resolvedAgent = Promise.resolve(agentLookup.resolve(sessionId))
  426. const resolvedSession = Promise.resolve(sessionLookup.resolve(sessionId))
  427. await vi.waitFor(() => { expect(resume).toHaveBeenCalledOnce() })
  428. release.resolve(undefined)
  429. await expect(resolvedAgent).resolves.toBe(resumedAgent)
  430. await expect(resolvedSession).resolves.toBe(resumedSession)
  431. expect(inspect).toHaveBeenCalledOnce()
  432. })
  433. it('preserves the subagent ownership fence for cold and live Remote lookups', async () => {
  434. const ctx = new Context()
  435. await ctx.plugin(TypertRegistry)
  436. await ctx.plugin(SessionStore)
  437. await ctx.plugin(AgentRegistry)
  438. const coldId = sid('session-remote-cold-child')
  439. const coldMeta = header(coldId, 1000, {
  440. parentSession: sid('session-parent'),
  441. origin: 'subagent',
  442. })
  443. const inspect = vi.fn(() => Promise.resolve({ meta: coldMeta, events: [] as SessionEvent[] }))
  444. providePersistence(ctx, {
  445. list: () => Promise.resolve([coldMeta]),
  446. inspect,
  447. locate: () => undefined,
  448. })
  449. const liveSession = ctx.sessions.create(sid('session-remote-live-child'), {
  450. meta: { cwd: '/proj', parentSession: sid('session-parent'), origin: 'subagent' },
  451. })
  452. const liveAgent = { id: liveSession.id, session: liveSession, status: 'idle', ctx } as Agent
  453. ctx.agents.register(liveAgent)
  454. const resume = vi.spyOn(ctx.agents, 'resume')
  455. const defaultAgentLookup = ctx.typert.lookups.get('agent')
  456. const defaultSessionLookup = ctx.typert.lookups.get('session')
  457. createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  458. await vi.waitFor(() => {
  459. expect(ctx.typert.lookups.get('agent')).not.toBe(defaultAgentLookup)
  460. expect(ctx.typert.lookups.get('session')).not.toBe(defaultSessionLookup)
  461. })
  462. const agentLookup = ctx.typert.lookups.get('agent')
  463. const sessionLookup = ctx.typert.lookups.get('session')
  464. if (agentLookup === undefined || sessionLookup === undefined) throw new Error('core lookup providers were not mounted')
  465. const ownershipFailure = {
  466. failure: {
  467. code: 'agent-busy',
  468. details: { reason: 'use subagent delivery for this child session' },
  469. },
  470. }
  471. const coldFailure = Promise.resolve(agentLookup.resolve(coldId))
  472. const liveFailure = Promise.resolve(sessionLookup.resolve(liveSession.id))
  473. await expect(coldFailure).rejects.toBeInstanceOf(TypertLookupFailure)
  474. await expect(coldFailure).rejects.toMatchObject(ownershipFailure)
  475. await expect(liveFailure).rejects.toBeInstanceOf(TypertLookupFailure)
  476. await expect(liveFailure).rejects.toMatchObject(ownershipFailure)
  477. expect(resume).not.toHaveBeenCalled()
  478. expect(inspect).toHaveBeenCalledOnce()
  479. })
  480. })
  481. describe('subagent ownership fence', () => {
  482. it('reads a cold child without an Agent and rejects generic resume or adoption', async () => {
  483. const ctx = new Context()
  484. await ctx.plugin(SessionStore)
  485. await ctx.plugin(AgentRegistry)
  486. const sessionId = sid('session-child')
  487. const meta = header('session-child', 1000, {
  488. parentSession: sid('session-parent'),
  489. seedLength: 0,
  490. origin: 'subagent',
  491. })
  492. const events = [
  493. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  494. {
  495. type: 'user/message',
  496. seq: 1,
  497. time: 2,
  498. data: createUserMessage({ content: [{ type: 'text', text: 'work' }], source: { kind: 'user' } }),
  499. surfaceOp: 'append',
  500. },
  501. {
  502. type: 'subagent/descriptor',
  503. seq: 2,
  504. time: 3,
  505. data: snapshotSubagentDescriptor({
  506. mode: 'continuable',
  507. provider: 'spawn',
  508. label: 'child',
  509. }),
  510. },
  511. { type: 'turn/end', seq: 3, time: 4, data: { turn: 1, reason: { kind: 'completed' } } },
  512. ] as SessionEvent[]
  513. const inspect = vi.fn(() => Promise.resolve({ meta, events }))
  514. providePersistence(ctx, {
  515. list: () => Promise.resolve([meta]),
  516. inspect,
  517. locate: () => undefined,
  518. })
  519. const resume = vi.spyOn(ctx.agents, 'resume')
  520. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  521. ctx.sessionProjections.register(subagentIdentityProjectionDefinition)
  522. const history = await new SessionHistoryController(
  523. ctx,
  524. (observation) => { observation[Symbol.dispose]() },
  525. ).page({
  526. address: {
  527. kind: 'subagent',
  528. parentSessionId: meta.parentSession as SessionId,
  529. childSessionId: sessionId,
  530. mode: 'continuable',
  531. },
  532. throughSeq: 3,
  533. }, new AbortController().signal)
  534. expect(history.events.map(entry => entry.event.type)).toEqual(events.map(event => event.type))
  535. expect(ctx.agents.get(sessionId)).toBeUndefined()
  536. const prompt = await remote.prompt(promptRequest({
  537. sessionId,
  538. mode: 'queue',
  539. content: [{ type: 'text', text: 'follow up' }],
  540. }))
  541. expect(prompt.ok).toBe(false)
  542. if (!prompt.ok) {
  543. expect(prompt.error).toMatchObject({
  544. code: 'agent-busy',
  545. details: { reason: 'use subagent delivery for this child session' },
  546. })
  547. }
  548. const create = await remote.create(request({ sessionId, cwd: '/proj' }))
  549. expect(create.ok).toBe(false)
  550. if (!create.ok) expect(create.error.code).toBe('agent-busy')
  551. expect(resume).not.toHaveBeenCalled()
  552. expect(ctx.agents.get(sessionId)).toBeUndefined()
  553. expect(inspect).toHaveBeenCalledTimes(3)
  554. })
  555. it('no longer treats a descriptor-only cold child without origin as subagent-owned', async () => {
  556. const ctx = new Context()
  557. await ctx.plugin(SessionStore)
  558. await ctx.plugin(AgentRegistry)
  559. const sessionId = sid('session-legacy-child')
  560. const meta = header('session-legacy-child', 1000, {
  561. parentSession: sid('session-parent'),
  562. seedLength: 0,
  563. })
  564. const events = [
  565. {
  566. type: 'subagent/descriptor',
  567. seq: 0,
  568. time: 1,
  569. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'child' },
  570. },
  571. ] as SessionEvent[]
  572. providePersistence(ctx, {
  573. list: () => Promise.resolve([meta]),
  574. inspect: () => Promise.resolve({ meta, events }),
  575. locate: () => undefined,
  576. })
  577. // Stores whose headers predate `origin` classify a child only through the
  578. // descriptor event; the pre-release decision stops recognizing them, so
  579. // the ownership fence lets generic resume reach the registry instead of
  580. // answering `agent-busy`.
  581. const resume = vi.spyOn(ctx.agents, 'resume')
  582. .mockRejectedValue(new Error('registry unavailable in this bench'))
  583. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  584. const prompt = await remote.prompt(promptRequest({
  585. sessionId,
  586. mode: 'queue',
  587. content: [{ type: 'text', text: 'follow up' }],
  588. }))
  589. expect(resume).toHaveBeenCalledTimes(1)
  590. expect(prompt.ok).toBe(false)
  591. if (!prompt.ok) expect(prompt.error.code).toBe('internal')
  592. })
  593. it('rejects origin-marked and runtime-owned live children from generic controls', async () => {
  594. const ctx = new Context()
  595. await ctx.plugin(SessionStore)
  596. await ctx.plugin(AgentRegistry)
  597. const parentSession = ctx.sessions.create(sid('session-parent'), { meta: { cwd: '/proj' } })
  598. const parent = { id: parentSession.id, session: parentSession, status: 'idle', ctx } as Agent
  599. ctx.agents.register(parent)
  600. const originSession = ctx.sessions.create(sid('session-origin-child'), {
  601. meta: { cwd: '/proj', parentSession: parent.id, origin: 'subagent' },
  602. })
  603. const cancel = vi.fn()
  604. const updateInbox = vi.fn(() => 'applied' as const)
  605. const originChild = {
  606. id: originSession.id,
  607. session: originSession,
  608. status: 'idle',
  609. ctx,
  610. cancel,
  611. updateInbox,
  612. } as unknown as Agent
  613. ctx.agents.register(originChild)
  614. const startingSession = ctx.sessions.create(sid('session-starting-child'), {
  615. meta: { cwd: '/proj', parentSession: parent.id },
  616. })
  617. const startingChild = { id: startingSession.id, session: startingSession, status: 'idle', ctx } as Agent
  618. ctx.agents.enter(startingChild, parent)
  619. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  620. const stopped = await remote.cancel(request({ sessionId: originChild.id }))
  621. expect(stopped.ok).toBe(false)
  622. if (!stopped.ok) expect(stopped.error.code).toBe('agent-busy')
  623. expect(cancel).not.toHaveBeenCalled()
  624. const queued = await remote.updateQueue(request({
  625. sessionId: originChild.id,
  626. itemId: MessageId('queued-item'),
  627. action: { kind: 'remove' },
  628. }))
  629. expect(queued.ok).toBe(false)
  630. if (!queued.ok) expect(queued.error.code).toBe('agent-busy')
  631. expect(updateInbox).not.toHaveBeenCalled()
  632. const selection = await remote.selectModel(request({
  633. sessionId: startingChild.id,
  634. provider: 'p',
  635. model: 'm',
  636. }))
  637. expect(selection.ok).toBe(false)
  638. if (!selection.ok) expect(selection.error.code).toBe('agent-busy')
  639. const create = await remote.create(request({ sessionId: originChild.id, cwd: '/proj' }))
  640. expect(create.ok).toBe(false)
  641. if (!create.ok) expect(create.error.code).toBe('agent-busy')
  642. expect(ctx.agents.get(originChild.id)).toBe(originChild)
  643. })
  644. it('does not classify an ordinary fork from an inherited ancestor descriptor', async () => {
  645. const ctx = new Context()
  646. await ctx.plugin(SessionStore)
  647. await ctx.plugin(AgentRegistry)
  648. const session = ctx.sessions.create(sid('session-ordinary-fork'), {
  649. seed: [{
  650. type: 'subagent/descriptor',
  651. seq: 0,
  652. time: 1,
  653. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'ancestor' },
  654. }],
  655. meta: { cwd: '/proj', parentSession: sid('session-source'), seedLength: 1 },
  656. })
  657. const followup = vi.fn()
  658. const agent = { id: session.id, session, status: 'idle', ctx, followup } as unknown as Agent
  659. ctx.agents.register(agent)
  660. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  661. const response = await remote.prompt(promptRequest({
  662. sessionId: agent.id,
  663. mode: 'queue',
  664. content: [{ type: 'text', text: 'ordinary work' }],
  665. }))
  666. expect(response.ok).toBe(true)
  667. expect(followup).toHaveBeenCalledOnce()
  668. })
  669. it('canonicalizes a supplied browser zone on the exact prompt and rejects invalid names', async () => {
  670. const ctx = new Context()
  671. await ctx.plugin(SessionStore)
  672. await ctx.plugin(AgentRegistry)
  673. const session = ctx.sessions.create(sid('session-browser-zone'), { meta: { cwd: '/proj' } })
  674. const followup = vi.fn()
  675. const agent = { id: session.id, session, status: 'idle', ctx, followup } as unknown as Agent
  676. ctx.agents.register(agent)
  677. const remote = createSessionTestRemote(ctx, {
  678. defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
  679. cwd: '/tmp',
  680. })
  681. const alias = 'US/Pacific'
  682. const canonical = new Intl.DateTimeFormat('en-US', { timeZone: alias })
  683. .resolvedOptions().timeZone
  684. const zonedRequest = promptRequest({
  685. sessionId: agent.id,
  686. mode: 'queue' as const,
  687. content: [{ type: 'text' as const, text: 'zoned work' }],
  688. clientTimeZone: alias,
  689. })
  690. await expect(remote.prompt(zonedRequest)).resolves.toMatchObject({ ok: true })
  691. expect(followup).toHaveBeenNthCalledWith(1, expect.objectContaining({
  692. source: { kind: 'user', rpcId: zonedRequest.requestId, clientTimeZone: canonical },
  693. }))
  694. const utcRequest = promptRequest({
  695. sessionId: agent.id,
  696. mode: 'queue' as const,
  697. content: [{ type: 'text' as const, text: 'UTC work' }],
  698. clientTimeZone: 'UTC',
  699. })
  700. await expect(remote.prompt(utcRequest)).resolves.toMatchObject({ ok: true })
  701. expect(followup).toHaveBeenNthCalledWith(2, expect.objectContaining({
  702. source: { kind: 'user', rpcId: utcRequest.requestId, clientTimeZone: 'UTC' },
  703. }))
  704. const unzonedRequest = promptRequest({
  705. sessionId: agent.id,
  706. mode: 'queue' as const,
  707. content: [{ type: 'text' as const, text: 'headless work' }],
  708. })
  709. await expect(remote.prompt(unzonedRequest)).resolves.toMatchObject({ ok: true })
  710. expect(followup).toHaveBeenNthCalledWith(3, expect.objectContaining({
  711. source: { kind: 'user', rpcId: unzonedRequest.requestId },
  712. }))
  713. for (const clientTimeZone of ['', ' UTC', 'CST', 'Not/A_Real_Zone']) {
  714. const invalid = await remote.prompt(promptRequest({
  715. sessionId: agent.id,
  716. mode: 'queue' as const,
  717. content: [{ type: 'text' as const, text: 'invalid zone' }],
  718. clientTimeZone,
  719. }))
  720. expect(invalid).toEqual({
  721. ok: false,
  722. error: {
  723. code: 'invalid-time-zone',
  724. message: 'clientTimeZone must be UTC or a valid IANA Area/Location name',
  725. details: { value: clientTimeZone },
  726. },
  727. })
  728. }
  729. expect(followup).toHaveBeenCalledTimes(3)
  730. })
  731. })
  732. describe('degenerate composition (no persistence, no factory)', () => {
  733. it('lists no cold rows and reports an absent point source as not found', async () => {
  734. const ctx = new Context()
  735. await ctx.plugin(SessionStore)
  736. await ctx.plugin(AgentRegistry)
  737. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  738. const listed = await remote.list(request({}))
  739. expect(listed.ok).toBe(true)
  740. if (listed.ok) expect(listed.value.items).toEqual([])
  741. // No persistence means cold history cannot inspect a transcript.
  742. const response = await remote.page({
  743. address: { kind: 'session', sessionId: sid('session-ghost') },
  744. throughSeq: -1,
  745. })
  746. expect(response.ok).toBe(false)
  747. if (!response.ok) {
  748. expect(response.error.code).toBe('session-not-found')
  749. }
  750. })
  751. it('maps a missing direct persistence read to session-not-found', async () => {
  752. const ctx = new Context()
  753. await ctx.plugin(SessionStore)
  754. await ctx.plugin(AgentRegistry)
  755. const inspect = vi.fn()
  756. providePersistence(ctx, {
  757. list: () => Promise.resolve([]),
  758. inspect,
  759. })
  760. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  761. const response = await remote.page({
  762. address: { kind: 'session', sessionId: sid('session-missing') },
  763. throughSeq: -1,
  764. })
  765. expect(response.ok).toBe(false)
  766. if (!response.ok) expect(response.error.code).toBe('session-not-found')
  767. expect(inspect).toHaveBeenCalledOnce()
  768. })
  769. })
  770. describe('sessions.prompt synchronous rejection', () => {
  771. it('maps a synchronous send throw (disposed/invalid input) to agent-busy with the reason attached', async () => {
  772. const ctx = new Context()
  773. await ctx.plugin(SessionStore)
  774. await ctx.plugin(AgentRegistry)
  775. const session = ctx.sessions.create(sid('session-throwing'))
  776. // A live structural stub whose delivery verbs throw synchronously, the
  777. // shape a disposed loop presents at this gateway boundary.
  778. ctx.agents.register({
  779. id: session.id,
  780. session,
  781. status: 'idle',
  782. ctx,
  783. followup: () => { throw new Error('agent "session-throwing" lifecycle disposed') },
  784. steer: () => { throw new Error('agent "session-throwing" lifecycle disposed') },
  785. } as unknown as Agent)
  786. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  787. for (const mode of ['queue', 'steer'] as const) {
  788. const response = await remote.prompt(promptRequest({
  789. sessionId: session.id, mode, content: [{ type: 'text' as const, text: 'x' }],
  790. }))
  791. expect(response.ok).toBe(false)
  792. if (!response.ok) {
  793. expect(response.error.code).toBe('agent-busy')
  794. expect(response.error.message).toBe('prompt rejected')
  795. expect(response.error.details).toEqual({
  796. reason: 'Error: agent "session-throwing" lifecycle disposed',
  797. })
  798. }
  799. }
  800. })
  801. it('classifies a raced cold-resume ID collision as agent-busy', async () => {
  802. const ctx = new Context()
  803. await ctx.plugin(SessionStore)
  804. await ctx.plugin(AgentRegistry)
  805. const sessionId = sid('race-resume')
  806. const meta: SessionHeader = header('race-resume', 1000)
  807. providePersistence(ctx, {
  808. list: () => Promise.resolve([meta]),
  809. inspect: () => Promise.resolve({ meta, events: [] as SessionEvent[] }),
  810. locate: () => undefined,
  811. })
  812. // The raced winner: a live parent-owned subagent publishes the identity
  813. // while the generic cold resume is in flight, so the resume collides.
  814. const parentSession = ctx.sessions.create(sid('race-parent'), { meta: { cwd: '/proj' } })
  815. const parent = { id: parentSession.id, session: parentSession, status: 'idle', ctx } as Agent
  816. ctx.agents.register(parent)
  817. const childSession = ctx.sessions.create(sessionId, {
  818. meta: { cwd: '/proj', parentSession: parent.id, origin: 'subagent' },
  819. })
  820. const child = { id: sessionId, session: childSession, status: 'idle', ctx } as unknown as Agent
  821. vi.spyOn(ctx.agents, 'resume').mockImplementationOnce(async () => {
  822. // The parent's `enter()` wins the identity between the pre-resume
  823. // re-check and publication; the generic resume then collides.
  824. ctx.agents.register(child)
  825. throw new Error('session id already published')
  826. })
  827. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  828. const selection = await remote.selectModel(request({ sessionId, provider: 'p', model: 'm' }))
  829. expect(selection.ok).toBe(false)
  830. if (!selection.ok) {
  831. expect(selection.error).toMatchObject({
  832. code: 'agent-busy',
  833. details: { reason: 'use subagent delivery for this child session' },
  834. })
  835. }
  836. })
  837. })