agent.ts 20 KB

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