UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

299 lines (298 loc) • 22 kB
/** * First-party agent loop (design/118 ④a — de-vendoring 4/6). * * Rewritten from the vendored openclaw distillation with the loop's control flow made EXPLICIT as a * state machine (the CC query.ts State/transition shape, sema deps injected): every "go around again" * is a named {@link LoopContinue} and every exit is a named {@link LoopTerminal}, so tests can assert * WHICH path ran (test/loop-transitions.test.ts) instead of inferring it from event order. ④a is * behavior-1:1 with the vendored loop — no new recovery chains; those land in ④b as new Continue * reasons on this skeleton. * * Load-bearing invariants carried over verbatim (the VENDORED EDIT provenance comments are kept at * their sites as history): * - A-1 layer ② abort-before-stream guard (a mid-batch abort must never reach the next provider * request) — {@link runSingleTurn} entry guard, Terminal `aborted_before_stream`. * - Durable double-execution gate (a deferred parallel tool closure must never run its side effect * after a mid-batch suspend/abort) — {@link executePreparedToolCall} entry guard. * - D4 post-hook posture (afterToolCall throw must not rewrite a committed side effect into a flat * failure) — {@link finalizeExecutedToolCall}. * - The TWO queue drain points (1.204 priority wiring基石): steer drains at every turn end * (Continue `steer_injected` / mid-work boundary), followUp drains only when the agent would * otherwise stop (Continue `follow_up_injected`). Never merge these into one queue. * - text_delta.partial reconstruction (upstream cherry-pick 6fcc945702). */ import type { AssistantMessage, Context, ToolResultMessage } from "../llm/index.js"; import { type AgentCoreStreamRuntimeDeps } from "./runtime-deps.js"; import type { AfterToolCallResult, AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, AgentTool, AgentToolCall, AgentToolResult, HaltRemainingDirective, StreamFn, TurnCutSettlement } from "./types.js"; /** Callback used by synchronous loop runners to publish agent lifecycle events. */ export type AgentEventSink = (event: AgentEvent) => Promise<void> | void; /** Named reasons the loop goes around again. Assertable in tests via the trace sink. */ export type LoopContinueReason = /** A turn finished with executable tool calls (or injected messages) still driving work. */ "next_turn" /** Drain point A (mid-work boundary): steering messages were injected after a turn. */ | "steer_injected" /** Drain point B (agent would otherwise stop): follow-up messages were injected. */ | "follow_up_injected" /** ④b recovery: a prompt-too-long failure was recovered (compacted context) and retried in-turn. */ | "reactive_compact_retry" /** The provider refused an image; the request view removed it and the turn was re-sent in-turn. */ | "image_refusal_retry" /** The provider refused one tool's input schema; the tool view emptied it and the turn was re-sent in-turn. */ | "tool_schema_refusal_retry" /** The provider refused the request over its media blocks; the run's media-item limit was lowered a rung and the turn * was re-sent in-turn, trimmed to it. */ | "media_items_refusal_retry" /** ④b recovery: a `length`-stopped answer triggered a synthetic continue nudge for another turn. */ | "max_output_tokens_recovery" /** S2 recovery (design/119): a `toolUse` stop with ZERO parseable tool calls got a retry nudge. (With a message already * pending the turn is counted all the same, and the step is that message's `steer_injected`.) */ | "malformed_tool_use_retry" /** S2 recovery (design/119): a thinking-only turn (no visible text, no tools) got a retry nudge. */ | "thinking_only_retry" /** design/124 tier A: a partially-finalized "stop" (mid-stream cut promoted to content) got a * bounded continue nudge so an unattended run doesn't book the cut as an incomplete success. */ | "midstream_partial_recovery" /** T1-4 recovery: a degenerate-repetition cutoff got a bounded "different approach" continue. */ | "degenerate_output_recovery"; /** Named reasons the loop exits. Assertable in tests via the trace sink. */ export type LoopTerminalReason = /** Natural end: no tool calls, no steering, no follow-ups. */ "completed" /** A-1 layer ② guard: the abort signal was already set before the next provider request. */ | "aborted_before_stream" /** The assistant message itself ended with stopReason "error" or "aborted". */ | "assistant_error" /** A clean stop was requested at a turn boundary (mod #16 one-shot): `shouldStopAfterTurn` * answered true after a turn, or — #504's pre-turn half — `shouldHaltBeforeTurn` refused to * start the next one. One reason for both consult points: the fact reported is the same (the * loop ended cleanly at a manufactured boundary, no reconcile owed), and which consult caught * it is timing, not semantics. */ | "stop_requested" /** RB-206 (the reference buckets it * with budget_exhausted/api_error/model_error/turn_setup_failed, explicitly NOT `"completed"`): every * tool call in the turn was dropped as malformed AND the bounded `malformed_tool_use_retry` nudge * budget is used up — the model believes it acted, nothing ran, and there is no more recovery budget * left to try again. Before this reason existed, this case fell through to the generic no-more-work * path and was reported as a plain `"completed"`, indistinguishable from a turn that genuinely had * nothing left to do. A Runner run reads this exit (and `truncated_output_exhausted`) as a `failed` * terminal: `model.malformed_tool_use_exhausted` / `model.truncated_output_exhausted`. * * The same word also ends a streak of turns whose every call named a tool the turn's roster does not * mount (each answered `tool.not_found`) — its own count under the same budget, and only while they miss * the same names: a miss under other names starts that streak over, so a model guessing its way to the * right tool is never cut. That arm is this engine's own (the reference answers every miss and stops only * at a turn cap). * * `malformedToolUseRetries` 数的是没带出调用的轮(调用全被丢、或报了工具停却一只没带)被重问的次数:只有两件事清零 —— * 这一轮里有一只工具调用真的执行了(不论成败),或人的新输入(见段末);被拒(门 / 人在卡上)、叫了名册里没有的工具的轮 * 既不清零也不加一。与上游「重试至多两次、成功即复位」同形——"exhausted" 说的是"这一串里第 maxRetries + 1 次没带出调用", * 不是"这个 run 总共累计过多少次畸形"。早先已恢复成功的畸形调用不再占用后来的预算。叫错名字的那一串另记一只数 * (`missedToolRetries`),规则如上段;人的新输入(送到模型,或在判点上等着送)对两只数都清零。 */ | "malformed_tool_use_exhausted" /** RB-258(RB-206 口径追查的衍生发现;RB-206 的同族对仗):the model kept ending its turn on the * provider's output cap (`length`) with no tool calls, and the bounded truncated-output continue * budget (`recovery.truncatedOutput.maxContinues`, default 3) is used up — every further nudge would * buy another cut-off fragment. Before this reason existed, this case fell through to the generic * no-more-work path and was reported as a plain `"completed"`, indistinguishable from an answer that * actually finished — the same defect RB-206 fixed in the malformed lane, on the shape production * hits MORE often (1/89 real questions reached the precondition). * * Scope notes (deliberate, mirroring the malformed lane): * - Only the CONFIGURED lane reports it. With `recovery.truncatedOutput` absent (the loop default * is OFF) there is no budget to exhaust, so a `length` stop still ends as a plain `completed` — * the pre-④b behavior, unchanged. * - `truncatedOutputContinues` counts CONSECUTIVE nudges and RESETS on any non-`length` turn (as * `malformedToolUseRetries` resets on a turn in which a call ran). So this reason means "the model * just ended `length` maxContinues+1 times in a row", not "this run has burnt N recoveries in total". * - Like every other terminal, it stops the loop BEFORE drain point B — a follow-up queue / Stop-hook * continuation no longer gets consulted on this path. That is the point (a stop-gate rescue would * re-enter the same wall with a spent budget), and queued follow-ups stay queued for the next * `prompt()` rather than being dropped. */ | "truncated_output_exhausted"; export type LoopStep = { kind: "continue"; reason: LoopContinueReason; } | { kind: "terminal"; reason: LoopTerminalReason; }; /** * Optional per-transition observer, for tests that assert WHICH path ran. * Attribution notes: `reactive_compact_retry` is traced IN-TURN at each retry (a turn may trace * several); the turn's boundary then traces at most ONE more Continue by priority — a recovery * reason (`max_output_tokens_recovery` / `midstream_partial_recovery` / `malformed_tool_use_retry` / * `thinking_only_retry`, mutually exclusive by stopReason/flag) wins, then `steer_injected` (masking the same turn's * `next_turn`), then `next_turn`. Don't read the trace as a complete enumeration of concurrent causes. */ export type LoopTraceSink = (step: LoopStep) => void; /** * A request to settle the transcript's trailing UNANSWERED tool batch before the prompts are delivered * (a resumed run whose suspended batch still holds calls no tool result answers). The batch is settled * as ONE turn of the loop: the live batch pipeline under a turn-scoped interrupt seat, the interrupted- * turn settlement when that seat is cut, then the ordinary turn boundary (`prepareNextTurn` + the stop * consult). `halt` settles every call as not-executed instead (the batch-halt form). `report` receives * the outcome once; `aborted` means the run ENDED before the prompts were delivered (the run signal * fired, or the boundary / the interrupt settlement stopped the run). */ export interface TrailingToolBatchSettlement { halt?: HaltRemainingDirective; report: (outcome: { assistantMessage: AssistantMessage; settled: number; aborted: boolean; }) => void; } /** A prompt run's seam beyond its prompts (the trailing-batch settlement); a prompt is delivered at its `message_end`. */ export interface RunAgentLoopSeams { settle?: TrailingToolBatchSettlement; /** The prompts RECORD a turn a person's bare refusal ended: they owe no model turn (a drain point's queued input still continues the run). */ endsAwaitingUser?: true; /** The answer to the turn the prompts open is already given ({@link GivenAnswer}): that turn calls no model. */ givenAnswer?: Omit<GivenAnswer, "input">; /** The prompt's own message when its text is declared not to be the turn's input: it is delivered with the prompts and owes * no turn of its own — it rides the first request the queued input opens. */ ridingPrompt?: AgentMessage; } /** An answer given before the model was asked — an extension's `{ reply }` to an input. The turn the input opens is answered * with it in place of a model request: its assistant row is this text, stamped `answeredBy`, with a known-zero usage; * everything after the row (the turn's end, the boundary, the drains) is the ordinary turn's. `input` is the message the * answer answers when the turn itself delivers it (a follow-up drained alone); absent when the input is already in the * transcript (the prompts). */ export interface GivenAnswer { readonly text: string; readonly by: string; readonly input?: AgentMessage; } /** The last assistant message of `messages` when at least one of its tool calls has no tool result after it. */ export declare function findUnansweredToolBatch(messages: readonly AgentMessage[]): AssistantMessage | undefined; /** * Settle the unanswered tool calls of `assistantMessage` (the batch tail a suspended run left open): * ONE pipeline with the live turn — the same partition, concurrency cap, preflight gate (a call may * suspend again), execution and source-ordered result commit — or, under `halt`, the same not-executed * settlement a batch-halt directive applies to never-started siblings. Every unanswered call gets a * tool result unless the signal fires mid-batch (the dangling remainder is the suspended batch's own shape). */ export declare function settleUnansweredToolCalls(context: AgentContext, assistantMessage: AssistantMessage, config: AgentLoopConfig, signal: AbortSignal | undefined, emit: AgentEventSink, halt?: HaltRemainingDirective): Promise<ExecutedToolCallBatch>; /** Run a prompt-started loop and emit events through a caller-owned sink. `prompts` may be a thunk: it is * taken only when the prompts are about to be delivered, so a caller whose prompt assembly CONSUMES queued * input (a harness draining its next-turn queue) loses nothing when a trailing-batch settlement ends the run first. */ export declare function runAgentLoop(prompts: AgentMessage[] | (() => Promise<AgentMessage[]>), context: AgentContext, config: AgentLoopConfig, emit: AgentEventSink, signal?: AbortSignal, streamFn?: StreamFn, runtime?: AgentCoreStreamRuntimeDeps, trace?: LoopTraceSink, seams?: RunAgentLoopSeams): Promise<AgentMessage[]>; /** design/373 S1 — the paired result closing a tool call a TURN interrupt kept from starting. Every * such call provably never began (a call whose preflight ran settles with its own committed result * — the guard arms — so "unanswered" ⇔ "no start frame, no preparation"): stating that is honest * AND actionable, where the outcome-unknown wording would force a needless verify detour. Static * string (prefix-cache stability, the session-reconcile family's own discipline). */ export declare const TURN_INTERRUPTED_TOOL_TEXT: string; /** The never-started call's text when an extension ended the turn (the reference's own sentence for that cut): nobody * refused the call, and the model is told so. */ export declare const TURN_ENDED_TOOL_TEXT = "[Tool call did not complete: the turn was ended to deliver the message that follows. Nothing refused it; re-run it if still needed.]"; /** The loop's own settlement row — a cut the host answers no row for (a raw loop, a seat cut by no named source): the * user interrupt's text, the marker, and a running command ended with its call. */ export declare const INTERRUPT_TURN_CUT_SETTLEMENT: TurnCutSettlement; /** * The request context a turn of this loop sends for messages already converted for the provider: the context's prompt face * and its tool view. One assembly for the loop's own call and for a rendering of the request the loop is about to send * (`AgentHarness.requestOf`), so the two cannot differ. */ export declare function llmRequestContext(context: AgentContext, llmMessages: Context["messages"]): Context; /** The request controls a turn's call carries (read from the same members the call spreads): the thinking tier, the output * cap (the per-call cap when the host shrinks it), and the requester's try-undeclared posture. */ export declare function loopRequestControls(config: AgentLoopConfig): { reasoning?: AgentLoopConfig["reasoning"]; maxTokens?: number; tryUndeclared: true; }; type ExecutedToolCallBatch = { messages: ToolResultMessage[]; terminate: boolean; /** Some call of the batch ran: its body started and gave the call's result, whatever that result says (a tool that ran and * failed ran). A call settled before its body started — refused at the gate, missing, its arguments rejected, halted, or * aborted or settled unstarted by the execution seat (`notExecuted`) — did not. */ ran: boolean; }; /** * ONE call through the loop's per-call pipeline — announced, prepared (the gate included), executed through the execution * seat, finalized, closed. The sequential lane runs each call through it and adds the call's tool-result message; a host's * own call (`AgentHarness.callTool`) runs it with no model message and adds nothing. The partitioned lane runs the same steps in * two phases. */ export declare function runToolCall(currentContext: AgentContext, assistantMessage: AssistantMessage | undefined, toolCall: AgentToolCall, config: AgentLoopConfig, signal: AbortSignal | undefined, emit: AgentEventSink): Promise<{ finalized: FinalizedToolCallOutcome; halt?: HaltRemainingDirective; ran: boolean; }>; /** * Partition rule: a call is batch-safe ONLY if its arguments * VALIDATE against the tool's schema (CC `safeParse` — a malformed call never rides a parallel batch; * it stays a singleton and surfaces its validation error at execution) AND the tool/hook opts in. * The hook sees the validated+coerced args — same as CC handing `parsed.data` to `isConcurrencySafe`. */ export declare function isBatchSafeToolCall(tool: AgentTool | undefined, toolCall: AgentToolCall): boolean; /** An executed call's raw outcome, before (and, from {@link finalizeToolOutcome}, after) the post-execution half. */ export type ExecutedToolCallOutcome = { result: AgentToolResult<unknown>; isError: boolean; /** Present (`true`) exactly when the call's body never started: the run was aborted between the gate and the body, or the host's * execution station ({@link AgentLoopConfig.executeTool}) settled the call without running it. Rides the end event as * `notExecuted`, like {@link ImmediateToolCallOutcome.notExecuted}. */ notExecuted?: true; }; type FinalizedToolCallOutcome = { toolCall: AgentToolCall; result: AgentToolResult<unknown>; isError: boolean; /** The loop's own mark that the call settled without its body starting (see {@link ImmediateToolCallOutcome.notExecuted}); rides the end event. */ notExecuted?: true; }; /** * THE reading a value gets on its way to becoming a call's arguments: the tool's own preparation (`prepareArguments` — * a default filled in, an alias folded), then the schema's coercions ({@link validateToolArguments}). The loop reads the * model's call through it before the gate, hands the same reading to the gate (`BeforeToolCallContext.readArguments`) * so every rewrite is judged as it will run, and reads the gate's output through the same two steps once more — refusing * an output they would move. A preparation that throws throws here too (the value cannot be read: whoever adopts it * refuses it, as the loop refuses a model call whose preparation throws). A value that does not VALIDATE is handed back as * given: nothing invalid runs (the loop's own reading of the gate's output throws on it), and a judge of it judges bytes * that never execute. */ export declare function readToolCallArguments(tool: AgentTool, toolCall: AgentToolCall, args: unknown): unknown; /** * How many tool names an unknown-tool miss spells out. A miss is a NAME problem: seeing a couple of dozen * real names is what lets a model spot the one it meant, while a full listing grows with the deployment * (a large roster turned every typo into a multi-kilobyte result) and buys no extra recovery. */ export declare const ROSTER_LISTING_MAX = 25; /** * The disclosure-search tool's wire name, kept as a literal here because this module is in the engine * layer and must not import the runner's tool definitions. A unit test asserts it equals the exported * `TOOL_SEARCH_NAME`, so the two cannot silently diverge (the `BRAIN_FLAT_CODES` arrangement in * core/tool-errors.ts, same reason). */ export declare const ROSTER_SEARCH_HINT_NAME = "ToolSearch"; /** The structured `details.code` of a tool result minted by an input pre-validation refusal (lifted onto * the wire frame's `errorCode` like every other loop-minted code, e.g. `tool.not_found`). */ export declare const TOOL_VALIDATION_REFUSED_CODE = "tool.validation_refused"; /** How long an asynchronous `validateInput` may take to answer before it is read as "no verdict" (and * reported on the fault seat): a validator is a precondition read, not a network call, so a single * bound serves every tool; a deployment validator that needs longer is a validator doing too much. */ export declare const TOOL_INPUT_VALIDATION_TIMEOUT_MS = 10000; /** * The post-execution half EVERY executed tool call passes through — the loop's own calls here, and a call * the harness executed outside a turn (a resumed approved call, `AgentHarness.finalizeToolCall`) through the * same function, so the two cannot drift into two dialects of one finalization: the `afterToolCall` patch * (content / details / terminate / isError), the D4 posture on a throwing hook, the delivery mark, and last * the media admission — the tool-result seat every supply of media reaches after the last hand that can change * it (`toolResultMediaBlocks`, then `admitToolResultMediaBlocks` with the run's image processor `media.imageProcessor`, * resolved only once a block claims media): a refused block becomes its text placeholder in the result (one refused for * its size has its bytes kept in the run's tool-result store, `media.toolResultBytes`, and the placeholder names the ref — * or says why they were not kept), `media.onToolMediaRefused` hears the call's refusals once, and `media.onImageUnprocessed` hears an image that goes on * unprocessed over the soft target. `after` absent and no media ⇒ the executed outcome stands as is (same object), with * nothing awaited. */ export declare function finalizeToolOutcome<C extends { id: string; name: string; }>(toolCall: C, executed: ExecutedToolCallOutcome, after: ((result: AgentToolResult<unknown>, isError: boolean) => Promise<AfterToolCallResult | undefined>) | undefined, media?: Pick<AgentLoopConfig, "imageProcessor" | "onToolMediaRefused" | "onImageUnprocessed" | "toolResultBytes">): Promise<ExecutedToolCallOutcome & { toolCall: C; }>; export {};