agent.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. /**
  2. * The concrete Agent implementation: ReactLoopAgent plus its inbox. Everything
  3. * observable happens through session events and the agent/* event taxonomy —
  4. * plugins never need this class.
  5. *
  6. * @module dsh-agent-loop/agent
  7. */
  8. import { randomUUID } from 'node:crypto'
  9. import type { Context } from 'cordis'
  10. import { agentEvents, AgentMessageId } from '@deepseek-ai/dsh-agent'
  11. import { Agent } from '@deepseek-ai/dsh-agent'
  12. import type { AgentCancelCause, AgentOptions, AgentStatus, CancelOptions, HookContext, SendOptions } from '@deepseek-ai/dsh-agent'
  13. import { deepFreeze, errorChain } from '@deepseek-ai/dsh-llm'
  14. import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm'
  15. import { snapshotJsonValue, type Session, type SessionId } from '@deepseek-ai/dsh-session'
  16. import { DISPOSED_INTERRUPT_REASON, TurnCancellation } from './cancellation.ts'
  17. import { Inbox, agentMessage, type InboxMessage } from './inbox.ts'
  18. import { isTurnOpen, lastTurnNumber, runLoop } from './loop.ts'
  19. /** Sessions already claimed by a concrete driver construction. */
  20. const claimedDriverSessions = new WeakSet<Session>()
  21. /** Module-private driver entry: its symbol is absent from the package surface. */
  22. const startDriver = Symbol('dsh.agent-loop.start-driver')
  23. /** Module-private quiescent stop, valid both before and after driver start. */
  24. const stopDriver = Symbol('dsh.agent-loop.stop-driver')
  25. /** Module-private context binding for the mutually referential agent scope. */
  26. const bindContext = Symbol('dsh.agent-loop.bind-context')
  27. /** Module-private publication marker. */
  28. const publishAgent = Symbol('dsh.agent-loop.publish-agent')
  29. /** Factory-owned controls that can operate only on the agent created with them. */
  30. export interface PreparedReactLoopAgent {
  31. /** The unpublished concrete agent. */
  32. agent: ReactLoopAgent
  33. /** Mark the agent public so teardown emits its status lifecycle. */
  34. markPublished(): void
  35. /** Stop the prepared instance even when publication has not started its loop. */
  36. dispose(): Promise<void> | void
  37. /**
  38. * Start its driver after publication and session-start notification.
  39. * The returned disposer reaches quiescence for both the loop and every
  40. * fire-and-forget idle-injection flush the agent started.
  41. */
  42. startDriver(): () => Promise<void> | void
  43. }
  44. /**
  45. * Construct an unpublished concrete agent with instance-bound lifecycle
  46. * controls. Only those paired controls can publish or start this instance.
  47. * @param ctx - the agent-loop service context used for driving and events.
  48. * @param id - the concrete agent identity.
  49. * @param options - loop options for the agent.
  50. * @param session - the prepared session the agent will own.
  51. * @param maxParallelToolCalls - resolved in-flight cap for this agent.
  52. * @returns the agent and closures bound only to that exact instance.
  53. */
  54. export function prepareReactLoopAgent(
  55. ctx: Context,
  56. id: SessionId,
  57. options: AgentOptions,
  58. session: Session,
  59. maxParallelToolCalls: number,
  60. ): PreparedReactLoopAgent {
  61. if (claimedDriverSessions.has(session)) {
  62. throw new Error(`session "${session.id}" already has a concrete agent driver`)
  63. }
  64. const agent = new ReactLoopAgent(ctx, id, options, session, maxParallelToolCalls)
  65. claimedDriverSessions.add(session)
  66. const dispose = () => agent[stopDriver]()
  67. return {
  68. agent,
  69. markPublished: () => { agent[publishAgent]() },
  70. dispose,
  71. startDriver: () => {
  72. agent[startDriver]()
  73. return dispose
  74. },
  75. }
  76. }
  77. /**
  78. * Install the concrete agent's scope context exactly once. Construction and
  79. * scope minting are mutually referential (the scope key is the agent), so the
  80. * factory performs this one post-construction binding before setup receives
  81. * the unpublished agent. The module-private binding rejects a second bind.
  82. * @param agent - the unpublished concrete agent to bind.
  83. * @param ctx - its fully extended agent scope context.
  84. */
  85. export function bindReactLoopAgentContext(agent: ReactLoopAgent, ctx: Context): void {
  86. agent[bindContext](ctx)
  87. }
  88. /**
  89. * The concrete {@link Agent} implementation owned by the agent-loop plugin.
  90. *
  91. * Owns the inbox (queued + steering FIFOs), turn cancellation, and
  92. * the loop driver. Everything observable happens through session events and
  93. * the agent/* event taxonomy — plugins never need this class.
  94. */
  95. export class ReactLoopAgent extends Agent {
  96. /** Queued + steering FIFOs; native-private so callers cannot bypass the public driving verbs. */
  97. readonly #inbox = new Inbox()
  98. /**
  99. * The agent's scope context ({@link Agent.ctx}), wired by the factory right
  100. * after the scope is minted — before the agent is registered, announced, or
  101. * driven, so no consumer can observe it unset. Definite-assignment (`!`)
  102. * expresses that two-phase construction: the agent object and its scope
  103. * context are mutually referential (the scope is keyed BY this agent), so
  104. * neither can exist strictly before the other.
  105. */
  106. private boundContext: Context | undefined
  107. /** The agent's scoped composition context, bound once by its factory. */
  108. get ctx(): Context {
  109. if (this.boundContext === undefined) throw new Error(`agent "${this.id}" context is not bound`)
  110. return this.boundContext
  111. }
  112. private _status: AgentStatus = 'idle'
  113. /** Active turn owner from pre-running publication through durability settlement. */
  114. private turnCancellation: TurnCancellation | undefined
  115. /** Whether runLoop has been installed into {@link done}. */
  116. private driverStarted = false
  117. /** Whether registry publication began and status disposal is externally visible. */
  118. private published = false
  119. /** Cause-less marker for queued work cancelled before the driver installs a turn owner. */
  120. private preRunCancelled = false
  121. private disposed: Promise<void>
  122. private resolveDisposed!: () => void
  123. /** Resolves when the driver loop has fully exited (tests/disposal). */
  124. done: Promise<void> = Promise.resolve()
  125. /**
  126. * Pending {@link whenIdle} waiters, resolved by {@link settleIdleWaiters} when
  127. * the agent next settles out of `running`. Kept as internal agent state (NOT
  128. * an effect-scoped `ctx.on` listener) so a concurrent fiber disposal — which
  129. * runs the agent's own listeners' disposers — cannot drop the waiter before
  130. * the `disposed` transition fires and leave the promise hanging.
  131. */
  132. private idleWaiters: (() => void)[] = []
  133. /** Maximum parallel-safe calls allowed in one step. */
  134. private readonly maxParallelToolCalls: number
  135. /**
  136. * Durability checkpoints started by idle {@link inject} calls. `inject()` is
  137. * synchronous, so it cannot await them itself; the driver disposer drains
  138. * this set before the lifecycle unregisters the agent or detaches its session.
  139. */
  140. private pendingIdleFlushes = new Set<Promise<void>>()
  141. /** Whether the current step is executing an assistant tool-call batch. */
  142. private toolBatchActive = false
  143. /** Open-turn injections waiting for the active assistant tool-call batch to close. */
  144. private deferredInjections: HookContext[] = []
  145. constructor(
  146. private loopCtx: Context,
  147. public readonly id: SessionId,
  148. public readonly options: AgentOptions,
  149. public readonly session: Session,
  150. maxParallelToolCalls: number,
  151. ) {
  152. super()
  153. this.maxParallelToolCalls = maxParallelToolCalls
  154. const { promise, resolve } = Promise.withResolvers<void>()
  155. this.disposed = promise
  156. this.resolveDisposed = resolve
  157. }
  158. get status(): AgentStatus {
  159. return this._status
  160. }
  161. private setStatus(status: AgentStatus): void {
  162. if (this._status === status || this._status === 'disposed') return
  163. this._status = status
  164. // Settle first so a throwing status listener cannot starve quiescence waiters.
  165. if (status !== 'running') this.settleIdleWaiters()
  166. agentEvents(this.loopCtx, this).emit('agent/status', status)
  167. }
  168. /**
  169. * Resolve and clear all pending {@link whenIdle} waiters. Called on a
  170. * running→idle transition (from {@link setStatus}) and on disposal (from the
  171. * internal driver disposer, which chains `done` for true loop-exit quiescence).
  172. */
  173. private settleIdleWaiters(): void {
  174. const waiters = this.idleWaiters
  175. this.idleWaiters = []
  176. for (const resolve of waiters) resolve()
  177. }
  178. /**
  179. * Accept one public message payload as a detached record. Lossless-JSON
  180. * materialization reads every nested field once; deep freeze prevents later
  181. * caller mutation before an inbox or deferred-injection queue drains it.
  182. */
  183. private acceptMessage(
  184. id: AgentMessageId, content: ContentBlock[], source: MessageSource, wakeup: boolean, options?: SendOptions,
  185. ): InboxMessage {
  186. const contexts = options?.contexts ?? []
  187. const accepted = snapshotJsonValue({
  188. id, content, source, contexts, wakeup,
  189. ...options?.meta !== undefined ? { meta: options.meta } : {},
  190. })
  191. if (accepted === undefined) {
  192. throw new TypeError('agent message content, source, and contexts must be losslessly JSON-serializable')
  193. }
  194. return deepFreeze(accepted)
  195. }
  196. /** Detach one context before it can outlive its caller in the active-batch FIFO. */
  197. private acceptContext(context: HookContext): HookContext {
  198. const accepted = snapshotJsonValue(context)
  199. if (accepted === undefined) {
  200. throw new TypeError('agent context must be losslessly JSON-serializable')
  201. }
  202. return deepFreeze(accepted)
  203. }
  204. /** Reject a driving operation once teardown has synchronously closed the agent. */
  205. private assertNotDisposed(): void {
  206. if (this._status === 'disposed') throw new Error(`agent "${this.id}" is disposed`)
  207. }
  208. send(content: ContentBlock[], options?: SendOptions): AgentMessageId {
  209. this.assertNotDisposed()
  210. const id = AgentMessageId(randomUUID())
  211. const target = options?.target ?? 'next-turn'
  212. const wakeup = options?.wakeup ?? true
  213. // next-step/no-wakeup is injection: durable context without running the model.
  214. if (target === 'next-step' && !wakeup) { this.injectContext(content, options); return id }
  215. // next-step/wakeup is steering into the running turn; idle falls back to a
  216. // woken follow-up turn (there is no active turn to attach to).
  217. const steering = target === 'next-step' && this._status === 'running'
  218. const source = options?.source ?? { kind: 'user' }
  219. const accepted = this.acceptMessage(id, content, source, wakeup, options)
  220. if (steering) {
  221. this.#inbox.steer(accepted)
  222. } else {
  223. this.#inbox.enqueue(accepted, wakeup)
  224. }
  225. agentEvents(this.loopCtx, this).emit('agent/inbox/enqueue', agentMessage(accepted, steering))
  226. return id
  227. }
  228. /** The `next-step`/no-wakeup injection path: durable context, no FIFO, no run. */
  229. private injectContext(content: ContentBlock[], options?: SendOptions): void {
  230. // Injection is synthetic durable context, not an inbox message: attached
  231. // contexts belong only to queued/steering sends, so reject them rather than
  232. // silently dropping a value the option type structurally permits.
  233. if (options?.contexts !== undefined && options.contexts.length > 0) {
  234. throw new TypeError('agent inject (next-step/no-wakeup) does not accept attached contexts')
  235. }
  236. const source = options?.source ?? { kind: 'plugin', plugin: '' }
  237. // Detach and validate the payload BEFORE any append, so malformed input
  238. // throws without opening a one-shot turn or mutating the session (the
  239. // unified send contract: invalid input throws before any append).
  240. const accepted = this.acceptContext({
  241. content,
  242. source,
  243. ...options?.meta !== undefined ? { meta: options.meta } : {},
  244. })
  245. if (isTurnOpen(this.session)) {
  246. // Provider protocols require every assistant tool-call batch to be
  247. // followed only by its tool results. Historical interrupted batches do
  248. // not own new context; only the currently executing batch may defer it.
  249. if (this.toolBatchActive) {
  250. this.deferredInjections.push(accepted)
  251. return
  252. }
  253. this.session.append('user/message', accepted, { surfaceOp: 'append' })
  254. return
  255. }
  256. // No turn open: wrap the injection in a one-shot turn so every event stays
  257. // turn-enclosed (the durability/replay boundary is the turn). The payload is
  258. // validated above, but `Session.append` can still reject a turn/start
  259. // pre-commit (append re-entrancy from a session/event listener, or an
  260. // internal-dispatch veto), so the finally owes a turn/end only when
  261. // turn/start actually committed.
  262. const turn = lastTurnNumber(this.session) + 1
  263. try {
  264. this.session.append('turn/start', { turn, trigger: { kind: 'injection', source } })
  265. this.session.append('user/message', accepted, { surfaceOp: 'append' })
  266. } finally {
  267. // Close the turn if turn/start made it into the log. A pre-commit veto
  268. // must escape rather than being mistaken for a committed turn/end.
  269. if (isTurnOpen(this.session)) {
  270. this.session.append('turn/end', { turn, reason: { kind: 'completed' } })
  271. }
  272. // Checkpoint only an accepted one-shot turn: a turn/start rejected
  273. // pre-commit recorded nothing, so it owes no flush (and a spurious flush
  274. // would emit a phantom-turn agent/error). The payload is validated up
  275. // front, so a committed turn/start is always followed by its user/message.
  276. const turnRecorded = this.session.events.some(e => e.type === 'turn/start' && e.data.turn === turn)
  277. // Keep inject() synchronous: report checkpoint failures live instead of
  278. // rejecting the caller, and track the task so disposal still drains it.
  279. if (turnRecorded) {
  280. // Through the store's flush (the carrier owner), never a raw parallel.
  281. const flush = this.loopCtx.sessions.flush(this.session).catch((error: unknown) => {
  282. const rendered = errorChain(error)
  283. const err = error instanceof Error ? error : new Error(rendered)
  284. this.loopCtx.logger.warn(`agent "${this.id}": flush after idle injection failed: ${rendered}`)
  285. agentEvents(this.loopCtx, this).emit('agent/error', turn, 0, err)
  286. })
  287. this.pendingIdleFlushes.add(flush)
  288. // Retire on either settlement path.
  289. const retire = (): void => { this.pendingIdleFlushes.delete(flush) }
  290. void flush.then(retire, retire)
  291. }
  292. }
  293. }
  294. /** Append deferred open-turn injections after the loop closes a tool-result batch. */
  295. private drainDeferredInjections(): void {
  296. const pending = this.deferredInjections.splice(0)
  297. for (const accepted of pending) {
  298. this.session.append('user/message', accepted, { surfaceOp: 'append' })
  299. }
  300. }
  301. /**
  302. * Run one tool-call batch and drain its deferred context before settlement.
  303. * The loop-owned acceptor remains valid after public disposal begins because
  304. * the interrupted turn stays open until this batch settles.
  305. */
  306. private async withToolBatch<T>(
  307. run: (acceptContext: (context: HookContext) => void) => Promise<T>,
  308. ): Promise<T> {
  309. this.toolBatchActive = true
  310. const acceptContext = (context: HookContext): void => {
  311. this.deferredInjections.push(this.acceptContext(context))
  312. }
  313. try {
  314. return await run(acceptContext)
  315. } finally {
  316. this.toolBatchActive = false
  317. this.drainDeferredInjections()
  318. }
  319. }
  320. cancel(cause?: AgentCancelCause, options?: CancelOptions): void {
  321. const resolvedCause = cause ?? { kind: 'user' }
  322. const keepInbox = options?.keepInbox ?? false
  323. const cancellation = this.turnCancellation
  324. // keepInbox preserves pending work, so un-started items must not arm the
  325. // pre-run cancel path that would otherwise drop the next queued turn.
  326. const preRun = !keepInbox && cancellation === undefined
  327. && (this.#inbox.hasQueued || this.#inbox.hasSteering)
  328. if (cancellation !== undefined || preRun) {
  329. if (preRun) this.preRunCancelled = true
  330. // Coordination consumers must update their own state before this call
  331. // clears the inbox or aborts the turn. Notification failures are
  332. // contained by the fused dispatcher and cannot veto cancellation.
  333. agentEvents(this.loopCtx, this).emit('agent/cancel-requested', resolvedCause)
  334. }
  335. if (!keepInbox) {
  336. // Snapshot before clearing so the discard notification carries the exact
  337. // dropped items; a replacement synchronously enqueued by an
  338. // `agent/cancel-requested` observer belongs to the next turn, not here.
  339. const discarded = this.#inbox.pending()
  340. // Clear work already present before abort observers run.
  341. this.#inbox.clear()
  342. if (discarded.length > 0) {
  343. const items = discarded.map(({ message, steering }) => agentMessage(message, steering))
  344. agentEvents(this.loopCtx, this).emit('agent/inbox/discard', items)
  345. }
  346. // No idle-waiter settle here: a `whenIdle` waiter exists only while the
  347. // agent is `running` or a waking item is queued, and neither is left
  348. // quiescent by clearing the inbox — a lone quiet item takes `whenIdle`'s
  349. // fast path (no waiter), a waking item keeps the woken driver running,
  350. // and a running agent owns its own idle transition (including the
  351. // post-turn flush window).
  352. }
  353. cancellation?.request(resolvedCause)
  354. }
  355. /**
  356. * Resolve immediately when idle with no queued work, on the next quiescent
  357. * idle transition otherwise, or after driver exit when already disposed.
  358. * This observes quiescence; it does not own teardown.
  359. */
  360. whenIdle(): Promise<void> {
  361. if (this._status === 'disposed') return this.done
  362. // A lone quiet (`wakeup:false`) queued item leaves the agent quiescent — the
  363. // driver stays parked — so gate on hasWakingQueued, not hasQueued.
  364. if (this._status !== 'running' && !this.#inbox.hasWakingQueued) return Promise.resolve()
  365. // Agent-owned waiters survive concurrent fiber disposal.
  366. return new Promise<void>((resolve) => {
  367. this.idleWaiters.push(() => {
  368. resolve(this._status === 'disposed' ? this.done : undefined)
  369. })
  370. })
  371. }
  372. /** Bind the mutually referential scope context once. */
  373. private [bindContext](ctx: Context): void {
  374. if (this.boundContext !== undefined) throw new Error(`agent "${this.id}" context is already bound`)
  375. this.boundContext = ctx
  376. }
  377. /** Mark that public lifecycle publication began. */
  378. private [publishAgent](): void {
  379. this.published = true
  380. }
  381. /**
  382. * Start the driver loop. The prepared controller already owns its stable
  383. * disposer, so teardown can mark the agent disposed even in the narrow
  384. * publication window before this method runs.
  385. */
  386. [startDriver](): void {
  387. if (this._status === 'disposed') return
  388. this.driverStarted = true
  389. this.done = this.loopCtx.agents.withInitiator(this, () => runLoop(this.loopCtx, {
  390. inbox: this.#inbox,
  391. maxParallelToolCalls: this.maxParallelToolCalls,
  392. setStatus: (status) => { this.setStatus(status) },
  393. installTurnCancellation: () => {
  394. const cancellation = new TurnCancellation()
  395. this.turnCancellation = cancellation
  396. return cancellation
  397. },
  398. clearTurnCancellation: (cancellation) => {
  399. /* v8 ignore else -- the driver clears only the exact owner returned by its latest install. */
  400. if (this.turnCancellation === cancellation) this.turnCancellation = undefined
  401. },
  402. disposed: this.disposed,
  403. isDisposed: () => this._status === 'disposed',
  404. isPreRunCancelled: () => this.preRunCancelled,
  405. clearPreRunCancel: () => { this.preRunCancelled = false },
  406. withToolBatch: run => this.withToolBatch(run),
  407. // Pre-run cancellation settles queued-work waiters before publishing idle.
  408. settleIdle: () => { this.settleIdleWaiters() },
  409. }))
  410. }
  411. /**
  412. * Quiescent stop shared by pre-start rollback and live teardown. It marks the
  413. * agent disposed synchronously, contains an unexpected loop rejection, and
  414. * drains every idle-injection flush before resolving.
  415. */
  416. private [stopDriver](): Promise<void> | void {
  417. if (this._status !== 'disposed') {
  418. // Snapshot any still-pending inbox items, then CLEAR and mark disposed
  419. // BEFORE emitting the discard — mirroring cancel()'s snapshot→clear→emit
  420. // order so a re-entrant send()/cancel() from a discard listener throws
  421. // `disposed` (or finds an empty inbox) instead of leaking or double-
  422. // discarding an id. `send()` emits enqueue unconditionally, so the discard
  423. // is unconditional too (even on an unpublished rollback) to keep every
  424. // enqueued id matched.
  425. const discarded = this.#inbox.pending()
  426. this.#inbox.clear()
  427. this._status = 'disposed'
  428. this.resolveDisposed()
  429. if (discarded.length > 0) {
  430. const items = discarded.map(({ message, steering }) => agentMessage(message, steering))
  431. agentEvents(this.loopCtx, this).emit('agent/inbox/discard', items)
  432. }
  433. // Release whenIdle waiters BEFORE the (guarded) event emit — they are
  434. // internal state that must settle even if a listener throws below. Each
  435. // waiter chains `done`, so it resolves only once the loop actually exits.
  436. this.settleIdleWaiters()
  437. this.turnCancellation?.request(DISPOSED_INTERRUPT_REASON)
  438. // An unpublished rollback has no public status lifecycle to announce.
  439. // Once publication begins, disposed is part of the agent/status contract.
  440. if (this.published) {
  441. agentEvents(this.loopCtx, this).emit('agent/status', 'disposed')
  442. }
  443. }
  444. // Before runLoop starts there is normally nothing asynchronous to drain;
  445. // keep publication rollback synchronous so create() cannot throw while its
  446. // session/agent entries are still briefly live. A session-start listener
  447. // may have called inject(), however, so preserve
  448. // its durability checkpoint as a real quiescence boundary.
  449. if (!this.driverStarted && this.pendingIdleFlushes.size === 0) return
  450. return this.drainDriver()
  451. }
  452. /** Await the loop (when started) and every outstanding idle flush. */
  453. private async drainDriver(): Promise<void> {
  454. // An unexpected driver rejection must not skip registry/session/scope
  455. // cleanup. The normal loop contains turn failures itself; allSettled is the
  456. // final lifecycle backstop for anything outside those boundaries.
  457. await Promise.allSettled([this.done])
  458. // Repeat because settled flushes retire in adjacent promise reactions;
  459. // allSettled keeps reporting failures from skipping ownership teardown.
  460. while (this.pendingIdleFlushes.size > 0) {
  461. await Promise.allSettled([...this.pendingIdleFlushes])
  462. }
  463. }
  464. }