agent.ts 19 KB

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