loop.ts 31 KB

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