loop.ts 33 KB

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