loop.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. /**
  2. * Drives one agent across queued durable turns. Turn failures are contained so
  3. * later work can run; the session log, not this driver, owns conversation state.
  4. * See .agents/notes/implemented/architecture/2026-06-18-agent-lifecycle-and-ownership-seams.md.
  5. * @module dsh-agent-loop/loop
  6. */
  7. import type { Context } from 'cordis'
  8. import type { ContentBlock, FinishReason, GenerateOptions, LlmCallConfig, LlmFailure, Message } from '@deepseek-ai/dsh-llm'
  9. import { isDeepStrictEqual } from 'node:util'
  10. import { BlockAssembler, HarnessError, LlmError, assertNever, deepFreeze, errorChain, llmFailureOf } from '@deepseek-ai/dsh-llm'
  11. import { agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent'
  12. import type { AgentEventDispatch, ContinuationDecision, HookContext, PromptDecision, RequestError, RequestErrorDecision } from '@deepseek-ai/dsh-agent'
  13. import { canonicalHeader } from '@deepseek-ai/dsh-session'
  14. import type { Session, TurnEndReason, TurnTrigger } from '@deepseek-ai/dsh-session'
  15. import { createTransmissionLog, recordRequestHeader } from './request-log.ts'
  16. import type { TransmissionLog } from './request-log.ts'
  17. import { renderPrompt } from '@deepseek-ai/dsh-system-prompt'
  18. import type { PromptAssembly } from '@deepseek-ai/dsh-system-prompt'
  19. import type {} from '@deepseek-ai/dsh-tools'
  20. import { executeToolCalls } from './tool-calls.ts'
  21. import type { Inbox } from './inbox.ts'
  22. /** Normalize thrown values while preserving an existing error code. */
  23. function toError(error: unknown): RequestError {
  24. return error instanceof Error ? error : new HarnessError(String(error), 'UNKNOWN', { cause: error })
  25. }
  26. /** Distinguishes final model-request failures from failures in later step processing. */
  27. class TerminalModelRequestFailure extends Error {
  28. constructor(
  29. readonly requestError: RequestError,
  30. readonly failure: LlmFailure,
  31. ) {
  32. super(failure.message, { cause: requestError })
  33. this.name = 'TerminalModelRequestFailure'
  34. }
  35. }
  36. /** Convert terminal failure finishes into step errors; unknown extensible finishes remain successful. */
  37. function finishError(finish: FinishReason): { error: RequestError; failure: LlmFailure } | undefined {
  38. switch (finish.kind) {
  39. case 'error':
  40. case 'aborted': {
  41. const facts = finish.failure
  42. const error = new LlmError(facts.message, facts.code, {
  43. ...facts.status === undefined ? {} : { status: facts.status },
  44. ...facts.providerRetryAfterMs === undefined
  45. ? {}
  46. : { providerRetryAfterMs: facts.providerRetryAfterMs },
  47. ...facts.requestId === undefined ? {} : { requestId: facts.requestId },
  48. })
  49. return { error, failure: error.failure }
  50. }
  51. // stop / tool-calls / max-tokens / plugin-added kinds → not a failure.
  52. default:
  53. return undefined
  54. }
  55. }
  56. /**
  57. * Build the `{ message, code? }` part of an error payload, omitting the
  58. * `code` key entirely when absent (exactOptionalPropertyTypes-correct).
  59. * The durable message renders the full cause chain: `turn/end` is the single
  60. * durable record of an in-turn failure, so a wrapper message alone (e.g.
  61. * `fetch failed`) would lose the diagnosis the session log exists to keep.
  62. */
  63. function errorData(err: RequestError): { message: string; code?: string } {
  64. return { message: errorChain(err), ...typeof err.code === 'string' ? { code: err.code } : {} }
  65. }
  66. /** Preserve cause diagnostics, falling back to adapter-normalized prose for a hostile Error. */
  67. function durableFailure(err: RequestError, failure: LlmFailure): LlmFailure {
  68. const message = errorChain(err)
  69. return { ...failure, message: message === '<unrenderable value>' ? failure.message : message }
  70. }
  71. /** Map a successful max-token finish onto the turn reason; other successful finishes add nothing. */
  72. function stepFinishReason(finish: FinishReason): TurnEndReason | undefined {
  73. switch (finish.kind) {
  74. case 'max-tokens':
  75. return { kind: 'max-tokens' }
  76. // stop / tool-calls / plugin-added kinds → no turn-end contribution
  77. // beyond the default `completed`. FinishReason is merge-extensible, so a
  78. // default (not assertNever) handles unknown kinds as ordinary success.
  79. default:
  80. return undefined
  81. }
  82. }
  83. /** Mutable agent controls supplied to the loop driver. */
  84. export interface LoopHandle {
  85. /** Native-private agent inbox handed to the driver only at internal startup. */
  86. readonly inbox: Inbox
  87. /** Maximum parallel-safe calls allowed in one step. */
  88. readonly maxParallelToolCalls: number
  89. setStatus(status: 'idle' | 'running'): void
  90. setAbort(controller: AbortController | undefined): void
  91. /** Resolves when the agent is disposed — unblocks the idle wait. */
  92. disposed: Promise<void>
  93. isDisposed(): boolean
  94. /** Whether cancellation is pending for the current loop iteration. */
  95. isCancelled(): boolean
  96. /** Resolved pending-cancellation reason; meaningful only while {@link isCancelled} is true. */
  97. cancelReason(): string
  98. /** Clear the cancel marker (called once per iteration after the turn returns). */
  99. clearCancel(): void
  100. /** Settle idle waiters before pre-running cancellation publishes idle. */
  101. settleIdle(): void
  102. /** Run an active tool-call batch, accepting post-tool context into the FIFO drained before settlement. */
  103. readonly withToolBatch: <T>(run: (acceptContext: (context: HookContext) => void) => Promise<T>) => Promise<T>
  104. }
  105. /**
  106. * Drive queued messages as independent durable turns until disposal. Plugin
  107. * failures end the current turn without terminating the driver. The caller
  108. * establishes the `ctx.agents.withInitiator()` boundary before entry; package-private
  109. * orchestration recovers that exact Agent and captures its Session locally.
  110. * @param ctx - the plugin context the loop reaches its initiating Agent,
  111. * events (agent/…, session/flush), and services (systemPrompt, llm, tools)
  112. * through.
  113. * @param handle - the bridge to the agent's mutable state: status/abort setters plus the disposal and cancel-marker reads.
  114. * @throws when no initiating Agent is active.
  115. */
  116. export async function runLoop(ctx: Context, handle: LoopHandle): Promise<void> {
  117. const agent = ctx.agents.requireInitiator()
  118. // Per-instance prefix and request-header state; conversation history remains in the session log.
  119. const transmission = createTransmissionLog()
  120. const { session } = agent
  121. // Fused subject and scope carrier for every agent event below.
  122. const events = agentEvents(ctx, agent)
  123. while (!handle.isDisposed()) {
  124. // An idle listener can enqueue and cancel replacement work before the next
  125. // wait is installed. Consume that empty marker before parking the driver.
  126. if (handle.isCancelled()) {
  127. handle.clearCancel()
  128. if (!handle.inbox.hasQueued) {
  129. handle.settleIdle()
  130. handle.setStatus('idle')
  131. continue
  132. }
  133. }
  134. await handle.inbox.waitForQueued(handle.disposed)
  135. if (handle.isDisposed()) break
  136. // Cancellation between wake and `running` skips only the cancelled work;
  137. // a replacement prompt still runs before the eventual idle transition.
  138. if (handle.isCancelled()) {
  139. handle.clearCancel()
  140. if (!handle.inbox.hasQueued) {
  141. // Settle before publishing idle: the already-idle path has no status
  142. // transition, while an idle listener can register waiters for new work.
  143. handle.settleIdle()
  144. handle.setStatus('idle')
  145. continue
  146. }
  147. }
  148. handle.setStatus('running')
  149. if (handle.isDisposed()) break
  150. // A synchronous `running` listener can cancel before `runTurn`; balance the
  151. // status only when no replacement prompt was queued by that listener.
  152. if (handle.isCancelled()) {
  153. handle.clearCancel()
  154. if (!handle.inbox.hasQueued) {
  155. handle.setStatus('idle')
  156. continue
  157. }
  158. }
  159. // Idle injection can add a turn, so derive the next number from the log.
  160. const turn = lastTurnNumber(session) + 1
  161. let terminalStopped = false
  162. try {
  163. terminalStopped = await runTurn(ctx, events, handle, turn, transmission)
  164. } catch (error: unknown) {
  165. // Pre-turn failure has no durable boundary to close; report it without appending outside a turn.
  166. const err = toError(error)
  167. ctx.logger.warn(`agent "${agent.id}": turn ${turn} failed before it started: ${errorChain(err)}`)
  168. try {
  169. events.emit('agent/error', turn, 0, err)
  170. } catch { /* contained: a throwing agent/error listener must not kill the driver */ }
  171. }
  172. // Reset per iteration, including when a prompt arrives during the flush window.
  173. handle.clearCancel()
  174. // Late steering becomes queued input unless terminal policy stopped the turn.
  175. for (const message of handle.inbox.drainSteering()) {
  176. if (!terminalStopped) handle.inbox.enqueue(message)
  177. }
  178. if (!handle.inbox.hasQueued) handle.setStatus('idle')
  179. }
  180. }
  181. async function runTurn(
  182. ctx: Context, events: AgentEventDispatch, handle: LoopHandle, turn: number, transmission: TransmissionLog,
  183. ): Promise<boolean> {
  184. const agent = ctx.agents.requireInitiator()
  185. const { session } = agent
  186. const drainSteering = (): boolean => {
  187. const messages = handle.inbox.drainSteering()
  188. for (const message of messages) {
  189. session.append('steering/message', { turn, content: message.content, source: message.source }, { surfaceOp: 'append' })
  190. }
  191. return messages.length > 0
  192. }
  193. // Claim one queued message before opening its turn, but append it only after `turn/start`.
  194. const message = handle.inbox.dequeueQueued()
  195. /* v8 ignore next 3 -- invariant guard: runLoop only calls runTurn when hasQueued */
  196. if (!message) throw new Error('runTurn invariant violated: no queued message at turn start')
  197. const trigger: TurnTrigger = { kind: 'message', source: message.source }
  198. let reason: TurnEndReason = { kind: 'completed' }
  199. let step = 0
  200. let requestFailureHistory: readonly LlmFailure[] = Object.freeze([])
  201. let stepOpen = false
  202. let errorReported = false
  203. let terminalStopped = false
  204. // Close the committed step once; pre-commit validation failure still escapes.
  205. const closeStep = (): void => {
  206. if (!stepOpen) return
  207. session.append('step/end', { turn, step })
  208. stepOpen = false
  209. }
  210. // Record the durable turn failure once and contain the live error notification.
  211. const failTurn = (err: RequestError, failure?: LlmFailure): void => {
  212. if (errorReported) return
  213. errorReported = true
  214. reason = failure === undefined
  215. ? { kind: 'error', step, ...errorData(err) }
  216. : { kind: 'error', step, failure: durableFailure(err, failure) }
  217. try {
  218. events.emit('agent/error', turn, step, err)
  219. } catch {
  220. // contained: the error is already captured on `reason`; a throwing
  221. // agent/error listener must not prevent the turn from closing.
  222. }
  223. }
  224. // Pre-commit validation failure escapes rather than masquerading as a committed boundary.
  225. const closeTurn = (): void => {
  226. session.append('turn/end', { turn, reason })
  227. }
  228. try {
  229. // --- Turn boundary. Once turn/start is appended, a turn/end is owed no
  230. // matter what throws below; the catch + closeTurn guarantee it. A pre-commit
  231. // veto leaves no turn/start in the log and therefore owes no turn/end.
  232. session.append('turn/start', { turn, trigger })
  233. // The claimed message runs the `agent/prompt-submit` waterfall before it
  234. // becomes a `user/message` — a hook can rewrite the prompt or block it.
  235. // Recorded INSIDE the turn (after turn/start) so every event is turn-enclosed;
  236. // turn/end is now owed, so a throwing prompt-submit listener (the waterfall
  237. // throws) is caught below and the turn still closes.
  238. const promptDecision = await events.waterfall(
  239. 'agent/prompt-submit', message.content, message.source,
  240. () => Promise.resolve<PromptDecision>({ kind: 'allow' }),
  241. )
  242. if (promptDecision.kind === 'block') {
  243. session.append('prompt/blocked', { content: message.content, source: message.source, reason: promptDecision.reason })
  244. reason = { kind: 'rejected', reason: promptDecision.reason }
  245. } else {
  246. // `allow.content` REPLACES the prompt bytes (a rewrite); absent keeps them.
  247. const content = promptDecision.content ?? message.content
  248. session.append('user/message', { content, source: message.source }, { surfaceOp: 'append' })
  249. // Every `allow.additionalContexts` entry is a separate context/message the
  250. // next request also sees. The turn is open, so inject() appends each one
  251. // into THIS turn without flattening provenance or metadata.
  252. for (const context of promptDecision.additionalContexts ?? []) {
  253. agent.inject(context.content, {
  254. source: context.source,
  255. ...context.meta !== undefined ? { meta: context.meta } : {},
  256. })
  257. }
  258. }
  259. while (true) {
  260. // A blocked prompt closes its zero-step turn as rejected.
  261. if (promptDecision.kind === 'block') break
  262. step += 1
  263. // Steering from the previous round's continuation listeners joins before
  264. // the request.
  265. drainSteering()
  266. // The step's AbortController exists BEFORE any async pre-step work so a
  267. // dispose() or cancel() — in a synchronous turn-start listener or an
  268. // async listener whose effect fires before we block — always has an armed
  269. // abort to cancel against. isDisposed below covers disposal, which does
  270. // NOT set the cancel marker. Cleared on every exit path below.
  271. const abort = new AbortController()
  272. handle.setAbort(abort)
  273. // Assemble once before pre-step so listener work and the request share one prompt value.
  274. const assembly = await ctx.systemPrompt.assemble(assembleContextFor(agent))
  275. const fullSystemPrompt = renderPrompt(assembly)
  276. // Cancellation or disposal during assembly ends the turn before any step opens.
  277. if (handle.isCancelled() || handle.isDisposed()) {
  278. handle.setAbort(undefined)
  279. reason = handle.isDisposed() ? { kind: 'disposed' } : { kind: 'aborted', reason: handle.cancelReason() }
  280. break
  281. }
  282. // Compose the request-only prefix once per loop instance before the first
  283. // request boundary. It precedes all derived history and is recorded only
  284. // in the request header, not as session history.
  285. if (transmission.sessionPrefix === undefined) {
  286. const emptyPrefix: Message[] = deepFreeze([])
  287. const composed = await events.waterfall(
  288. 'agent/session-prefix', emptyPrefix, abort.signal,
  289. () => Promise.resolve(emptyPrefix),
  290. )
  291. // Never cache an interrupted composition; the next turn recomposes it.
  292. if (handle.isCancelled() || handle.isDisposed()) {
  293. handle.setAbort(undefined)
  294. reason = handle.isDisposed() ? { kind: 'disposed' } : { kind: 'aborted', reason: handle.cancelReason() }
  295. break
  296. }
  297. transmission.sessionPrefix = deepFreeze(structuredClone(composed))
  298. }
  299. // Await surface mutations outside the step before snapshotting history.
  300. await events.serial('agent/pre-step', turn, step, abort.signal)
  301. // Interruption landing during the pre-step seam: do not open an empty step.
  302. if (handle.isCancelled() || handle.isDisposed()) {
  303. handle.setAbort(undefined)
  304. reason = handle.isDisposed() ? { kind: 'disposed' } : { kind: 'aborted', reason: handle.cancelReason() }
  305. break
  306. }
  307. // Snapshot the exact log prefix before step/start: the reconstruction
  308. // boundary. Appends after this synchronous snapshot join the next request.
  309. const boundaryMessages = session.deriveMessages()
  310. session.append('step/start', { turn, step })
  311. // Only a committed step/start creates a balancing obligation. A
  312. // pre-commit veto throws before this assignment; post-commit observers
  313. // are contained inside Session.append().
  314. stepOpen = true
  315. // Cancel landing in the step-start window: a synchronous `session/event`
  316. // step/start listener can cancel after the step is already open. Check
  317. // AFTER the step/start append and before `runStep`: drop the step, end the
  318. // turn accordingly. closeStep balances the already-appended step/start.
  319. if (handle.isCancelled() || handle.isDisposed()) {
  320. handle.setAbort(undefined)
  321. reason = handle.isDisposed() ? { kind: 'disposed' } : { kind: 'aborted', reason: handle.cancelReason() }
  322. closeStep()
  323. break
  324. }
  325. let stepOutcome:
  326. | { hadToolCalls: boolean; finish: FinishReason }
  327. | { requestError: RequestError; failure: LlmFailure }
  328. | { error: RequestError }
  329. try {
  330. stepOutcome = await runStep(
  331. ctx, events, handle, turn, step, assembly, fullSystemPrompt, boundaryMessages, transmission, abort.signal)
  332. } catch (error: unknown) {
  333. if (error instanceof TerminalModelRequestFailure) {
  334. stepOutcome = { requestError: error.requestError, failure: error.failure }
  335. } else {
  336. stepOutcome = { error: toError(error) }
  337. }
  338. }
  339. if ('requestError' in stepOutcome) {
  340. // Recovery observes a balanced failed step and the original provider
  341. // error while the failed step's signal remains the active owner.
  342. closeStep()
  343. if (handle.isDisposed() || abort.signal.aborted) {
  344. handle.setAbort(undefined)
  345. reason = handle.isDisposed()
  346. ? { kind: 'disposed' }
  347. : { kind: 'aborted', reason: String(abort.signal.reason) }
  348. break
  349. }
  350. const defaultDecision: RequestErrorDecision = { action: 'fail' }
  351. let recoveryDecision: RequestErrorDecision = defaultDecision
  352. try {
  353. recoveryDecision = await events.waterfall(
  354. 'agent/request-error', turn, step, stepOutcome.requestError,
  355. stepOutcome.failure, requestFailureHistory, abort.signal,
  356. () => Promise.resolve(defaultDecision),
  357. )
  358. } catch (recoveryError: unknown) {
  359. ctx.logger.warn(
  360. `agent "${agent.id}": request recovery failed at turn ${turn}, step ${step}: ${errorChain(recoveryError)}`,
  361. )
  362. }
  363. handle.setAbort(undefined)
  364. // Cancellation and disposal always win over either a recovery decision
  365. // or a recovery-listener failure.
  366. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
  367. if (handle.isDisposed() || abort.signal.aborted) {
  368. reason = handle.isDisposed()
  369. ? { kind: 'disposed' }
  370. : { kind: 'aborted', reason: String(abort.signal.reason) }
  371. break
  372. }
  373. switch (recoveryDecision.action) {
  374. case 'retry':
  375. requestFailureHistory = Object.freeze([...requestFailureHistory, stepOutcome.failure])
  376. continue
  377. case 'fail':
  378. failTurn(stepOutcome.requestError, stepOutcome.failure)
  379. break
  380. /* v8 ignore next -- closed-union exhaustiveness guard */
  381. default:
  382. assertNever(recoveryDecision, 'agent request-error decision')
  383. }
  384. break
  385. }
  386. if ('error' in stepOutcome) {
  387. // Steering that arrived during the failed step stays in the inbox —
  388. // runLoop re-enqueues it as a queued message, so an abort-then-steer
  389. // starts a fresh turn instead of being silently consumed.
  390. closeStep()
  391. handle.setAbort(undefined)
  392. const { error } = stepOutcome
  393. /* v8 ignore next -- narrow race: disposal while non-request step work throws. */
  394. if (handle.isDisposed()) {
  395. reason = { kind: 'disposed' }
  396. } else if (abort.signal.aborted) {
  397. /* v8 ignore next -- signal.reason always set: cancel()/disposal provide a default */
  398. reason = { kind: 'aborted', reason: String(abort.signal.reason ?? 'aborted') }
  399. } else {
  400. failTurn(error)
  401. }
  402. break
  403. }
  404. requestFailureHistory = Object.freeze([])
  405. // Preserve max-token completion unless a later disposal, abort, or error wins.
  406. const stepReason = stepFinishReason(stepOutcome.finish)
  407. if (stepReason) reason = stepReason
  408. // Steering that arrived during streaming/tool execution.
  409. const steered = drainSteering()
  410. try {
  411. await events.serial('agent/post-step', turn, step, abort.signal)
  412. } catch (error: unknown) {
  413. stepOutcome = { error: toError(error) }
  414. }
  415. if ('error' in stepOutcome) {
  416. closeStep()
  417. handle.setAbort(undefined)
  418. /* v8 ignore next -- narrow race: disposal while a post-step listener throws. */
  419. if (handle.isDisposed()) {
  420. reason = { kind: 'disposed' }
  421. } else if (abort.signal.aborted) {
  422. /* v8 ignore next -- signal.reason always set by cancellation or disposal. */
  423. reason = { kind: 'aborted', reason: String(abort.signal.reason ?? 'aborted') }
  424. } else {
  425. failTurn(stepOutcome.error)
  426. }
  427. break
  428. }
  429. if (handle.isDisposed() || abort.signal.aborted) {
  430. reason = handle.isDisposed()
  431. ? { kind: 'disposed' }
  432. : { kind: 'aborted', reason: String(abort.signal.reason) }
  433. closeStep()
  434. handle.setAbort(undefined)
  435. break
  436. }
  437. closeStep()
  438. handle.setAbort(undefined)
  439. const defaultDecision: ContinuationDecision = { action: stepOutcome.hadToolCalls || steered ? 'continue' : 'stop' }
  440. let decision: ContinuationDecision
  441. try {
  442. decision = await events.waterfall(
  443. 'agent/turn-continuation', turn, defaultDecision,
  444. () => Promise.resolve(defaultDecision),
  445. )
  446. } catch (error: unknown) {
  447. // A broken continuation plugin ends the turn, not the loop.
  448. failTurn(toError(error))
  449. break
  450. }
  451. // A continuation reason becomes next-step steering.
  452. if (decision.action === 'continue' && decision.reason) {
  453. handle.inbox.steer({ content: decision.reason.content, source: decision.reason.source })
  454. }
  455. let shouldContinue = decision.action === 'continue'
  456. // Pending steering overrides an ordinary stop.
  457. if (!shouldContinue && handle.inbox.hasSteering) shouldContinue = true
  458. // Terminal policy is monotonic and runs after ordinary continuation folding.
  459. let terminalStop = false
  460. try {
  461. const stop = await events.serial('agent/turn-stop', turn)
  462. terminalStop = stop !== undefined
  463. } catch (error: unknown) {
  464. // A broken terminal policy is an ordinary continuation failure: fail
  465. // this turn closed while leaving the driver alive for later turns.
  466. failTurn(toError(error))
  467. break
  468. }
  469. if (terminalStop) {
  470. terminalStopped = true
  471. // Terminal stop discards steering but preserves ordinary queued prompts.
  472. handle.inbox.drainSteering()
  473. shouldContinue = false
  474. }
  475. // The marker catches cancellation after the step controller was cleared.
  476. if (handle.isCancelled()) {
  477. reason = { kind: 'aborted', reason: handle.cancelReason() }
  478. break
  479. }
  480. if (!shouldContinue || handle.isDisposed()) {
  481. /* v8 ignore next -- disposal during continuation-decision window is a narrow race; error-path disposal is covered elsewhere */
  482. if (handle.isDisposed()) reason = { kind: 'disposed' }
  483. break
  484. }
  485. }
  486. // Normal / inline-error loop exit: close the turn.
  487. closeTurn()
  488. } catch (error: unknown) {
  489. // Close only a turn whose start committed to the log.
  490. const turnStartLogged = session.events.some(e => e.type === 'turn/start' && e.data.turn === turn)
  491. if (!turnStartLogged) throw error
  492. closeStep()
  493. // Preserve an established disposal reason; otherwise report the failure.
  494. if (handle.isDisposed() && !errorReported) { // eslint-disable-line @typescript-eslint/no-unnecessary-condition
  495. reason = { kind: 'disposed' }
  496. } else {
  497. failTurn(toError(error))
  498. }
  499. closeTurn()
  500. }
  501. // Flush through the store-owned durability checkpoint without killing the driver on failure.
  502. try {
  503. await ctx.sessions.flush(session)
  504. } catch (error: unknown) {
  505. // The turn is closed, so report the failed flush live rather than append outside a turn.
  506. const err = toError(error)
  507. ctx.logger.warn(`agent "${agent.id}": session/flush failed at turn ${turn}: ${errorChain(err)}`)
  508. try {
  509. events.emit('agent/error', turn, step, err)
  510. } catch {
  511. // contained: a throwing agent/error listener must not escape the loop.
  512. }
  513. }
  514. return terminalStopped
  515. }
  516. /**
  517. * Run one committed step: transform call config, log the request header, build
  518. * the request from the cached prefix plus the step-boundary snapshot, stream and
  519. * record the response, then execute tools. The caller has already assembled the
  520. * prompt, run `agent/pre-step`, snapshotted history, and opened the step.
  521. */
  522. async function runStep(
  523. ctx: Context,
  524. events: AgentEventDispatch,
  525. handle: LoopHandle,
  526. turn: number,
  527. step: number,
  528. assembly: PromptAssembly,
  529. system: string,
  530. boundaryMessages: Message[],
  531. transmission: TransmissionLog,
  532. signal: AbortSignal,
  533. ): Promise<{ hadToolCalls: boolean; finish: FinishReason }> {
  534. const agent = ctx.agents.requireInitiator()
  535. const { session, options } = agent
  536. // Seed the first request from agent options and later requests from the logged header;
  537. // detach and freeze so listeners must return an attributable replacement.
  538. const seedConfig: LlmCallConfig = deepFreeze(structuredClone(transmission.loggedHeader
  539. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- loggedHeader ⟹ a snapshot is in the log
  540. ? session.requestHeader()!.config
  541. : { provider: options.provider ?? '', model: options.model ?? '' }))
  542. // Listener replacements are recorded in the request header before dispatch.
  543. const config = await events.waterfall('agent/request', turn, step, seedConfig, () => Promise.resolve(seedConfig))
  544. if (!config.provider || !config.model) {
  545. throw new Error(`agent "${agent.id}" has no provider/model: set AgentOptions.provider and AgentOptions.model or supply both via the agent/request waterfall`)
  546. }
  547. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- runTurn composes the prefix before every runStep call
  548. const sessionPrefix = transmission.sessionPrefix!
  549. // Record the canonical header, including the otherwise-unlogged prefix, before dispatch.
  550. const header = canonicalHeader({
  551. config,
  552. ...system ? { system } : {},
  553. ...assembly.tools.length > 0 ? { tools: assembly.tools } : {},
  554. ...sessionPrefix.length > 0 ? { messagePrefix: sessionPrefix } : {},
  555. })
  556. recordRequestHeader(session, transmission, header)
  557. // Freeze the logged header plus boundary snapshot; the prefix precedes derived history.
  558. const request: GenerateOptions = deepFreeze({
  559. provider: header.config.provider,
  560. model: header.config.model,
  561. messages: [...header.messagePrefix ?? [], ...boundaryMessages],
  562. ...header.system !== undefined ? { system: header.system } : {},
  563. ...header.tools !== undefined ? { tools: header.tools } : {},
  564. ...header.config.temperature !== undefined ? { temperature: header.config.temperature } : {},
  565. ...header.config.maxTokens !== undefined ? { maxTokens: header.config.maxTokens } : {},
  566. ...header.config.stop !== undefined ? { stop: header.config.stop } : {},
  567. sessionId: session.id,
  568. signal,
  569. })
  570. // --- Model call (streaming-first; raw chunks are the replay record) ---
  571. const assembler = new BlockAssembler()
  572. const chunkSeqs: number[] = []
  573. const stream = ctx.llm.stream(request)
  574. try {
  575. for await (const chunk of stream) {
  576. /* v8 ignore next -- signal.reason always set: cancel()/disposal provide a default */
  577. if (signal.aborted) throw new Error(String(signal.reason ?? 'aborted'))
  578. const chunkEvent = session.append('assistant/chunk', { turn, step, chunk })
  579. chunkSeqs.push(chunkEvent.seq)
  580. assembler.push(chunk)
  581. }
  582. } catch (error: unknown) {
  583. const failure = llmFailureOf(stream, error)
  584. if (failure !== undefined && error instanceof Error) throw new TerminalModelRequestFailure(error, failure)
  585. throw error
  586. }
  587. // Normalize failure finish chunks into the same path as thrown stream errors.
  588. const stepError = finishError(assembler.finish)
  589. if (stepError) throw new TerminalModelRequestFailure(stepError.error, stepError.failure)
  590. const recordAssistantMessage = (
  591. assembledContent: ContentBlock[],
  592. message: Message,
  593. preserveReplayState = true,
  594. ): void => {
  595. session.append(
  596. 'assistant/message',
  597. {
  598. turn,
  599. step,
  600. content: message.content,
  601. provenance: assistantProvenance(
  602. header.config,
  603. assembler.replayState,
  604. preserveReplayState && isDeepStrictEqual(message.content, assembledContent),
  605. ),
  606. ...assembler.usage === undefined ? {} : { usage: assembler.usage },
  607. },
  608. { surfaceOp: 'append', sourceEventSeqs: chunkSeqs },
  609. )
  610. }
  611. // A rejected result still records the successful provider call without retaining rejected output.
  612. const processStepResult = async (assembledContent: ContentBlock[], message: Message): Promise<Message> => {
  613. try {
  614. return await events.waterfall(
  615. 'agent/step-result', turn, step, message, () => Promise.resolve(message),
  616. )
  617. } catch (error: unknown) {
  618. recordAssistantMessage(assembledContent, { ...message, content: [] }, false)
  619. throw error
  620. }
  621. }
  622. if (assembler.finish.kind === 'max-tokens') {
  623. const assembled = assembler.message()
  624. const assembledContent = structuredClone(assembled.content)
  625. let message: Message = withoutToolCalls(assembled)
  626. message = withoutToolCalls(await processStepResult(assembledContent, message))
  627. // Preserve usage even when max-token truncation produced no content.
  628. recordAssistantMessage(assembledContent, message)
  629. return { hadToolCalls: false, finish: assembler.finish }
  630. }
  631. // Record the post-waterfall message that tool dispatch uses.
  632. const assembled = assembler.message()
  633. const assembledContent = structuredClone(assembled.content)
  634. let message: Message = assembled
  635. message = await processStepResult(assembledContent, message)
  636. // Every successful call records its completion anchor, including explicit
  637. // empty chunk provenance for a contentless, usage-less provider response.
  638. recordAssistantMessage(assembledContent, message)
  639. // Dispatch may overlap; policy, durable results, and result context stay model-ordered.
  640. const toolCalls = message.content.filter(block => block.type === 'tool-call')
  641. if (toolCalls.length === 0) return { hadToolCalls: false, finish: assembler.finish }
  642. return handle.withToolBatch(async (acceptContext) => {
  643. await executeToolCalls(
  644. ctx, turn, step, toolCalls, signal, handle.maxParallelToolCalls, acceptContext,
  645. )
  646. return { hadToolCalls: true, finish: assembler.finish }
  647. })
  648. }
  649. /** Build durable assistant provenance, dropping replay state after any content rewrite. */
  650. function assistantProvenance(config: LlmCallConfig, replayState: unknown, contentUnchanged: boolean): NonNullable<Message['provenance']> {
  651. return {
  652. provider: config.provider,
  653. model: config.model,
  654. ...contentUnchanged && replayState !== undefined ? { replayState } : {},
  655. }
  656. }
  657. function withoutToolCalls(message: Message): Message {
  658. return { ...message, content: message.content.filter(block => block.type !== 'tool-call') }
  659. }
  660. /**
  661. * The last turn number in a (possibly seeded) session log, or 0.
  662. * @param session - the session whose log is scanned for the latest `turn/start`.
  663. * @returns the latest `turn/start`'s turn number, or 0 when the log has none (the next turn is this plus one).
  664. */
  665. export function lastTurnNumber(session: Session): number {
  666. const lastStart = session.events.findLast(event => event.type === 'turn/start')
  667. return lastStart?.data.turn ?? 0
  668. }
  669. /**
  670. * Whether the session log has an unmatched `turn/start`. Agent status is not
  671. * sufficient during pre-start and post-end windows.
  672. * @param session - the session whose log is inspected.
  673. * @returns true when the log's last turn boundary is a `turn/start` with no matching `turn/end` yet.
  674. */
  675. export function isTurnOpen(session: Session): boolean {
  676. const last = session.events.findLast(e => e.type === 'turn/start' || e.type === 'turn/end')
  677. return last?.type === 'turn/start'
  678. }