UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

1,860 lines • 79.9 kB
import { changedFilesNoticesOf, createAssistantMessageEventStream, ensureToolTurnInvariants, findToolByName, snapshotActorAssertion, stripEngineMetadata, userAttachmentOf } from "../llm/index.js";
import { imageRefusalAt, isImageRefusal, removeRefusedRequestParts } from "../llm/rejected-images.js";
import { finalizeToolOutcome, findUnansweredToolBatch, isBatchSafeToolCall, llmRequestContext, loopRequestControls, runAgentLoop, runToolCall, TURN_ENDED_TOOL_TEXT, TURN_INTERRUPTED_TOOL_TEXT } from "../loop/agent-loop.js";
import { resolveAgentCoreStreamFn } from "../loop/runtime-deps.js";
import { normalizeEngineSegments } from "../../core/untrusted-text.js";
import { isCredentialHeaderName } from "../../core/secret-env.js";
import { isRunOrigin } from "../../core/run-origin.js";
import { readBundledAttachments } from "../../core/attachment-source.js";
import { countsAsOperator, isBlankInput, judgedAuthorOf, readInputAuthor } from "../../core/input-author.js";
import { personInputRow, stampLegFirstInput } from "../../core/user-row-origin.js";
import { isProviderEchoShape } from "../../brain/errors.js";
import { askPerModelAuth, PerModelAuthRefusal } from "../../brain/route-adjudicator.js";
import { convertToLlm } from "./messages.js";
import { readMember, thrownText } from "../../core/thrown-value.js";
import { remoteWords } from "../../core/protocol-http-auth.js";
import { AgentHarnessError, CompactionError, NothingQueuedError, SessionError, SYNTHETIC_MESSAGE_MODEL, toError, } from "./types.js";
const API_FAILURE_RECORD_MAX_CHARS = 2000;
const API_FAILURE_RECORD_ERROR_KINDS = Object.freeze({
    length_empty: "plain",
    degenerate: "plain",
    input_too_long: "plain",
    image_unprocessable: "plain",
    tool_schema_refused: "with_refused_tool",
    output_cap_too_large: "plain",
    media_items_refused: "plain",
});
function admittedApiFailureErrorKind(errorKind, refusedTool) {
    if (typeof errorKind !== "string" || !Object.hasOwn(API_FAILURE_RECORD_ERROR_KINDS, errorKind))
        return {};
    const kind = errorKind;
    if (API_FAILURE_RECORD_ERROR_KINDS[kind] === "plain")
        return { errorKind: kind };
    return typeof refusedTool === "string" ? { errorKind: kind, refusedTool } : {};
}
const TURN_CUT_SETTLEMENTS = Object.freeze({
    halt: Object.freeze({ neverStartedText: TURN_INTERRUPTED_TOOL_TEXT, marker: true, movesArmedCommandAside: false }),
    steer: Object.freeze({ neverStartedText: TURN_INTERRUPTED_TOOL_TEXT, marker: false, movesArmedCommandAside: false }),
    extension: Object.freeze({ neverStartedText: TURN_ENDED_TOOL_TEXT, marker: false, movesArmedCommandAside: true }),
});
function createUserMessage(text, images, provenance) {
    const content = text.length > 0 ? [{ type: "text", text }] : [];
    if (images) {
        content.push(...images);
    }
    const engineNote = provenance?.provenance === "engine-note";
    const segments = normalizeEngineSegments(text, provenance?.engineSegments);
    const message = {
        role: "user",
        content,
        timestamp: Date.now(),
        ...(segments.state === "valid" ? { engineSegments: segments.segments } : {}),
        ...(segments.state === "absent" &&
            provenance?.enginePrefixChars !== undefined &&
            Number.isInteger(provenance.enginePrefixChars) &&
            provenance.enginePrefixChars > 0 &&
            provenance.enginePrefixChars <= text.length
            ? { enginePrefixChars: provenance.enginePrefixChars }
            : {}),
        ...(provenance?.engineMinted === true && !engineNote ? { engineMinted: true } : {}),
        ...((bundled) => (provenance?.engineMinted === true && !engineNote && bundled !== undefined ? { attachments: bundled } : {}))(readBundledAttachments(provenance?.attachments, text.length)),
        ...(engineNote ? { provenance: "engine-note" } : {}),
        ...(engineNote && typeof provenance?.engineNoteKey === "string" && provenance.engineNoteKey.length > 0 ? { engineNoteKey: provenance.engineNoteKey } : {}),
        ...(provenance?.actor !== undefined &&
            typeof provenance.actor.id === "string" &&
            provenance.actor.id.length > 0 &&
            typeof provenance.actor.hostAsserted === "boolean"
            ? { actor: snapshotActorAssertion(provenance.actor) }
            : {}),
        ...((runOrigin) => (isRunOrigin(runOrigin) ? { runOrigin } : {}))(provenance?.runOrigin),
    };
    const notices = changedFilesNoticesOf({ role: "user", content, changedFilesNotices: provenance?.changedFilesNotices });
    if (notices !== undefined)
        message.changedFilesNotices = notices;
    if (provenance?.input !== undefined)
        Object.assign(message, personInputRow(provenance.input.inputId));
    return message;
}
export function turnContextOptions(model) {
    const windowTokens = model.contextTokens ?? model.contextWindow;
    return {
        ...(typeof windowTokens === "number" && windowTokens > 0 ? { windowTokens } : {}),
        ...(model.charsPerToken !== undefined ? { charsPerToken: model.charsPerToken } : {}),
    };
}
function createTrailingMessage(seed) {
    return { role: "user", content: [...seed.content], timestamp: Date.now(), provenance: "engine-note", attachment: seed.attachment };
}
const engineNotePayloads = new WeakMap();
const engineNoteTiers = new WeakMap();
function releaseEngineNote(m) {
    engineNotePayloads.delete(m);
    engineNoteTiers.delete(m);
}
const engineAuthoredInjections = new WeakSet();
const inputAuthors = new WeakMap();
function isOperatorInput(m) {
    return !engineAuthoredInjections.has(m) && countsAsOperator(readInputAuthor(inputAuthors.get(m)));
}
function inputClassOf(m) {
    return engineNotePayloads.has(m) ? "notification" : judgedAuthorOf(readInputAuthor(inputAuthors.get(m)));
}
function isEngineAdvisory(m) {
    return engineAuthoredInjections.has(m) && !engineNotePayloads.has(m);
}
const userInputParkRecords = new WeakMap();
const givenAnswerFrames = new WeakMap();
const drainedFromLane = new WeakMap();
const immediateClassInjections = new WeakSet();
const capPreferredInjections = new WeakSet();
function isEngineAuthoredInjection(options) {
    if (options === undefined)
        return false;
    if (options.engineMinted === true || options.enginePayload !== undefined)
        return true;
    return options.provenance === "engine-note" && options.author === undefined;
}
const ENGINE_NOTE_STEER_BACKLOG_CAP = 50;
function createFailureMessage(model, error, aborted) {
    return {
        role: "assistant",
        content: [{ type: "text", text: "" }],
        api: model.api,
        provider: model.provider,
        model: model.id,
        stopReason: aborted ? "aborted" : "error",
        errorMessage: remoteWords(thrownText(error), []),
        timestamp: Date.now(),
        usage: {
            input: 0,
            output: 0,
            cacheRead: 0,
            cacheWrite: 0,
            totalTokens: 0,
            cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
        },
    };
}
function cloneStreamOptions(streamOptions) {
    return {
        ...streamOptions,
        headers: streamOptions?.headers ? { ...streamOptions.headers } : undefined,
        metadata: streamOptions?.metadata ? { ...streamOptions.metadata } : undefined,
    };
}
function mergeHeaders(...headers) {
    const merged = {};
    let hasHeaders = false;
    for (const entry of headers) {
        if (!entry) {
            continue;
        }
        Object.assign(merged, entry);
        hasHeaders = true;
    }
    return hasHeaders ? merged : undefined;
}
function dropAuthCarriers(bag) {
    if (!bag)
        return bag;
    const out = {};
    for (const [k, v] of Object.entries(bag)) {
        if (!isCredentialHeaderName(k))
            out[k] = v;
    }
    return out;
}
function credentialHeaderEntries(bag) {
    const out = new Map();
    for (const [k, v] of Object.entries(bag ?? {}))
        if (isCredentialHeaderName(k))
            out.set(k, v);
    return out;
}
function refuseRewrittenDeclaredCredential(modelId, answered, sent) {
    const before = credentialHeaderEntries(answered);
    const after = credentialHeaderEntries(sent);
    const changed = [...new Set([...before.keys(), ...after.keys()])].filter((name) => before.get(name) !== after.get(name)).sort();
    if (changed.length === 0)
        return;
    throw new PerModelAuthRefusal(`per-model auth for model "${modelId}": the answer names the origin its credential is for (credentialOrigin), and a ` +
        `provider-request hook changed the credential header(s) ${changed.map((n) => `"${n}"`).join(", ")} beside it — the request ` +
        `is refused and nothing is sent; a credential whose answer names its origin goes out as the answer handed it`);
}
function refuseAuthCarriersInStreamOptions(bag) {
    if (!bag)
        return;
    for (const k of Object.keys(bag)) {
        if (isCredentialHeaderName(k)) {
            throw new Error(`streamOptions.headers must not carry an auth header ("${k}") — the run-static bag is not an auth channel ` +
                `(the route pairing law reads options-borne carriers as per-model credentials, which a run-wide bag is not). ` +
                `Put a deployment credential on the brain config (apiKey / headers, where its URL half is judged), or serve ` +
                `per-model credentials through getApiKeyAndHeaders.`);
        }
    }
}
function applyStreamOptionsPatch(base, patch) {
    const result = cloneStreamOptions(base);
    if (!patch) {
        return result;
    }
    if (Object.hasOwn(patch, "transport")) {
        result.transport = patch.transport;
    }
    if (Object.hasOwn(patch, "timeoutMs")) {
        result.timeoutMs = patch.timeoutMs;
    }
    if (Object.hasOwn(patch, "maxRetries")) {
        result.maxRetries = patch.maxRetries;
    }
    if (Object.hasOwn(patch, "maxRetryDelayMs")) {
        result.maxRetryDelayMs = patch.maxRetryDelayMs;
    }
    if (Object.hasOwn(patch, "headers")) {
        if (patch.headers === undefined) {
            result.headers = undefined;
        }
        else {
            const headers = { ...result.headers };
            for (const [key, value] of Object.entries(patch.headers)) {
                if (value === undefined) {
                    delete headers[key];
                }
                else {
                    headers[key] = value;
                }
            }
            result.headers = Object.keys(headers).length > 0 ? headers : undefined;
        }
    }
    if (Object.hasOwn(patch, "metadata")) {
        if (patch.metadata === undefined) {
            result.metadata = undefined;
        }
        else {
            const metadata = { ...result.metadata };
            for (const [key, value] of Object.entries(patch.metadata)) {
                if (value === undefined) {
                    delete metadata[key];
                }
                else {
                    metadata[key] = value;
                }
            }
            result.metadata = Object.keys(metadata).length > 0 ? metadata : undefined;
        }
    }
    return result;
}
const SUBSCRIBER_EVENT_TYPE = "*";
function normalizeHarnessError(error, fallbackCode) {
    if (error instanceof AgentHarnessError) {
        return error;
    }
    const cause = toError(error);
    if (cause instanceof SessionError) {
        return new AgentHarnessError("session", cause.message, cause);
    }
    if (cause instanceof CompactionError) {
        return new AgentHarnessError("compaction", cause.message, cause);
    }
    return new AgentHarnessError(fallbackCode, cause.message, cause);
}
function normalizeHookError(error) {
    return normalizeHarnessError(error, "hook");
}
const PORT_PARKED_REFUSAL = "$.session.append: refused: the leg parked durably — the conversation it resumes is its checkpoint's";
const PORT_CLOSED_REFUSAL = {
    committed: PORT_PARKED_REFUSAL,
    indeterminate: PORT_PARKED_REFUSAL,
    superseded: "$.session.append: refused: the leg stopped — its run's grant is no longer current, so nothing more is written for it (no checkpoint was written)",
};
export class AgentHarness {
    env;
    session;
    phase = "idle";
    get acceptsInjections() {
        return this.takingInput && !this.aborting && !this.stopRequested;
    }
    get takingInput() {
        return this.phase !== "idle";
    }
    stopRequestSources = new Set();
    get stopRequested() {
        return this.stopRequestSources.size > 0;
    }
    boundaryStopConsumed;
    lastPublishedSeat;
    seatCuts = new WeakMap();
    endedOnPriorAnswer = false;
    promptReceipt;
    turnCutConsumed;
    turnOpenedAt = 0;
    acceptedCuts = [];
    consumedCuts = new Set();
    committedEntryIds = new WeakMap();
    answerSources = new WeakMap();
    aborting = false;
    drainedPendingInjection = [];
    runAbortController;
    runPromise;
    pendingSessionWrites = [];
    parkCaptureInFlight;
    parkedPortClosed;
    model;
    modelRef;
    thinkingLevel;
    onUndrainedEngineNotes;
    onToolTurnRepaired;
    projectRequestCopies;
    onImagesRemoved;
    onToolSchemaRefused;
    mediaItemLimit;
    priorImageRefusals;
    runHistory;
    onUndrainedUserInputs;
    onUndrainedOtherInputs;
    onEngineNoteConsumed;
    onUserInputConsumed;
    onFrameCommitted;
    engineInjectionsHeld;
    imageRefusalView(messages) {
        const view = removeRefusedRequestParts(messages);
        const met = view.removals.filter((r) => this.priorImageRefusals?.has(r.refusalAt) !== true);
        if (met.length > 0) {
            try {
                this.onImagesRemoved?.(met);
            }
            catch {
            }
        }
        return view.messages;
    }
    holdToolTurnLaw(messages) {
        const { messages: view, repairs } = this.toolTurnLawView(messages);
        if (repairs.length > 0) {
            try {
                this.onToolTurnRepaired?.(repairs);
            }
            catch {
            }
        }
        return view;
    }
    toolTurnLawView(messages) {
        const view = ensureToolTurnInvariants(messages, this.runHistory);
        return { messages: this.projectRequestCopies?.(view.messages, view.folds) ?? view.messages, repairs: view.repairs };
    }
    requestOf(view) {
        const run = this.activeRun;
        if (run === undefined)
            return undefined;
        const law = this.toolTurnLawView(convertToLlm(view));
        return { context: llmRequestContext(run.context(), stripEngineMetadata(law.messages)), controls: loopRequestControls(run.config), repairs: law.repairs };
    }
    recoverUndrainedEngineNotes() {
        this.sweepUndrainedEngineNotes([this.drainedPendingInjection, this.nextTurnQueue, this.steerQueue, this.followUpQueue]);
    }
    sweepUndrainedEngineNotes(queues) {
        const undrained = [];
        const tiers = [];
        for (const q of queues) {
            for (let i = 0; i < q.length; i++) {
                const payload = engineNotePayloads.get(q[i]);
                if (payload !== undefined) {
                    undrained.push(payload);
                    tiers.push(engineNoteTiers.get(q[i]));
                    q.splice(i, 1);
                    i--;
                }
            }
        }
        if (undrained.length > 0 && this.onUndrainedEngineNotes) {
            try {
                this.onUndrainedEngineNotes(undrained, tiers);
            }
            catch {
            }
        }
    }
    pendingUserInputFramesByLane() {
        const inFlight = (lane) => this.drainedPendingInjection.filter((m) => isOperatorInput(m) && drainedFromLane.get(m) === lane);
        return {
            steer: [...inFlight("steer"), ...this.steerQueue.filter((m) => isOperatorInput(m))],
            followUp: [...inFlight("followUp"), ...this.followUpQueue.filter((m) => isOperatorInput(m))],
        };
    }
    pendingUserInputsByLane() {
        const frames = this.pendingUserInputFramesByLane();
        return { steer: frames.steer.length, followUp: frames.followUp.length };
    }
    hasPendingUserInput() {
        if (this.aborting)
            return false;
        return this.pendingUserInputsByLane().steer > 0;
    }
    announceUndrainedUserInputs() {
        const counts = this.pendingUserInputsByLane();
        if ((counts.steer > 0 || counts.followUp > 0) && this.onUndrainedUserInputs) {
            try {
                const frames = this.pendingUserInputFramesByLane();
                const records = (lane) => lane.flatMap((m) => {
                    const r = userInputParkRecords.get(m);
                    return r !== undefined ? [r] : [];
                });
                this.onUndrainedUserInputs(counts, { steer: records(frames.steer), followUp: records(frames.followUp) });
            }
            catch {
            }
        }
        const others = [this.drainedPendingInjection, this.steerQueue, this.followUpQueue].flatMap((q) => q.flatMap((m) => (engineAuthoredInjections.has(m) || isOperatorInput(m) ? [] : [inputAuthors.get(m)])));
        if (others.length > 0 && this.onUndrainedOtherInputs) {
            try {
                this.onUndrainedOtherInputs(others);
            }
            catch {
            }
        }
        return counts;
    }
    systemPrompt;
    systemBlocks;
    promptLocale;
    streamOptions;
    getApiKeyAndHeaders;
    answerRefusalSeen;
    get answerRefusal() {
        return this.answerRefusalSeen;
    }
    answerRefused(err) {
        if (err instanceof PerModelAuthRefusal)
            this.answerRefusalSeen ??= err;
        return err;
    }
    runtime;
    resources;
    tools = new Map();
    activeToolNames;
    steerQueue = [];
    maxOutputTokens;
    maxOutputTokensPerCall;
    stallTimeoutsPerCall;
    fastModePerCall;
    abortResultDetails;
    heldCallResult;
    executeTool;
    admitRows;
    legInputAppended = false;
    activeRun;
    loopTrace;
    onToolInputValidationFault;
    retiredCallName;
    absentToolReason;
    toolResultMedia;
    resilience;
    maxToolConcurrency;
    followUpQueue = [];
    nextTurnQueue = [];
    loopRecovery;
    stopGate;
    turnWatch;
    turnInterruptSeat;
    handlers = new Map();
    constructor(options) {
        this.env = options.env;
        this.session = options.session;
        this.resources = options.resources ?? {};
        refuseAuthCarriersInStreamOptions(options.streamOptions?.headers);
        this.streamOptions = cloneStreamOptions(options.streamOptions);
        this.systemPrompt = options.systemPrompt;
        this.systemBlocks = options.systemBlocks;
        this.promptLocale = options.promptLocale;
        this.getApiKeyAndHeaders = options.getApiKeyAndHeaders;
        this.runtime = options.runtime;
        for (const tool of options.tools ?? []) {
            this.tools.set(tool.name, tool);
        }
        this.model = options.model;
        this.modelRef = options.modelRef ?? options.model;
        this.thinkingLevel = options.thinkingLevel;
        this.activeToolNames =
            options.activeToolNames ?? (options.tools ?? []).map((tool) => tool.name);
        this.maxOutputTokens = options.maxOutputTokens;
        this.maxOutputTokensPerCall = options.maxOutputTokensPerCall;
        this.stallTimeoutsPerCall = options.stallTimeoutsPerCall;
        this.fastModePerCall = options.fastModePerCall;
        this.abortResultDetails = options.abortResultDetails;
        this.heldCallResult = options.heldCallResult;
        this.executeTool = options.executeTool;
        this.admitRows = options.admitRows ?? (async (rows) => rows);
        this.pendingSessionWrites = (options.heldWrites ?? []).map((message) => ({ type: "message", message }));
        this.loopTrace = options.loopTrace;
        this.onToolInputValidationFault = options.onToolInputValidationFault;
        this.retiredCallName = options.retiredCallName;
        this.absentToolReason = options.absentToolReason;
        this.toolResultMedia = {
            ...(options.imageProcessor !== undefined ? { imageProcessor: options.imageProcessor } : {}),
            ...(options.onToolMediaRefused !== undefined ? { onToolMediaRefused: options.onToolMediaRefused } : {}),
            ...(options.onImageUnprocessed !== undefined ? { onImageUnprocessed: options.onImageUnprocessed } : {}),
            ...(options.toolResultBytes !== undefined ? { toolResultBytes: options.toolResultBytes } : {}),
        };
        this.resilience = options.resilience;
        this.maxToolConcurrency = options.maxToolConcurrency;
    }
    getHandlers(type) {
        return this.handlers.get(type);
    }
    async emitOwn(event, signal) {
        for (const listener of this.getHandlers(SUBSCRIBER_EVENT_TYPE) ?? []) {
            try {
                await listener(event, signal);
            }
            catch (error) {
                throw normalizeHookError(error);
            }
        }
    }
    async emitAny(event, signal) {
        for (const listener of this.getHandlers(SUBSCRIBER_EVENT_TYPE) ?? []) {
            try {
                await listener(event, signal);
            }
            catch (error) {
                throw normalizeHookError(error);
            }
        }
    }
    async emitHook(event) {
        const handlers = this.getHandlers(event.type);
        if (!handlers || handlers.size === 0) {
            return undefined;
        }
        let lastResult;
        for (const handler of handlers) {
            try {
                const result = (await handler(event));
                if (result !== undefined) {
                    lastResult = result;
                }
            }
            catch (error) {
                throw normalizeHookError(error);
            }
        }
        return lastResult;
    }
    async emitBeforeProviderRequest(model, sessionId, streamOptions) {
        const handlers = this.getHandlers("before_provider_request");
        let current = cloneStreamOptions(streamOptions);
        if (!handlers || handlers.size === 0) {
            return current;
        }
        for (const handler of handlers) {
            try {
                const result = (await handler({
                    type: "before_provider_request",
                    model,
                    sessionId,
                    streamOptions: cloneStreamOptions(current),
                }));
                if (result?.streamOptions) {
                    current = applyStreamOptionsPatch(current, result.streamOptions);
                }
            }
            catch (error) {
                throw normalizeHookError(error);
            }
        }
        return current;
    }
    async emitBeforeProviderPayload(model, payload) {
        const handlers = this.getHandlers("before_provider_payload");
        let current = payload;
        if (!handlers || handlers.size === 0) {
            return current;
        }
        for (const handler of handlers) {
            try {
                const result = (await handler({
                    type: "before_provider_payload",
                    model,
                    payload: current,
                }));
                if (result !== undefined) {
                    current = result.payload;
                }
            }
            catch (error) {
                throw normalizeHookError(error);
            }
        }
        return current;
    }
    async emitQueueUpdate() {
        await this.emitOwn({
            type: "queue_update",
            steer: [...this.steerQueue],
            followUp: [...this.followUpQueue],
            nextTurn: [...this.nextTurnQueue],
        });
    }
    startRunPromise() {
        let finish = () => { };
        this.runPromise = new Promise((resolve) => {
            finish = resolve;
        });
        return () => {
            this.runPromise = undefined;
            finish();
        };
    }
    async createTurnState() {
        const context = await this.session.buildContext(turnContextOptions(this.model));
        const resources = this.getResources();
        const sessionMetadata = await this.session.getMetadata();
        const tools = [...this.tools.values()];
        const activeTools = this.activeToolNames
            .map((name) => this.tools.get(name))
            .filter((tool) => tool !== undefined);
        let systemPrompt = "You are a helpful assistant.";
        if (typeof this.systemPrompt === "string") {
            systemPrompt = this.systemPrompt;
        }
        else if (this.systemPrompt) {
            systemPrompt = await this.systemPrompt({
                env: this.env,
                session: this.session,
                model: this.model,
                thinkingLevel: this.thinkingLevel,
                activeTools,
                resources,
            });
        }
        return {
            messages: context.messages,
            resources,
            streamOptions: cloneStreamOptions(this.streamOptions),
            sessionId: sessionMetadata.id,
            systemPrompt,
            model: this.model,
            thinkingLevel: this.thinkingLevel,
            tools,
            activeTools,
        };
    }
    createContext(turnState, systemPrompt) {
        const effectivePrompt = systemPrompt ?? turnState.systemPrompt;
        const blocksSafe = this.systemBlocks !== undefined &&
            systemPrompt === undefined &&
            typeof this.systemPrompt === "string" &&
            this.systemBlocks.map((b) => b.text).join("\n\n") === effectivePrompt;
        return {
            systemPrompt: effectivePrompt,
            ...(blocksSafe ? { systemBlocks: this.systemBlocks } : {}),
            messages: turnState.messages.slice(),
            tools: turnState.activeTools.slice(),
            ...(this.promptLocale !== undefined ? { promptLocale: this.promptLocale } : {}),
        };
    }
    createStreamFn(getTurnState) {
        return async (model, context, streamOptions) => {
            const turnState = getTurnState();
            const auth = await askPerModelAuth(this.getApiKeyAndHeaders, model, this).catch((err) => {
                throw this.answerRefused(err);
            });
            const snapshotOptions = {
                ...turnState.streamOptions,
                headers: mergeHeaders(dropAuthCarriers(turnState.streamOptions.headers), auth?.headers),
            };
            const requestOptions = await this.emitBeforeProviderRequest(model, turnState.sessionId, snapshotOptions);
            if (streamOptions?.signal?.aborted) {
                const out = createAssistantMessageEventStream();
                out.push({
                    type: "error",
                    reason: "aborted",
                    error: {
                        role: "assistant",
                        content: [{ type: "text", text: "" }],
                        api: model.api,
                        provider: model.provider,
                        model: model.id,
                        stopReason: "aborted",
                        timestamp: Date.now(),
                        usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
                        usageMissing: true,
                    },
                });
                return out;
            }
            if (auth?.credentialOrigin !== undefined) {
                try {
                    refuseRewrittenDeclaredCredential(model.id, auth.headers, requestOptions.headers);
                }
                catch (err) {
                    throw this.answerRefused(err);
                }
            }
            return resolveAgentCoreStreamFn(this.runtime)(model, context, {
                ...(auth?.apiKey !== undefined ? { apiKey: auth.apiKey } : {}),
                ...(auth?.credentialOrigin !== undefined ? { credentialOrigin: auth.credentialOrigin } : {}),
                ...(auth?.credentialOriginUnsettled === true ? { credentialOriginUnsettled: true } : {}),
                headers: requestOptions.headers,
                maxRetries: requestOptions.maxRetries,
                maxRetryDelayMs: requestOptions.maxRetryDelayMs,
                metadata: requestOptions.metadata,
                onPayload: async (payload) => await this.emitBeforeProviderPayload(model, payload),
                onResponse: async (response) => {
                    const headers = { ...response.headers };
                    await this.emitOwn({ type: "after_provider_response", status: response.status, headers }, streamOptions?.signal);
                },
                reasoning: streamOptions?.reasoning,
                maxTokens: streamOptions?.maxTokens,
                stallTimeouts: streamOptions?.stallTimeouts,
                maxTokensDynamic: streamOptions?.maxTokensDynamic,
                staticReasoningCutDowngrade: streamOptions?.staticReasoningCutDowngrade,
                reissueDroppedCalls: streamOptions?.reissueDroppedCalls,
                tryUndeclared: streamOptions?.tryUndeclared,
                resilience: streamOptions?.resilience,
                fastMode: streamOptions?.fastMode,
                signal: streamOptions?.signal,
                sessionId: turnState.sessionId,
                timeoutMs: requestOptions.timeoutMs,
                transport: requestOptions.transport,
                apiKey: auth?.apiKey,
            });
        };
    }
    isDrainable(m, continuing) {
        if (isOperatorInput(m))
            return true;
        if (this.engineInjectionsHeld?.() === true)
            return false;
        return continuing || !isEngineAdvisory(m);
    }
    async drainQueuedMessages(queue, take, continuing) {
        if (this.aborting)
            return [];
        const head = queue.findIndex((m) => this.isDrainable(m, continuing) && !isEngineAdvisory(m));
        const alone = head !== -1 && givenAnswerFrames.has(queue[head]);
        const messages = alone ? queue.splice(head, 1) : [];
        let first;
        let selecting = true;
        for (let i = 0; i < queue.length && !alone; i++) {
            const m = queue[i];
            if (!this.isDrainable(m, continuing)) {
                if (first !== undefined && take === "class" && !isEngineAdvisory(m))
                    selecting = false;
                continue;
            }
            if (!isEngineAdvisory(m)) {
                if (!selecting)
                    continue;
                if (first !== undefined && (givenAnswerFrames.has(m) || (take === "class" && inputClassOf(m) !== inputClassOf(first)))) {
                    selecting = false;
                    continue;
                }
                first ??= m;
            }
            messages.push(...queue.splice(i, 1));
            i--;
        }
        if (messages.length === 0) {
            return messages;
        }
        const lane = queue === this.steerQueue ? "steer" : queue === this.followUpQueue ? "followUp" : undefined;
        if (lane !== undefined) {
            for (const m of messages)
                drainedFromLane.set(m, lane);
            this.drainedPendingInjection.push(...messages);
        }
        try {
            await this.emitQueueUpdate();
            for (const m of messages) {
                const payload = engineNotePayloads.get(m);
                if (payload !== undefined) {
                    try {
                        this.onEngineNoteConsumed?.(payload);
                    }
                    catch {
                    }
                }
            }
            return messages;
        }
        catch (error) {
            queue.unshift(...messages);
            this.unbookInFlight(messages);
            throw normalizeHookError(error);
        }
    }
    unbookInFlight(messages) {
        if (messages.length === 0 || this.drainedPendingInjection.length === 0)
            return;
        const gone = new Set(messages);
        this.drainedPendingInjection = this.drainedPendingInjection.filter((m) => !gone.has(m));
    }
    settleInjectedFrame(message, entryId) {
        if (!this.drainedPendingInjection.includes(message))
            return;
        this.unbookInFlight([message]);
        const parkRecord = userInputParkRecords.get(message);
        userInputParkRecords.delete(message);
        if (parkRecord !== undefined) {
            try {
                this.onUserInputConsumed?.(parkRecord);
            }
            catch {
            }
        }
        if (entryId !== undefined) {
            const payload = engineNotePayloads.get(message);
            if (payload !== undefined) {
                try {
                    this.onFrameCommitted?.({ kind: "engine_note", payload }, entryId);
                }
                catch {
                }
            }
        }
        releaseEngineNote(message);
    }
    createLoopConfig(getTurnState, setTurnState, runPromptOverride) {
        const turnState = getTurnState();
        const self = this;
        return {
            model: turnState.model,
            reasoning: turnState.thinkingLevel,
            ...(this.maxOutputTokens !== undefined ? { maxTokens: this.maxOutputTokens } : {}),
            ...(this.maxOutputTokensPerCall !== undefined ? { maxTokensPerCall: this.maxOutputTokensPerCall } : {}),
            ...(this.stallTimeoutsPerCall !== undefined ? { stallTimeoutsPerCall: this.stallTimeoutsPerCall } : {}),
            ...(this.fastModePerCall !== undefined ? { fastModePerCall: this.fastModePerCall } : {}),
            ...(this.abortResultDetails !== undefined ? { abortResultDetails: this.abortResultDetails } : {}),
            ...(this.heldCallResult !== undefined ? { heldCallResult: this.heldCallResult } : {}),
            ...(this.executeTool !== undefined ? { executeTool: this.executeTool } : {}),
            ...(this.onToolInputValidationFault !== undefined ? { onToolInputValidationFault: this.onToolInputValidationFault } : {}),
            ...(this.retiredCallName !== undefined ? { retiredCallName: this.retiredCallName } : {}),
            ...(this.absentToolReason !== undefined ? { absentToolReason: this.absentToolReason } : {}),
            onToolSchemaRefused: (refusal) => this.onToolSchemaRefused?.(refusal),
            mediaItemLimit: {
                lower: () => this.mediaItemLimit?.lower() === true,
                answered: async (by) => {
                    await this.mediaItemLimit?.answered(by);
                },
            },
            ...this.toolResultMedia,
            ...(this.resilience !== undefined ? { resilience: this.resilience } : {}),
            ...(this.maxToolConcurrency !== undefined ? { maxToolConcurrency: this.maxToolConcurrency } : {}),
            convertToLlm: (messages) => stripEngineMetadata(this.holdToolTurnLaw(convertToLlm(messages))),
            shouldStopAfterTurn: () => this.consultStopLatch("post_turn"),
            shouldHaltBeforeTurn: () => this.consultStopLatch("pre_turn"),
            transformContext: async (messages, signal) => {
                const view = this.imageRefusalView(messages);
                const result = await this.emitHook({ type: "context", messages: [...view], ...(signal !== undefined ? { signal } : {}) });
                if (result?.adoptSessionRebuild !== true) {
                    const messages = result?.messages ?? view;
                    return result?.trimmedRequestTokens !== undefined ? { messages, trimmedRequestTokens: result.trimmedRequestTokens } : messages;
                }
                await this.flushPendingSessionWrites();
                const nextTurnState = await this.createTurnState();
                setTurnState(nextTurnState);
                const rebuiltContext = this.createContext(nextTurnState, runPromptOverride);
                const rebuiltView = this.imageRefusalView(rebuiltContext.messages);
                const recheck = await this.emitHook({ type: "context", messages: [...rebuiltView], ...(signal !== undefined ? { signal } : {}), recheck: true });
                return {
                    messages: recheck?.messages ?? rebuiltView,
                    ...(recheck?.trimmedRequestTokens !== undefined ? { trimmedRequestTokens: recheck.trimmedRequestTokens } : {}),
                    adoptedContext: {
                        messages: rebuiltContext.messages,
                        systemPrompt: rebuiltContext.systemPrompt,
                        ...(rebuiltContext.systemBlocks !== undefined ? { systemBlocks: rebuiltContext.systemBlocks } : {}),
                    },
                };
            },
            beforeToolCall: async ({ toolCall, args, readArguments }, signal) => {
                const result = await this.emitHook({
                    type: "tool_call",
                    toolCallId: toolCall.id,
                    toolName: toolCall.name,
                    input: args,
                    ...(signal !== undefined ? { signal } : {}),
                    ...(readArguments !== undefined ? { readArguments } : {}),
                });
                return result;
            },
            afterToolCall: ({ toolCall, args, result, isError }) => this.afterToolCallHook(toolCall, args, result, isError),
            prepareNextTurn: async ({ continues, message }) => {
                await this.flushPendingSessionWrites();
                await this.emitHook({ type: "turn_boundary", model: this.model, continues, message });
                const nextTurnState = await this.createTurnState();
                setTurnState(nextTurnState);
                return {
                    context: this.createContext(nextTurnState, runPromptOverride),
                    model: nextTurnState.model,
                    thinkingLevel: nextTurnState.thinkingLevel,
                };
            },
            getSteeringMessages: async (continuing) => this.drainQueuedMessages(this.steerQueue, "every", continuing),
            publishTurnInterruptSeat: (seat) => {
                if (seat !== undefined)
                    this.lastPublishedSeat = seat;
                this.turnInterruptSeat = seat;
            },
            noteTurnCutConsumed: (seat) => this.noteTurnCutConsumed(seat),
            noteTurnOpened: (opensAt) => {
                this.turnCutConsumed = undefined;
                this.turnOpenedAt = opensAt;
                this.turnWatch?.opened();
            },
            recheckImmediateInjections: async (pending) => this.absorbImmediateSteering(pending),
            pendingInjectionCount: () => this.pendingInjectionCount(),
            getFollowUpMessages: async () => {
                if (this.turnWatch !== undefined)
                    await this.turnWatch.ended();
                const queued = await this.drainQueuedMessages(this.followUpQueue, "class", false);
                if (queued.length > 0)
                    return queued;
                return this.stopGate ? await this.stopGate() : queued;
            },
            answerOf: (message) => givenAnswerFrames.get(message),
            recovery: {
                get truncatedOutput() {
                    return self.loopRecovery?.truncatedOutput;
                },
                get malformedToolUse() {
                    return self.loopRecovery?.malformedToolUse;
                },
                get thinkingOnly() {
                    return self.loopRecovery?.thinkingOnly;
                },
                get degenerateOutput() {
                    return self.loopRecovery?.degenerateOutput;
                },
                get promptTooLong() {
                    const ptl = self.loopRecovery?.promptTooLong;
                    if (!ptl)
                        return undefined;
                    return {
                        detect: ptl.detect,
                        maxRetries: ptl.maxRetries,
                        withholdErrorEvents: ptl.withholdErrorEvents,
                        recover: async (_messages, attempt, turnSignal, refused) => {
                            let shrank = false;
                            try {
                                shrank = await ptl.recover(attempt, turnSignal, refused);
                            }
                            catch {
                                shrank = false;
                            }
                            if (!shrank)
                                return undefined;
                            if (shrank !== true)
                                return { messages: _messages, outputCap: shrank.outputCap };
                            const nextTurnState = await self.createTurnState();
                            setTurnState(nextTurnState);
                            const rebuilt = self.createContext(nextTurnState, runPromptOverride);
                            return {
                                messages: rebuilt.messages,
                                systemPrompt: rebuilt.systemPrompt,
                                ...(rebuilt.systemBlocks !== undefined ? { systemBlocks: rebuilt.systemBlocks } : {}),
                            };
                        },
                    };
                },
            },
        };
    }
    setLoopRecovery(recovery) {
        this.loopRecovery = recovery;
    }
    setStopGate(gate) {
        this.stopGate = gate;
    }
    setTurnWatch(watch) {
        this.turnWatch = watch;
    }
    validateToolNames(toolNames, tools = this.tools) {
        const missing = toolNames.filter((name) => !tools.has(name));
        if (missing.length > 0) {
            throw new AgentHarnessError("invalid_argument", `Unknown tool(s): ${missing.join(", ")}`);
        }
    }
    async flushPendingSessionWrites() {
        if (this.runAbortController?.signal.aborted) {
            return;
        }
        for (let write = this.pendingSessionWrites[0]; write !== undefined; write = this.pendingSessionWrites[0]) {
            if (write.type === "message") {
                await this.session.appendMessage(write.message);
            }
            else if (write.type === "model_change") {
                await this.session.appendModelChange(write.provider, write.modelId);
            }
            else if (write.type === "thinking_level_change") {
                await this.session.appendThinkingLevelChange(write.thinkingLevel);
            }
            else {
                const unreachable = write;
                throw new AgentHarnessError("invalid_argument", `flushPendingSessionWrites: unhandled queued write type ${unreachable.type}`);
            }
            const at = this.pendingSessionWrites.indexOf(write);
            if (at >= 0)
                this.pendingSessionWrites.splice(at, 1);
        }
    }
    async recordApiFailure(failure) {
        const errorMessage = readMember(failure, "errorMessage");
        const apiErrorStatus = readMember(failure, "apiErrorStatus");
        const requestId = readMember(failure, "requestId");
        const errorKind = readMember(failure, "errorKind");
        const refusedTool = readMember(failure, "refusedTool");
        const raw = typeof errorMessage === "string" ? errorMessage.trim() : undefined;
        const detail = raw !== undefined && raw.length > API_FAILURE_RECORD_MAX_CHARS
            ? `${raw.slice(0, API_FAILURE_RECORD_MAX_CHARS)}… (truncated)`
            : raw;
        const record = {
            role: "assistant",
            content: [{ type: "text", text: detail ? `API Error: ${detail}` : "API Error" }],
            api: failure.api,
            provider: failure.provider,
            model: SYNTHETIC_MESSAGE_MODEL,
            isApiErrorMessage: true,
            ...(typeof apiErrorStatus === "number" ? { apiErrorStatus } : {}),
            ...(typeof requestId === "string" && isProviderEchoShape(requestId) ? { requestId } : {}),
            usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
            usageMissing: true,
            stopReason: "error",
            ...(typeof errorMessage === "string" ? { errorMessage } : {}),
            ...admittedApiFailureErrorKind(errorKind, refusedTool),
            timestamp: failure.timestamp,
        };
        try {
            await this.admitRows([record]);
            await this.session.appendMessage(record);
        }
        catch {
        }
    }
    async handleAgentEvent(event, signal) {
        if (event.type === "message_end") {
            let entryId;
            if (!isEmptyFailureAssistant(event.message)) {
                await this.admitRows([event.message]);
                if (stampLegFirstInput(event.message, !this.legInputAppended))
                    this.legInputAppended = true;
                entryId = await this.session.appendMessage(event.message);
                this.committedEntryIds.set(event.message, entryId);
                this.settleInjectedFrame(event.message, entryId);
                if (this.promptReceipt?.message === event.message) {
                    const { commit } = this.promptReceipt;
                    this.promptReceipt = undefined;
                    commit(entryId);
                }
                if (entryId !== undefined && event.message.role === "toolResult" && typeof event.message.toolCallId === "string") {
                    try {
                        this.onFrameCommitted?.({ kind: "tool_result", toolCallId: event.message.toolCallId, content: event.message.content }, entryId);
                    }
                    catch {
                    }
                }
                const attachment = entryId !== undefined ? userAttachmentOf(event.message) : undefined;
                if (attachment !== undefined) {
                    try {
                        this.onFrameCommitted?.({ kind: "attachment", inputId: attachment.inputId, ordinal: attachment.ordinal }, entryId);
                    }
                    catch {
                    }
                }
            }
            else if (event.message.isApiErrorMessage === true) {
                await this.recordApiFailure(event.message);
            }
            await this.emitAny(entryId !== undefined ? { ...event, entryId } : event, signal);
            return;
        }
        if (event.type === "turn_end") {
            let eventError;
            try {
                await this.emitAny(event, signal);
            }
            catch (error) {
                eventError = error;
            }
            const queued = this.pendingSessionWrites.length > 0;
            await this.flushPendingSessionWrites();
            const hadPendingMutations = queued && this.pendingSessionWrites.length === 0;
            if (eventError) {
                throw toLintErrorObject(eventError, "Non-Error thrown");
            }
            await this.emitOwn({ type: "save_point", hadPendingMutations });
            return;
        }
        if (event.type === "agent_end") {
            await this.flushPendingSessionWrites();
            this.sweepUndrainedEngineNotes([this.drainedPendingInjection, this.nextTurnQueue, this.steerQueue, this.followUpQueue]);
            const undrainedUser = this.announceUndrainedUserInputs();
            this.phase = "idle";
            await this.emitAny(event, signal);
            await this.emitOwn({
                type: "settled",
                nextTurnCount: this.nextTurnQueue.length,
                ...(undrainedUser.steer > 0 ? { undrainedSteerCount: undrainedUser.steer } : {}),
                ...(undrainedUser.followUp > 0 ? { undrainedFollowUpCount: undrainedUser.followUp } : {}),
            }, signal);
            return;
        }
        await this.emitAny(event, signal);
    }
    async emitRunFailure(model, error, aborted, signal) {
        const failureMessage = createFailureMessage(model, error, aborted);
        await this.handleAgentEvent({ type: "message_start", message: failureMessage }, signal);
        await this.handleAgentEvent({ type: "message_end", message: failureMessage }, signal);
        await this.handleAgentEvent({ type: "turn_end", message: failureMessage, toolResults: [] }, signal);
        await this.handleAgentEvent({ type: "agent_end", messages: [failureMessage] }, signal);
        return [failureMessage];
    }
    async executeTurn(turnState, text, options, abortController) {
        let activeTurnState = turnState;
        const opensOnQueuedInput = options?.opensOnQueuedInput === true;
        const userMessage = opensOnQueuedInput && AgentHarness.emptyInjection(text, options) ? undefined : createUserMessage(text, options?.images, options);
        const answered = (options?.answeredInputs ?? []).map((seed) => this.mintInjection(seed.text, { ...seed.provenance, givenAnswer: seed.answer }));
        const onCommitted = options?.onCommitted;
        const commit = (entryId) => {
            onCommitted?.(entryId);
            this.followUpQueue.push(...answered);
        };
        this.promptReceipt = userMessage !== undefined && (onCommitted !== undefined || answered.length > 0) ? { message: userMessage, commit } : undefined;
        const trailingMessages = (options?.trailing ?? []).map(createTrailingMessage);
        this.runHistory = new WeakSet(turnState.messages.filter((m) => m.role === "assistant"));
        this.priorImageRefusals = new Set(turnState.messages.filter(isImageRefusal).map(imageRefusalAt));
        const beforeResult = await this.emitHook({
            type: "before_agent_start",
            prompt: text,
            images: options?.images,
            systemPrompt: turnState.systemPrompt,
            resources: turnState.resources,
        });
        if (opensOnQueuedInput && this.nextTurnQueue.length + this.pendingInjectionCount() + (beforeResult?.messages?.length ?? 0) === 0) {
            if (userMessage !== undefined && this.promptReceipt?.message === userMessage)
                this.promptReceipt = undefined;
            throw new NothingQueuedError();
        }
        const takePrompts = async () => {
            let messages = [...(userMessage !== undefined ? [userMessage] : []), ...trailingMessages];
            if (this.nextTurnQueue.length > 0) {
                const queuedMessages = this.nextTurnQueue.splice(0);
                try {
                    await this.emitQueueUpdate();
                }
                catch (error) {
                    this.nextTurnQueue.unshift(...queuedMessages);
                    throw normalizeHookError(error);
                }
                for (const m of queuedMessages) {
                    const payload = engineNotePayloads.get(m);
                    if (payload !== undefined) {
                        try {
                            this.onEngineNoteConsumed?.(payload);
                        }
                        catch {
                        }
                    }
                    releaseEngineNote(m);
                }
                messages = [...queuedMessages, ...messages];
            }
            if (beforeResult?.messages) {
                messages = [...messages, ...beforeResult.messages];
            }
            return messages;
        };
        const getTurnState = () => activeTurnState;
        const setTurnState = (nextTurnState) => {
            activeTurnState = nextTurnState;
        };
        const loopConfig = this.createLoopConfig(getTurnState, setTurnState, beforeResult?.systemPrompt);
        const emitRunEvent = (event) => this.handleAgentEvent(event, abortController.signal);
        this.activeRun = { config: loopConfig, context: () => this.createContext(getTurnState(), beforeResult?.systemPrompt), emit: emitRunEvent, signal: abortController.signal };
        const runResultPromise = (async () => {
            try {
                return await runAgentLoop(takePrompts, this.createContext(turnState, beforeResult?.systemPrompt), loopConfig, emitRunEvent, abortController.signal, this.createStreamFn(getTurnState), undefined, this.loopTrace, {
                    ...(options?.settleUnansweredToolCalls !== undefined
                        ? {
                            settle: {
                                ...(options.settleUnansweredToolCalls.halt !== undefined ? { halt: options.settleUnansweredToolCalls.halt } : {}),
                                report: (outcome) => {
                                    if (outcome.aborted)
                                        this.endedOnPriorAnswer = true;
                                },
                            },
                        }
                        : {}),
                    ...(options?.endsAwaitingUser === true ? { endsAwaitingUser: true } : {}),
                    ...(options?.givenAnswer !== undefined ? { givenAnswer: options.givenAnswer } : {}),
                    ...(opensOnQueuedInput && userMessage !== undefined ? { ridingPrompt: userMessage } : {}),
                });
            }
            catch (error) {
                this.turnOpenedAt = 0;
                try {
                    return await this.emitRunFailure(activeTurnState.model, error, abortController.signal.aborted, abortController.signal);
                }
                catch (failureError) {
                    const cause = new AggregateError([toError(error), toError(failureError)], "Agent run failed and failure reporting failed");
                    throw new AgentHarnessError("unknown", cause.message, cause);
                }
            }
        })();
        try {
            const newMessages = await runResultPromise;
            let answerFloor = this.turnCutConsumed !== undefined ? this.turnOpenedAt : 0;
            if (answerFloor > 0 && continuesAnswer(newMessages[answerFloor - 1], newMessages[answerFloor]))
                answerFloor -= 1;
            for (let i = newMessages.length - 1; i >= answerFloor; i--) {
                const message = newMessages[i];
                if (message.role === "assistant") {
                    const answer = mergeTruncatedOutputChain(newMessages, i);
                    return this.answeredFrom(answer.message, answer.members);
                }
            }
            if (this.stopRequested || this.turnCutConsumed !== undefined || abortController.signal.aborted)
                return undefined;
            if (this.endedOnPriorAnswer || options?.endsAwaitingUser === true) {
                const prior = turnState.messages.findLast((m) => m.role === "assistant");
                if (prior !== undefined)
                    return this.answeredFrom(prior, [prior]);
                if (options?.endsAwaitingUser === true)
                    return undefined;
            }
            throw new AgentHarnessError("invalid_state", "AgentHarness prompt completed without an assistant message");
        }
        finally {
            try {
                await this.flushPendingSessionWrites();
            }
            finally {
                this.runAbortController = undefined;
                this.activeRun = undefined;
                if (userMessage !== undefined && this.promptReceipt?.message === userMessage)
                    this.promptReceipt = undefined;
            }
        }
    }
    async prompt(text, options) {
        if (this.phase !== "idle") {
            throw new AgentHarnessError("busy", "AgentHarness is busy");
        }
        this.endedOnPriorAnswer = false;
        this.stopRequestSources.clear();
        this.boundaryStopConsumed = undefined;
        this.turnCutConsumed = undefined;
        this.turnOpenedAt = 0;
        this.acceptedCuts = [];
        this.consumedCuts.clear();
        this.lastPublishedSeat = undefined;
        this.aborting = false;
        if (this.drainedPendingInjection.length > 0) {
            const stranded = this.drainedPendingInjection;
            this.drainedPendingInjection = [];
            for (let i = stranded.length - 1; i >= 0; i--) {
                const frame = stranded[i];
                const lane = drainedFromLane.get(frame);
                if (lane === "steer")
                    this.steerQueue.unshift(frame);
                else if (lane === "followUp")
                    this.followUpQueue.unshift(frame);
            }
        }
        this.phase = "turn";
        const abortController = new AbortController();
        this.runAbortController = abortController;
        const finishRunPromise = this.startRunPromise();
        try {
            if (this.pendingSessionWrites.length > 0 && findUnansweredToolBatch((await this.session.buildContext()).messages) === undefined)
                await this.flushPendingSessionWrites();
            const turnState = await this.createTurnState();
            return await this.executeTurn(turnState, text, options, abortController);
        }
        catch (error) {
            this.phase = "idle";
            throw normalizeHarnessError(error, "unknown");
        }
        finally {
            if (this.runAbortController === abortController)
                this.runAbortController = undefined;
            finishRunPromise();
        }
    }
    static emptyInjection(text, options) {
        return isBlankInput(text) && (options?.images === undefined || options.images.length === 0);
    }
    mintInjection(text, options) {
        const m = createUserMessage(text, options?.images, options);
        if (options?.enginePayload !== undefined)
            engineNotePayloads.set(m, options.enginePayload);
        if (options?.enginePayload !== undefined && options.engineTier !== undefined)
            engineNoteTiers.set(m, options.engineTier);
        if (options?.givenAnswer !== undefined)
            givenAnswerFrames.set(m, { text: options.givenAnswer.text, by: options.givenAnswer.by });
        if (isEngineAuthoredInjection(options))
            engineAuthoredInjections.add(m);
        if (options?.author !== undefined)
            inputAuthors.set(m, options.author);
        if (options?.parkRecord !== undefined)
            userInputParkRecords.set(m, options.parkRecord);
        if (options?.immediate === true)
            immediateClassInjections.add(m);
        if (options?.capPreferred === true && options?.enginePayload !== undefined)
            capPreferredInjections.add(m);
        return m;
    }
    async enqueueInjection(queue, text, options, frame) {
        if (frame === undefined && AgentHarness.emptyInjection(text, options))
            return undefined;
        let displaced;
        if (options?.enginePayload !== undefined && queue.filter((q) => engineNotePayloads.has(q)).length >= ENGINE_NOTE_STEER_BACKLOG_CAP) {
            const victimIdx = options.capPreferred === true
                ? queue.findIndex((q) => engineNotePayloads.has(q) && !capPreferredInjections.has(q))
                : -1;
            if (victimIdx === -1) {
                throw new AgentHarnessError("invalid_state", `engine-note backlog at cap (${ENGINE_NOTE_STEER_BACKLOG_CAP}) — park the payload for the session's next run`);
            }
            displaced = { frame: queue.splice(victimIdx, 1)[0], at: victimIdx };
        }
        const m = frame !== undefined ? createTrailingMessage(frame) : this.mintInjection(text, options);
        if (frame !== undefined)
            engineAuthoredInjections.add(m);
        if (options?.immediate === true && queue === this.steerQueue) {
            let at = 0;
            while (at < queue.length && immediateClassInjections.has(queue[at]))
                at++;
            queue.splice(at, 0, m);
        }
        else {
            queue.push(m);
        }
        try {
            await this.emitQueueUpdate();
        }
        catch (error) {
            const at = queue.indexOf(m);
            if (at !== -1) {
                queue.splice(at, 1);
                if (displaced !== undefined)
                    queue.splice(Math.min(displaced.at, queue.length), 0, displaced.frame);
                throw error;
            }
        }
        if (displaced !== undefined) {
            const victimPayload = engineNotePayloads.get(displaced.frame);
            const victimTier = engineNoteTiers.get(displaced.frame);
            releaseEngineNote(displaced.frame);
            if (victimPayload !== undefined && this.onUndrainedEngineNotes) {
                try {
                    this.onUndrainedEngineNotes([victimPayload], [victimTier]);
                }
                catch {
                }
            }
        }
        return m;
    }
    refuseHeldEngineInjection(options) {
        if (isEngineAuthoredInjection(options) && this.engineInjectionsHeld?.() === true) {
            throw new AgentHarnessError("invalid_state", "engine-authored injection refused: the run is halted awaiting the user's own direction — park the payload for the session's next run");
        }
    }
    async steer(text, options) {
        if (!this.takingInput) {
            throw new AgentHarnessError("invalid_state", "Cannot steer while idle");
        }
        this.refuseHeldEngineInjection(options);
        return await this.enqueueInjection(this.steerQueue, text, options);
    }
    async steerFrame(seed) {
        if (!this.takingInput) {
            throw new AgentHarnessError("invalid_state", "Cannot steer while idle");
        }
        this.refuseHeldEngineInjection({ provenance: "engine-note" });
        return await this.enqueueInjection(this.steerQueue, "", undefined, seed);
    }
    async followUp(text, options) {
        if (!this.takingInput) {
            throw new AgentHarnessError("invalid_state", "Cannot follow up while idle");
        }
        this.refuseHeldEngineInjection(options);
        await this.enqueueInjection(this.followUpQueue, text, options);
    }
    interruptTurn(frame) {
        if (!this.steerQueue.includes(frame))
            return false;
        return this.cutTurn("steer") === "cut";
    }
    halt() {
        if (this.phase === "idle") {
            throw new AgentHarnessError("invalid_state", "Cannot halt while idle");
        }
        if (this.aborting)
            return { turnCut: false, accepted: false };
        this.stopRequestSources.add("halt");
        return { turnCut: this.cutTurn("halt") === "cut", accepted: true };
    }
    cutTurn(source, extension) {
        const seat = this.seatToCut();
        if (typeof seat === "string")
            return seat;
        const cut = extension !== undefined ? { source, by: extension.by, turn: extension.turn } : { source };
        this.seatCuts.set(seat, cut);
        this.acceptedCuts.push(cut);
        const runQuietBefore = this.runAbortController?.signal.aborted !== true;
        seat.abort();
        if (runQuietBefore && this.runAbortController?.signal.aborted === true)
            this.consumeTurnCut(cut);
        return "cut";
    }
    consumeTurnCut(cut) {
        this.turnCutConsumed = { cut };
        if (cut !== undefined)
            this.consumedCuts.add(cut);
    }
    turnSeatState() {
        const seat = this.seatToCut();
        return typeof seat === "string" ? seat : "live";
    }
    cutMovesArmedCommandAside(signal) {
        const seat = this.lastPublishedSeat;
        if (seat === undefined || seat.signal !== signal)
            return false;
        const cut = this.seatCuts.get(seat);
        return cut !== undefined && TURN_CUT_SETTLEMENTS[cut.source].movesArmedCommandAside;
    }
    seatToCut() {
        if (this.aborting)
            return "ending";
        const seat = this.turnInterruptSeat;
        if (seat === undefined)
            return "none";
        return seat.signal.aborted ? "ending" : seat;
    }
    answerEntryIdsOf(answer) {
        return answer === undefined ? [] : this.answerSources.get(answer);
    }
    answeredFrom(answer, members) {
        const ids = [];
        for (const m of members) {
            const id = this.committedEntryIds.get(m);
            if (id !== undefined)
                ids.push(id);
            else if (this.runHistory?.has(m) === true)
                return answer;
        }
        this.answerSources.set(answer, ids);
        return answer;
    }
    haltConsumption() {
        const cut = this.turnCutConsumed?.cut;
        const unconsumedCuts = this.acceptedCuts.filter((c) => !this.consumedCuts.has(c));
        return {
            ...(cut !== undefined ? { turnCut: cut.source } : {}),
            ...(cut?.by !== undefined ? { turnCutBy: cut.by } : {}),
            ...(this.boundaryStopConsumed !== undefined ? { boundaryStop: this.boundaryStopConsumed } : {}),
            ...(unconsumedCuts.length > 0 ? { unconsumedCuts } : {}),
        };
    }
    consumeStopAtEnding() {
        return this.consultStopLatch("post_turn");
    }
    consultStopLatch(face) {
        if (!this.stopRequested)
            return false;
        if (this.runAbortController?.signal.aborted !== true) {
            this.boundaryStopConsumed ??= { face, sources: [...this.stopRequestSources] };
        }
        return true;
    }
    noteTurnCutConsumed(seat) {
        if (seat !== this.lastPublishedSeat) {
            throw new AgentHarnessError("invalid_state", "turn-cut consumption reported for a seat the harness did not publish last");
        }
        const cut = this.seatCuts.get(seat);
        this.consumeTurnCut(cut);
        return cut !== undefined ? TURN_CUT_SETTLEMENTS[cut.source] : undefined;
    }
    pendingInjectionCount() {
        if (this.aborting)
            return 0;
        const drainable = (q) => q.filter((m) => this.isDrainable(m, false)).length;
        return drainable(this.steerQueue) + drainable(this.followUpQueue);
    }
    async absorbImmediateSteering(pending) {
        if (this.aborting)
            return pending;
        const taken = [];
        for (let i = 0; i < this.steerQueue.length; i++) {
            const m = this.steerQueue[i];
            if (!immediateClassInjections.has(m))
                break;
            if (!this.isDrainable(m, true))
                continue;
            taken.push(...this.steerQueue.splice(i, 1));
            i--;
        }
        if (taken.length === 0)
            return pending;
        for (const m of taken)
            drainedFromLane.set(m, "steer");
        this.drainedPendingInjection.push(...taken);
        try {
            await this.emitQueueUpdate();
            for (const m of taken) {
                const payload = engineNotePayloads.get(m);
                if (payload !== undefined) {
                    try {
                        this.onEngineNoteConsumed?.(payload);
                    }
                    catch {
                    }
                }
            }
        }
        catch (error) {
            this.steerQueue.unshift(...taken);
            this.unbookInFlight(taken);
            throw normalizeHookError(error);
        }
        let at = 0;
        while (at < pending.length && immediateClassInjections.has(pending[at]))
            at++;
        return [...pending.slice(0, at), ...taken, ...pending.slice(at)];
    }
    async nextTurn(text, options) {
        await this.enqueueInjection(this.nextTurnQueue, text, options);
    }
    async appendMessage(message, raising) {
        const kept = await this.admitRows([message], raising);
        if (!kept.includes(message))
            return;
        while (this.parkCaptureInFlight !== undefined)
            await this.parkCaptureInFlight;
        if (this.parkedPortClosed !== undefined)
            throw new AgentHarnessError("invalid_state", PORT_CLOSED_REFUSAL[this.parkedPortClosed]);
        try {
            if (this.phase === "idle" && this.pendingSessionWrites.length === 0) {
                await this.session.appendMessage(message);
            }
            else {
                this.pendingSessionWrites.push({ type: "message", message });
            }
        }
        catch (error) {
            throw normalizeHarnessError(error, "session");
        }
    }
    async afterToolCallHook(toolCall, args, result, isError) {
        const patch = await this.emitHook({
            type: "tool_result",
            toolCallId: toolCall.id,
            toolName: toolCall.name,
            input: args,
            content: result.content,
            details: result.details,
            isError,
        });
        return patch;
    }
    finalizeToolCall(toolCall, args, executed) {
        return finalizeToolOutcome(toolCall, executed, (result, isError) => this.afterToolCallHook(toolCall, args, result, isError), this.toolResultMedia);
    }
    async callTool(toolCall, signal, admit) {
        const run = this.activeRun;
        if (run === undefined)
            throw new AgentHarnessError("invalid_state", "a host's tool call runs inside a running prompt, and none is running");
        const context = run.context();
        const tool = findToolByName(context.tools, toolCall.name);
        if (tool === undefined)
            throw new AgentHarnessError("invalid_state", `no tool named "${toolCall.name}" in this run (it has ${(context.tools ?? []).map((t) => t.name).join(", ") || "none"})`);
        admit(tool);
        const both = signal !== undefined ? AbortSignal.any([signal, run.signal]) : run.signal;
        return (await runToolCall(context, undefined, toolCall, run.config, both, run.emit)).finalized;
    }
    isBatchSafe(toolName, args) {
        const tools = this.activeRun?.context().tools;
        const tool = findToolByName(tools, toolName);
        return tool !== undefined && isBatchSafeToolCall(tool, { type: "toolCall", id: "", name: toolName, arguments: (typeof args === "object" && args !== null ? args : {}) });
    }
    getModel() {
        return this.model;
    }
    getModelRef() {
        return this.modelRef;
    }
    getThinkingLevel() {
        return this.thinkingLevel;
    }
    async setModel(model, ref) {
        try {
            const previousModel = this.model;
            if (this.phase === "idle") {
                await this.session.appendModelChange(model.provider, model.id);
            }
            else {
                this.pendingSessionWrites.push({
                    type: "model_change",
                    provider: model.provider,
                    modelId: model.id,
                });
            }
            this.model = model;
            this.modelRef = ref ?? model;
            await this.emitOwn({ type: "model_select", model, previousModel, source: "set" });
        }
        catch (error) {
            throw normalizeHarnessError(error, "session");
        }
    }
    async setThinkingLevel(level) {
        try {
            const previousLevel = this.thinkingLevel;
            if (this.phase === "idle") {
                await this.session.appendThinkingLevelChange(level);
            }
            else {
                this.pendingSessionWrites.push({ type: "thinking_level_change", thinkingLevel: level });
            }
            this.thinkingLevel = level;
            await this.emitOwn({ type: "thinking_level_select", level, previousLevel });
        }
        catch (error) {
            throw normalizeHarnessError(error, "session");
        }
    }
    async setActiveTools(toolNames) {
        try {
            this.validateToolNames(toolNames);
            this.activeToolNames = [...toolNames];
        }
        catch (error) {
            throw normalizeHarnessError(error, "invalid_argument");
        }
    }
    getResources() {
        return {
            skills: this.resources.skills?.slice(),
            promptTemplates: this.resources.promptTemplates?.slice(),
        };
    }
    async setResources(resources) {
        const previousResources = this.getResources();
        this.resources = {
            skills: resources.skills?.slice(),
            promptTemplates: resources.promptTemplates?.slice(),
        };
        await this.emitOwn({
            type: "resources_update",
            resources: this.getResources(),
            previousResources,
        });
    }
    getStreamOptions() {
        return cloneStreamOptions(this.streamOptions);
    }
    async setStreamOptions(streamOptions) {
        refuseAuthCarriersInStreamOptions(streamOptions?.headers);
        this.streamOptions = cloneStreamOptions(streamOptions);
    }
    setSystemPrompt(prompt, blocks) {
        this.systemPrompt = prompt;
        this.systemBlocks = blocks;
    }
    async setTools(tools, activeToolNames) {
        try {
            const nextTools = new Map(tools.map((tool) => [tool.name, tool]));
            const nextActiveToolNames = activeToolNames ? [...activeToolNames] : this.activeToolNames;
            this.validateToolNames(nextActiveToolNames, nextTools);
            this.tools = nextTools;
            this.activeToolNames = [...nextActiveToolNames];
        }
        catch (error) {
            throw normalizeHarnessError(error, "invalid_argument");
        }
    }
    requestStopAfterTurn() {
        this.stopRequestSources.add("soft");
    }
    async flushQueuedSessionWrites() {
        try {
            await this.flushPendingSessionWrites();
        }
        catch (error) {
            throw normalizeHarnessError(error, "session");
        }
    }
    parkCapture() {
        if (this.parkCaptureInFlight !== undefined)
            throw new AgentHarnessError("invalid_state", "a park's capture of the held rows is already in progress");
        const rows = this.pendingSessionWrites.flatMap((write) => (write.type === "message" ? [write.message] : []));
        let release = () => undefined;
        this.parkCaptureInFlight = new Promise((resolve) => (release = resolve));
        let settled = false;
        return {
            rows,
            settle: (outcome) => {
                if (settled)
                    return;
                settled = true;
                if (outcome === "committed") {
                    const taken = new Set(rows);
                    this.pendingSessionWrites = this.pendingSessionWrites.filter((write) => write.type !== "message" || !taken.has(write.message));
                }
                if (outcome !== "absent")
                    this.parkedPortClosed = outcome;
                this.parkCaptureInFlight = undefined;
                release();
            },
        };
    }
    heldSessionWrites() {
        return [...this.pendingSessionWrites];
    }
    readParkableUserInputs() {
        const out = [];
        for (const q of [this.drainedPendingInjection, this.steerQueue, this.followUpQueue]) {
            for (const m of q) {
                const record = userInputParkRecords.get(m);
                if (record !== undefined && isOperatorInput(m))
                    out.push(record);
            }
        }
        return out;
    }
    dropParkedUserInputs(records) {
        const dropped = { steer: 0, followUp: 0, records: { steer: [], followUp: [] } };
        if (records.length === 0)
            return dropped;
        const migrated = new Set(records);
        for (const q of [this.drainedPendingInjection, this.steerQueue, this.followUpQueue]) {
            const fixedLane = q === this.steerQueue ? "steer" : q === this.followUpQueue ? "followUp" : undefined;
            for (let i = 0; i < q.length; i++) {
                const frame = q[i];
                const record = userInputParkRecords.get(frame);
                if (record === undefined || !migrated.has(record))
                    continue;
                const lane = fixedLane ?? drainedFromLane.get(frame);
                userInputParkRecords.delete(frame);
                q.splice(i, 1);
                i--;
                if (lane !== undefined) {
                    dropped[lane] += 1;
                    dropped.records[lane].push(record);
                }
            }
        }
        return dropped;
    }
    async abort() {
        this.aborting = true;
        this.runAbortController?.abort();
        const errors = [];
        try {
            await this.emitQueueUpdate();
        }
        catch (error) {
            errors.push(toError(error));
        }
        try {
            await this.waitForIdle();
        }
        catch (error) {
            errors.push(toError(error));
        }
        this.sweepUndrainedEngineNotes([this.drainedPendingInjection, this.nextTurnQueue, this.steerQueue, this.followUpQueue]);
        const { steer: undrainedSteer, followUp: undrainedFollowUp } = this.pendingUserInputFramesByLane();
        try {
            await this.emitOwn({ type: "abort", undrainedSteer, undrainedFollowUp });
        }
        catch (error) {
            errors.push(toError(error));
        }
        if (errors.length > 0) {
            const cause = errors.length === 1 ? errors[0] : new AggregateError(errors, "Abort completed with errors");
            throw normalizeHarnessError(cause, "hook");
        }
        return { undrainedSteer, undrainedFollowUp };
    }
    async waitForIdle() {
        await this.runPromise;
    }
    subscribe(listener) {
        let handlers = this.handlers.get(SUBSCRIBER_EVENT_TYPE);
        if (!handlers) {
            handlers = new Set();
            this.handlers.set(SUBSCRIBER_EVENT_TYPE, handlers);
        }
        handlers.add(listener);
        return () => handlers.delete(listener);
    }
    on(type, handler) {
        let handlers = this.handlers.get(type);
        if (!handlers) {
            handlers = new Set();
            this.handlers.set(type, handlers);
        }
        handlers.add(handler);
        return () => handlers.delete(handler);
    }
}
function isEmptyFailureAssistant(message) {
    if (message.role !== "assistant")
        return false;
    const m = message;
    if (m.stopReason !== "aborted" && m.stopReason !== "error")
        return false;
    return m.content.every((c) => c.type === "text" ? c.text.trim() === "" : c.type === "thinking" ? c.thinking.trim() === "" : false);
}
function continuesAnswer(head, nudge) {
    const mid = nudge;
    if (head?.role !== "assistant" || mid?.role !== "custom")
        return false;
    const stopReason = head.stopReason;
    return ((mid.customType === "loop:truncated-output-continue" && stopReason === "length") ||
        (mid.customType === "loop:midstream-partial-continue" && stopReason === "stop"));
}
function mergeTruncatedOutputChain(messages, lastAssistantIndex) {
    const last = messages[lastAssistantIndex];
    const lastText = last.content.map((c) => (c.type === "text" ? c.text : "")).join("");
    const parts = [];
    const members = [last];
    let i = lastAssistantIndex;
    while (i - 2 >= 0) {
        if (!continuesAnswer(messages[i - 2], messages[i - 1]))
            break;
        const head = messages[i - 2];
        parts.unshift(head.content.map((c) => (c.type === "text" ? c.text : "")).join(""));
        members.unshift(head);
        i = i - 2;
    }
    if (parts.length === 0) {
        return { message: last, members };
    }
    const message = {
        ...last,
        content: [
            { type: "text", text: parts.join("") + lastText },
            ...last.content.filter((c) => c.type !== "text"),
        ],
    };
    return { message, members };
}
function toLintErrorObject(value, fallbackMessage) {
    if (value instanceof Error) {
        return value;
    }
    if (typeof value === "string") {
        return new Error(value);
    }
    const error = new Error(fallbackMessage, { cause: value });
    if ((typeof value === "object" && value !== null) || typeof value === "function") {
        Object.assign(error, value);
    }
    return error;
}