agent.ts 19 KB

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