Files
deepseek-harness/packages/core/agent-loop/src/agent.ts
T
涂轶翔 101f26de4e fix(system-prompt): 保留 section API 的增量系统指令 (#6941)
* feat(system-prompt): admit section updates incrementally

* docs(system-prompt): accept retirement restart gap

* test(system-prompt): cover retirement and reentry before admission

* test(system-prompt): align rebase fixtures and persistence history

* fix: align section prompt consumers and CI fixtures

* test: pin credentials for section snapshot fixtures

* test: align remaining snapshots with section admission

* test: preserve section metadata in Web and PowerShell replays

* refactor(system-prompt): retire sections through Cordis cleanup

* chore: refresh section admission history after rebase

* fix(system-prompt): advance admission head after compaction

* fix(system-prompt): trim sections before admission hashing

* docs: move system upgrade guides to current version

* docs: add system message contribution cookbook

* perf(system-prompt): avoid indexing history for admission

* refactor(system-prompt): derive admission from logged sections

* test(system-prompt): update lifecycle and compaction consumers

* test(system-prompt): refresh CLI section event expectations

* test(system-prompt): refresh question composer section metadata

* feat(system-prompt): resolve same-name sections by scope

* refactor(persona): use ordinary section registrations

* refactor(system-prompt): clarify assembly and related control flow

* test(system-prompt): reconcile rebased section snapshots

* test(python): use current system text helper after rebase

* test(system-prompt): refresh CLI expected section blocks

* test(system-prompt): reconcile latest master integration

* test(agent-loop): seed tools before deferred addition assertion

* refactor(compaction): replace system heads when compacting prefixes

* refactor(system-prompt): separate source text and notice attribution

* fix(system-prompt): preserve legacy instructions in compaction snapshots

* refactor(compaction): build system snapshots while reading the summary prefix

* refactor(compaction): rebuild current system instructions

* refactor(system-prompt): defer compaction rebuild to admission

* refactor(system-prompt): remove redundant fixtures and setup

* fix(plan-mode): announce committed user transitions

* docs(system-prompt): reconcile section lifecycle and compaction design

* refactor(system-prompt): consolidate projection version increments

* fix(system-prompt): reconcile master integration and replay fixtures

* docs(system-prompt): align upgrade guide with current release

* refactor(system-prompt): make admission operations explicit

* fix(system-prompt): reconcile master API and release changes

* docs(system-prompt): regenerate catalogs after master refresh

* refactor(llm-pi-ai): delegate text rendering to pi-ai

* fix(llm-pi-ai): preserve blank lines between system text parts

* refactor(system-prompt): remove redundant retirement metadata

* refactor(system-prompt): own admission and use canonical surface targets

* refactor(system-prompt): compare captured sections at commitment

Assembly fixes section text and lifecycle; PromptAssembly.systemUpdates() compares them with the committed projection when the loop commits. This replaces SystemPrompt.admit(), needsRebuild() and isCurrent(), the SystemAdmission export, the loop's reassembly after compaction, and SessionSurface.systemHeadResetSeq. The projection records a pending rebuild as a boolean that an attributed reset clears.

After a compaction inside a step, the rebuilt head uses the sections captured for that step; later source changes arrive as ordinary updates at the next step.

* test: await the session read fixture and type a matcher for lint

* test(tool-executor-ptc): describe same-name section override on executor replacement

Duplicate section names no longer reject a scoped executor; the earlier registration is overridden and returns as an ordinary update when the executor leaves.

* docs(upgrade-guide): move system-prompt integrations to v0.2.2-rc.3

The root version on master is 0.2.2-rc.3; verify-upgrade-guides rejects a guide added under an earlier version directory.

* refactor(system-prompt): rebuild over system messages without sections

A system message without source.sections now marks rebuilding pending, like a compaction summary. The next model attempt replaces the head with current sections and clears later system messages. This removes the separate legacy flag and its appended whole-prompt replacement and notice.

Sessions written by earlier releases, migrated logs, and imported DeepSeek conversations take the same path, so the importer and its tests return to their master versions.

* test(web): refresh the imported-conversation recording and drop a stray bytecode file

The Web recording for a resumed DeepSeek import was recorded while the prompt was appended after the imported history; the head is replaced again, as on master. The .pyc under the macOS signing skill was staged by accident in an earlier merge.

* refactor(session): scan system nodes on read

surface.systemNodes is read only when a system rebuild is written. Scanning the current surface nodes on each read restores the surface fold's plan types and state to their master definitions, which no longer carry the system message.

* refactor(session): rename SystemSurfaceNode.hasContent to isEmpty

The flag reports that the logged content array has no blocks. isEmpty matches the documented "empty head" wording and covers a head that was written empty without ever being cleared.

* refactor(llm): join system text through extractTextContent

extractTextContent gains a trim option that trims each text block and omits blocks left empty. The DeepSeek serializer, the pi-ai converter, and the prompt inspector use it with a blank-line separator in place of three hand-written joins.

The pi-ai converter now trims system and developer text like the other two, so whitespace-only blocks are omitted there as well.

* test(snapshots): refresh the PowerShell and cordis-inspect recordings

The two PowerShell scenarios still held the initial system message as one unattributed block; replay now writes one block per section with its attribution. The cordis-inspect-jsdoc recording embeds the API catalog, which names SystemSurfaceNode.isEmpty since the rename.

* test(plan-mode,harness-dev-context): cover a rejected pre-step and a repeated legacy prompt

A rejected pre-step must leave a queued plan-mode switch pending and unannounced until the next accepted step. A second unattributed system message with the same legacy paragraphs must keep the admitted paragraphs.

* test(web): refresh Web recordings for section-attributed system messages

Twenty-seven Web recordings still held the initial system message as one unattributed block. Replay now writes one text block per section with its attribution; twenty-six recordings differ only in that line.

plan-review also records the plan-mode switch notice before the first prompt and appends a plan:status update on exit in place of a head replacement and a series header, so its expanded golden gains the notice row.

The Creator persona test joins the system text blocks with blank lines, as the adapters do, before matching the persona line.

* refactor(system-prompt): require the retry argument of systemUpdates

The agent loop passes it on every attempt. A custom loop that omitted it on a retry received a full comparison in place of the pending rebuild, with no diagnostic; the type now makes each caller state which attempt it is.

* docs(upgrade-guide): move the system prompt integrations guide to v0.2.2-rc.5

The root version is 0.2.2-rc.5 after the master merge, and verify-upgrade-guides rejects a guide added under an earlier version directory.

* test(web): refresh the mention path presence recording for section-attributed system messages

* test: align two specs that master left failing

The DeepSeek settings spec waited for a saved notice carrying the provider label from before the rename to DeepSeek API. The Windows packaging workflow spec seeded one of the two helpers that the Stage workflow helpers step copies.

* chore: remove a Python cache file committed by mistake
2026-11-19 21:11:38 +08:00

736 lines
30 KiB
TypeScript

/**
* Default Agent driver over queued turns and step-boundary input. Every request
* is derived from the session log.
* @module dsh-agent-loop/agent
*/
import type {
Agent,
AgentCancelCause,
AgentEventDispatch,
AgentOptions,
AgentStatus,
CancelOptions,
ModelSelection,
ModelSelectionProjectionState,
InboxTarget,
InboxState,
PreStepDecision,
RequestErrorAction,
} from '@deepseek-ai/dsh-agent'
import { AgentModel, agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent'
import type { GenerateOptions, LlmCallConfig, Message, PreparedLlmCall } from '@deepseek-ai/dsh-llm'
import {
LlmError,
createAssistantMessage,
createDeveloperMessage,
errorChain,
markAgentLoopRequest,
} from '@deepseek-ai/dsh-llm'
import { assertNever, deepFreeze } from '@deepseek-ai/dsh-util-values'
import type { Scope } from '@deepseek-ai/dsh-scope'
import { createScope } from '@deepseek-ai/dsh-scope'
import type { EpochHeader, RequestContext, Session, SessionId, SessionSeq, TurnEndReason, UserMessage } from '@deepseek-ai/dsh-session'
import { canonicalHeader, headerEquals, ToolCallRecovery } from '@deepseek-ai/dsh-session'
import { renderContextSections } from '@deepseek-ai/dsh-system-prompt'
import type { PromptAssembly } from '@deepseek-ai/dsh-system-prompt'
import { ToolActivationError, ToolBatchExecutionError } from '@deepseek-ai/dsh-tools'
import type { ResolvedToolSet } from '@deepseek-ai/dsh-tools'
import type { Context } from '@deepseek-ai/cordis'
import { ReactLoopInbox } from './inbox.ts'
import { RuntimeContextProjection } from './runtime-context.ts'
import { AssistantStreamAttempt } from './assistant-stream.ts'
/** Projected facts consumed by this driver; registration stays with the factory. */
interface LoopProjections {
/** Current model selection, including pending changes. */
readonly modelSelection: () => ModelSelectionProjectionState
/** Current queued and claimed input. */
readonly inbox: () => InboxState
}
type Phase =
| { kind: 'idle'; lastTurn: number }
| {
kind: 'maintenance'
abort: AbortController
lastTurn: number
wakeRequested: boolean
}
| { kind: 'running'; abort: AbortController; turn: number; step: number; wakeRequested: boolean }
type StepEndReason = Extract<TurnEndReason, { kind: 'completed' | 'max-tokens' }>
type PreparedStep =
| { kind: 'reject' }
| {
kind: 'enter'
messages: UserMessage[]
startsRequestSeries?: true
assembly: PromptAssembly
selection: Readonly<ModelSelection>
/** Admission shared by the step's declarations and dispatch; the turn disposes it after the step. */
toolSet: ResolvedToolSet
}
/** Remove adapter-derived values before plugins propose the next request config. */
function requestProposal(header: EpochHeader): LlmCallConfig {
if (header.adapterDefaults === undefined) return header.config
const proposal = { ...header.config }
if (header.adapterDefaults.reasoningEffort === true) delete proposal.reasoningEffort
if (header.adapterDefaults.maxTokens === true) delete proposal.maxTokens
return proposal
}
/**
* Read the cause `cancel()` passed when aborting a loop-owned signal, copying
* only the fields `turn/end` records. The live reason stays the caller's
* object, and Node's fetch assigns a `stack` onto it that `Session.append`
* would either log or reject as data JSON cannot hold.
* @param signal - a turn or maintenance signal this loop owns.
* @returns the copied cause, or undefined while the signal is still live.
*/
function abortedCancelCause(signal: AbortSignal): AgentCancelCause | undefined {
if (!signal.aborted) return undefined
// `cancel()` is the only aborter of the signals this loop owns.
const cause = signal.reason as AgentCancelCause
switch (cause.kind) {
case 'user':
case 'parent':
case 'disposed':
return { kind: cause.kind }
case 'hook':
return { kind: 'hook', reason: cause.reason }
/* v8 ignore next -- cancel accepts the closed AgentCancelCause union */
default:
return assertNever(cause)
}
}
/** Drives one session through turn and step boundaries. */
export class ReactLoopAgent implements Agent {
readonly model: AgentModel
readonly inbox: ReactLoopInbox
private phase: Phase
private activityDone: Promise<void> = Promise.resolve()
/** The agent-scoped registration boundary; the lifecycle owner unwinds it after the driver exits. */
readonly scope: Scope
readonly ctx: Context
/** Fused dispatcher, built once in the constructor so hot-path dispatches never allocate. */
private readonly dispatch: AgentEventDispatch
/** Whether this loop instance has appended its initial/resume request anchor. */
private requestHeaderLogged = false
/** Surface generation at attachment or the preceding built request. */
private requestSurfaceGeneration: number
private readonly runtimeContext: RuntimeContextProjection
/** Process-local revision of assistant frames for this attached Session. */
private assistantStreamRevision = 0
private assistantAttemptCounter = 0
/** Identities fully frozen by this loop; weak references do not retain replaced history. */
private readonly frozenMessages = new WeakSet<Message>()
constructor(
private loopCtx: Context,
public readonly id: SessionId,
public readonly options: AgentOptions,
public readonly session: Session,
projections: LoopProjections,
lastTurn: number,
private readonly lifetimeSignal: AbortSignal,
) {
this.requestSurfaceGeneration = session.surface.contentGeneration
this.dispatch = agentEvents(loopCtx, this)
this.scope = createScope(loopCtx, this)
this.ctx = this.scope.ctx
this.model = new AgentModel(projections.modelSelection, session, options)
this.inbox = new ReactLoopInbox(projections.inbox, session, this.dispatch)
this.phase = { kind: 'idle', lastTurn }
this.runtimeContext = new RuntimeContextProjection(this.ctx, session)
}
get status(): AgentStatus {
return this.phase.kind === 'idle' || this.phase.kind === 'maintenance' ? 'idle' : 'running'
}
/** Commit a phase and publish its externally visible status transition. */
private setPhase(next: Phase): void {
const previousStatus = this.status
this.phase = next
const status = this.status
if (status !== previousStatus) {
this.dispatch.emit('agent/status', { status })
}
}
send(message: UserMessage, target: InboxTarget, wakeup: boolean): void {
// Waking input cannot join an aborted activity, so it starts the next turn.
// Captured before the insertion so a reentrant cancel from a splice observer cannot reclassify it.
const wakingAfterAbort = wakeup && this.phase.kind !== 'idle' && this.phase.abort.signal.aborted
const resolvedTarget = wakingAfterAbort ? 'next-turn' : target
this.inbox.splice(resolvedTarget, Infinity, 0, [message])
if (wakeup) this.wakeDriver(wakingAfterAbort)
}
followup(input: UserMessage): void {
this.send(input, 'next-turn', true)
}
steer(input: UserMessage): void {
this.send(input, 'next-step', true)
}
inject(input: UserMessage): void {
this.send(input, 'next-step', false)
}
cancel(cause: AgentCancelCause, options: CancelOptions = {}): void {
try {
if (!options.keepInbox) this.inbox.clear()
} finally {
// Queue persistence must not prevent cancellation of admitted work.
if (this.phase.kind !== 'idle') {
if (!options.keepInbox) this.phase.wakeRequested = false
this.phase.abort.abort(cause)
}
}
}
runMaintenance<T>(job: (signal: AbortSignal) => Promise<T>): Promise<T> {
if (this.phase.kind !== 'idle') throw new Error(`agent "${this.id}" already has active work`)
const done = Promise.withResolvers<void>()
const maintenance: Phase = {
kind: 'maintenance',
abort: new AbortController(),
lastTurn: this.phase.lastTurn,
wakeRequested: false,
}
this.setPhase(maintenance)
this.activityDone = done.promise
return (async () => {
try {
return await job(maintenance.abort.signal)
} finally {
this.setPhase({ kind: 'idle', lastTurn: maintenance.lastTurn })
const cause = abortedCancelCause(maintenance.abort.signal)
if (cause?.kind !== 'disposed' && maintenance.wakeRequested && this.inbox.hasPending) this.wakeDriver()
done.resolve()
}
})()
}
/**
* Start one driver, or latch its wake behind maintenance or an aborted
* activity. A wake sent while idle always opens its turn boundary, even
* when its message was cleared; only a latched replay is suppressed when
* the queue no longer holds the wake.
* @param wakeAfterAbort - the {@link send} classification, captured before
* the inbox insertion so a reentrant cancel cannot reclassify it.
*/
private wakeDriver(wakeAfterAbort = false): void {
if (this.lifetimeSignal.aborted) return
if (this.phase.kind !== 'idle') {
// Maintenance and aborted drivers cannot deliver the wake: latch it for
// replay at convergence. Live drivers claim queued work themselves;
// disposal never latches, so teardown waits on no model turn.
const reason = abortedCancelCause(this.phase.abort.signal)
if (reason?.kind !== 'disposed' && (this.phase.kind === 'maintenance' || wakeAfterAbort)) {
this.phase.wakeRequested = true
}
return
}
const driver = Promise.withResolvers<void>()
this.activityDone = driver.promise
this.setPhase({
kind: 'running',
abort: new AbortController(),
turn: this.phase.lastTurn,
step: 0,
wakeRequested: false,
})
this.loopCtx.agents.withInitiator(this, () => this.kick()).then(driver.resolve, driver.reject)
}
async whenIdle(): Promise<void> {
let activity: Promise<void>
do {
await (activity = this.activityDone)
} while (activity !== this.activityDone)
}
/** Report one failure at its live boundary, then preserve it for driver containment. */
private throwError(error: unknown): never {
const turn = this.phase.kind === 'running' ? this.phase.turn : this.phase.lastTurn
const step = this.phase.kind === 'running' ? this.phase.step : 0
this.dispatch.emit('agent/error', { turn, step, error })
throw error
}
private async kick(): Promise<void> {
try {
while (await this.turn()) {}
} catch (_error) {
// Reported failures and cancellation are contained at the driver boundary.
} finally {
/* v8 ignore next -- kick owns a running phase until this driver boundary */
if (this.phase.kind === 'running') {
const { turn, wakeRequested } = this.phase
this.setPhase({ kind: 'idle', lastTurn: turn })
if (wakeRequested && this.inbox.hasPending) this.wakeDriver()
}
}
}
private async preStep(target: InboxTarget, position: { turn: number; step: number }): Promise<PreparedStep> {
/* v8 ignore next -- private callers establish the running phase before proposing a step */
if (this.phase.kind !== 'running') throw new Error(`agent "${this.id}": pre-step outside running phase`)
const signal = this.phase.abort.signal
const claimed = this.inbox.claim(target, position.turn)
const selection = this.model.current()
if (selection === undefined) {
throw new Error(`agent "${this.id}" has no provider/model: set AgentOptions.provider and AgentOptions.model or record a model selection`)
}
const toolSet = await this.loopCtx.tools.resolve({ agent: this, modelSelection: selection, signal })
try {
const assembly = await this.loopCtx.systemPrompt.assemble({ ...assembleContextFor(this, signal), modelSelection: selection, toolSet })
signal.throwIfAborted()
const decision = await this.dispatch.waterfall(
'agent/pre-step', { messages: claimed, ...position, signal, modelSelection: selection },
(): Promise<PreStepDecision> => {
const sections = renderContextSections(assembly)
const context = this.runtimeContext.project(sections)
return Promise.resolve<PreStepDecision>({
kind: 'enter',
messages: context === undefined ? claimed : [...claimed, context],
})
},
)
signal.throwIfAborted()
if (decision.kind === 'reject') {
toolSet.dispose()
return decision
}
return { ...decision, assembly, selection, toolSet }
} catch (error: unknown) {
toolSet.dispose()
throw error
}
}
/** Open one turn before claiming its first proposed step. */
private async turn(): Promise<boolean> {
if (this.phase.kind !== 'running') {
this.throwError(new Error(`agent "${this.id}": turn without driver reservation`))
}
const phase = this.phase
const { signal } = phase.abort
signal.throwIfAborted()
const turn = phase.turn + 1
try {
this.session.append('turn/start', { turn })
} catch (error: unknown) {
this.throwError(error)
}
phase.turn = turn
let turnEnds: TurnEndReason | null = null
let target: InboxTarget = 'next-turn'
try {
while (true) {
signal.throwIfAborted()
const step = phase.step + 1
const decision = await this.preStep(target, { turn, step })
if (decision.kind === 'reject') {
turnEnds = { kind: 'blocked' }
return false
}
try {
if (turnEnds && decision.messages.length === 0) break
// A removed waking message or an enter decision rewritten to empty
// still owns the initial turn boundary, but it spends no model call.
if (phase.step === 0 && decision.messages.length === 0) {
turnEnds = { kind: 'completed' }
return false
}
signal.throwIfAborted()
this.session.append('step/start', { turn, step })
phase.step = step
const toolRecovery = new ToolCallRecovery()
const stopRecovery = this.ctx.on('session/event', (session, event) => {
if (session === this.session) toolRecovery.observe(event)
})
try {
// max-tokens is sticky: once any step hits the ceiling, later steps
// that complete normally must not downgrade the turn outcome.
const stepEnd = await this.step(decision)
// max-tokens stays sticky: a later completed step must not
// downgrade the turn outcome.
if (turnEnds === null || turnEnds.kind !== 'max-tokens') turnEnds = stepEnd
} catch (error: unknown) {
try {
for (const event of toolRecovery.results()) {
this.session.append('tool/result', event.data, {
surfaceOp: 'append',
...event.sourceEventSeqs === undefined ? {} : { sourceEventSeqs: event.sourceEventSeqs },
})
}
} catch (recoveryError: unknown) {
throw new AggregateError([error, recoveryError], 'Step failed and its pending tool results could not be recorded', { cause: error })
}
throw error
} finally {
stopRecovery()
this.session.append('step/end', { turn, step })
}
} finally {
// Admission closes once the step's tool batch settles or no step opens.
decision.toolSet.dispose()
}
signal.throwIfAborted()
if (turnEnds && this.inbox.nextStep.length === 0) {
await this.dispatch.serial('agent/turn-stopping', { turn, signal })
signal.throwIfAborted()
}
if (turnEnds && this.inbox.nextStep.length === 0) break
target = 'next-step'
}
} catch (error: unknown) {
// A cause is present exactly while the signal is aborted.
const cause = abortedCancelCause(signal)
if (cause !== undefined) {
turnEnds = { kind: 'aborted', reason: cause }
throw error
}
// Every failure is structured: an `LlmError` keeps its facts, a tool
// activation failure keeps its code, and anything else flattens to
// `errorChain` text under the `UNKNOWN` code.
turnEnds = {
kind: 'error',
error: error instanceof LlmError
? error.failure
: { message: errorChain(error), code: error instanceof ToolActivationError ? error.code : 'UNKNOWN' },
}
this.throwError(error)
} finally {
try {
// oxlint-disable-next-line typescript/no-non-null-assertion -- every exit assigns a turn ending
this.session.append('turn/end', { turn, reason: turnEnds! })
} catch (error: unknown) {
this.throwError(error)
}
}
if (!this.inbox.hasPending) return false
phase.abort = new AbortController()
// A fresh controller makes a latch set on the old one stale: the live driver claims the queue itself.
phase.wakeRequested = false
phase.step = 0
return true
}
private async step(decision: Extract<PreparedStep, { kind: 'enter' }>): Promise<StepEndReason | null> {
/* v8 ignore next -- private callers establish the running phase before executing a step */
if (this.phase.kind !== 'running') throw new Error(`agent "${this.id}": step outside running phase`)
const { turn, step, abort: { signal } } = this.phase
signal.throwIfAborted()
const { assembly } = decision
let firstAttempt = true
while (true) {
const { config, preparedCall } = await this.prepareRequest(turn, step, decision.selection, signal)
const currentContext = this.loopCtx.systemPrompt.refreshContext(assembly, {
...assembleContextFor(this, signal), modelSelection: decision.selection,
})
const sections = renderContextSections(currentContext)
const context = this.runtimeContext.project(sections)
signal.throwIfAborted()
const startsRequestSeries = firstAttempt && decision.startsRequestSeries === true
let contextAdmitted = false
// A retry writes only the rebuild that an intervening compaction requires.
for (const { message, intent } of assembly.systemUpdates(!firstAttempt)) {
this.session.append('system/message', { turn, step, message }, intent)
}
if (firstAttempt) {
for (const message of decision.messages) {
if (message.source.kind === 'runtime-context') {
if (context !== undefined && !contextAdmitted) {
this.session.append('user/message', context, { surfaceOp: 'append' })
contextAdmitted = true
}
} else {
this.session.append('user/message', message, { surfaceOp: 'append' })
}
}
}
if (context !== undefined && !contextAdmitted) {
this.session.append('user/message', context, { surfaceOp: 'append' })
}
firstAttempt = false
const request = this.buildRequest(config, preparedCall, assembly.tools, { turn, step }, startsRequestSeries, signal)
const live = new AssistantStreamAttempt(
this.session.id,
++this.assistantAttemptCounter,
() => ++this.assistantStreamRevision,
turn,
step,
(frame) => { this.dispatch.emit('agent/assistant-stream', { frame }) },
)
let started = false
try {
const stream = preparedCall?.stream(request) ?? this.loopCtx.llm.stream(request)
signal.throwIfAborted()
live.start()
started = true
for await (const chunk of stream) {
signal.throwIfAborted()
live.push(chunk)
}
signal.throwIfAborted()
} catch (error: unknown) {
if (!started) throw error
try {
if (signal.aborted) {
const content = live.interruptedBlocks()
if (content.length > 0) {
live.settle('assistant/message', () => this.session.append('assistant/message', {
turn,
step,
message: createAssistantMessage({
content,
source: {
provider: request.provider,
model: request.model,
...live.replayState === undefined ? {} : { replayState: live.replayState },
},
}),
interrupted: true,
...live.usage === undefined ? {} : { usage: live.usage },
stream: live.stream,
}, { surfaceOp: 'append' }).seq)
} else {
live.settle(
'assistant/attempt',
() => this.session.append('assistant/attempt', { turn, step, stream: live.stream }).seq,
)
}
} else {
live.settle(
'assistant/attempt',
() => this.session.append('assistant/attempt', { turn, step, stream: live.stream }).seq,
)
}
} catch (settlementError: unknown) {
throw new AggregateError(
[error, settlementError],
'Assistant stream failed and its durable settlement was rejected',
{ cause: error },
)
}
throw error
}
try {
const finish = live.finish
if (finish.kind === 'error' || finish.kind === 'aborted') {
live.settle(
'assistant/attempt',
() => this.session.append('assistant/attempt', { turn, step, stream: live.stream }).seq,
)
const action = await this.dispatch.waterfall(
'agent/request-error', {
turn,
step,
provider: request.provider,
failure: finish.failure,
retryPolicy: preparedCall?.retryPolicy,
signal,
},
() => Promise.resolve<RequestErrorAction>(undefined),
)
signal.throwIfAborted()
if (action?.kind !== 'retry') {
throw LlmError.fromFailure(finish.failure)
}
continue
}
const message = createAssistantMessage({
content: live.blocks(),
source: {
provider: request.provider,
model: request.model,
...live.replayState !== undefined ? { replayState: live.replayState } : {},
},
})
live.settle(
'assistant/message',
() => this.session.append('assistant/message', {
turn,
step,
message,
...live.usage === undefined ? {} : { usage: live.usage },
stream: live.stream,
}, { surfaceOp: 'append' }).seq,
)
if (finish.kind === 'max-tokens') return { kind: 'max-tokens' }
const toolCalls = message.content.filter(block => block.type === 'tool-call')
if (toolCalls.length === 0) return { kind: 'completed' }
const maxParallelToolCalls = this.loopCtx.agentLoop.config.maxParallelToolCalls.get()
try {
const result = await this.loopCtx.tools.execute({
calls: toolCalls, signal, agent: this, log: { turn, step },
maxParallelToolCalls, toolSet: decision.toolSet,
})
for (const context of result.additionalContexts) {
this.inbox.splice('next-step', this.inbox.nextStep.length, 0, [context])
}
return result.concluded ? { kind: 'completed' } : null
} catch (error: unknown) {
if (!(error instanceof ToolBatchExecutionError)) throw error
for (const context of error.partial.additionalContexts) {
this.inbox.splice('next-step', this.inbox.nextStep.length, 0, [context])
}
throw error.cause
}
} catch (error: unknown) {
if (!live.ended) live.abandon()
throw error
}
}
}
/** Resolve request config for the step's selection and bind its adapter before admitting model-visible input. */
private async prepareRequest(
turn: number,
step: number,
selection: Readonly<ModelSelection>,
signal: AbortSignal,
): Promise<{ config: LlmCallConfig; preparedCall?: PreparedLlmCall }> {
const { session } = this
// A loop instance seeds output controls from its options until it logs its
// own header; later steps re-resolve marked defaults.
const maxTokens = this.options.maxTokens
const persisted: Partial<LlmCallConfig> = this.requestHeaderLogged
// oxlint-disable-next-line typescript/no-non-null-assertion -- the instance logged the header it now folds
? requestProposal(session.requestHeader()!)
: maxTokens === undefined ? {} : { maxTokens }
const { provider: _provider, model: _model, reasoningEffort: _effort, ...controls } = persisted
const seedConfig = deepFreeze(structuredClone({ ...controls, ...selection }))
const proposedConfig = await this.dispatch.waterfall(
'agent/request', { turn, step, signal },
() => Promise.resolve(seedConfig),
)
signal.throwIfAborted()
if (proposedConfig.provider !== selection.provider || proposedConfig.model !== selection.model) {
throw new Error(`agent "${this.id}": agent/request proposed "${proposedConfig.provider}/${proposedConfig.model}" after step preparation fixed "${selection.provider}/${selection.model}"; use agent.model.select() before step preparation`)
}
if (proposedConfig.reasoningEffort !== selection.reasoningEffort) {
throw new Error(`agent "${this.id}": agent/request proposed reasoning effort "${proposedConfig.reasoningEffort ?? 'adapter default'}" after step preparation fixed "${selection.reasoningEffort ?? 'adapter default'}"; use agent.model.select() before step preparation`)
}
let config: LlmCallConfig
let preparedCall: PreparedLlmCall | undefined
try {
preparedCall = await this.loopCtx.llm.prepareCall(proposedConfig, signal)
config = preparedCall.config
} catch (error: unknown) {
// Middleware may serve an unregistered route; terminal dispatch still requires an adapter.
if (!(error instanceof LlmError) || error.code !== 'NO_ADAPTER') throw error
config = proposedConfig
}
signal.throwIfAborted()
return { config, ...preparedCall === undefined ? {} : { preparedCall } }
}
/** Log the resolved envelope and derive a frozen request from the admitted surface. */
private buildRequest(
config: LlmCallConfig,
preparedCall: PreparedLlmCall | undefined,
tools: GenerateOptions['tools'] & object,
position: { turn: number; step: number },
startsRequestSeries: boolean,
signal: AbortSignal,
): GenerateOptions {
const { session } = this
const surfaceGeneration = session.surface.contentGeneration
const header = canonicalHeader({
config,
...preparedCall === undefined ? {} : { adapterDefaults: preparedCall.adapterDefaults },
...tools.length > 0 ? { tools } : {},
})
const baseline = this.session.requestHeader()
const startsSeries = startsRequestSeries
|| this.requestSurfaceGeneration !== surfaceGeneration
let headerSeq: SessionSeq | undefined
if (!this.requestHeaderLogged) {
// Compaction during the first resumed pre-step must still mark a new series.
headerSeq = this.session.append('request/header', {
header,
reason: baseline === undefined ? 'initial' : 'resume',
...startsSeries ? { startsSeries: true } : {},
}).seq
this.requestHeaderLogged = true
} else if (baseline === undefined || !headerEquals(baseline, header)) {
headerSeq = this.session.append('request/header', {
header,
reason: 'change',
...startsSeries ? { startsSeries: true } : {},
}).seq
} else if (startsSeries) {
this.session.append('request/header', { header, reason: 'series' })
}
if (baseline !== undefined && headerSeq !== undefined) {
const previousNames = new Set(baseline.tools?.map(tool => tool.name))
const currentNames = new Set(tools.map(tool => tool.name))
const additions = tools.filter(tool => !previousNames.has(tool.name))
.map(tool => ({ type: 'tool-addition' as const, toolName: tool.name }))
const removals = (baseline.tools ?? []).filter(tool => !currentNames.has(tool.name))
.map(tool => ({ type: 'tool-removal' as const, toolName: tool.name }))
if (additions.length > 0 || removals.length > 0) {
session.append('developer/message', {
...position,
message: createDeveloperMessage({ source: { kind: 'tool-registry' }, content: [...additions, ...removals] }),
...additions.length > 0 ? { headerSeq } : {},
}, { surfaceOp: 'append' })
}
}
this.requestSurfaceGeneration = surfaceGeneration
const contextWindow = preparedCall?.context?.contextWindow
const systemPromptUpdate = preparedCall?.systemPromptUpdate
const requestContext: RequestContext = {
provider: config.provider,
model: config.model,
...contextWindow === undefined ? {} : { contextWindow },
...systemPromptUpdate === undefined ? {} : { systemPromptUpdate },
}
const previousContext = session.requestContext()
if (previousContext?.provider !== requestContext.provider
|| previousContext.model !== requestContext.model
|| previousContext.contextWindow !== requestContext.contextWindow
|| previousContext.systemPromptUpdate !== requestContext.systemPromptUpdate) {
session.append('request/context', requestContext)
}
signal.throwIfAborted()
// canonicalHeader is shallow; append logs a detached snapshot, not these local values.
deepFreeze(header)
const boundaryMessages = session.deriveMessages()
for (const message of boundaryMessages) {
if (this.frozenMessages.has(message)) continue
deepFreeze(message)
this.frozenMessages.add(message)
}
Object.freeze(boundaryMessages)
const request = markAgentLoopRequest(Object.freeze({
...header.config,
messages: boundaryMessages,
toolHistory: session.toolHistory(),
...header.tools !== undefined ? { tools: header.tools } : {},
sessionId: this.session.id,
signal,
}))
return request
}
}