@mastra/core
Version:
9,510 lines • 367 kB
JavaScript
const require_run_registry = require("./run-registry-BrKoxzT0.cjs");
const require_message_list = require("./message-list-Bc69E1sT.cjs");
const require_signals = require("./signals-CWxAMEmE.cjs");
const require_ee_iTj2bRDt = require("./ee-iTj2bRDt-D3-QLGDF.cjs");
const require_channels = require("./channels-Dp9ZT859.cjs");
const require_llm = require("./llm-BoBmCoSK.cjs");
const require_mastra = require("./mastra-DGIYMiih.cjs");
const require_stream = require("./stream-hnlwNJ12.cjs");
const require_request_context = require("./request-context-D9RXYCy8.cjs");
const require_dynamic_argument = require("./dynamic-argument-CUc1BBOS.cjs");
const require_error = require("./error-D90lJ6M7.cjs");
const require_utils_safe_stringify = require("./utils/safe-stringify.cjs");
const require_workspace = require("./workspace-BVFsqhNw.cjs");
const require_output_helpers = require("./output-helpers-JL-HeCbT.cjs");
const require_tools = require("./tools-Bq9L93t8.cjs");
const require_payload_transform = require("./payload-transform-CWgnsO9w.cjs");
const require_tool = require("./tool-BMl4Lb5_.cjs");
const require_state_processor = require("./state-processor-Co7RZlSr.cjs");
let zod_v4 = require("zod/v4");
let _mastra_schema_compat_schema = require("@mastra/schema-compat/schema");
// src/agent-controller/errors.ts
/** The session was aborted or switched before a pending prompt could start. */
var SessionStartupCancelledError = class extends Error {
code = "SESSION_STARTUP_CANCELLED";
constructor() {
super("Session startup cancelled");
this.name = "AbortError";
}
};
/** Distinguish session cancellation from provider and transport AbortErrors. */
function isSessionStartupCancelledError(error) {
return error instanceof Error && "code" in error && error.code === "SESSION_STARTUP_CANCELLED";
}
/** A caller asked to resume a session that was never started and has no stored thread to recover from. */
var SessionNotStartedError = class extends Error {
code = "SESSION_NOT_STARTED";
constructor(resourceId) {
super(`No session has been started for resource "${resourceId}"`);
this.name = "SessionNotStartedError";
}
};
function isSessionNotStartedError(error) {
return error instanceof Error && "code" in error && error.code === "SESSION_NOT_STARTED";
}
// src/agent-controller/model-catalog-cache.ts
/**
* How long a built catalog is served before configured gateways and
* per-provider auth are checked again. Configured gateways can read state the
* app changes at runtime (stored credentials, custom providers), so this stays
* short.
*/
const MODEL_CATALOG_TTL_MS = 1e4;
/** How long a downloaded remote catalog (models.dev, Netlify, ...) is served before a call refreshes it in the background. */
const REMOTE_CATALOG_REFRESH_MS = 3e5;
/** After a remote catalog fails, how long its last known providers are served before the next try. */
const REMOTE_CATALOG_RETRY_MS = 6e4;
/**
* Model catalog cache with two refresh speeds.
*
* Remote gateways download public catalogs (models.dev's is ~6 MB). Once a
* downloaded catalog is older than {@link REMOTE_CATALOG_REFRESH_MS}, the next
* call refreshes it in the background and keeps serving the last good result,
* including when the refresh fails. A call waits for a remote gateway only
* while it has nothing to serve: before its first successful download.
*
* Everything else (configured gateways and per-provider auth) is rebuilt at
* most every {@link MODEL_CATALOG_TTL_MS}, or on the next call after
* {@link invalidate}, on top of the latest remote snapshot.
*
* Concurrent callers share one build. Each remote gateway downloads on its
* own, so a slow or stalled one never holds back the others.
*/
var ModelCatalogCache = class {
#manager;
#isRemote;
#remote = /* @__PURE__ */ new Map();
#remoteVersion = 0;
/** In-flight download per remote gateway, so a stalled gateway never holds back the others. */
#remoteRefreshes = /* @__PURE__ */ new Map();
#built;
#build;
/** Bumped by {@link invalidate} so builds started before it are not kept. */
#generation = 0;
constructor(manager, isRemote) {
this.#manager = manager;
this.#isRemote = isRemote;
}
async list() {
if (this.#mustWaitForRemote()) return this.#rebuild();
if (this.#dueRemoteGateways().length > 0) this.#refreshRemote().catch(() => {});
const built = this.#built;
if (built && built.remoteVersion === this.#remoteVersion && Date.now() - built.builtAt < MODEL_CATALOG_TTL_MS) return built.models;
return this.#rebuild();
}
/**
* Rebuild configured gateways and auth on the next call (for example after a
* credential change), and download the remote catalogs again in the
* background.
*/
invalidate() {
this.#generation += 1;
this.#built = void 0;
this.#build = void 0;
for (const snapshot of this.#remote.values()) snapshot.nextFetchAt = 0;
}
#rebuild() {
if (this.#build) return this.#build;
const build = this.#buildCatalog(this.#generation).finally(() => {
if (this.#build === build) this.#build = void 0;
});
this.#build = build;
return build;
}
async #buildCatalog(generation) {
const gateways = this.#manager.gateways;
const local = gateways.filter((gateway) => !this.#isRemote(gateway));
const [localProviders] = await Promise.all([this.#fetchLocal(local), this.#mustWaitForRemote() ? this.#refreshRemote() : void 0]);
const remoteVersion = this.#remoteVersion;
const registry = this.#manager.mergeProviders(gateways.map((gateway) => ({
gateway,
providers: (this.#isRemote(gateway) ? this.#remote.get(gateway)?.providers : localProviders.get(gateway)) ?? {}
})));
const models = await this.#manager.listModelsForProviders(registry);
if (generation === this.#generation) this.#built = {
models,
builtAt: Date.now(),
remoteVersion
};
return models;
}
async #fetchLocal(gateways) {
const providers = /* @__PURE__ */ new Map();
for (const gateway of gateways) providers.set(gateway, await this.#manager.fetchGatewayProviders(gateway));
return providers;
}
#dueRemoteGateways() {
const now = Date.now();
return this.#manager.gateways.filter((gateway) => this.#isRemote(gateway) && (this.#remote.get(gateway)?.nextFetchAt ?? 0) <= now);
}
#mustWaitForRemote() {
return this.#dueRemoteGateways().some((gateway) => !this.#remote.get(gateway)?.providers);
}
/**
* Starts a download for each due remote gateway that is not already
* downloading. Resolves once the gateways with nothing to serve yet have
* answered; the others finish in the background.
*/
#refreshRemote() {
const waits = [];
for (const gateway of this.#dueRemoteGateways()) {
let refresh = this.#remoteRefreshes.get(gateway);
if (!refresh) {
refresh = this.#fetchRemote(gateway).finally(() => this.#remoteRefreshes.delete(gateway));
this.#remoteRefreshes.set(gateway, refresh);
}
if (!this.#remote.get(gateway)?.providers) waits.push(refresh);
}
return Promise.all(waits).then(() => {});
}
/** Downloads one remote gateway and publishes its result as soon as it lands. */
async #fetchRemote(gateway) {
const providers = await this.#manager.fetchGatewayProviders(gateway);
const fetchedAt = Date.now();
const previous = this.#remote.get(gateway)?.providers;
if (providers) this.#remote.set(gateway, {
providers,
nextFetchAt: fetchedAt + REMOTE_CATALOG_REFRESH_MS
});
else if (previous) this.#remote.set(gateway, {
providers: previous,
nextFetchAt: fetchedAt + REMOTE_CATALOG_RETRY_MS
});
else this.#remote.set(gateway, {
providers: void 0,
nextFetchAt: fetchedAt + MODEL_CATALOG_TTL_MS
});
this.#remoteVersion += 1;
}
};
// src/agent-controller/message-author.ts
function readMessageAuthor(requestContext) {
const value = requestContext?.get(require_request_context.MASTRA_MESSAGE_AUTHOR_KEY);
if (!value || typeof value !== "object") return void 0;
const { id, name, avatarUrl } = value;
if (typeof id !== "string" || !id) return void 0;
return {
id,
...typeof name === "string" ? { name } : {},
...typeof avatarUrl === "string" ? { avatarUrl } : {}
};
}
function withMessageAuthor(providerOptions, author) {
if (!author) return providerOptions;
return {
...providerOptions,
mastra: {
...providerOptions?.mastra,
author
}
};
}
// src/agent-controller/stream-content.ts
/**
* Pure transforms shared by the run engine for folding raw agent-stream chunk
* payloads into the `MastraDBMessage` shape a Session renders, plus
* server-side-fallback diagnostics. They hold no
* AgentController or Session state, so they live in their own module.
*/
function getDisplayTransform(metadata, phase, fallback) {
const transform = require_payload_transform.getTransformedToolPayload(metadata, "display", phase);
return require_payload_transform.hasTransformedToolPayload(transform) ? transform.transformed : fallback;
}
/**
* Build a user-facing notice when a turn was served by an Anthropic server-side
* fallback model instead of the primary model. Without a notice the user has no
* way to tell the response did not come from the model they selected.
*/
function describeServerSideFallback(providerMetadata) {
const fallback = require_run_registry.getServerSideFallbackInfo(providerMetadata);
if (!fallback) return;
return fallback.model ? `The selected model declined this turn; the response was generated by fallback model ${fallback.model}.` : "The selected model declined this turn; the response was generated by a fallback model.";
}
/** Coerce a usage field to a finite number, accepting numeric strings. */
function getUsageNumber(usage, key) {
const value = usage[key];
if (typeof value === "number" && Number.isFinite(value)) return value;
if (typeof value === "string" && value.trim() !== "") {
const numericValue = Number(value);
if (Number.isFinite(numericValue)) return numericValue;
}
}
/**
* Normalize a step's usage payload. Returns undefined when no primary count is
* present so an absent measurement is never reported as a measured zero.
*/
function toStepTokenUsage(usage) {
if (typeof usage !== "object" || usage === null || Array.isArray(usage)) return void 0;
const record = usage;
const rawPrompt = getUsageNumber(record, "promptTokens") ?? getUsageNumber(record, "inputTokens");
const rawCompletion = getUsageNumber(record, "completionTokens") ?? getUsageNumber(record, "outputTokens");
const rawTotal = getUsageNumber(record, "totalTokens");
if (rawPrompt === void 0 && rawCompletion === void 0 && rawTotal === void 0) return void 0;
const promptTokens = rawPrompt ?? 0;
const completionTokens = rawCompletion ?? 0;
const stepUsage = {
promptTokens,
completionTokens,
totalTokens: rawTotal ?? promptTokens + completionTokens
};
for (const key of OPTIONAL_USAGE_FIELDS) addOptionalUsageField$1(stepUsage, key, getUsageNumber(record, key));
if (record.raw !== void 0) stepUsage.raw = record.raw;
return stepUsage;
}
/** Return a new tally with one step's usage folded in. */
function addTokenUsage(total, step) {
const next = {
...total,
promptTokens: total.promptTokens + step.promptTokens,
completionTokens: total.completionTokens + step.completionTokens,
totalTokens: total.totalTokens + step.totalTokens
};
for (const key of OPTIONAL_USAGE_FIELDS) addOptionalUsageField$1(next, key, step[key]);
if (step.raw !== void 0) next.raw = step.raw;
return next;
}
const OPTIONAL_USAGE_FIELDS = [
"reasoningTokens",
"cachedInputTokens",
"cacheCreationInputTokens",
"cacheCreationInputTokens5m",
"cacheCreationInputTokens1h"
];
/** Fold an optional usage field into a tally when present. */
function addOptionalUsageField$1(usage, key, value) {
if (value !== void 0) usage[key] = (usage[key] ?? 0) + value;
}
// src/agent-controller/tool-result.ts
function getRecord$1(value) {
return typeof value === "object" && value !== null ? value : void 0;
}
/** Classify the raw result before display transforms replace its content. */
function isToolResultError(payload) {
const modelOutput = getRecord$1(getRecord$1(getRecord$1(payload.providerMetadata)?.mastra)?.modelOutput);
return payload.isError === true || require_tool.isValidationError(payload.result) || modelOutput?.type === "error-json" || modelOutput?.type === "error-text";
}
// src/agent-controller/types.ts
/** Creates a zero-initialized TokenUsage object. */
function createEmptyTokenUsage() {
return {
promptTokens: 0,
completionTokens: 0,
totalTokens: 0,
cachedInputTokens: 0,
cacheCreationInputTokens: 0
};
}
/**
* Creates the default/initial `AgentControllerDisplayState`.
*/
function defaultDisplayState() {
return {
isRunning: false,
currentMessage: null,
queuedFollowUps: 0,
tokenUsage: createEmptyTokenUsage(),
activeTools: /* @__PURE__ */ new Map(),
toolInputBuffers: /* @__PURE__ */ new Map(),
pendingApprovals: /* @__PURE__ */ new Map(),
pendingSuspensions: /* @__PURE__ */ new Map(),
activeSubagents: /* @__PURE__ */ new Map(),
omProgress: defaultOMProgressState(),
bufferingMessages: false,
bufferingObservations: false,
modifiedFiles: /* @__PURE__ */ new Map(),
tasks: [],
previousTasks: []
};
}
/**
* Creates the default OM progress state.
*/
function defaultOMProgressState() {
return {
status: "idle",
pendingTokens: 0,
threshold: 3e4,
thresholdPercent: 0,
observationTokens: 0,
reflectionThreshold: 4e4,
reflectionThresholdPercent: 0,
buffered: {
observations: {
status: "idle",
chunks: 0,
messageTokens: 0,
projectedMessageRemoval: 0,
observationTokens: 0
},
reflection: {
status: "idle",
inputObservationTokens: 0,
observationTokens: 0
}
},
generationCount: 0,
stepNumber: 0,
preReflectionTokens: 0
};
}
// src/agent-controller/session-run-engine.ts
function isRecord(value) {
return typeof value === "object" && value !== null;
}
function isProviderMetadata(value) {
return isRecord(value);
}
function getString(value) {
return typeof value === "string" ? value : void 0;
}
function getNumber(value, fallback) {
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
}
function getOptionalNumber(value) {
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
}
function getBoolean(value, fallback) {
return typeof value === "boolean" ? value : fallback;
}
function getRecord(value) {
return isRecord(value) ? value : void 0;
}
function getPayload(chunk) {
return "payload" in chunk ? getRecord(chunk.payload) ?? {} : {};
}
function getDataRecord(chunk) {
return "data" in chunk ? getRecord(chunk.data) : void 0;
}
function getNestedRecord(record, key) {
return record ? getRecord(record[key]) : void 0;
}
function isTaskCompletePayload(value) {
const record = getRecord(value);
return Boolean(record && typeof record.passed === "boolean" && Array.isArray(record.results));
}
function isGoalEvaluationPayload(value) {
const record = getRecord(value);
return Boolean(record && typeof record.objective === "string" && typeof record.iteration === "number" && typeof record.maxRuns === "number" && typeof record.passed === "boolean" && (record.status === "active" || record.status === "paused" || record.status === "done") && Array.isArray(record.results) && typeof record.duration === "number" && typeof record.timedOut === "boolean" && typeof record.maxRunsReached === "boolean" && typeof record.suppressFeedback === "boolean");
}
function getOperationType(value) {
return value === "reflection" ? "reflection" : "observation";
}
function getActivationTrigger(value) {
if (value === "ttl" || value === "threshold" || value === "provider_change") return value;
}
function getOmStatus(value) {
if (value === "running" || value === "complete") return value;
return "idle";
}
function formatToolProgressOutput(progress) {
if (typeof progress === "string") return progress.endsWith("\n") ? progress : `${progress}\n`;
if (typeof progress !== "object" || progress === null) return `${String(progress)}\n`;
const record = progress;
const parts = [record.status, record.detail].filter((part) => typeof part === "string" && part.length > 0);
return parts.length > 0 ? `${parts.join(": ")}\n` : `${JSON.stringify(progress)}\n`;
}
const ABORT_STREAM_GRACE_MS = 5e3;
const abortBailed = Symbol("abort-bailed");
/**
* Resolves `graceMs` after an abort is requested for the session's run, but
* only while that abort is still pending. Raced against the chunk-consuming
* loop: a hung upstream await (e.g. a model call that never settles) ignores
* the abort signal and would otherwise leave the loop suspended forever with
* the session stuck in `running` — the only recovery being a server restart.
*
* The deadline is scoped to the abort request that armed it: if the aborted
* run settles on its own during the grace (terminal chunk → `run.reset()`,
* observed via teardown), the deadline re-arms for the next abort instead of
* firing. A persistent consumer (subscribed thread stream) outlives many runs,
* and a stale deadline must never bail a follow-up run. `guard` cancels the
* deadline once the consuming loop settles (the value still resolves, but the
* race is already won).
*/
async function abortDeadline(run, guard, graceMs) {
while (!guard.aborted) {
await run.waitForAbortRequest(guard);
if (guard.aborted) break;
if (!run.isAbortRequested()) continue;
if (await new Promise((resolve) => {
const timer = setTimeout(() => resolve(true), graceMs);
run.waitForTeardown(guard).then(() => {
clearTimeout(timer);
resolve(false);
});
}) && run.isAbortRequested()) break;
}
return abortBailed;
}
/**
* The per-session agent run engine: it consumes an agent's event stream, folds
* each chunk into the session's display messages and token usage, drives tool
* approval/suspension, and finalizes the run. In the multi-user host the run
* loop, run state, and thread stream are per-session and cannot be shared, so
* they live on the Session — this engine is owned by exactly one Session.
*
* It reaches the host only through the narrow {@link SessionMachinery} it is
* constructed with (resolve the agent, build run/stream options, persist usage,
* drive tool approval/resume, drain follow-ups). It never reaches back into the
* AgentController or another session: all per-run state is read and written on its own
* {@link Session}.
*/
var SessionRunEngine = class {
#session;
#machinery;
constructor(session, machinery) {
this.#session = session;
this.#machinery = machinery;
}
createEmptyAssistantMessage(threadId) {
return {
id: this.#machinery.generateId(),
...threadId ? { threadId } : {},
role: "assistant",
content: {
format: 2,
parts: []
},
createdAt: /* @__PURE__ */ new Date()
};
}
/**
* Build a DB-native signal message from a streamed `data-signal` /
* `data-user-message` / `data-system-reminder` chunk. The raw data-part is
* carried verbatim on `content.parts` and the signal identity is preserved on
* `content.metadata.signal` so consumers read the native shape (no flattening).
*/
createSignalMessage(partType, payload) {
const part = {
type: partType,
data: payload
};
const signalId = typeof payload.id === "string" ? payload.id : this.#machinery.generateId();
const createdAt = typeof payload.createdAt === "string" && !Number.isNaN(Date.parse(payload.createdAt)) ? new Date(payload.createdAt) : /* @__PURE__ */ new Date();
return {
id: signalId,
role: "signal",
content: {
format: 2,
parts: [part],
metadata: { signal: payload }
},
createdAt
};
}
hasCurrentMessageContent(state) {
return state.currentMessage.content.parts.length > 0;
}
isCurrentMessageObserved(state) {
return this.hasCurrentMessageContent(state) || state.messageIdObserved;
}
setStopReason(message, stopReason, force = false) {
message.content.metadata ??= {};
const metadata = message.content.metadata;
if (force) metadata.stopReason = stopReason;
else metadata.stopReason ??= stopReason;
}
setErrorMessage(message, errorMessage) {
message.content.metadata ??= {};
message.content.metadata.errorMessage = errorMessage;
}
stampResponseModel(message, stepStart) {
const modelId = getString(stepStart.modelId);
if (!modelId) return;
const provider = getString(stepStart.provider);
message.content.metadata = {
...message.content.metadata,
modelId,
...provider ? { provider } : {}
};
}
startCurrentMessage(state) {
if (state.messageStarted) return false;
this.#session.emit({
type: "message_start",
message: structuredClone(state.currentMessage)
});
state.messageStarted = true;
return true;
}
emitMessagePart(state, index) {
if (this.startCurrentMessage(state)) return;
const part = state.currentMessage.content.parts[index];
if (!part) return;
this.#session.emit({
type: "message_update",
id: state.currentMessage.id,
event: {
type: "part",
index,
part: structuredClone(part)
}
});
}
emitInitialPart(state, index, part) {
if (!state.messageStarted) {
const message = structuredClone(state.currentMessage);
message.content.parts[index] = part;
state.messageIdObserved = true;
this.#session.emit({
type: "message_start",
message
});
state.messageStarted = true;
return;
}
this.#session.emit({
type: "message_update",
id: state.currentMessage.id,
event: {
type: "part",
index,
part
}
});
}
finishCurrentMessage(state) {
if (!state.messageStarted) return;
this.#session.emit({
type: "message_end",
id: state.currentMessage.id
});
state.messageStarted = false;
}
finishCurrentMessageAndRotate(state) {
if (!this.isCurrentMessageObserved(state)) return;
this.setStopReason(state.currentMessage, "complete");
this.finishCurrentMessage(state);
state.lastFinishedMessage = state.currentMessage;
state.currentMessage = this.createEmptyAssistantMessage(state.threadId);
state.spans.clear();
state.announcedTextSpans.clear();
state.announcedReasoningSpans.clear();
state.messageIdObserved = false;
state.toolPartById.clear();
state.completedToolPrelude = false;
}
createStreamState(threadId = this.#session.thread.getId() ?? void 0, resourceId = this.#session.identity.getResourceId()) {
return {
resourceId,
threadId,
currentMessage: this.createEmptyAssistantMessage(threadId),
messageStarted: false,
isSuspended: false,
spans: new require_run_registry.MessagePartSpans({ providerMetadata: false }),
announcedTextSpans: /* @__PURE__ */ new Set(),
announcedReasoningSpans: /* @__PURE__ */ new Set(),
messageIdObserved: false,
toolPartById: /* @__PURE__ */ new Map(),
offeredResponseIds: /* @__PURE__ */ new Set(),
completedToolPrelude: false
};
}
/**
* Fold a `tool-result`/`tool-error` chunk into the invocation part and
* notify — an errored tool must reach a terminal state or clients spin forever.
*/
applyToolOutcome(state, outcome) {
const { toolCallId, toolName, result, isError, providerMetadata } = outcome;
const toolIndex = state.toolPartById.get(toolCallId);
const existing = toolIndex !== void 0 ? state.currentMessage.content.parts[toolIndex] : void 0;
const partIndex = toolIndex ?? state.currentMessage.content.parts.length;
if (existing && existing.type === "tool-invocation") {
existing.toolInvocation = Object.assign(existing.toolInvocation, {
state: "result",
result,
isError
});
if (providerMetadata) existing.providerMetadata = providerMetadata;
} else {
const toolInvocationPart = {
type: "tool-invocation",
toolInvocation: {
state: "result",
toolCallId,
toolName,
args: {},
result,
isError
}
};
if (providerMetadata) toolInvocationPart.providerMetadata = providerMetadata;
state.currentMessage.content.parts.push(toolInvocationPart);
state.toolPartById.set(toolCallId, partIndex);
}
this.emitMessagePart(state, partIndex);
if (toolName.startsWith("agent-")) {
const subagent = this.#session.displayState.get().activeSubagents.get(toolCallId);
if (subagent) this.endDelegatedSubagent(toolCallId, subagent, result, isError);
}
this.#session.emit({
type: "tool_end",
threadId: state.threadId,
toolCallId,
result,
isError,
...providerMetadata ? { providerMetadata } : {}
});
}
/** Open an `agent-<key>` delegation in `activeSubagents`, taking its task from the tool call's prompt. */
startDelegatedSubagent(state, toolCallId, toolName) {
const toolIndex = state.toolPartById.get(toolCallId);
const toolPart = toolIndex !== void 0 ? state.currentMessage.content.parts[toolIndex] : void 0;
const args = toolPart?.type === "tool-invocation" ? toolPart.toolInvocation.args : void 0;
this.#session.emit({
type: "subagent_start",
toolCallId,
agentType: toolName.slice(6),
task: getString(getRecord(args)?.prompt) ?? "",
modelId: ""
});
}
/** Close an `agent-<key>` delegation once its tool call settles. */
endDelegatedSubagent(toolCallId, subagent, result, isError) {
this.#session.emit({
type: "subagent_end",
toolCallId,
agentType: subagent.agentType,
result: getString(getRecord(result)?.text) ?? (typeof result === "string" ? result : JSON.stringify(result) ?? ""),
isError,
durationMs: subagent.startedAt !== void 0 ? Date.now() - subagent.startedAt : 0
});
}
abortForOmFailure({ operationType, stage, error }) {
this.#session.emit({
type: "error",
error: /* @__PURE__ */ new Error(`Observational memory ${operationType} ${stage} failed: ${error}`)
});
this.#session.abortRun();
}
/**
* Process a stream response. Production runs stream through
* `processSubscribedThreadStream`; only tests call this entry directly.
*/
async processStream(response, requestContextInput) {
const state = this.createStreamState();
const requestContext = await this.#machinery.buildRequestContext(requestContextInput);
this.#session.run.nextOperation();
this.#session.emit({ type: "agent_start" });
let result;
let error = false;
let aborted = false;
let bailed = false;
const consume = async () => {
for await (const chunk of response.fullStream) {
if (bailed) return;
result = await this.processStreamChunk(state, chunk, requestContext);
if (chunk.type === "error") error = true;
if (chunk.type === "abort") aborted = true;
if (result || chunk.type === "finish" || chunk.type === "error" || chunk.type === "abort" || chunk.type === "tripwire" || chunk.type === "tool-call-suspended" || this.#session.run.isAbortRequested()) {
result ??= this.finishStreamState(state);
break;
}
}
};
const bailGuard = new AbortController();
try {
bailed = await Promise.race([consume(), abortDeadline(this.#session.run, bailGuard.signal, ABORT_STREAM_GRACE_MS)]) === abortBailed;
} finally {
bailGuard.abort();
}
result ??= this.finishStreamState(state);
if (state.terminalError && !error && !aborted && !this.#session.run.isAbortRequested() && !result.suspended) {
error = true;
this.#session.emit({
type: "error",
error: new Error(state.terminalError),
finishReason: state.terminalFinishReason
});
}
await this.#session.finishAgentRun(error ? "error" : result.suspended ? "suspended" : aborted || this.#session.run.isAbortRequested() ? "aborted" : "complete");
this.#session.run.reset();
return result;
}
/**
* Mutates and emits one live accumulated message throughout the assistant turn.
* Consumers that require a point-in-time value must copy or serialize at their
* ownership boundary. Do not restore producer-side per-delta snapshots: even
* selective snapshots retain growing historical text and allocate message/part
* shells for every token.
*/
async processStreamChunk(state, chunk, requestContext, agent = this.#machinery.getAgent()) {
if ("runId" in chunk && chunk.runId) {
this.#session.run.setRunId({ runId: chunk.runId });
this.#session.__captureRunThreadOwnerId(chunk.runId, requestContext);
}
if (require_run_registry.isSpanChunk(chunk)) {
const partIndex = state.currentMessage.content.parts.length;
if (chunk.type === "text-start") {
state.spans.fold(state.currentMessage.content.parts, chunk);
const part = state.spans.openTextSpan(state.currentMessage.content.parts, chunk.payload.id);
state.announcedTextSpans.add(chunk.payload.id);
this.emitInitialPart(state, partIndex, structuredClone(part));
return;
}
if (chunk.type === "reasoning-start") {
state.spans.fold(state.currentMessage.content.parts, chunk);
const part = state.spans.openReasoningSpan(state.currentMessage.content.parts, chunk.payload.id);
state.announcedReasoningSpans.add(chunk.payload.id);
this.emitInitialPart(state, partIndex, structuredClone(part));
return;
}
const folded = state.spans.fold(state.currentMessage.content.parts, chunk);
if (!folded) return void 0;
const index = state.currentMessage.content.parts.indexOf(folded.part);
if (index === -1) return void 0;
if (chunk.type === "text-delta" && folded.part.type === "text") {
if (!state.announcedTextSpans.delete(chunk.payload.id) && folded.created) this.emitInitialPart(state, index, {
...folded.part,
text: ""
});
this.#session.emit({
type: "message_update",
id: state.currentMessage.id,
event: {
type: "text-delta",
delta: chunk.payload.text
}
});
} else if (chunk.type === "reasoning-delta" && folded.part.type === "reasoning") {
if (!state.announcedReasoningSpans.delete(chunk.payload.id) && folded.created) this.emitMessagePart(state, index);
else this.#session.emit({
type: "message_update",
id: state.currentMessage.id,
event: {
type: "reasoning-delta",
index,
delta: chunk.payload.text
}
});
} else this.emitMessagePart(state, index);
return;
}
switch (chunk.type) {
case "step-start": {
const payload = getPayload(chunk);
const messageId = getString(payload.messageId);
if (!messageId) break;
if (state.offeredResponseIds.has(messageId)) {
if (messageId === state.currentMessage.id) this.stampResponseModel(state.currentMessage, payload);
break;
}
if (state.offeredResponseIds.size > 0 || state.completedToolPrelude && state.currentMessage.content.parts.every((part) => part.type === "tool-invocation" && part.toolInvocation.state === "result")) this.finishCurrentMessageAndRotate(state);
state.completedToolPrelude = false;
state.offeredResponseIds.add(messageId);
if (!this.isCurrentMessageObserved(state)) state.currentMessage.id = messageId;
this.stampResponseModel(state.currentMessage, payload);
break;
}
case "tool-call-input-streaming-start": {
const payload = getPayload(chunk);
const toolCallId = getString(payload.toolCallId) ?? "";
const toolName = getString(payload.toolName) ?? "";
const title = getString(payload.title);
this.#session.emit({
type: "tool_input_start",
threadId: state.threadId,
toolCallId,
toolName,
title,
messageId: state.currentMessage.id
});
break;
}
case "tool-call-delta": {
const payload = getPayload(chunk);
const toolCallId = getString(payload.toolCallId) ?? "";
const argsTextDelta = getString(payload.argsTextDelta) ?? "";
const toolName = getString(payload.toolName);
const transform = require_payload_transform.getTransformedToolPayload(chunk.metadata, "display", "input-delta");
if (!transform?.suppress) this.#session.emit({
type: "tool_input_delta",
threadId: state.threadId,
toolCallId,
argsTextDelta: require_payload_transform.hasTransformedToolPayload(transform) ? transform.transformed : argsTextDelta,
toolName,
messageId: state.currentMessage.id
});
break;
}
case "tool-call-input-streaming-end": {
const toolCallId = getString(getPayload(chunk).toolCallId) ?? "";
this.#session.emit({
type: "tool_input_end",
threadId: state.threadId,
toolCallId,
messageId: state.currentMessage.id
});
break;
}
case "tool-call": {
const toolCall = getPayload(chunk);
const toolCallId = getString(toolCall.toolCallId) ?? "";
const toolName = getString(toolCall.toolName) ?? "";
const args = getDisplayTransform(chunk.metadata, "input-available", toolCall.args);
const title = getString(toolCall.title);
const toolIndex = state.currentMessage.content.parts.length;
state.currentMessage.content.parts.push({
type: "tool-invocation",
toolInvocation: {
state: "call",
toolCallId,
toolName,
args
},
title
});
state.toolPartById.set(toolCallId, toolIndex);
this.emitMessagePart(state, toolIndex);
this.#session.emit({
type: "tool_start",
threadId: state.threadId,
toolCallId,
toolName,
args,
title
});
break;
}
case "tool-result": {
const toolResult = getPayload(chunk);
this.applyToolOutcome(state, {
toolCallId: getString(toolResult.toolCallId) ?? "",
toolName: getString(toolResult.toolName) ?? "",
result: getDisplayTransform(chunk.metadata, "output-available", toolResult.result),
isError: isToolResultError(toolResult),
providerMetadata: isProviderMetadata(toolResult.providerMetadata) ? toolResult.providerMetadata : void 0
});
break;
}
case "tool-error": {
const toolError = getPayload(chunk);
this.applyToolOutcome(state, {
toolCallId: getString(toolError.toolCallId) ?? "",
toolName: getString(toolError.toolName) ?? "",
result: getDisplayTransform(chunk.metadata, "error", require_error.getErrorFromUnknown(toolError.error).message),
isError: true,
providerMetadata: isProviderMetadata(toolError.providerMetadata) ? toolError.providerMetadata : void 0
});
break;
}
case "tool-output": {
const toolOutput = getPayload(chunk);
const toolCallId = getString(toolOutput.toolCallId) ?? "";
const toolName = getString(toolOutput.toolName) ?? "";
const output = getRecord(toolOutput.output);
if (output?.from !== "AGENT" || !toolName.startsWith("agent-")) break;
const agentType = toolName.slice(6);
if (!this.#session.displayState.get().activeSubagents.has(toolCallId)) this.startDelegatedSubagent(state, toolCallId, toolName);
const nested = getRecord(output.payload) ?? {};
switch (output.type) {
case "text-delta":
this.#session.emit({
type: "subagent_text_delta",
toolCallId,
agentType,
textDelta: getString(nested.text) ?? ""
});
break;
case "tool-call":
this.#session.emit({
type: "subagent_tool_start",
toolCallId,
agentType,
subToolName: getString(nested.toolName) ?? "",
subToolArgs: nested.args
});
break;
case "tool-result":
case "tool-error": this.#session.emit({
type: "subagent_tool_end",
toolCallId,
agentType,
subToolName: getString(nested.toolName) ?? "",
subToolResult: output.type === "tool-error" ? nested.error : nested.result,
isError: output.type === "tool-error" || isToolResultError(nested)
});
}
break;
}
case "tool-output-denied": {
const payload = getPayload(chunk);
const toolCallId = getString(payload.toolCallId) ?? "";
const toolName = getString(payload.toolName) ?? "";
const approval = getRecord(payload.approval);
const reason = getString(approval?.reason);
const approvalTransform = require_payload_transform.getTransformedToolPayload(chunk.metadata, "display", "approval");
const args = require_payload_transform.hasTransformedToolPayload(approvalTransform) ? approvalTransform.transformed : getDisplayTransform(chunk.metadata, "input-available", payload.args);
const toolIndex = state.toolPartById.get(toolCallId);
const existing = toolIndex !== void 0 ? state.currentMessage.content.parts[toolIndex] : void 0;
const toolInvocation = {
state: "output-denied",
toolCallId,
toolName,
args,
approval: {
id: getString(approval?.id) ?? "",
approved: false,
...reason ? { reason } : {}
}
};
const partIndex = toolIndex ?? state.currentMessage.content.parts.length;
if (existing && existing.type === "tool-invocation") existing.toolInvocation = Object.assign(existing.toolInvocation, toolInvocation);
else {
state.currentMessage.content.parts.push({
type: "tool-invocation",
toolInvocation
});
state.toolPartById.set(toolCallId, partIndex);
}
this.emitMessagePart(state, partIndex);
this.#session.emit({
type: "tool_end",
threadId: state.threadId,
toolCallId,
result: reason,
isError: false,
denied: true
});
break;
}
case "tool-call-approval": {
const toolCallId = getString(getPayload(chunk).toolCallId) ?? "";
const toolName = getString(getPayload(chunk).toolName) ?? "";
const approvalTransform = require_payload_transform.getTransformedToolPayload(chunk.metadata, "display", "approval");
const toolArgs = require_payload_transform.hasTransformedToolPayload(approvalTransform) ? approvalTransform.transformed : getDisplayTransform(chunk.metadata, "input-available", getPayload(chunk).args);
const policy = this.#session.resolveToolApproval(toolName, requestContext);
const binding = {
threadId: state.threadId,
runId: chunk.runId ?? this.#session.run.getRunId() ?? void 0,
resourceId: this.#session.identity.getResourceId(),
agent,
abortSignal: this.#session.run.getAbortSignal()
};
if (binding.runId && this.#machinery.getRunScope(binding.runId)?.get(SOURCE_APPROVAL_CALLS_KEY)?.has(toolCallId)) break;
const currentRunId = binding.runId;
const currentThreadId = binding.threadId;
const pubsub = typeof agent.getPubSub === "function" ? agent.getPubSub() : void 0;
const getLeaseProvider = pubsub?.getLeaseProvider;
const hasPersistentLease = getLeaseProvider ? getLeaseProvider.call(pubsub) !== void 0 : require_output_helpers.isLeaseProvider(pubsub);
const currentSuspension = currentRunId && currentThreadId && hasPersistentLease ? require_run_registry.agentThreadStreamRuntime.getResumableThreadRunSuspension({
threadId: currentThreadId,
resourceId: binding.resourceId,
runId: currentRunId,
toolCallId
}, pubsub) : void 0;
let currentSuspensionRequiresApproval = currentSuspension ? currentSuspension.kind === "approval" : void 0;
if (currentRunId && hasPersistentLease && currentSuspensionRequiresApproval === void 0 && typeof agent.listSuspendedRuns === "function") try {
currentSuspensionRequiresApproval = (await agent.listSuspendedRuns({
threadId: currentThreadId,
resourceId: binding.resourceId
}))?.runs.find((run) => run.runId === currentRunId)?.toolCalls.find((toolCall) => toolCall.toolCallId === toolCallId)?.requiresApproval;
} catch (error) {
if (!(error instanceof require_error.MastraError) || error.id !== "AGENT_LIST_SUSPENDED_RUNS_NO_STORAGE") throw error;
}
if (currentSuspensionRequiresApproval === false) break;
if (this.#session.approval.isArmed({
toolCallId,
threadId: binding.threadId,
runId: binding.runId
}) || binding.runId && this.#machinery.getRunScope(binding.runId)?.get(SOURCE_APPROVAL_CALLS_KEY)?.has(toolCallId)) break;
if (policy === "allow") {
await this.#session.approveToolCall({
toolCallId,
requestContext,
...binding
});
break;
}
if (policy === "deny") {
await this.#session.declineToolCall({
toolCallId,
requestContext,
...binding
});
break;
}
if (binding.runId) {
const approvalRunScope = this.#machinery.getRunScope(binding.runId);
if (!approvalRunScope?.get(SUSPENDED_RUN_AGENT_KEY)) approvalRunScope?.set(SUSPENDED_RUN_AGENT_KEY, agent);
}
const armApproval = () => {
const promise = this.#session.approval.arm({
toolName,
toolCallId,
threadId: binding.threadId,
runId: binding.runId
});
this.#session.emit({
type: "tool_approval_required",
threadId: state.threadId,
toolCallId,
toolName,
args: toolArgs
});
return promise;
};
const armedBindingGeneration = this.#session.run.bindingGeneration();
let approvalPromise = armApproval();
while (true) {
const approval = await approvalPromise;
if (approval.decision === "detached") break;
const deferredAbortOrigin = this.#session.takeDeferredAbortOrigin();
const deferredAbort = deferredAbortOrigin !== void 0;
let dispatchAttempted = false;
const onDispatch = () => {
dispatchAttempted = true;
};
try {
if (!deferredAbort && approval.decision === "approve") await this.#session.approveToolCall({
toolCallId,
requestContext: approval.requestContext ?? requestContext,
...binding
}, onDispatch);
else await this.#session.declineToolCall({
toolCallId,
requestContext: approval.requestContext ?? requestContext,
...binding,
declineContext: deferredAbort ? {
reason: ABORTED_BY_USER_REASON,
message: ABORTED_BY_USER_REASON
} : approval.declineContext
}, onDispatch);
} catch (error) {
if (deferredAbort || binding.abortSignal?.aborted || this.#session.run.bindingGeneration() !== armedBindingGeneration || dispatchAttempted && !await this.#isAwaitingApproval(agent, binding, toolCallId)) throw error;
this.#session.emit({
type: "error",
error: require_error.getErrorFromUnknown(error)
});
approvalPromise = armApproval();
continue;
}
if (deferredAbort) {
this.settleToolCallAsDenied(state, {
toolCallId,
toolName,
args: toolArgs
});
this.#session.completeDeferredAbort(deferredAbortOrigin);
}
break;
}
break;
}
case "tool-call-suspended": {
const suspToolCallId = getString(getPayload(chunk).toolCallId) ?? "";
const suspToolName = getString(getPayload(chunk).toolName) ?? "";
const suspArgs = getDisplayTransform(chunk.metadata, "input-available", getPayload(chunk).args);
const suspPayload = getDisplayTransform(chunk.metadata, "suspend", getPayload(chunk).suspendPayload);
const suspResumeSchema = getString(getPayload(chunk).resumeSchema);
const suspRunId = this.#session.run.getRunId();
const suspThreadId = state.threadId;
const suspResourceId = state.resourceId;
let emitSuspension = true;
if (suspRunId) {
const runScope = this.#machinery.getRunScope(suspRunId);
if (!runScope?.get(SUSPENDED_RUN_AGENT_KEY)) runScope?.set(SUSPENDED_RUN_AGENT_KEY, agent);
if (runScope && !runScope.get(SUSPENDED_RUN_MEMORY_KEY)) try {
const suspMemory = await agent.getMemory({ requestContext });
if (suspMemory) runScope.set(SUSPENDED_RUN_MEMORY_KEY, suspMemory);
} catch {}
if (suspThreadId) {
emitSuspension = !this.#session.suspensions.has({
toolCallId: suspToolCallId,
runId: suspRunId,
threadId: suspThreadId,
resourceId: suspResourceId
});
this.#session.suspensions.register({
toolCallId: suspToolCallId,
runId: suspRunId,
toolName: suspToolName,
threadId: suspThreadId,
resourceId: suspResourceId
});
}
}
state.isSuspended = true;
const suspensionEvent = {
type: "tool_suspended",
resourceId: suspResourceId,
threadId: suspThreadId,
runId: suspRunId ?? void 0,
toolCallId: suspToolCallId,
toolName: suspToolName,
args: suspArgs,
suspendPayload: suspPayload,
resumeSchema: suspResumeSchema
};
if (emitSuspension) this.#session.emit(suspensionEvent);
else this.#session.displayState.apply(suspensionEvent);
break;
}
case "error": {
const errorPayload = getPayload(chunk);
const streamError = require_error.getErrorFromUnknown(errorPayload.error);
const failedToolCallId = getString(errorPayload.toolCallId);
this.#session.emit({
type: "error",
error: streamError
});
if (!(streamError instanceof require_run_registry.AgentThreadLeaseLostError)) this.retractFailedRunSuspensions({
resourceId: state.resourceId,
threadId: state.threadId,
runId: chunk.runId ?? this.#session.run.getRunId(),
reason: streamError.message,
toolCallId: failedToolCallId
});
break;
}
case "tripwire": {
const payload = getPayload(chunk);
const reason = getString(payload.reason) || "A processor stopped the run.";
const processorId = getString(payload.processorId);
const errorMessage = processorId ? `Processor "${processorId}" stopped the run: ${reason}` : reason;
this.setStopReason(state.currentMessage, "error", true);
this.setErrorMessage(state.currentMessage, errorMessage);
state.terminalError = errorMessage;
state.terminalFinishReason = "tripwire";
this.retractFailedRunSuspensions({
resourceId: state.resourceId,
threadId: state.threadId,
runId: chunk.runId ?? this.#session.run.getRunId(),
reason: errorMessage
});
break;
}
case "step-finish": {
state.completedToolPrelude = state.offeredResponseIds.size === 0 && this.hasCurrentMessageContent(state) && state.currentMessage.content.parts.every((part) => part.type === "tool-invocation" && part.toolInvocation.state === "result");
const stepUsage = toStepTokenUsage(getRecord(getPayload(chunk).output)?.usage);
if (stepUsage) {
const bindingGeneration = this.#session.run.bindingGeneration();
let savedUsage;
try {
if (state.threadId) savedUsage = (await this.#session.thread.getById({ threadId: state.threadId }))?.metadata?.tokenUsage;
} catch {
break;
}
if (this.#session.run.bindingGeneration() !== bindingGeneration || this.#session.thread.getId() !== state.threadId || this.#session.identity.getResourceId() !== state.resourceId) break;
if (savedUsage) this.#session.setTokenUsage({
...createEmptyTokenUsage(),
...savedUsage
});
else this.#session.addUsage(stepUsage);
this.#session.emit({
type: "usage_update",
usage: stepUsage,
total: this.#session.getTokenUsage()
});
}
break;
}
case "finish": {
const finishReason = getString(getRecord(getPayload(chunk).stepResult)?.reason) ?? "";
const finishProviderMetadata = getRecord(getPayload(chunk).metadata)?.providerMetadata ?? getPayload(chunk).providerMetadata;
const fallbackNotice = describeServerSideFallback(finishProviderMetadata);
if (fallbackNotice) this.#session.emit({
type: "info",
message: fallbackNotice
});
if (finishReason === "stop" || finishReason === "end-turn") this.setStopReason(state.currentMessage, "complete", true);
else if (finishReason === "tool-calls") this.setStopReason(state.currentMessage, "tool_use", true);
else {
const errorMessage = require_run_registry.describeNonSuccessFinishReason(finishReason, finishProviderMetadata);
if (errorMessage) {
this.setStopReason(state.currentMessage, "error", true);
this.setErrorMessage(state.currentMessage, errorMessage);
state.terminalError = errorMessage;
state.terminalFinishReason = finishReason;
} else this.setStopReason(state.currentMessage, "complete", true);
}
break;
}
case "goal": {
this.finishCurrentMessageAndRotate(state);
const goalPayload = getPayload(chunk);
if (isGoalEvaluationPayload(goalPayload)) this.#session.emit({
type: "goal_evaluation",
payload: goalPayload
});
break;
}
case "is-task-complete": {
this.finishCurrentMessageAndRotate(state);
const taskCompletePayload = getPayload(chunk);
if (isTaskCompletePayload(taskCompletePayload)) this.#session.emit({
type: "task_complete_evaluation",
payload: taskCompletePayload
});
break;
}
case "data-om-status": {
const d = getDataRecord(chunk);
const w = getRecord(d?.windows);
if (d && w) {
const active = getNestedRecord(w, "active");
const msgs = getNestedRecord(active, "messages");
const obs = getNestedRecord(active, "observations");
const buffered = getNestedRecord(w, "buffered");
const buffObs = getNestedRecord(buffered, "observations");
const buffRef = getNestedRecord(buffered, "reflection");
this.#session.emit({
type: "om_status",
windows: {
active: {
messages: {
tokens: getNumber(msgs?.tokens, 0),
threshold: getNumber(msgs?.threshold, 0)
},
observations: {
tokens: getNumber(obs?.tokens, 0),
threshold: getNumber(obs?.threshold, 0)
}
},
buffered: {
observations: {
status: getOmStatus(buffObs?.status),
chunks: getNumber(buffObs?.chunks, 0),
messageTokens: getNumber(buffObs?.messageTokens, 0),
projectedMessageRemoval: getNumber(buffObs?.projectedMessageRemoval, 0),
observationTokens: getNumber(buffObs?.observationTokens, 0)
},
reflection: {
status: getOmStatus(buffRef?.status),
inputObservationTokens: getNumber(buffRef?.inputObservationTokens, 0),
observationTokens: getNumber(buffRef?.observationTokens, 0)
}
}
},
recordId: getString(d.recordId) ?? "",
threadId: getString(d.threadId) ?? "",
stepNumber: getNumber(d.stepNumber, 0),
generationCount: getNumber(d.generationCount, 0)
});
}
break;
}
case "data-om-observation-start": {
const payload = getDataRecord(chunk);
const cycleId = getString(payload?.cycleId);
if (payload && cycleId) {
const operationType = getOperationType(payload.operationType);
if (operationType === "observation") this.#session.emit({
type: "om_observation_start",
cycleId,
operationType,
tokensToObserve: getNumber(payload.tokensToObserve, 0)
});
else this.#session.emit({
type: "om_reflection_start",
cycleId,
tokensToReflect: getNumber(payload.tokensToObserve, 0)
});
}
break;
}
case "data-om-observation-end": {
const payload = getDataRecord(chunk);
const cycleId = getString(payload?.cycleId);
if (payload && cycleId) {
if (payload.operationType === "reflection") this.#session.emit({
type: "om_reflection_end",
cycleId,
durationMs: getNumber(payload.durationMs, 0),
compressedTokens: getNumber(payload.observationTokens, 0),
observations: getString(payload.observations)
});
else this.#session.emit({
type: "om_observation_end",
cycleId,
durationMs: getNumber(payload.durationMs, 0),
tokensObserved: getNumber(payload.tokensObserved, 0),
observationTokens: getNumber(payload.observationTokens, 0),
observations: getString(payload.observations),
currentTask: getString(payload.currentTask),
suggestedResponse: getString(payload.suggestedResponse)
});
}
break;
}
case "data-om-observation-failed": {
const payload = getDataRecord(chunk);
if (payload) {
const operationType = getOperationType(payload.operationType);
const error = getString(payload.error) ?? "Unknown error";
if (operationType === "reflection") this.#session.emit({
type: "om_reflection_failed",
cycleId: getString(payload.cycleId) ?? "unknown",
error,
durationMs: getNumber(payload.durationMs, 0)
});
else this.#session.emit({
type: "om_observation_failed",
cycleId: getString(payload.cycleId) ?? "unknown",
error,
durationMs: getNumber(payload.durationMs, 0)
});
if (!(Object.hasOwn(payload, "retrying") && payload.retrying === true) && (!Object.hasOwn(payload, "failurePolicy") || !Object.hasOwn(payload, "failureKind") || payload.failurePolicy !== "continue" || payload.failureKind !== (operationType === "reflection" ? "reflector-model" : "observer-model"))) {
this.abortForOmFailure({
operationType,
stage: "run",
error
});
return { message: state.currentMessage };
}
}
break;
}
case "data-om-buffering-start": {
const payload = getDataRecord(chunk);
const cycleId = getString(payload?.cycleId);
if (payload && cycleId) this.#session.emit({
type: "om_buffering_start",
cycleId,
operationType: getOperationType(payload.operationType),
tokensToBuffer: getNumber(payload.tokensToBuffer, 0)
});
break;
}
case "data-om-buffering-end": {
const payload = getDataRecord(chunk);
const cycleId = getString(payload?.cycleId);
if (payload && cycleId) this.#session.emit({
type: "om_buffering_end",
cycleId,
operationType: getOperationType(payload.operationType),
tokensBuffered: getNumber(payload.tokensBuffered, 0),
bufferedTokens: getNumber(payload.bufferedTokens, 0),
observations: getString(payload.observations)
});
break;
}
case "data-om-buffering-failed": {
const payload = getDataRecord(chunk);
if (payload) {
const operationType = getOperationType(payload.operationType);
const error = getString(payload.error) ?? "Unknown error";
this.#session.emit({
type: "om_buffering_failed",
cycleId: getString(payload.cycleId) ?? "unknown",
operationType,
error
});
}
break;
}
case "data-signal": {
const payload = getDataRecord(chunk);
if (payload) {
const message = this.createSignalMessage("data-signal", payload);
this.#session.emit({
type: "message_start",
message
});
this.#session.emit({
type: "message_end",
id: message.id
});
}
break;
}
case "data-user-message": {
const payload = getDataRecord(chunk);
if (payload) {
this.finishCurrentMessageAndRotate(state);
const message = this.createSignalMessage("data-user-message", payload);
this.#session.emit({
type: "message_start",
message
});
this.#session.emit({
type: "message_end",
id: message.id
});
}
break;
}
case "data-system-reminder": {
const payload = getDataRecord(chunk);
if (payload) {
const message = this.createSignalMessage("data-system-reminder", payload);
this.#session.emit({
type: "message_start",
message
});
this.#session.emit({
type: "message_end",
id: message.id
});
}
break;
}
case "data-om-activation": {
const payload = getDataRecord(chunk);
const cycleId = getString(payload?.cycleId);
if (payload && cycleId) this.#session.emit({
type: "om_activation",
cycleId,
operationType: getOperationType(payload.operationType),
chunksActivated: getNumber(payload.chunksActivated, 0),
tokensActivated: getNumber(payload.tokensActivated, 0),
observationTokens: getNumber(payload.observationTokens, 0),
messagesActivated: getNumber(payload.messagesActivated, 0),
generationCount: getNumber(payload.generationCount, 0),
triggeredBy: getActivationTrigger(payload.triggeredBy),
lastActivityAt: getOptionalNumber(payload.lastActivityAt),
ttlExpiredMs: getOptionalNumber(payload.ttlExpiredMs),
activateAfterIdle: getOptionalNumber(getRecord(payload.config)?.activateAfterIdle),
previousModel: getString(payload.previousModel),
currentModel: getString(payload.currentModel)
});
break;
}
case "data-om-thread-update": {
const payload = getDataRecord(chunk);
const newTitle = getString(payload?.newTitle);
if (payload && newTitle) this.#session.emit({
type: "om_thread_title_updated",
cycleId: getString(payload.cycleId) ?? "unknown",
threadId: getString(payload.threadId) ?? this.#session.thread.getId() ?? "unknown",
oldTitle: getString(payload.oldTitle),
newTitle
});
break;
}
case "data-mastracode-tool-progress": {
const d = chunk.data;
if (d?.toolCallId && d?.progress !== void 0) {
this.#session.emit({
type: "tool_update",
threadId: state.threadId,
toolCallId: d.toolCallId,
partialResult: d.progress
});
const output = formatToolProgressOutput(d.progress);
if (output) this.#session.emit({
type: "shell_output",
threadId: state.threadId,
toolCallId: d.toolCallId,
output,
stream: "stdout"
});
}
break;
}
case "data-sandbox-stdout": {
const d = getDataRecord(chunk);
const output = getString(d?.output);
const toolCallId = getString(d?.toolCallId);
if (output && toolCallId) this.#session.emit({
type: "shell_output",
threadId: state.threadId,
toolCallId,
output,
stream: "stdout"
});
break;
}
case "data-sandbox-stderr": {
const d = getDataRecord(chunk);
const output = getString(d?.output);
const toolCallId = getString(d?.toolCallId);
if (output && toolCallId) this.#session.emit({
type: "shell_output",
threadId: state.threadId,
toolCallId,
output,
stream: "stderr"
});
break;
}
case "data-sandbox-exit": {
const d = getDataRecord(chunk);
const toolCallId = getString(d?.toolCallId);
const exitCode = getOptionalNumber(d?.exitCode);
if (toolCallId && exitCode !== void 0) this.#session.emit({
type: "command_exit",
threadId: state.threadId,
toolCallId,
exitCode,
success: getBoolean(d?.success, exitCode === 0),
killed: getBoolean(d?.killed, false),
timedOut: getBoolean(d?.timedOut, false),
error: getString(d?.error)
});
break;
}
}
}
/**
* Settle parked native tool suspensions before aborting their suspended run.
* The run cannot emit another chunk after `suspend()`, so update the saved
* assistant message directly instead of leaving its tool invocation in
* `state: 'call'` forever.
*
* Each suspension is settled through its own originating binding: the agent
* retained on its run scope and the thread/resource it was persisted under.
* The session may have been rebound (new thread, resource, or agent) while
* the run stayed suspended, so the current binding cannot be assumed. If one
* suspension fails to settle, the rest are still attempted and the first
* error is rethrown for the caller to surface.
*/
async settleSuspendedToolCallsAsDenied(suspensions) {
if (suspensions.length === 0) return;
const currentMessage = this.#session.displayState.get().currentMessage;
const currentThreadId = this.#session.thread.getId();
const currentResourceId = this.#session.identity.getResourceId();
const currentMessageUpdates = /* @__PURE__ */ new Map();
let firstError;
for (const suspension of suspensions) try {
const runScope = this.#machinery.getRunScope(suspension.runId);
const agent = runScope?.get(SUSPENDED_RUN_AGENT_KEY) ?? this.#machinery.getAgent();
const memory = runScope?.get(SUSPENDED_RUN_MEMORY_KEY) ?? await agent.getMemory();
const persistedMessages = memory ? (await memory.recall({
threadId: suspension.threadId,
resourceId: suspension.resourceId
})).messages : [];
const candidates = currentMessage && suspension.threadId === currentThreadId && suspension.resourceId === currentResourceId ? [currentMessage, ...persistedMessages] : persistedMessages;
const changedMessages = /* @__PURE__ */ new Map();
let settled = false;
for (const message of candidates) {
const partIndex = message.content.parts.findIndex((part) => part.type === "tool-invocation" && part.toolInvocation.toolCallId === suspension.toolCallId);
const part = message.content.parts[partIndex];
if (!part || part.type !== "tool-invocation" || part.toolInvocation.state !== "call") continue;
part.toolInvocation = Object.assign(part.toolInvocation, {
state: "output-denied",
approval: {
id: suspension.toolCallId,
approved: false,
reason: ABORTED_BY_USER_REASON
}
});
if (message.threadId) changedMessages.set(message.id, message);
if (message === currentMessage) currentMessageUpdates.set(partIndex, part);
settled = true;
}
if (settled) this.#session.emit({
type: "tool_end",
threadId: suspension.threadId,
toolCallId: suspension.toolCallId,
result: ABORTED_BY_USER_REASON,
isError: false,
denied: true
});
if (changedMessages.size > 0) await memory?.saveMessages({ messages: [...changedMessages.values()] });
} catch (error) {
firstError ??= require_error.getErrorFromUnknown(error);
}
if (currentMessage) for (const [index, part] of currentMessageUpdates) this.#session.emit({
type: "message_update",
id: currentMessage.id,
event: {
type: "part",
index,
part: structuredClone(part)
}
});
if (firstError) throw firstError;
}
/**
* Mark a tool call as denied on the in-flight assistant message and notify
* subscribers, mirroring what the `tool-output-denied` chunk would do. Used
* when the run is torn down before that chunk can be consumed (abort while a
* tool-approval gate is parked).
*/
settleToolCallAsDenied(state, { toolCallId, toolName, args }) {
const toolInvocation = {
state: "output-denied",
toolCallId,
toolName,
args,
approval: {
id: toolCallId,
approved: false,
reason: ABORTED_BY_USER_REASON
}
};
const toolIndex = state.toolPartById.get(toolCallId);
const existing = toolIndex !== void 0 ? state.currentMessage.content.parts[toolIndex] : void 0;
const partIndex = toolIndex ?? state.currentMessage.content.parts.length;
if (existing && existing.type === "tool-invocation") existing.toolInvocation = Object.assign(existing.toolInvocation, toolInvocation);
else {
state.currentMessage.content.parts.push({
type: "tool-invocation",
toolInvocation
});
state.toolPartById.set(toolCallId, partIndex);
}
this.emitMessagePart(state, partIndex);
this.#session.emit({
type: "tool_end",
threadId: state.threadId,
toolCallId,
result: ABORTED_BY_USER_REASON,
isError: false,
denied: true
});
}
/**
* Whether storage still lists `toolCallId` as awaiting approval on the run
* that parked it. A resume that failed after dispatch may or may not have
* consumed the snapshot; only a confirmed pending call is safe to re-arm.
*/
async #isAwaitingApproval(agent, binding, toolCallId) {
if (!binding.runId || typeof agent.listSuspendedRuns !== "function") return false;
try {
return (await agent.listSuspendedRuns({
threadId: binding.threadId,
resourceId: binding.resourceId
}))?.runs.find((run) => run.runId === binding.runId)?.toolCalls.find((toolCall) => toolCall.toolCallId === toolCallId)?.requiresApproval === true;
} catch {
return false;
}
}
finishStreamState(state) {
if (this.hasCurrentMessageContent(state) || !state.lastFinishedMessage) {
this.finishCurrentMessage(state);
return {
message: state.currentMessage,
suspended: state.isSuspended || void 0
};
}
return {
message: state.lastFinishedMessage,
suspended: state.isSuspended || void 0
};
}
async finishSubscribedStreamRun({ suspended, error, aborted, resourceId, threadId, terminalError, abortReason }) {
const reason = error ? "error" : suspended ? "suspended" : aborted || this.#session.run.isAbortRequested() ? "aborted" : "complete";
const runId = this.#session.run.getRunId();
if (reason === "complete" && resourceId && threadId && runId) for (const s of this.#session.suspensions.deleteForRun({
resourceId,
threadId,
runId
})) this.#session.displayState.deletePendingSuspension({
resourceId: s.resourceId,
threadId: s.threadId,
runId: s.runId,
toolCallId: s.toolCallId
});
else if (reason === "aborted") this.retractFailedRunSuspensions({
resourceId,
threadId,
runId,
reason: ABORTED_BY_USER_REASON
});
else if (reason === "error" && terminalError) this.retractFailedRunSuspensions({
resourceId,
threadId,
runId,
reason: terminalError
});
await this.#session.finishAgentRun(reason, reason === "aborted" ? { abortReason } : void 0);
this.#session.run.reset();
}
/**
* Drop suspensions that a failed run can no longer resume. With `toolCallId`, only that
* call's suspension is dropped: the stream reported a failure scoped to one tool call
* (for example its own save failed) while the rest of the run is still live.
*/
retractFailedRunSuspensions({ resourceId, threadId, runId, reason, toolCallId }) {
if (!resourceId || !threadId || !runId) return;
if (toolCallId) {
const suspension = this.#session.suspensions.get({
resourceId,
threadId,
runId,
toolCallId
});
if (!suspension) return;
this.#session.suspensions.delete({
resourceId,
threadId,
runId,
toolCallId
});
this.emitSuspensionCancelled(suspension, reason);
return;
}
for (const suspension of this.#session.suspensions.deleteForRun({
resourceId,
threadId,
runId
})) this.emitSuspensionCancelled(suspension, reason);
}
emitSuspensionCancelled(suspension, reason) {
this.#session.emit({
type: "tool_suspension_cancelled",
resourceId: suspension.resourceId,
threadId: suspension.threadId,
runId: suspension.runId,
toolCallId: suspension.toolCallId,
toolName: suspension.toolName,
reason
});
}
async handleSubscribedStreamError(error, resourceId, threadId) {
if (error instanceof Error && error.name === "AbortError") await this.#session.finishAgentRun("aborted");
else {
const streamError = require_error.getErrorFromUnknown(error);
this.#session.emit({
type: "error",
error: streamError
});
if (!(streamError instanceof require_run_registry.AgentThreadLeaseLostError)) this.retractFailedRunSuspensions({
resourceId,
threadId,
runId: this.#session.run.getRunId(),
reason: streamError.message
});
await this.#session.finishAgentRun("error");
}
this.#session.stream.detach();
this.#session.run.reset();
}
async processSubscribedThreadStream(subscription) {
const binding = this.#session.stream.getBinding({ subscription });
if (!binding) return;
const { resourceId, threadId } = binding;
const agent = this.#session.stream.getAgent({ subscription }) ?? this.#machinery.getAgent();
let currentRun;
let requestContext;
let bailed = false;
const consume = async () => {
for await (const chunk of subscription.stream) {
if (bailed) return;
if (!this.#session.stream.isCurrent({ subscription })) {
subscription.unsubscribe();
break;
}
if (chunk.type === "thread-history") continue;
const runId = ("runId" in chunk ? chunk.runId : void 0) ?? subscription.activeRunId();
const abortedRunId = this.#session.stream.abortedRunId({ subscription });
if (runId && runId === abortedRunId) continue;
if (runId && abortedRunId) this.#session.stream.clearAbortedRun();
if (!currentRun) {
currentRun = this.createStreamState(threadId, resourceId);
this.#session.run.nextOperation();
this.#session.run.ensureAbortController();
this.#session.run.setRunId({ runId });
this.#session.run.setTraceId({ traceId: null });
requestContext = await this.#machinery.buildRequestContext(subscription.__getCurrentRunRequestContext?.(), {
threadId,
resourceId,
runId: runId ?? void 0,
execution: true
});
if (!this.#session.stream.isCurrent({ subscription })) break;
this.#session.emit({ type: "agent_start" });
}
if (chunk.type === "start") continue;
try {
const streamResult = await this.processStreamChunk(currentRun, chunk, requestContext, agent);
if (streamResult || chunk.type === "finish" || chunk.type === "error" || chunk.type === "abort" || chunk.type === "tripwire" || chunk.type === "tool-call-suspended") {
const finished = streamResult ?? this.finishStreamState(currentRun);
const suspended = chunk.type === "tool-call-suspended" || finished.suspended || void 0;
const aborted = chunk.type === "abort";
let isError = chunk.type === "error";
let terminalError;
if (currentRun.terminalError && !isError && !aborted && !this.#session.run.isAbortRequested() && !suspended) {
isError = true;
terminalError = currentRun.terminalError;
this.#session.emit({
type: "error",
error: new Error(currentRun.terminalError),
finishReason: currentRun.terminalFinishReason
});
}
await this.finishSubscribedStreamRun({
suspended,
error: isError,
aborted,
resourceId: currentRun.resourceId,
threadId: currentRun.threadId,
terminalError,
abortReason: aborted ? getString(getRecord(chunk.payload)?.reason) : void 0
});
currentRun = void 0;
if (aborted) this.#session.stream.markAbortedRun({
subscription,
runId: runId ?? null
});
}
} catch (error) {
await this.handleSubscribedStreamError(error, resourceId, threadId);
currentRun = void 0;
}
}
};
try {
const bailGuard = new AbortController();
try {
bailed = await Promise.race([consume(), abortDeadline(this.#session.run, bailGuard.signal, ABORT_STREAM_GRACE_MS)]) === abortBailed;
} finally {
bailGuard.abort();
}
if (currentRun && this.#session.stream.isCurrent({ subscription })) {
const streamResult = this.finishStreamState(currentRun);
await this.finishSubscribedStreamRun({
suspended: streamResult.suspended,
resourceId: currentRun.resourceId,
threadId: currentRun.threadId
});
currentRun = void 0;
}
if ((bailed || this.#session.stream.abortedRunId({ subscription })) && this.#session.stream.isCurrent({ subscription })) this.#session.stream.detach();
} catch (error) {
if (this.#session.stream.isCurrent({ subscription })) await this.handleSubscribedStreamError(error, resourceId, threadId);
}
}
};
// src/agent-controller/session.ts
const SUSPENDED_RUN_AGENT_KEY = require_stream.createRunScopeKey("agent-controller.suspendedRunAgent");
const SOURCE_APPROVAL_CALLS_KEY = require_stream.createRunScopeKey("agent-controller.sourceApprovalCalls");
const THREAD_OWNER_ID_RUN_SCOPE_KEY = require_stream.createRunScopeKey("agent-controller.threadOwnerId");
const THREAD_OWNER_ID_CONTEXT_KEY = "mastra__agentControllerThreadOwnerId";
/**
* The mode a run was started (or explicitly transitioned) in. Stored as a raw
* request-context value so the suspend snapshot persists it, and a resume can
* apply that mode's tool allowlist even after the session switched modes.
*/
const RUN_MODE_ID_CONTEXT_KEY = "mastra__agentControllerRunModeId";
/**
* Bucket key for grants that apply to every thread. Grant calls that name no
* thread (an embedder granting up front) land here; grants made from an
* approval prompt are filed under the thread that owns the gate instead.
*/
const SESSION_WIDE_GRANT_BUCKET = "\0session-wide";
/**
* Memory the suspended run persisted its messages under, resolved with the
* run's own RequestContext while the stream was live. Abort settlement cannot
* rebuild that context later (dynamic `memory: ({ requestContext }) => …`
* configs would resolve differently against an empty context), so the resolved
* instance is retained beside the owning agent for the life of the run scope.
*/
const SUSPENDED_RUN_MEMORY_KEY = require_stream.createRunScopeKey("agent-controller.suspendedRunMemory");
function addOptionalUsageField(usage, key, value) {
if (value !== void 0) usage[key] = (usage[key] ?? 0) + value;
}
/** Persisted thread-setting key for the currently-selected mode. */
const MODE_ID_KEY = "currentModeId";
/**
* Reason attached to tool prompts retracted because the user aborted the run.
* Shared by the parked-suspension retraction and the gated-approval decline so
* both render the same "the user interrupted this" explanation.
*/
const ABORTED_BY_USER_REASON = "Aborted by the user";
/**
* Session-state keys that are transparently persisted to thread metadata on
* every state update and restored by `Session.loadMetadata()`. These are user
* preferences that must survive a host restart (sessions themselves are
* in-memory only).
*/
const PERSISTED_STATE_KEYS = [
"thinkingLevel",
"notifications",
"permissionRules"
];
const THREAD_DERIVED_STATE_KEYS = [...[
"observerModelId",
"reflectorModelId",
"observerModelSelection",
"reflectorModelSelection",
"observationThreshold",
"reflectionThreshold"
], ...PERSISTED_STATE_KEYS];
function isSubagentModelKey(key) {
return key === "subagentModelId" || key.startsWith("subagentModelId_");
}
function threadDerivedStateKeys(state) {
return [...THREAD_DERIVED_STATE_KEYS, ...Object.keys(state).filter(isSubagentModelKey)];
}
/** Version marker for thread metadata using the single-model persistence format. */
const MODEL_PERSISTENCE_VERSION = 2;
const MODEL_PERSISTENCE_VERSION_KEY = "modelPersistenceVersion";
const modelPersistenceQueues = /* @__PURE__ */ new Map();
async function runModelPersistenceOperation(threadId, operation) {
if (!threadId) return operation();
const result = (modelPersistenceQueues.get(threadId) ?? Promise.resolve()).catch(() => {}).then(operation);
const settled = result.then(() => void 0, () => void 0);
modelPersistenceQueues.set(threadId, settled);
try {
return await result;
} finally {
if (modelPersistenceQueues.get(threadId) === settled) modelPersistenceQueues.delete(threadId);
}
}
/**
* Resolve and migrate a thread's persisted model selection.
*
* Threads created before single-model sessions have a create-time `currentModelId`
* plus the actual last selection in `modeModelId_<mode>`. Without the version
* marker, the active mode's legacy value wins. Migration copies that selection
* to `currentModelId`, stamps the marker, then removes all obsolete mode keys.
*/
async function migratePersistedModelSelection({ metadata, getMetadata, modeId, onResolved, set, threadId, validModeIds }) {
return runModelPersistenceOperation(threadId, async () => {
const persistedMetadata = getMetadata ? await getMetadata() : metadata ?? {};
const currentModelId = typeof persistedMetadata.currentModelId === "string" ? persistedMetadata.currentModelId : void 0;
const persistedModeId = persistedMetadata.currentModeId;
const legacyKey = `modeModelId_${typeof persistedModeId === "string" && (!validModeIds || validModeIds.includes(persistedModeId)) ? persistedModeId : modeId}`;
const legacyModelId = typeof persistedMetadata[legacyKey] === "string" ? persistedMetadata[legacyKey] : void 0;
const legacyKeys = Object.keys(persistedMetadata).filter((key) => key.startsWith("modeModelId_") && persistedMetadata[key] !== void 0);
const persistenceVersion = persistedMetadata[MODEL_PERSISTENCE_VERSION_KEY];
const isNewerFormat = typeof persistenceVersion === "number" && persistenceVersion > 2;
const isSingleModelFormat = persistenceVersion === 2 || isNewerFormat;
const modelId = isSingleModelFormat ? currentModelId : legacyModelId ?? currentModelId;
if (isNewerFormat || isSingleModelFormat && legacyKeys.length === 0) {
if (modelId) await onResolved?.(modelId, persistedMetadata);
return modelId;
}
if (!modelId && legacyKeys.length === 0) return void 0;
if (modelId) await set("currentModelId", modelId);
for (const key of legacyKeys) await set(key, void 0);
await set(MODEL_PERSISTENCE_VERSION_KEY, 2);
if (modelId) await onResolved?.(modelId, persistedMetadata);
return modelId;
});
}
/**
* Internal thread-metadata keys used by `Session.loadMetadata()` to persist
* runtime bookkeeping (selected model/mode, observer/reflector config, token
* usage). These share the flat thread `metadata` bag with user-provided
* session scoping tags, so they must never be treated as tags: they are
* skipped when stamping tags onto a thread and excluded when reading tags
* back out of thread metadata.
*/
const RESERVED_THREAD_METADATA_KEYS = [
"currentModelId",
MODEL_PERSISTENCE_VERSION_KEY,
MODE_ID_KEY,
"observerModelId",
"reflectorModelId",
"observerModelSelection",
"reflectorModelSelection",
"observationThreshold",
"reflectionThreshold",
"tokenUsage",
"ownerId",
"createdBy",
...PERSISTED_STATE_KEYS
];
function isReservedThreadMetadataKey(key) {
return RESERVED_THREAD_METADATA_KEYS.some((reserved) => reserved === key) || key.startsWith("modeModelId_");
}
/**
* Identifies an in-memory session host. A session is not a durable conversation:
* it is the process-local handle for `{ id, resourceId, tags, active threadId }`.
* Conversation settings and run state belong to the active thread and are
* re-derived whenever the host creates or switches threads.
*
* `defaultResourceId` is the resourceId the host started with; switching to a
* different resource (e.g. impersonation, or browsing another user's threads)
* updates the current resourceId while the default is retained so the host can
* return to its original resource.
*
* `id` and `ownerId` are stable host identity fields. They are not persisted by
* AgentController and do not describe ownership of any particular thread. The
* active thread binding lives on {@link SessionThread}.
*/
var SessionIdentity = class {
/** The memory resourceId the session currently reads/writes under. */
#resourceId;
/** The resourceId the session started with, retained across resource switches. */
#defaultResourceId;
/** Stable identifier for this process-local session host. */
#id;
/** Stable identity attached to this process-local session host. */
#ownerId;
constructor({ resourceId, id, ownerId }) {
this.#resourceId = resourceId;
this.#defaultResourceId = resourceId;
this.#id = id;
this.#ownerId = ownerId;
}
/** The resourceId the session currently reads/writes under. */
getResourceId() {
return this.#resourceId;
}
/** The resourceId the session started with. */
getDefaultResourceId() {
return this.#defaultResourceId;
}
/** The stable session identifier for this session. */
getId() {
return this.#id;
}
/**
* The stable identity of this process-local session host.
* Use `AgentControllerRequestContext.threadOwnerId` for thread ownership and billing attribution.
*/
getOwnerId() {
return this.#ownerId;
}
/** Point the session at a different resourceId (the default is unchanged). */
setResourceId({ resourceId }) {
this.#resourceId = resourceId;
}
};
/**
* Owns the session's thread domain: the navigational binding (which thread the
* session is currently on) plus the data reads/queries scoped to it. `null`
* until the session is bound (a thread is created, switched to, or reacquired on
* startup); switching/deleting updates it.
*
* In the multi-user model each session has its own current thread and reads its
* own threads, while the AgentController host shares storage, the thread lock, and the
* event bus. So the binding + data queries are per-session and live here; the
* session leverages the host's storage via an injected {@link ThreadDataStore}.
* Lifecycle *transitions* (create/switch/clone/delete) remain host machinery
* because they drive the shared event bus and rebind the shared agent stream.
*/
const threadOwnershipMutexes = /* @__PURE__ */ new Map();
async function withThreadOwnershipMutex(threadId, operation) {
const previous = threadOwnershipMutexes.get(threadId) ?? Promise.resolve();
let release;
const current = new Promise((resolve) => {
release = resolve;
});
const tail = previous.then(() => current);
threadOwnershipMutexes.set(threadId, tail);
await previous;
try {
return await operation();
} finally {
release();
if (threadOwnershipMutexes.get(threadId) === tail) threadOwnershipMutexes.delete(threadId);
}
}
var SessionThread = class {
/** The active thread id, or null when the session is not bound to a thread. */
#threadId = null;
/** Fences async hydration and queued state writes across binding changes. */
#bindingGeneration = 0;
/** Gateway to the host's shared thread storage, injected via {@link connect}. */
#store;
/** Reads the session's current resourceId (sibling identity state). */
#getResourceId;
/**
* The owning session, injected via {@link connect}. Thread lifecycle
* transitions (create/switch/clone/delete) orchestrate sibling session
* subsystems (model/mode/om/state/stream/run/usage/event bus) plus rebind the
* agent subscription, so the thread domain reaches its peers through this
* back-reference. Host-owned primitives (storage, lock, clone) stay behind the
* injected {@link ThreadDataStore}.
*/
#session;
/** Serializes create/clone/switch/delete so bindings and locks commit in call order. */
#lifecycleQueue;
#hasBoundThread = false;
constructor(getResourceId) {
this.#getResourceId = getResourceId;
}
/**
* Attach the shared-host storage gateway the thread domain reads/writes
* through and the owning session whose subsystems lifecycle transitions
* orchestrate. The AgentController calls this once during wiring; without a store the
* data methods degrade gracefully.
*/
connect(store, session) {
this.#store = store;
this.#session = session;
}
/** The owning session, throwing when accessed before {@link connect}. */
get #owner() {
if (!this.#session) throw new Error("SessionThread has not been connected to its session");
return this.#session;
}
#runLifecycle(operation) {
const predecessor = this.#lifecycleQueue;
let release;
const tail = new Promise((resolve) => {
release = resolve;
});
this.#lifecycleQueue = tail;
return (async () => {
try {
if (predecessor) await predecessor;
return await operation();
} finally {
release();
if (this.#lifecycleQueue === tail) this.#lifecycleQueue = void 0;
}
})();
}
/** The active thread id, or null when the session is not bound to a thread. */
getId() {
return this.#threadId;
}
/** Whether the session is currently bound to a thread. */
isSet() {
return this.#threadId !== null;
}
/** The active thread id, throwing when the session is not bound to a thread. */
requireId() {
if (this.#threadId === null) throw new Error("No active thread on this session");
return this.#threadId;
}
/**
* The active thread id, creating and binding a new thread when the session
* is unbound. Concurrent callers share one creation.
*/
async ensureId({ requestContext } = {}) {
if (!this.#lifecycleQueue && this.#threadId !== null) return this.#threadId;
return this.#runLifecycle(async () => {
if (this.#threadId !== null) return this.#threadId;
return (await this.#create({ requestContext })).id;
});
}
/**
* Bind the session directly to a thread and reset its live projection.
*
* Prefer {@link create}, {@link clone}, or {@link switch}; direct binding is
* rejected while a serialized lifecycle transition is pending.
*/
set({ threadId }) {
if (this.#lifecycleQueue) throw new Error("Cannot set the active thread during a thread lifecycle transition");
return this.#set({ threadId });
}
#set({ threadId, preserveStartupSelection = false }) {
this.#threadId = threadId;
this.#hasBoundThread = true;
this.#bindingGeneration++;
if (this.#session) {
if (preserveStartupSelection) this.#session.state.rebind([]);
else {
this.#resetThreadSelection();
this.#session.resetThreadDerivedState();
}
this.#session.resetTokenUsage();
}
return this.#bindingGeneration;
}
#resetThreadSelection() {
const session = this.#session;
if (!session) return;
const previousModeId = session.mode.get();
const previousModelId = session.model.get();
session.resetThreadSelection();
const modeId = session.mode.get();
const modelId = session.model.get();
if (modeId !== previousModeId) session.emit({
type: "mode_changed",
modeId,
previousModeId
});
if (modelId !== previousModelId) session.emit({
type: "model_changed",
modelId,
thinkingLevel: session.state.get().thinkingLevel
});
}
/**
* Clear the session's thread binding and reset its live projection.
*
* Prefer lifecycle methods; direct clearing is rejected while a serialized
* lifecycle transition is pending.
*/
clear() {
if (this.#lifecycleQueue) throw new Error("Cannot clear the active thread during a thread lifecycle transition");
this.#clear();
}
#clear() {
this.#threadId = null;
this.#bindingGeneration++;
if (this.#session) {
this.#resetThreadSelection();
this.#session.resetThreadDerivedState();
this.#session.resetTokenUsage();
}
}
/** Whether an async operation still targets the current thread binding. */
#isCurrentBinding(threadId, bindingGeneration) {
return this.#threadId === threadId && this.#bindingGeneration === bindingGeneration;
}
/** Serialize teardown with thread lifecycle work, then clear the binding and release its lock. */
clearAndReleaseLock() {
return this.#runLifecycle(() => this.#clearAndReleaseLock());
}
async #clearAndReleaseLock({ ignoreReleaseFailure = false } = {}) {
const threadId = this.#threadId;
this.cleanupSubscription();
this.#clear();
if (threadId) try {
await this.#store?.releaseLock(threadId);
} catch (error) {
if (!ignoreReleaseFailure) throw error;
}
}
/** Serialize a resource transition with thread lifecycle work. */
setResourceId({ resourceId }) {
return this.#runLifecycle(async () => {
await this.#clearAndReleaseLock({ ignoreReleaseFailure: true });
this.#owner.identity.setResourceId({ resourceId });
});
}
/** List this session's threads (its own resource by default, or all resources). */
async list(options) {
if (!this.#store) return [];
const resourceId = options?.allResources ? void 0 : this.#getResourceId();
return await this.#store.listThreads({
resourceId,
includeForkedSubagents: options?.includeForkedSubagents,
metadata: options?.metadata
});
}
/** Fetch a single thread by id, or null when it doesn't exist / no storage. */
async getById({ threadId }) {
if (!this.#store) return null;
return this.#store.getById({ threadId });
}
/** Clone a detected cross-resource project thread into this session's resource. */
cloneToCurrentResource(options) {
return this.#runLifecycle(() => this.#cloneToCurrentResource(options));
}
async #cloneToCurrentResource({ threadId, expectedResourceId, expectedProjectPath, requestContext }) {
if (!this.#store?.hasStorage()) throw new Error("Memory is not configured on this AgentController");
const thread = await this.#store.getById({ threadId });
if (!thread || thread.resourceId !== expectedResourceId || thread.metadata?.projectPath !== expectedProjectPath || expectedResourceId === this.#getResourceId()) throw new Error(`Thread not found: ${threadId}`);
return this.#cloneThread({
sourceThreadId: thread.id,
resourceId: this.#getResourceId(),
title: thread.title,
metadata: thread.metadata,
requestContext
});
}
/**
* Load a thread and verify it belongs to this session's resourceId before
* allowing access. Threads owned by another resource are treated as missing
* so a session can never read, switch to, rename, or delete a thread it does
* not own (the thread id is otherwise an unguessable but unscoped key). Throws
* `Thread not found: <id>` when the thread is absent or owned by someone else.
*/
async #requireOwnedThread({ threadId }) {
const thread = await this.#store?.getById({ threadId });
if (!thread || thread.resourceId !== this.#getResourceId()) throw new Error(`Thread not found: ${threadId}`);
return thread;
}
/** List messages for a thread (newest-`limit`, returned oldest-first), or all. */
async listMessages({ threadId, limit }) {
if (!this.#store) return [];
await this.#requireOwnedThread({ threadId });
return (await this.#store.listMessages({
threadId,
limit
})).messages;
}
/** List messages for the session's active thread (empty when not bound). */
async listActiveMessages({ limit } = {}) {
if (this.#threadId === null) return [];
return this.listMessages({
threadId: this.#threadId,
limit
});
}
/** The first user message for a single thread, or null. */
async firstUserMessage({ threadId }) {
return (await this.firstUserMessages({ threadIds: [threadId] })).get(threadId) ?? null;
}
/** The first user message for each given thread id. */
async firstUserMessages({ threadIds }) {
if (!this.#store || threadIds.length === 0) return /* @__PURE__ */ new Map();
return this.#store.firstUserMessages({ threadIds });
}
/** Read a setting (metadata value) for the active thread. */
async getSetting({ key }) {
if (this.#threadId === null) return void 0;
return this.getSettingOn({
threadId: this.#threadId,
key
});
}
/** Read a setting from a specific thread, regardless of the current binding. */
async getSettingOn({ threadId, key }) {
if (!this.#store) return void 0;
return this.#store.getMetadata({
threadId,
key
});
}
/** Persist a setting (metadata value) for the active thread. */
async setSetting({ key, value }) {
if (this.#threadId === null) return;
await this.setSettingOn({
threadId: this.#threadId,
key,
value
});
}
/** Persist a setting to a specific thread, regardless of the current binding. */
async setSettingOn({ threadId, key, value }) {
if (!this.#store) return;
if (value === void 0) {
await this.#store.deleteMetadata({
threadId,
key
});
return;
}
await this.#store.setMetadata({
threadId,
key,
value
});
}
/** Delete a setting (metadata value) for the active thread. */
async deleteSetting({ key }) {
if (!this.#store || this.#threadId === null) return;
await this.#store.deleteMetadata({
threadId: this.#threadId,
key
});
}
/**
* Read a thread's durable owner. Owner-less legacy threads lazily inherit this
* session host's identity without writing a backfill.
*/
async getOwner({ threadId = this.#threadId } = {}) {
if (!threadId) return void 0;
if (!this.#store?.hasStorage()) return this.#owner.identity.getOwnerId();
const thread = await this.#store.getById({ threadId });
if (!thread) {
if (threadId === this.#threadId) return this.#owner.identity.getOwnerId();
throw new Error(`Thread not found: ${threadId}`);
}
if (thread.resourceId !== this.#getResourceId()) throw new Error(`Thread not found: ${threadId}`);
const ownerId = thread.metadata?.ownerId;
return typeof ownerId === "string" ? ownerId : this.#owner.identity.getOwnerId();
}
/**
* Transfer a thread to a new owner. Defaults to the active thread; pass
* `threadId` to transfer another thread of this resource without switching to it.
*
* Transfers are serialized within this process. Hosts needing strict durable
* compare-and-set semantics should commit that change in their own store before
* mirroring it here.
*/
async transferOwnership({ toOwnerId, threadId: requestedThreadId }) {
const threadId = requestedThreadId ?? this.requireId();
await withThreadOwnershipMutex(threadId, async () => {
const store = this.#store;
if (!store) throw new Error("Memory is not configured on this AgentController");
const storedOwnerId = (await this.#requireOwnedThread({ threadId })).metadata?.ownerId;
const currentOwnerId = typeof storedOwnerId === "string" ? storedOwnerId : this.#owner.identity.getOwnerId();
if (currentOwnerId === toOwnerId) return;
await store.setMetadata({
threadId,
key: "ownerId",
value: toOwnerId
});
if ((await this.#requireOwnedThread({ threadId })).metadata?.ownerId !== toOwnerId) throw new Error(`Failed to persist owner for thread: ${threadId}`);
this.#owner.emit({
type: "thread_owner_changed",
threadId,
fromOwnerId: currentOwnerId,
toOwnerId
});
});
}
/** Tear down the current agent subscription and reset the run tracker. */
cleanupSubscription() {
this.#owner.cleanupFollowUpBinding();
if (this.#owner.suspensions.hasPending()) this.#owner.stream.detach();
else {
if (!this.#owner.run.getRunId() && this.#owner.run.isRunning()) this.#owner.run.requestAbort();
this.#owner.stream.cleanup();
}
this.#owner.run.supersedeBinding();
this.#owner.run.reset();
}
/**
* Ensure the session is subscribed to the given agent/thread stream, opening a
* fresh subscription (and driving its run loop) when the binding changed.
*/
async ensureSubscription(threadId, agent = this.#owner.machinery.getAgent(), requestContext, resourceId = this.#getResourceId(), shouldAttach) {
const session = this.#owner;
const key = SessionStream.keyFor({
agent,
resourceId,
threadId
});
if (session.stream.matches({ key })) {
session.ensureFollowUpBinding(agent, resourceId, threadId);
return;
}
if (shouldAttach && !shouldAttach()) return;
this.cleanupSubscription();
const subscription = await session.machinery.subscribeToThread({
agent,
resourceId,
threadId,
requestContext
});
if (shouldAttach && !shouldAttach()) {
subscription.unsubscribe();
return;
}
session.stream.attach({
subscription,
agent,
key,
resourceId,
threadId
});
session.ensureFollowUpBinding(agent, resourceId, threadId);
session.stream.trackConsumer(subscription, session.processSubscribedThreadStream(subscription));
}
/** Ensure a subscription for the session's active thread (no-op when unbound). */
async ensureCurrentSubscription(requestContext) {
if (this.#threadId === null) return;
await this.ensureSubscription(this.#threadId, void 0, requestContext);
}
/**
* Detach this host from the current thread without changing durable run state.
* Pending suspension and approval prompts are removed from the host projection
* and can be rebuilt when a session binds the thread again. A parked tool
* approval is not declined: its run stays suspended and can still be answered,
* for example with `respondToPersistedToolApproval`.
*/
detachFromCurrent() {
this.#owner.abort({
localOnly: true,
keepParked: true
});
this.cleanupSubscription();
}
/** Create a new thread, bind the session to it, and rebind the agent stream. */
create(options = {}) {
return this.#runLifecycle(() => this.#create(options));
}
async #create({ title, id, requestContext }) {
const session = this.#owner;
const store = this.#store;
const now = /* @__PURE__ */ new Date();
const thread = {
id: id ?? session.machinery.generateId(),
resourceId: session.identity.getResourceId(),
title: title || "",
createdAt: now,
updatedAt: now
};
const preserveStartupSelection = !this.#hasBoundThread;
const modeId = preserveStartupSelection ? session.mode.get() : session.mode.getDefault();
const mode = session.mode.resolveId(modeId);
const modelId = (preserveStartupSelection ? session.model.get() : session.model.getDefault()) || mode.defaultModelId;
const metadata = { [MODE_ID_KEY]: modeId };
if (preserveStartupSelection) {
const state = session.state.get();
for (const key of threadDerivedStateKeys(state)) if (state[key] !== void 0) metadata[key] = state[key];
}
if (modelId) {
metadata.currentModelId = modelId;
metadata[MODEL_PERSISTENCE_VERSION_KEY] = 2;
}
Object.assign(metadata, session.getThreadScope());
const ownerId = session.identity.getOwnerId();
metadata.ownerId ??= ownerId;
metadata.createdBy ??= ownerId;
const oldThreadId = this.#threadId;
if (store) {
try {
await store.acquireLock(thread.id);
} catch (err) {
if (oldThreadId) try {
await store.acquireLock(oldThreadId);
} catch {}
throw err;
}
if (oldThreadId) try {
await store.releaseLock(oldThreadId);
} catch {}
}
if (store?.hasStorage()) try {
await store.saveThread({ thread: {
id: thread.id,
resourceId: thread.resourceId,
title: thread.title,
createdAt: thread.createdAt,
updatedAt: thread.updatedAt,
metadata: Object.keys(metadata).length > 0 ? metadata : void 0
} });
} catch (err) {
try {
await store.releaseLock(thread.id);
} catch {}
if (oldThreadId) try {
await store.acquireLock(oldThreadId);
} catch {
this.cleanupSubscription();
this.#clear();
}
throw err;
}
this.cleanupSubscription();
this.#set({
threadId: thread.id,
preserveStartupSelection
});
if (modelId) session.model.set({ modelId });
session.emit({
type: "thread_created",
thread
});
await this.ensureCurrentSubscription(requestContext);
return thread;
}
/**
* Rename the session's active thread. No-op when unbound or storageless.
*
* Renames pin the title by default (`metadata.titlePinned`) so Observational
* Memory's title extractor cannot overwrite a user's manual rename. Pass
* `pin: false` for programmatic title writes that should keep auto-naming.
*/
async rename({ title, pin = true }) {
const store = this.#store;
const threadId = this.#threadId;
if (!threadId || !store?.hasStorage()) return;
const thread = await store.getById({ threadId });
if (thread) {
await store.saveThread({ thread: {
...thread,
title,
metadata: {
...thread.metadata,
[require_stream.TITLE_PINNED_THREAD_METADATA_KEY]: pin
},
updatedAt: /* @__PURE__ */ new Date()
} });
this.#owner.emit({
type: "thread_title_updated",
threadId,
title
});
}
}
/** Clone a thread (and its messages), bind the session to the clone, and rebind the stream. */
clone(options = {}) {
return this.#runLifecycle(() => this.#clone(options));
}
async #clone({ sourceThreadId, title, resourceId, requestContext }) {
const sourceId = sourceThreadId ?? this.#threadId;
if (!sourceId) throw new Error("No source thread to clone");
if (this.#store?.hasStorage()) await this.#requireOwnedThread({ threadId: sourceId });
return this.#cloneThread({
sourceThreadId: sourceId,
resourceId: resourceId ?? this.#owner.identity.getResourceId(),
title,
requestContext
});
}
async #cloneThread({ sourceThreadId, resourceId, title, metadata, requestContext }) {
const session = this.#owner;
const store = this.#store;
if (!store) throw new Error("Memory is not configured on this AgentController");
const ownerId = session.identity.getOwnerId();
const clonedThread = await store.cloneThread({
sourceThreadId,
resourceId,
title,
metadata: {
...metadata,
ownerId,
createdBy: ownerId
},
requestContext
});
const oldThreadId = this.#threadId;
try {
await store.acquireLock(clonedThread.id);
} catch (err) {
if (oldThreadId) try {
await store.acquireLock(oldThreadId);
} catch {}
throw err;
}
if (oldThreadId) await store.releaseLock(oldThreadId);
this.cleanupSubscription();
this.#set({ threadId: clonedThread.id });
await this.loadMetadata({ preserveTokenUsageOnFailure: false });
session.resetTokenUsage();
session.emit({
type: "thread_created",
thread: clonedThread
});
await this.ensureCurrentSubscription(requestContext);
return clonedThread;
}
/** Switch the session to an existing thread, hydrating its persisted settings and rebinding the stream. */
switch(options) {
return this.#runLifecycle(() => this.#switch(options));
}
async #switch({ threadId, emitEvent = true, requestContext }) {
const session = this.#owner;
const store = this.#store;
await store?.acquireLock(threadId);
const previousThreadId = this.#threadId;
if (previousThreadId) await store?.releaseLock(previousThreadId);
if (store?.hasStorage()) try {
await this.#requireOwnedThread({ threadId });
} catch (err) {
await store.releaseLock(threadId).catch(() => {});
if (previousThreadId) await store.acquireLock(previousThreadId).catch(() => {});
throw err;
}
this.cleanupSubscription();
const bindingGeneration = this.#set({ threadId });
await this.loadMetadata({ preserveTokenUsageOnFailure: false });
if (!this.#isCurrentBinding(threadId, bindingGeneration)) return;
if (emitEvent) session.emit({
type: "thread_changed",
threadId,
previousThreadId
});
await this.ensureCurrentSubscription(requestContext);
}
/** Delete a thread; when it's the active thread, clear the binding and tear down the run. */
delete(options) {
return this.#runLifecycle(() => this.#delete(options));
}
async #delete({ threadId, requestContext }) {
const session = this.#owner;
const store = this.#store;
if (!store?.hasStorage()) return;
await this.#requireOwnedThread({ threadId });
const isDeletingCurrentThread = this.#threadId === threadId;
await store.deleteThread({
threadId,
requestContext
});
session.suspensions.deleteForThread({ threadId });
if (isDeletingCurrentThread) {
try {
await store.releaseLock(threadId);
} catch {}
this.cleanupSubscription();
this.#clear();
session.resetTokenUsage();
}
session.emit({
type: "thread_deleted",
threadId
});
}
/**
* Hydrate the session's per-thread settings from the active thread's metadata:
* token usage, the persisted mode (restored first), the selected model, and
* observer/reflector model ids + thresholds. Best-effort: on any failure the
* token tally is reset and the rest is left at defaults.
*/
async loadMetadata({ preserveTokenUsageOnFailure = true } = {}) {
const session = this.#owner;
const store = this.#store;
const threadId = this.#threadId;
const bindingGeneration = this.#bindingGeneration;
if (!threadId || !store?.hasStorage()) {
session.resetThreadSelection();
session.resetThreadDerivedState();
session.resetTokenUsage();
return;
}
if (!preserveTokenUsageOnFailure) session.resetTokenUsage();
try {
const thread = await store.getById({ threadId });
if (!this.#isCurrentBinding(threadId, bindingGeneration)) return;
const previousModeId = session.mode.get();
const previousModelId = session.model.get();
session.resetThreadSelection();
session.resetThreadDerivedState();
const meta = thread?.metadata;
const savedUsage = meta?.tokenUsage;
if (savedUsage) session.setTokenUsage({
...createEmptyTokenUsage(),
...savedUsage,
promptTokens: savedUsage.promptTokens ?? 0,
completionTokens: savedUsage.completionTokens ?? 0,
totalTokens: savedUsage.totalTokens ?? 0,
cachedInputTokens: savedUsage.cachedInputTokens ?? 0,
cacheCreationInputTokens: savedUsage.cacheCreationInputTokens ?? 0
});
else session.resetTokenUsage();
const savedModeId = meta?.currentModeId;
if (typeof savedModeId === "string" && store.getModeIds().includes(savedModeId)) session.mode.set({ modeId: savedModeId });
const updates = {};
const observerSelection = meta?.observerModelSelection;
if (typeof observerSelection === "string") {
updates.observerModelSelection = observerSelection;
updates.observerModelId = observerSelection === "auto" ? void 0 : observerSelection;
} else if (typeof meta?.observerModelId === "string") {
updates.observerModelId = meta.observerModelId;
updates.observerModelSelection = meta.observerModelId;
}
const reflectorSelection = meta?.reflectorModelSelection;
if (typeof reflectorSelection === "string") {
updates.reflectorModelSelection = reflectorSelection;
updates.reflectorModelId = reflectorSelection === "auto" ? void 0 : reflectorSelection;
} else if (typeof meta?.reflectorModelId === "string") {
updates.reflectorModelId = meta.reflectorModelId;
updates.reflectorModelSelection = meta.reflectorModelId;
}
const hasObservationThreshold = typeof meta?.observationThreshold === "number";
const hasReflectionThreshold = typeof meta?.reflectionThreshold === "number";
if (hasObservationThreshold) updates.observationThreshold = meta.observationThreshold;
if (hasReflectionThreshold) updates.reflectionThreshold = meta.reflectionThreshold;
if (Object.keys(updates).length > 0) {
try {
await session.state.hydrate(updates, () => this.#isCurrentBinding(threadId, bindingGeneration));
} catch {}
if (!this.#isCurrentBinding(threadId, bindingGeneration)) return;
}
const persistedModelId = await migratePersistedModelSelection({
getMetadata: async () => (await store.getById({ threadId }))?.metadata ?? {},
modeId: session.mode.get(),
onResolved: async (modelId, metadata) => {
if (!this.#isCurrentBinding(threadId, bindingGeneration)) return;
session.model.set({ modelId });
const thinkingLevel = metadata.thinkingLevel;
if (thinkingLevel !== void 0) try {
await session.state.hydrate({ thinkingLevel }, () => this.#isCurrentBinding(threadId, bindingGeneration));
} catch {}
},
set: (key, value) => this.setSettingOn({
threadId,
key,
value
}),
threadId,
validModeIds: store.getModeIds()
});
if (!this.#isCurrentBinding(threadId, bindingGeneration)) return;
if (!persistedModelId) {
const currentMode = session.mode.resolve();
if (currentMode.defaultModelId) session.model.set({ modelId: currentMode.defaultModelId });
}
const modeId = session.mode.get();
const modelId = session.model.get();
if (modeId !== previousModeId) session.emit({
type: "mode_changed",
modeId,
previousModeId
});
if (modelId !== previousModelId) session.emit({
type: "model_changed",
modelId,
thinkingLevel: session.state.get().thinkingLevel
});
for (const key of [...PERSISTED_STATE_KEYS, ...Object.keys(meta ?? {}).filter(isSubagentModelKey)]) {
if (key === "thinkingLevel" && persistedModelId) continue;
const value = meta?.[key];
if (value === void 0) continue;
try {
await session.state.hydrate({ [key]: value }, () => this.#isCurrentBinding(threadId, bindingGeneration));
} catch {}
if (!this.#isCurrentBinding(threadId, bindingGeneration)) return;
}
if (!hasObservationThreshold) {
const observationThreshold = session.om.observer.threshold();
if (observationThreshold !== void 0) await this.setSettingOn({
threadId,
key: "observationThreshold",
value: observationThreshold
});
}
if (!this.#isCurrentBinding(threadId, bindingGeneration)) return;
if (!hasReflectionThreshold) {
const reflectionThreshold = session.om.reflector.threshold();
if (reflectionThreshold !== void 0) await this.setSettingOn({
threadId,
key: "reflectionThreshold",
value: reflectionThreshold
});
}
} catch {}
}
};
/**
* Owns the session's live subscription to the active thread's agent event
* stream. A subscription is created per `(agent, resource, thread)` and reused
* while that triple is unchanged (tracked by {@link key}); switching threads or
* agents tears the old one down and opens a new one.
*
* The Session owns the subscription *handle* and its dedup key plus the
* mechanical lifecycle (reuse check, teardown, identity check, run-id read).
* The AgentController still owns *how* a subscription is produced (calling the agent)
* and *how* its stream is consumed, passing the resolved handle in via
* {@link attach}.
*/
var SessionStream = class {
getSessionRun;
/** The live subscription to the active thread, or null when none is open. */
#subscription = null;
/** Agent that created the live subscription, or null when none is open. */
#agent = null;
/** Dedup key (`agentId:resourceId:threadId`) for the open subscription, or null. */
#key = null;
/** Durable binding owned by the open subscription. */
#binding = null;
#teardownWaiters = /* @__PURE__ */ new Set();
#consumerFailureWaiters = /* @__PURE__ */ new Set();
/** Set once the live subscription's run loop has failed; cleared on attach. */
#consumerFailure = null;
/**
* Run id whose trailing chunks the live subscription drops after an abort.
* Cleared by a later run, by an explicit resume of that run, or on attach/teardown.
*/
#abortedRunId = null;
constructor(getSessionRun) {
this.getSessionRun = getSessionRun;
}
#notifyTeardown() {
const waiters = [...this.#teardownWaiters];
this.#teardownWaiters.clear();
for (const waiter of waiters) waiter();
}
/**
* Track the run loop consuming `subscription`. If it rejects while no other
* subscription has replaced it, consumer-failure waiters receive the error, so
* callers awaiting a run on this stream don't wait on a loop that is gone.
*/
trackConsumer(subscription, consumer) {
consumer.catch((error) => {
if (this.#subscription !== null && this.#subscription !== subscription) return;
this.#consumerFailure = { error };
const waiters = [...this.#consumerFailureWaiters];
this.#consumerFailureWaiters.clear();
for (const waiter of waiters) waiter(error);
});
}
/** Rejects with the live run loop's error if it fails; resolves when `signal` cancels the wait. */
waitForConsumerFailure(signal) {
return new Promise((resolve, reject) => {
const done = (error) => {
signal.removeEventListener("abort", abort);
reject(error);
};
const abort = () => {
this.#consumerFailureWaiters.delete(done);
resolve();
};
if (signal.aborted) return resolve();
if (this.#consumerFailure) return reject(this.#consumerFailure.error);
this.#consumerFailureWaiters.add(done);
signal.addEventListener("abort", abort, { once: true });
});
}
waitForTeardown(signal) {
return new Promise((resolve) => {
const done = () => {
signal.removeEventListener("abort", abort);
resolve();
};
const abort = () => {
this.#teardownWaiters.delete(done);
resolve();
};
if (signal.aborted) return resolve();
this.#teardownWaiters.add(done);
signal.addEventListener("abort", abort, { once: true });
});
}
/** Build the dedup key identifying a subscription to `threadId` for `agent`. */
static keyFor({ agent, resourceId, threadId }) {
return `${agent.id}:${resourceId}:${threadId}`;
}
/** Whether the open subscription already targets `key` (so it can be reused). */
matches({ key }) {
return this.#key === key && this.#subscription !== null && this.#consumerFailure === null;
}
/** Adopt `subscription` as the live one, recording its owning agent and dedup `key`. */
attach({ subscription, agent, key, resourceId, threadId }) {
this.#subscription = subscription;
this.#agent = agent ?? null;
this.#key = key;
this.#binding = {
resourceId,
threadId
};
this.#consumerFailure = null;
this.#abortedRunId = null;
}
/** Record that `runId` was aborted on `subscription`, so its trailing chunks are dropped. */
markAbortedRun({ subscription, runId }) {
if (this.#subscription === subscription) this.#abortedRunId = runId;
}
/** The run id `subscription` is dropping chunks for, or null. */
abortedRunId({ subscription }) {
return this.#subscription === subscription ? this.#abortedRunId : null;
}
/**
* Stop dropping chunks for the aborted run (only if it is `runId`, when given).
* Returns a callback that restores the filter while the same subscription is
* still live and no other run has replaced it, or undefined if nothing was cleared.
*/
clearAbortedRun({ runId } = {}) {
const cleared = this.#abortedRunId;
if (cleared === null || runId !== void 0 && cleared !== runId) return void 0;
this.#abortedRunId = null;
const subscription = this.#subscription;
return () => {
if (this.#subscription === subscription && this.#abortedRunId === null) this.#abortedRunId = cleared;
};
}
/** Agent that owns `subscription`, when it is the live subscription. */
getAgent({ subscription }) {
return this.#subscription === subscription ? this.#agent : null;
}
/** Durable binding owned by `subscription`, when it is the live subscription. */
getBinding({ subscription }) {
return this.#subscription === subscription ? this.#binding : null;
}
/** Whether a subscription is currently open. */
isOpen() {
return this.#subscription !== null;
}
/** Whether `subscription` is the one currently adopted (identity check). */
isCurrent({ subscription }) {
return this.#subscription === subscription;
}
/** The run id the live subscription reports as active, or null when none/idle. */
activeRunId() {
return this.#subscription?.activeRunId() ?? null;
}
/** Whether the live subscription currently has a run in flight. */
isActive() {
return this.activeRunId() !== null;
}
/**
* Abort the live subscription's in-flight run, if any. Swallows errors.
* `localOnly` keeps an abort caused by a thread lifecycle transition (detach,
* switch) from asking a remote thread owner to stop its run.
*/
abort(options) {
try {
this.#subscription?.abort(options);
} catch {}
}
/** Detach the live subscription without aborting (e.g. on stream error). */
detach() {
this.#subscription?.unsubscribe();
this.#subscription = null;
this.#agent = null;
this.#key = null;
this.#binding = null;
this.#abortedRunId = null;
this.#notifyTeardown();
}
/** Tear down this binding, cancelling only an execution initiated by this session. */
cleanup() {
const { sessionId, runId } = this.getSessionRun();
const origin = this.#subscription?.__getCurrentRunRequestContext?.()?.get("controller");
if (runId && this.#subscription?.activeRunId() === runId && origin?.session.id === sessionId) this.#subscription.abort({ localOnly: true });
this.#subscription?.unsubscribe();
this.#subscription = null;
this.#agent = null;
this.#key = null;
this.#binding = null;
this.#abortedRunId = null;
this.#notifyTeardown();
}
};
function getSuspensionAddressKey({ resourceId, threadId, runId, toolCallId }) {
return JSON.stringify([
resourceId,
threadId,
runId,
toolCallId
]);
}
/**
* Owns the session's parked tool suspensions: tool calls paused via the native
* tool-suspension primitive (e.g. `ask_user` / `request_access` / `submit_plan`)
* that are awaiting a resume, keyed by `(threadId, runId, toolCallId)`. Each entry
* records the run id to resume and the tool name. A Map lets several
* tools — e.g. parallel `ask_user` calls in one step — stay suspended and be
* resumed independently.
*
* This is the resume *data* the AgentController reads to drive a resume. The richer
* per-suspension UI snapshot lives on the AgentController display state; the Session
* owns only what's needed to resume.
*/
var SessionSuspensions = class {
/** Parked tool calls awaiting a resume, keyed by `(threadId, runId, toolCallId)`. */
#pending = /* @__PURE__ */ new Map();
#getActiveBinding;
constructor(getActiveBinding) {
this.#getActiveBinding = getActiveBinding;
}
#activeEntries() {
if (!this.#getActiveBinding) return [...this.#pending];
const { resourceId, threadId } = this.#getActiveBinding();
if (threadId === null) return [];
return [...this.#pending].filter(([, suspension]) => suspension.resourceId === resourceId && suspension.threadId === threadId);
}
/**
* Park `toolCallId` as awaiting a resume on `runId` for `toolName`, recording
* the thread/resource the suspended invocation was persisted under. When the
* same tool call is replayed for the same run (e.g. a resumed stream re-emits
* the suspension), the original thread/resource binding is preserved so later
* settlement still targets where the invocation was first persisted.
*/
register({ toolCallId, runId, toolName, threadId, resourceId }) {
const key = getSuspensionAddressKey({
resourceId,
threadId,
runId,
toolCallId
});
const existing = this.#pending.get(key);
if (existing) {
this.#pending.set(key, {
...existing,
toolName
});
return;
}
this.#pending.set(key, {
toolCallId,
runId,
toolName,
threadId,
resourceId
});
}
/** Resolve one active-thread suspension, rejecting ambiguous partial addresses. */
resolve({ toolCallId, runId } = {}) {
const matches = this.#activeEntries().map(([, suspension]) => suspension).filter((suspension) => toolCallId === void 0 || suspension.toolCallId === toolCallId).filter((suspension) => runId === void 0 || suspension.runId === runId);
return matches.length === 1 ? matches[0] : void 0;
}
/** Read a suspension by exact address, or by an unambiguous active-thread selector. */
get(address) {
if ("threadId" in address) return this.#pending.get(getSuspensionAddressKey(address));
return this.resolve(address);
}
/** Whether an exact or unambiguous suspension is currently parked. */
has(address) {
return this.get(address) !== void 0;
}
/** Drop exactly one parked suspension; ambiguous partial addresses are ignored. */
delete(address) {
const resolved = "threadId" in address ? address : this.resolveAddress(address);
if (resolved) this.#pending.delete(getSuspensionAddressKey(resolved));
}
/**
* Drop every suspension parked on `runId`, returning the dropped toolCallIds.
* Used when a run reaches a terminal failure after emitting `tool_suspended`
* (e.g. persisting the suspended snapshot failed): those suspensions can never
* be resumed, so keeping them parked would leave the user with prompts whose
* answers fail with a misleading "could not find a suspended run" error.
* Suspensions parked on other runs are left intact.
*/
deleteForRun({ resourceId, threadId, runId }) {
const dropped = [];
for (const [key, suspension] of this.#pending) if (suspension.resourceId === resourceId && suspension.threadId === threadId && suspension.runId === runId) {
this.#pending.delete(key);
dropped.push({ ...suspension });
}
return dropped;
}
/** Discard the in-memory suspension mirror for a deleted thread. */
deleteForThread({ threadId }) {
for (const [key, suspension] of this.#pending) if (suspension.threadId === threadId) this.#pending.delete(key);
}
/**
* Drop every suspension parked on the active thread, returning the dropped
* entries with their original thread/resource binding. Suspensions for other
* threads remain available when the host switches back.
*/
clear() {
const dropped = this.#activeEntries().map(([, suspension]) => ({ ...suspension }));
for (const [key] of this.#activeEntries()) this.#pending.delete(key);
return dropped;
}
/** Whether the active thread has tool calls parked awaiting a resume. */
hasPending() {
return this.#activeEntries().length > 0;
}
/**
* Resolve which active-thread suspension to act on. A partial address only
* succeeds when it identifies exactly one parked suspension.
*/
resolveAddress({ toolCallId, runId } = {}) {
const suspension = this.resolve({
toolCallId,
runId
});
if (!suspension) return void 0;
const { threadId, resourceId, runId: resolvedRunId, toolCallId: resolvedToolCallId } = suspension;
return {
threadId,
resourceId,
runId: resolvedRunId,
toolCallId: resolvedToolCallId
};
}
/** @deprecated Use {@link resolveAddress} to retain the complete suspension identity. */
resolveToolCallId(toolCallId) {
return this.resolveAddress({ toolCallId })?.toolCallId;
}
};
/**
* Owns the session's interactive tool-approval gates: when a tool requires user
* approval, the run parks on a promise here until the UI responds approve or
* decline.
*
* Gates retain the tool call and thread/run that opened them. Bare call-ID
* responses are rejected when more than one owner has that ID. More than one gate can be parked at once — a background/sub-agent run on a
* detached thread arms its own gate while the foreground run arms another — so
* arming never overwrites or strands an existing gate, and a response can only
* release the gate it names. Thread-scoped callers (abort, a user-message
* interjection) release only their own thread's gate, so one thread can never
* mutate another thread's approval authority.
*
* The Session owns the gate mechanics (arm / respond / cancel); the
* AgentController still maps a decision to its effects (running vs declining the
* tool, and any "always allow" grant), since those touch config-derived tool
* categories.
*/
var SessionApproval = class {
/** Parked gates retain their full thread/run ownership, even when call IDs repeat. */
#gates = /* @__PURE__ */ new Set();
/**
* Park an approval for `toolCallId` and return a promise that resolves once
* {@link respond} or {@link cancel} releases it. The caller awaits this while
* the run is suspended on the gate. Re-arming the same call returns the
* already-parked promise rather than replacing its resolver, so a duplicate
* arm can never strand the first waiter.
*/
arm({ toolName, toolCallId, threadId, runId }) {
const existing = [...this.#gates].find((gate) => gate.toolCallId === toolCallId && gate.threadId === threadId && gate.runId === runId);
if (existing) return existing.promise;
let resolve;
const promise = new Promise((r) => {
resolve = r;
});
this.#gates.add({
toolCallId,
toolName,
threadId,
runId,
promise,
resolve
});
return promise;
}
/**
* Whether a gate is parked. With no filter this is true when *any* gate is
* parked; with a filter it is true only when a gate matches every supplied
* field, so callers can ask "is my thread/run parked?" without seeing another
* thread's gate.
*/
isArmed(filter) {
if (!filter) return this.#gates.size > 0;
return this.#matching(filter).length > 0;
}
/** The parked gates' tool and owner, without their resolvers. */
list() {
return [...this.#gates].map(({ toolCallId, toolName, threadId, runId }) => ({
toolCallId,
toolName,
threadId,
runId
}));
}
/** Ids of the parked gates that match `filter` (or every gate when omitted). */
getToolCallIds(filter) {
return (filter ? this.#matching(filter) : [...this.#gates.values()]).map((gate) => gate.toolCallId);
}
/**
* Apply a user's {@link ApprovalResponse} to the gate named by `toolCallId`.
* A no-op for an id that is not parked, so a missing *or* stale id can never
* resolve a different pending gate. `always_allow_category` runs
* `onAlwaysAllow` with the gated tool name and the gate's thread (so the
* caller can grant the tool's category to the thread that owns the gate — a
* lookup that needs AgentController config) and then approves;
* `approve`/`decline` resolve as-is.
*/
respond({ decision, toolCallId, threadId, runId, requestContext, declineContext, onAlwaysAllow }) {
const matches = this.#matching({
toolCallId,
...threadId !== void 0 && { threadId },
...runId !== void 0 && { runId }
});
if (matches.length !== 1) return {
accepted: false,
reason: this.#gates.size > 0 ? "stale_tool_call" : "not_pending"
};
const gate = matches[0];
if (decision === "always_allow_category") onAlwaysAllow?.(gate.toolName, gate.threadId);
this.#gates.delete(gate);
gate.resolve({
decision: decision === "decline" ? "decline" : "approve",
requestContext,
declineContext
});
return { accepted: true };
}
/**
* Release parked gate(s) without a user decision — on abort, or when a user
* message interrupts a run. Each is resolved as a `decline` so the gated tool
* is rejected (not run) and the run can finalize. `filter` narrows the release
* to a specific call, thread, or run (so aborting one thread cannot decline
* another's gate): naming `threadId`/`runId` with an undefined value — a
* caller with no thread binding — releases only the untagged gates rather than
* every gate. With no filter every gate is released. Returns the ids that were
* released.
*/
cancel(options = {}) {
const gates = this.#matching(options);
for (const gate of gates) {
this.#gates.delete(gate);
gate.resolve({
decision: "decline",
requestContext: options.requestContext,
declineContext: options.declineContext
});
}
return gates.map((gate) => gate.toolCallId);
}
/**
* Release parked gate(s) without a decision, for a host detaching from the
* thread. Each waiter resolves as `detached`, so the gated call is neither
* run nor declined: the run stays parked in storage and can be answered after
* a session binds the thread again. `filter` narrows the release exactly as
* for {@link cancel}. Returns the ids that were released.
*/
detach(filter = {}) {
const gates = this.#matching(filter);
for (const gate of gates) {
this.#gates.delete(gate);
gate.resolve({ decision: "detached" });
}
return gates.map((gate) => gate.toolCallId);
}
/**
* Parked gates matching every field `filter` *names*. For the optional gate
* tags (thread/run) a named field is a constraint even when its value is
* undefined: `{ threadId: undefined }` matches the gates the producer left
* untagged, which is what a caller with no thread binding must be limited to,
* since a gate tagged with another thread is that thread's authority to
* release. `toolCallId` is always present on a gate, so an unset one imposes
* no constraint.
*
* A gate that never recorded the field a filter names is treated as matching:
* it cannot be attributed to a *different* thread, and stranding it would hang
* the run it belongs to.
*/
#matching(filter) {
const matched = [];
for (const gate of this.#gates.values()) {
if (filter.toolCallId !== void 0 && gate.toolCallId !== filter.toolCallId) continue;
if ("threadId" in filter && gate.threadId !== void 0 && gate.threadId !== filter.threadId) continue;
if ("runId" in filter && gate.runId !== void 0 && gate.runId !== filter.runId) continue;
matched.push(gate);
}
return matched;
}
};
/**
* Owns the session's transient run identity and abort control: the id of the
* run currently streaming on the active thread, its trace id, a monotonic
* operation counter bumped each time a new operation starts, and the
* AbortController/abort-requested flag governing cancellation. All of this is
* per-run scratch state — it is never persisted and resets between runs.
*
* The live agent subscription itself lives on {@link SessionStream}
* (`session.stream`); this holds the last run id observed on a chunk so callers
* have a stable value once the subscription has settled.
*/
var SessionRun = class {
/** Id of the run currently streaming on the active thread, or null when idle. */
#runId = null;
/** Trace id for the current run, or null when unset. */
#traceId = null;
/** Monotonic counter bumped at the start of each operation. */
#operationId = 0;
/** Bumped when the thread binding is torn down; see {@link bindingGeneration}. */
#bindingGeneration = 0;
/** Controller whose signal cancels the active run; null when no run is armed. */
#abortController = null;
/** Bumped every time the run is armed; see {@link armCount}. */
#armCount = 0;
/** Whether an abort has been requested for the current run. */
#abortRequested = false;
/** Incremented on every abort request, so waiters can ignore earlier ones. */
#abortGeneration = 0;
#teardownWaiters = /* @__PURE__ */ new Set();
#abortRequestWaiters = /* @__PURE__ */ new Set();
#notifyTeardown() {
const waiters = [...this.#teardownWaiters];
this.#teardownWaiters.clear();
for (const waiter of waiters) waiter();
}
waitForTeardown(signal) {
return new Promise((resolve) => {
const done = () => {
signal.removeEventListener("abort", abort);
resolve();
};
const abort = () => {
this.#teardownWaiters.delete(done);
resolve();
};
if (signal.aborted) return resolve();
this.#teardownWaiters.add(done);
signal.addEventListener("abort", abort, { once: true });
});
}
#notifyAbortRequested() {
const waiters = [...this.#abortRequestWaiters];
this.#abortRequestWaiters.clear();
for (const waiter of waiters) waiter();
}
/** Generation of the latest abort request; pass to {@link waitForAbortRequest} as `after`. */
getAbortGeneration() {
return this.#abortGeneration;
}
/**
* Resolves once an abort is requested for the current run (immediately if
* one already was), or when `signal` cancels the wait. With `after`, only an
* abort requested after that generation counts.
*/
waitForAbortRequest(signal, { after } = {}) {
const requested = () => after === void 0 ? this.#abortRequested : this.#abortGeneration > after;
return new Promise((resolve) => {
const done = () => {
signal.removeEventListener("abort", abort);
resolve();
};
const abort = () => {
this.#abortRequestWaiters.delete(done);
resolve();
};
if (requested() || signal.aborted) return resolve();
this.#abortRequestWaiters.add(done);
signal.addEventListener("abort", abort, { once: true });
});
}
/** The current run id (null when idle). */
getRunId() {
return this.#runId;
}
/** Set the current run id. */
setRunId({ runId }) {
this.#runId = runId;
}
/** The current trace id (null when unset). */
getTraceId() {
return this.#traceId;
}
/** Set the current trace id. */
setTraceId({ traceId }) {
this.#traceId = traceId;
}
/**
* Clear all run state (run id, trace id, abort controller + requested flag)
* when a run ends or is reset. Does not touch the operation counter.
*/
reset() {
this.#runId = null;
this.#traceId = null;
this.#abortController = null;
this.#abortRequested = false;
this.#notifyTeardown();
}
/**
* Generation of the session's thread binding. Bumped whenever the binding is
* torn down (detach, switch, `/new`, ...), so async work started for one run
* can tell that the session has since moved on to another.
*/
bindingGeneration() {
return this.#bindingGeneration;
}
/** Mark the current binding as superseded; see {@link bindingGeneration}. */
supersedeBinding() {
this.#bindingGeneration += 1;
}
/** Bump and return the operation counter at the start of a new operation. */
nextOperation() {
this.#operationId += 1;
return this.#operationId;
}
/**
* Lazily create (if needed) and return the AbortController for the current
* run. Callers pass its `.signal` into the underlying stream.
*/
ensureAbortController() {
this.#armCount += 1;
this.#abortController ??= new AbortController();
return this.#abortController;
}
/**
* How many times the run has been armed via {@link ensureAbortController}.
* Lets a caller tell whether anyone else joined the run it armed.
*/
armCount() {
return this.#armCount;
}
/** Signal for the current run's AbortController, or undefined when none is armed. */
getAbortSignal() {
return this.#abortController?.signal;
}
/**
* Whether a run is currently in progress. A run is armed with an
* AbortController for its duration, so the presence of one is what "running"
* means; this is the semantic accessor callers should use.
*/
isRunning() {
return this.#abortController !== null;
}
/**
* Whether an AbortController is currently armed. Equivalent to
* {@link isRunning} today; kept for callers that assert on the controller's
* lifecycle specifically (e.g. that it was cleared after an abort).
*/
hasAbortController() {
return this.#abortController !== null;
}
/** Clear the abort-requested flag at the start of a fresh run. */
clearAbortRequested() {
this.#abortRequested = false;
}
/** Whether an abort has been requested for the current run. */
isAbortRequested() {
return this.#abortRequested;
}
/**
* Request an abort: mark the run as aborting and fire the AbortController (if
* armed), then drop the controller. Leaves the requested flag set so the
* run-end path can resolve its reason as 'aborted'; {@link reset} clears it.
*
* `deferSignal` marks the run as aborting without firing the controller. Used
* when the abort interrupts a parked tool-approval gate: the gated call still
* has to be declined through the (still live) agent run so the denial is
* persisted, and firing the signal first would tear that run down underneath
* the decline. The engine fires the signal itself once the decline lands.
*/
requestAbort({ deferSignal } = {}) {
this.#abortRequested = true;
this.#abortGeneration++;
if (deferSignal) {
this.#notifyAbortRequested();
return;
}
if (this.#abortController) {
try {
this.#abortController.abort();
} catch {}
this.#abortController = null;
}
this.#notifyAbortRequested();
}
};
var SessionModel = class {
#id = "";
#defaultId;
#store;
/** This session's event bus; {@link switch} emits `model_changed` here. */
#bus;
/** Reads the active mode id for the legacy per-mode restore fallback. */
#getCurrentModeId;
/** Reads configured mode ids so persisted mode metadata can be validated. */
#getModeIds;
/** App hook to track model usage for ranking. Injected via {@link setResolver}. */
#trackModelUse;
#setThinkingLevel;
#getThinkingLevel;
#switchQueue = Promise.resolve();
constructor(store, bus, setThinkingLevel, getThinkingLevel) {
this.#store = store;
this.#bus = bus;
this.#setThinkingLevel = setThinkingLevel;
this.#getThinkingLevel = getThinkingLevel;
}
/** Attach mode accessors and the optional model-use tracker. */
setResolver(options) {
this.#getCurrentModeId = options.getCurrentModeId;
this.#getModeIds = options.getModeIds;
this.#trackModelUse = options.trackModelUse;
}
/** The currently-selected model id ('' when none selected yet). */
get() {
return this.#id;
}
/** Whether a model is currently selected. */
hasSelection() {
return this.#id !== "";
}
/**
* A short display name for the selected model: the last segment of the model
* id (e.g. `__GATEWAY_ANTHROPIC_MODEL_SONNET__` -> `claude-sonnet-4-6`). Returns
* `'unknown'` when no model is selected.
*/
displayName() {
const modelId = this.#id;
if (!modelId || modelId === "unknown") return modelId || "unknown";
const parts = modelId.split("/");
return parts[parts.length - 1] || modelId;
}
/** Set the in-memory selected model id (no persistence). */
set({ modelId }) {
this.#id = modelId;
}
/** @internal Record the host-configured model used when resetting or creating threads. */
setDefault({ modelId }) {
this.#defaultId = modelId;
}
/** Restore the host-configured model before hydrating another thread. */
reset() {
this.#id = this.#defaultId ?? "";
}
/** @internal The host-configured model used to seed a new thread. */
getDefault() {
return this.#defaultId ?? "";
}
/**
* Re-sync the in-memory model and thinking level from the persisted thread.
*
* Unmarked legacy metadata is migrated before the selection is applied. Only
* emits `model_changed` when either value changes the in-memory selection.
*/
async syncFromPersisted() {
const store = this.#store();
if (!store) return;
const threadId = store.getThreadId();
if (!threadId) return;
await migratePersistedModelSelection({
getMetadata: () => store.getAllOn(threadId),
modeId: this.#getCurrentModeId?.() ?? "",
onResolved: async (modelId, metadata) => {
const isActive = () => store.getThreadId() === threadId;
if (!isActive()) return;
const previousModelId = this.#id;
const previousThinkingLevel = this.#getThinkingLevel();
if (metadata.thinkingLevel !== previousThinkingLevel) {
if (!await this.#setThinkingLevel(metadata.thinkingLevel, void 0, isActive, () => this.set({ modelId }))) return;
} else this.set({ modelId });
if (!isActive()) return;
const thinkingLevel = this.#getThinkingLevel();
if (modelId !== previousModelId || thinkingLevel !== previousThinkingLevel) this.#bus.emit({
type: "model_changed",
modelId,
thinkingLevel
});
},
set: (key, value) => store.setOn(threadId, key, value),
threadId,
validModeIds: this.#getModeIds?.()
});
}
/**
* Switch to a different model at runtime.
*
* Persists the selection for the thread, reports it to the model-use tracker,
* and emits `model_changed` with the current thinking level. When
* `thinkingLevel` is provided it is applied and persisted with the model
* (through the session-state preference, which also survives restarts).
* Rejects if a thread change cancels the switch before any selection is committed.
*/
async switch(modelId, { thinkingLevel } = {}) {
const store = this.#store();
const threadId = store?.getThreadId();
const isActive = () => store?.getThreadId() === threadId;
const run = this.#switchQueue.then(() => runModelPersistenceOperation(threadId, async () => {
let committed = false;
const commit = async () => {
if (threadId) {
await store?.setModelOn(threadId, {
currentModelId: modelId,
[MODEL_PERSISTENCE_VERSION_KEY]: 2,
...thinkingLevel !== void 0 ? { thinkingLevel } : {}
});
committed = true;
}
};
const applyModel = () => {
this.set({ modelId });
committed = true;
};
if (thinkingLevel !== void 0) {
if (isActive()) await this.#setThinkingLevel(thinkingLevel, commit, isActive, applyModel);
} else {
await commit();
if (isActive()) applyModel();
}
if (!committed) throw new Error("Model switch canceled because the active thread changed");
if (isActive()) this.#bus.emit({
type: "model_changed",
modelId,
thinkingLevel: this.#getThinkingLevel()
});
}));
this.#switchQueue = run.catch(() => void 0);
await run;
try {
await Promise.resolve(this.#trackModelUse?.(modelId));
} catch (error) {
console.error("Failed to track model usage count", error);
}
}
};
/**
* Owns the session's currently-selected mode and the logic for switching modes.
* The AgentController still owns the mode *definitions* (`config.modes`); this
* owns "which mode is active" and persists that selection without changing the
* session's model.
*/
var SessionMode = class {
/** Id of the currently-selected mode. Empty until the AgentController resolves its default mode. */
#id = "";
#defaultId;
#store;
/** This session's event bus; {@link switch} emits mode_changed here. */
#bus;
/**
* Resolves a mode id to its full definition. Injected by the AgentController via
* {@link setResolver}, since the mode *catalog* (`config.modes`) is host config.
*/
#resolveMode;
constructor(store, bus) {
this.#store = store;
this.#bus = bus;
}
/**
* Attach the resolver that maps a mode id to its definition. The AgentController owns
* the mode catalog (`config.modes`) and injects this once.
*/
setResolver(resolve) {
this.#resolveMode = resolve;
}
/** The currently-selected mode id. */
get() {
return this.#id;
}
/**
* Resolve the currently-selected mode id to its full definition against the
* host's mode catalog. Throws if the selected mode id isn't in the catalog.
*/
resolve() {
const mode = this.#resolveMode?.(this.#id) ?? null;
if (!mode) throw new Error(`Mode not found: ${this.#id}`);
return mode;
}
/** Set the currently-selected mode id (on default resolution or hydration). */
set({ modeId }) {
this.#id = modeId;
}
/** @internal Record the host-configured mode used when resetting or creating threads. */
setDefault({ modeId }) {
this.#defaultId = modeId;
}
/** Restore the host-configured mode before hydrating another thread. */
reset() {
this.#id = this.#defaultId ?? "";
}
/** @internal The host-configured mode id used to seed a new thread. */
getDefault() {
return this.#defaultId ?? "";
}
/** @internal Resolve a mode without changing the live selection. */
resolveId(modeId) {
const mode = this.#resolveMode?.(modeId) ?? null;
if (!mode) throw new Error(`Mode not found: ${modeId}`);
return mode;
}
/** Switch to a different mode without changing the session's selected model. */
async switch({ modeId }) {
if (!(this.#resolveMode?.(modeId) ?? null)) throw new Error(`Mode not found: ${modeId}`);
const previousModeId = this.#id;
this.#id = modeId;
this.#bus.emit({
type: "mode_changed",
modeId,
previousModeId
});
await this.#store()?.set(MODE_ID_KEY, modeId);
}
};
/**
* One observational-memory role (observer or reflector): its model id, resolved
* model instance, threshold, and model switch. Reads return the session-state
* value when set, falling back to the AgentController's `omConfig` defaults. The shared
* wiring is injected by {@link SessionOM.setResolver}.
*/
var SessionOMRole = class {
#config;
#bus;
#getState;
#getCurrentModelId;
#setState;
#omConfig;
#gateways;
constructor(config, bus) {
this.#config = config;
this.#bus = bus;
}
/** @internal Injected by {@link SessionOM.setResolver}. */
setWiring(wiring) {
this.#getState = wiring.getState;
this.#getCurrentModelId = wiring.getCurrentModelId;
this.#setState = wiring.setState;
this.#omConfig = wiring.omConfig;
this.#gateways = wiring.gateways;
}
/** This role's configured model. `auto` follows the active main model. */
model() {
const state = this.#getState?.() ?? {};
const selection = state[this.#config.selectionKey];
if (typeof selection === "string" && selection.length > 0) return selection;
const modelId = state[this.#config.modelIdKey];
if (typeof modelId === "string") return modelId;
return (this.#config.role === "observer" ? this.#omConfig?.observerModel : this.#omConfig?.reflectorModel) ?? this.#config.defaultModelId(this.#omConfig);
}
/** This role's effective concrete model id. */
modelId() {
return this.#resolveModelId(this.model(), this.#getState?.() ?? {});
}
#resolveModelId(model, state) {
if (model !== "auto") return model;
try {
const resolved = this.#omConfig?.resolveAutoModelId?.({
role: this.#config.role,
currentModelId: this.#getCurrentModelId?.(),
state
});
if (resolved) return resolved;
} catch {}
return this.#config.defaultModelId(this.#omConfig);
}
/** This role's threshold from session state, falling back to `omConfig`. */
threshold() {
const fromState = this.#getState?.()[this.#config.thresholdKey];
return (typeof fromState === "number" ? fromState : void 0) ?? this.#config.defaultThreshold(this.#omConfig);
}
/**
* Resolve this role's effective model id to a model instance via the
* configured gateways, or undefined when unset.
*/
resolvedModel() {
const modelId = this.modelId();
if (!modelId) return void 0;
return new require_llm.ModelRouterLanguageModel(modelId, this.#gateways);
}
/** Switch this role's model, persist it, and emit the effective concrete model. */
async switchModel({ modelId }) {
const updates = {
[this.#config.selectionKey]: modelId,
[this.#config.modelIdKey]: modelId === "auto" ? void 0 : modelId
};
const effectiveModelId = this.#resolveModelId(modelId, {
...this.#getState?.(),
...updates
});
const event = effectiveModelId ? {
type: "om_model_changed",
role: this.#config.role,
modelId: effectiveModelId
} : void 0;
if (this.#setState) await this.#setState(updates, event);
else if (event) this.#bus.emit(event);
}
};
/**
* Owns the session's observational-memory model selection, grouped by role:
* {@link SessionOM.observer} and {@link SessionOM.reflector}. The AgentController owns
* `omConfig` and the model resolver, so it injects them — plus the session-state
* read/write and thread-settings persistence — once via {@link setResolver},
* which fans the wiring out to both roles.
*/
var SessionOM = class {
observer;
reflector;
constructor(bus) {
this.observer = new SessionOMRole({
role: "observer",
modelIdKey: "observerModelId",
selectionKey: "observerModelSelection",
thresholdKey: "observationThreshold",
defaultModelId: (omConfig) => omConfig?.defaultObserverModelId,
defaultThreshold: (omConfig) => omConfig?.defaultObservationThreshold
}, bus);
this.reflector = new SessionOMRole({
role: "reflector",
modelIdKey: "reflectorModelId",
selectionKey: "reflectorModelSelection",
thresholdKey: "reflectionThreshold",
defaultModelId: (omConfig) => omConfig?.defaultReflectorModelId,
defaultThreshold: (omConfig) => omConfig?.defaultReflectionThreshold
}, bus);
}
/**
* Attach the session-state read/write, thread-settings persistence, and the
* AgentController-owned `omConfig` defaults plus model resolver. The AgentController injects
* these once; the wiring is shared by both roles.
*/
setResolver(options) {
this.observer.setWiring(options);
this.reflector.setWiring(options);
}
};
/** The permission rules held in a session state snapshot, or empty rules when none are set. */
function readPermissionRules(state) {
return state?.permissionRules ?? {
categories: {},
tools: {}
};
}
/**
* Owns the session's tool-permission rules: the per-category and per-tool
* approval policies persisted in session state under `permissionRules`. The
* AgentController injects the session-state read/write once via {@link setResolver}.
*
* These are the persisted rules consulted during tool-approval resolution; they
* are distinct from the in-memory "allow for this session" grants on the
* Session.
*/
var SessionPermissions = class {
#getState;
#setState;
#onChange;
/** Attach the session-state read/write. The AgentController injects these once. */
setResolver(options) {
this.#getState = options.getState;
this.#setState = options.setState;
this.#onChange = options.onChange;
}
/** The current permission rules, or empty rules when none are set. */
getRules() {
return readPermissionRules(this.#getState?.());
}
/** Set the approval policy for a tool category. Resolves once persisted. */
setForCategory({ category, policy }) {
return this.#write((rules) => ({
...rules,
categories: {
...rules.categories,
[category]: policy
}
}));
}
/** Set the approval policy for an individual tool. Resolves once persisted. */
setForTool({ toolName, policy }) {
return this.#write((rules) => ({
...rules,
tools: {
...rules.tools,
[toolName]: policy
}
}));
}
#writes = Promise.resolve();
#write(edit) {
const write = this.#writes.then(async () => {
await this.#setState?.({ permissionRules: edit(this.getRules()) });
});
this.#writes = write.catch(() => {});
return write.then(() => this.#onChange?.());
}
};
/**
* How long a message submitted right after an abort waits for the aborted run
* to finish tearing down before it is dispatched anyway. Real teardown includes
* stream cancellation and every output processor; a few seconds is normal.
*/
const POST_ABORT_TEARDOWN_TIMEOUT_MS = 3e4;
/** Stamp at submit time: a steer aborts its own run, so the route resolved downstream reads idle. */
function asInterjection(signal) {
if (signal.type !== "user" || signal.attributes?.delivery !== void 0) return signal;
return require_signals.resolveDeliveryAttributes(signal, { delivery: "while-active" });
}
/** The session-state / thread-settings key holding a subagent model id. */
function subagentModelKey(agentType) {
return agentType ? `subagentModelId_${agentType}` : "subagentModelId";
}
/**
* The subagent model selection. Reads prefer the per-`agentType` value and fall
* back to the global subagent model; writes persist to thread settings and emit
* a `subagent_model_changed` event. Wiring is injected by
* {@link SessionSubagents.setResolver}.
*/
var SessionSubagentModel = class {
#bus;
#getState;
#setState;
constructor(bus) {
this.#bus = bus;
}
/** @internal Injected by {@link SessionSubagents.setResolver}. */
setWiring(wiring) {
this.#getState = wiring.getState;
this.#setState = wiring.setState;
}
/**
* The subagent model id, preferring the `agentType`-specific value when one is
* given, then the global subagent model, or `null` when neither is set.
*/
get({ agentType } = {}) {
const state = this.#getState?.() ?? {};
if (agentType) {
const perType = state[subagentModelKey(agentType)];
if (typeof perType === "string") return perType;
}
const global = state.subagentModelId;
return typeof global === "string" ? global : null;
}
/**
* Set the subagent model id (per-`agentType` when given, otherwise global).
* Persists to thread settings and emits `subagent_model_changed`.
*/
async set({ modelId, agentType }) {
const key = subagentModelKey(agentType);
const event = {
type: "subagent_model_changed",
modelId,
scope: "thread",
agentType
};
if (this.#setState) await this.#setState({ [key]: modelId }, event);
else this.#bus.emit(event);
}
};
/**
* The session's subagent configuration. Currently exposes the subagent model
* selection under {@link SessionSubagents.model}; grouped under `subagents` to
* leave room for additional subagent settings. The AgentController injects the
* session-state read/write, thread-settings persistence, and event emitter once
* via {@link setResolver}.
*/
var SessionSubagents = class {
model;
constructor(bus) {
this.model = new SessionSubagentModel(bus);
}
/**
* Attach the session-state read/write and thread-settings persistence. The
* AgentController injects these once.
*/
setResolver(options) {
this.model.setWiring(options);
}
};
var SessionState = class {
getSelection;
#state;
#initialState;
#updateQueue = Promise.resolve();
#source;
#sources = /* @__PURE__ */ new Set();
#getBinding;
#schema;
#bus;
#capturePersistSetting;
constructor({ initialState, stateSchema }, bus, capturePersistSetting, getBinding = () => ({
resourceId: "",
threadId: null
}), getSelection = () => ({
modeId: "",
modelId: ""
})) {
this.getSelection = getSelection;
this.#schema = stateSchema ? (0, _mastra_schema_compat_schema.toStandardSchema)(stateSchema) : void 0;
this.#initialState = {
...this.getSchemaDefaults(),
...initialState
};
this.#state = { ...this.#initialState };
this.#bus = bus;
this.#capturePersistSetting = capturePersistSetting;
this.#getBinding = getBinding;
this.#source = this.#newSource(this.#state);
}
#newSource(state) {
const source = {
...this.#getBinding(),
preferences: Object.fromEntries(threadDerivedStateKeys(state).map((key) => [key, state[key]])),
writtenKeys: /* @__PURE__ */ new Set(),
references: 0,
persistSetting: this.#capturePersistSetting?.()
};
this.#sources.add(new WeakRef(source));
return source;
}
get() {
return this.#read(this.#source);
}
#read(source) {
const state = { ...this.#state };
for (const key of threadDerivedStateKeys({
...state,
...source.preferences
})) if (source.preferences[key] === void 0) delete state[key];
else state[key] = source.preferences[key];
return state;
}
#pruneSources() {
const sources = [];
for (const reference of this.#sources) {
const source = reference.deref();
if (!source || source !== this.#source && source.references === 0) this.#sources.delete(reference);
else sources.push(source);
}
return sources;
}
#release(source) {
source.references--;
this.#pruneSources();
}
captureSelection() {
this.#source.selection = this.getSelection();
}
/** Internal source handle. Run-held handles follow runScope reachability; temporary owners may release explicitly. */
retain(input, retain = true) {
let source = input ? this.#pruneSources().find((source) => source.resourceId === input.resourceId && source.threadId === input.threadId) : this.#source;
if (!source) {
source = this.#newSource({
...this.#initialState,
...input.preferences
});
source.resourceId = input.resourceId;
source.threadId = input.threadId;
source.persistSetting = input.persistSetting;
source.selection = input.selection;
}
const retainedSource = source;
if (source === this.#source) this.captureSelection();
if (retain) source.references++;
let released = false;
return {
resourceId: source.resourceId,
threadId: source.threadId,
isActive: () => retainedSource === this.#source,
selection: () => retainedSource === this.#source ? this.getSelection() : retainedSource.selection,
setSelection: (selection) => {
retainedSource.selection = selection;
},
emit: (event) => this.#emitForSource(retainedSource, event),
get: () => this.#read(retainedSource),
set: (updates) => this.#set(retainedSource, updates),
update: (updater) => this.#update(retainedSource, updater),
release: () => {
if (released) return;
released = true;
if (retain) this.#release(retainedSource);
}
};
}
#enqueue(source, operation) {
source.references++;
const run = this.#updateQueue.then(operation).finally(() => this.#release(source));
this.#updateQueue = run.then(() => void 0, () => void 0);
return run;
}
getSchemaDefaults() {
if (!this.#schema) return {};
const defaults = {};
try {
const jsonSchema = this.#schema["~standard"].jsonSchema.output({ target: "draft-07" });
if (jsonSchema?.properties) {
for (const [key, prop] of Object.entries(jsonSchema.properties)) if (prop.default !== void 0) defaults[key] = prop.default;
}
} catch {}
return defaults;
}
async apply(source, updates, persistSetting, shouldApply, commit, onApply, hydrating = false) {
if (shouldApply && !shouldApply()) return false;
const changedKeys = Object.keys(updates);
const newState = {
...this.#read(source),
...updates
};
let validatedState;
if (this.#schema) {
const result = await this.#schema["~standard"].validate(newState);
if (result.issues) {
const messages = result.issues.map((i) => i.message).join("; ");
throw new Error(`Invalid state update: ${messages}`);
}
validatedState = result.value;
} else validatedState = newState;
if (shouldApply && !shouldApply()) return false;
if (commit) {
if (validatedState.thinkingLevel !== updates.thinkingLevel) throw new Error("State schema must preserve the selected thinkingLevel");
await commit();
}
if (shouldApply && !shouldApply()) return false;
onApply?.();
const state = validatedState;
for (const key of threadDerivedStateKeys({
...source.preferences,
...state
})) {
source.preferences[key] = state[key];
if (!hydrating && changedKeys.includes(key)) source.writtenKeys.add(key);
}
this.#state = validatedState;
const visibleKeys = changedKeys.filter((key) => source === this.#source || !THREAD_DERIVED_STATE_KEYS.includes(key) && !isSubagentModelKey(key));
if (visibleKeys.length > 0) this.#bus.emit({
type: "state_changed",
state: this.get(),
changedKeys: visibleKeys
});
const persistedValues = {};
for (const key of changedKeys) persistedValues[key] = state[key];
await this.#persistSettings(persistedValues, persistSetting);
return true;
}
rebind(keys) {
const binding = this.#getBinding();
const previous = this.#source;
const before = this.get();
const retained = this.#pruneSources().find((source) => source.resourceId === binding.resourceId && source.threadId === binding.threadId);
this.#source = retained ?? this.#newSource(keys.length === 0 ? before : this.#initialState);
if (previous !== this.#source) this.#pruneSources();
const after = this.get();
const changedKeys = threadDerivedStateKeys({
...before,
...after
}).filter((key) => before[key] !== after[key]);
if (changedKeys.length > 0) this.#bus.emit({
type: "state_changed",
state: after,
changedKeys
});
}
/** Hydration must not overwrite successful writes held by a warm source view. */
hydrate(updates, shouldApply) {
const source = this.#source;
return this.#enqueue(source, async () => {
const pending = Object.fromEntries(Object.entries(updates).filter(([key]) => !source.writtenKeys.has(key)));
if (Object.keys(pending).length === 0) return false;
return this.apply(source, pending, void 0, shouldApply, void 0, void 0, true);
});
}
async #persistSettings(updates, persistSetting) {
if (!persistSetting) return;
const values = updates;
for (const key of threadDerivedStateKeys(values)) {
if (!Object.prototype.hasOwnProperty.call(values, key)) continue;
try {
await persistSetting({
key,
value: values[key]
});
} catch {}
}
}
set(updates) {
return this.#set(this.#source, updates);
}
#set(source, updates) {
const snapshot = { ...updates };
return this.#enqueue(source, async () => {
if (Object.keys(snapshot).length > 0) await this.apply(source, snapshot, source.persistSetting);
});
}
/** Validate a model preference before applying its model and optionally committing metadata. */
setWithCommit(updates, commit, shouldApply, onApply) {
const updateSnapshot = { ...updates };
const source = this.#source;
return this.#enqueue(source, () => this.apply(source, updateSnapshot, void 0, shouldApply, commit, onApply));
}
/** Apply an update only while a caller-owned identity still matches. */
setIf(updates, shouldApply) {
const snapshot = { ...updates };
const source = this.#source;
return this.#enqueue(source, () => this.apply(source, snapshot, source.persistSetting, shouldApply));
}
update(updater) {
return this.#update(this.#source, updater);
}
#update(source, updater) {
return this.#enqueue(source, async () => {
const update = await updater(this.#read(source));
if (update.updates && Object.keys(update.updates).length > 0) await this.apply(source, update.updates, source.persistSetting);
for (const event of update.events ?? []) this.#emitForSource(source, event);
return update.result;
});
}
#emitForSource(source, event) {
switch (event.type) {
case "thread_created":
case "thread_deleted":
case "thread_title_updated":
case "om_thread_title_updated":
case "workspace_status_changed":
case "workspace_ready":
case "workspace_error":
this.#bus.emit(event);
return;
case "tool_approval_required":
this.#bus.emit({
...event,
threadId: event.threadId ?? source.threadId ?? void 0
});
return;
case "tool_suspended":
case "tool_suspension_cancelled":
this.#bus.emit({
...event,
threadId: event.threadId ?? source.threadId ?? void 0,
resourceId: event.resourceId ?? source.resourceId
});
return;
case "subagent_model_changed":
if (event.scope === "global" || source === this.#source) this.#bus.emit(event);
return;
default: if (source === this.#source) this.#bus.emit(event);
}
}
};
/**
* A AgentController session owns the per-conversation runtime state that today lives
* flattened on the {@link AgentController} instance. This class is the seam we extract
* that state into, one concern at a time, so the AgentController can eventually own a
* `Session` rather than the state itself.
*
* Currently owns:
* - the live AgentController state (`session.state`): schema-validated snapshots and
* serialized updates that emit `state_changed`.
* - session-scoped permission grants — the "allow for this session" approvals a
* user makes when a tool or tool category is gated behind the permission check.
* - the live token-usage counter for the active thread. The Session holds the
* in-memory running tally; the AgentController remains responsible for persisting it
* to (and hydrating it from) thread metadata, because usage is thread-scoped.
* - the currently-selected mode (`session.mode`) and model (`session.model`).
* The Session is the source of truth for which mode/model is active and owns
* the mode-switch sequence and per-mode model memory. The AgentController still owns
* the mode *definitions* (`config.modes`).
* - transient run identity and abort control (`session.run`): the current run
* id, trace id, monotonic operation counter, and the AbortController/
* abort-requested flag. This is per-run scratch state and is never persisted.
* - the live agent thread subscription (`session.stream`): the open
* subscription to the active thread's event stream and its dedup key. The
* AgentController still produces the subscription (calling the agent) and consumes its
* stream; the Session owns the handle and its lifecycle.
* - the parked tool suspensions (`session.suspensions`): tool calls paused via
* the native tool-suspension primitive awaiting a resume, keyed by toolCallId.
* The Session owns the resume data; the AgentController keeps the richer per-suspension
* UI snapshot on its display state.
* - follow-up queue observation: a subscription to the Agent-owned FIFO for
* the active resource/thread. The Agent runtime schedules messages; the
* Session renders its current shared `queuedFollowUps` count. * - the interactive tool-approval gate (`session.approval`): when a tool needs
* user approval, the run parks on a promise here until the UI responds. The
* Session owns the gate; the AgentController maps the decision to its effects (run vs
* decline, any "always allow" grant), which touch config-derived categories.
*
* It also exposes a couple of accessors that compose `run` and `stream`:
* {@link getCurrentRunId} (the active run id, preferring the live subscription)
* and {@link abortRun} (abort the live run and mark it aborting).
*
* Mode/model persistence is thread-scoped, so the Session writes through a
* {@link ThreadSettingsStore} the AgentController backs with thread metadata; when no
* storage is configured the store is absent and state stays in memory.
*/
/**
* Owns the session's canonical display state — the projection a UI renders from
* instead of folding raw events itself. The Session holds the snapshot and the
* reducer ({@link apply}) that keeps it in sync with every AgentController event; the
* AgentController still owns the event bus and dispatches `display_state_changed` to
* listeners after applying.
*
* The reducer needs a few read-only host/session facts it doesn't own: the live
* token-usage tally, a subagent display-name lookup (AgentController config), and the
* active thread id (to decide whether a `thread_deleted` clears the view). Those
* are injected at construction so the reducer stays self-contained.
*/
var SessionDisplayState = class {
deps;
#state = defaultDisplayState();
constructor(deps) {
this.deps = deps;
}
/**
* A read-only snapshot of the canonical display state. UIs should render from
* this instead of building state up from raw events.
*/
get() {
return this.#state;
}
/**
* Drop the display mirror of every parked tool suspension. Used on abort,
* which abandons the run's parked suspensions; the caller dispatches
* `display_state_changed`.
*/
clearPendingSuspensions() {
this.#state.pendingSuspensions.clear();
}
/**
* Clear the modified-files tally without touching the rest of the snapshot.
* Used after a clone, which starts the cloned thread with a clean working set
* while the surrounding UI reset handles tasks/tools explicitly.
*/
clearModifiedFiles() {
this.#state.modifiedFiles.clear();
}
/** Add or update one suspension without conflating duplicate tool-call ids across runs. */
#setPendingSuspension(suspension) {
const pending = this.#state.pendingSuspensions;
if (!(suspension.resourceId !== void 0 && suspension.threadId !== void 0 && suspension.runId !== void 0)) {
pending.set(suspension.toolCallId, suspension);
return;
}
const address = suspension;
pending.set(getSuspensionAddressKey(address), suspension);
}
/**
* Drop the display mirror of exactly one parked tool suspension once it has
* resumed, preserving a sibling that reused the same tool-call id.
*/
deletePendingSuspension(address) {
const pending = this.#state.pendingSuspensions;
for (const [key, entry] of pending) if (entry.toolCallId === address.toolCallId && entry.resourceId === address.resourceId && entry.threadId === address.threadId && entry.runId === address.runId) pending.delete(key);
}
/**
* Restore task display state after a UI replays persisted task-tool history.
* Updates the snapshot without emitting a live `task_updated` event, since no
* task tool just ran. The caller dispatches `display_state_changed`.
*/
restoreTasks(tasks) {
this.#state.previousTasks = [...this.#state.tasks];
this.#state.tasks = [...tasks];
}
/**
* Reset display fields scoped to a thread. Called on thread switch/creation.
* Also clears the session's follow-up queue (mirrored by `queuedFollowUps`).
*/
resetThread() {
const ds = this.#state;
ds.activeTools = /* @__PURE__ */ new Map();
ds.toolInputBuffers = /* @__PURE__ */ new Map();
ds.pendingApprovals = /* @__PURE__ */ new Map();
ds.pendingSuspensions = /* @__PURE__ */ new Map();
ds.activeSubagents = /* @__PURE__ */ new Map();
ds.currentMessage = null;
this.deps.clearFollowUps();
ds.queuedFollowUps = 0;
ds.modifiedFiles = /* @__PURE__ */ new Map();
ds.tasks = [];
ds.previousTasks = [];
ds.omProgress = defaultOMProgressState();
ds.bufferingMessages = false;
ds.bufferingObservations = false;
}
/**
* Drop the pending-approval display entries for the given tool calls. Called
* when a gate is answered (approve/decline) or released (abort / interjection)
* so the UI stops rendering approvals that can no longer be resolved.
*/
clearPendingApprovals(toolCallIds) {
for (const toolCallId of toolCallIds) this.#state.pendingApprovals.delete(toolCallId);
}
/**
* Apply a display-state update based on an incoming event. The centralized
* state machine that keeps {@link AgentControllerDisplayState} in sync with every
* event the AgentController emits.
*/
apply(event) {
const ds = this.#state;
switch (event.type) {
case "agent_start":
ds.isRunning = true;
ds.activeTools = /* @__PURE__ */ new Map();
ds.toolInputBuffers = /* @__PURE__ */ new Map();
ds.currentMessage = null;
break;
case "agent_end":
ds.isRunning = false;
if (event.reason !== "suspended") {
const runId = this.deps.getRunId();
for (const [key, suspension] of ds.pendingSuspensions) if (!runId || suspension.runId === void 0 || suspension.runId === runId) ds.pendingSuspensions.delete(key);
}
for (const [, tool] of ds.activeTools) if (tool.status === "running" || tool.status === "streaming_input") tool.status = "error";
ds.activeSubagents = /* @__PURE__ */ new Map();
break;
case "message_start":
ds.currentMessage = {
...event.message,
content: {
...event.message.content,
parts: event.message.content.parts.map((part) => part.type === "text" ? { ...part } : part)
}
};
break;
case "message_update": {
if (ds.currentMessage?.id !== event.id) break;
const parts = [...ds.currentMessage.content.parts];
if (event.event.type === "text-delta") {
const textIndex = parts.findLastIndex((part) => part.type === "text");
const textPart = parts[textIndex];
if (textPart?.type === "text") parts[textIndex] = {
...textPart,
text: textPart.text + event.event.delta
};
else parts.push({
type: "text",
text: event.event.delta
});
} else if (event.event.type === "reasoning-delta") {
const reasoningPart = parts[event.event.index];
if (reasoningPart?.type === "reasoning") {
const reasoning = reasoningPart.reasoning + event.event.delta;
parts[event.event.index] = {
...reasoningPart,
reasoning,
details: [{
type: "text",
text: reasoning
}]
};
}
} else parts[event.event.index] = structuredClone(event.event.part);
ds.currentMessage = {
...ds.currentMessage,
content: {
...ds.currentMessage.content,
parts
}
};
break;
}
case "message_end": break;
case "tool_input_start": {
ds.toolInputBuffers.set(event.toolCallId, {
text: "",
toolName: event.toolName
});
const existing = ds.activeTools.get(event.toolCallId);
if (existing) existing.status = "streaming_input";
else ds.activeTools.set(event.toolCallId, {
name: event.toolName,
args: {},
status: "streaming_input"
});
break;
}
case "tool_input_delta": {
const buf = ds.toolInputBuffers.get(event.toolCallId);
if (buf && typeof event.argsTextDelta === "string") buf.text += event.argsTextDelta;
break;
}
case "tool_input_end":
ds.toolInputBuffers.delete(event.toolCallId);
break;
case "tool_start": {
const existingTool = ds.activeTools.get(event.toolCallId);
if (existingTool) {
existingTool.name = event.toolName;
existingTool.args = event.args;
existingTool.status = "running";
} else ds.activeTools.set(event.toolCallId, {
name: event.toolName,
args: event.args,
status: "running"
});
break;
}
case "tool_update": {
const tool = ds.activeTools.get(event.toolCallId);
if (tool) tool.partialResult = typeof event.partialResult === "string" ? event.partialResult : require_utils_safe_stringify.safeStringify(event.partialResult);
break;
}
case "tool_end": {
const endedTool = ds.activeTools.get(event.toolCallId);
if (endedTool) {
endedTool.status = event.isError ? "error" : "completed";
endedTool.result = event.result;
endedTool.isError = event.isError;
}
if (!event.isError) {
const FILE_TOOLS = [
"string_replace_lsp",
"write_file",
"ast_smart_edit"
];
const toolState = ds.activeTools.get(event.toolCallId);
if (toolState && FILE_TOOLS.includes(toolState.name)) {
const filePath = toolState.args?.path;
if (filePath) {
const existing = ds.modifiedFiles.get(filePath);
if (existing) existing.operations.push(toolState.name);
else ds.modifiedFiles.set(filePath, {
operations: [toolState.name],
firstModified: /* @__PURE__ */ new Date()
});
}
}
}
ds.pendingApprovals.delete(event.toolCallId);
break;
}
case "shell_output": {
const shellTool = ds.activeTools.get(event.toolCallId);
if (shellTool) {
const limit = 1048576;
shellTool.shellOutput = event.output.length >= limit ? JSON.parse(JSON.stringify(event.output.slice(-1048576))) : (shellTool.shellOutput ?? "").slice(-(limit - event.output.length)) + event.output;
}
break;
}
case "tool_approval_required":
ds.pendingApprovals.set(event.toolCallId, {
toolCallId: event.toolCallId,
toolName: event.toolName,
args: event.args,
threadId: event.threadId
});
break;
case "tool_suspended":
this.#setPendingSuspension({
toolCallId: event.toolCallId,
toolName: event.toolName,
args: event.args,
suspendPayload: event.suspendPayload,
resumeSchema: event.resumeSchema,
resourceId: event.resourceId,
threadId: event.threadId,
runId: event.runId
});
break;
case "tool_suspension_cancelled":
if (event.resourceId && event.threadId && event.runId) this.deletePendingSuspension({
resourceId: event.resourceId,
threadId: event.threadId,
runId: event.runId,
toolCallId: event.toolCallId
});
else ds.pendingSuspensions.delete(event.toolCallId);
break;
case "subagent_start": {
const displayName = this.deps.getSubagentDisplayName(event.agentType);
ds.activeSubagents.set(event.toolCallId, {
agentType: event.agentType,
...displayName !== void 0 ? { displayName } : {},
task: event.task,
modelId: event.modelId,
forked: event.forked,
toolCalls: [],
textDelta: "",
status: "running",
startedAt: Date.now()
});
break;
}
case "subagent_text_delta": {
const sub = ds.activeSubagents.get(event.toolCallId);
if (sub) sub.textDelta += event.textDelta;
break;
}
case "subagent_tool_start": {
const subAgent = ds.activeSubagents.get(event.toolCallId);
if (subAgent) subAgent.toolCalls.push({
name: event.subToolName,
isError: false
});
break;
}
case "subagent_tool_end": {
const subTool = ds.activeSubagents.get(event.toolCallId);
if (subTool) {
const tc = subTool.toolCalls.find((t) => t.name === event.subToolName && !t.isError);
if (tc) tc.isError = event.isError;
}
break;
}
case "subagent_end": {
const endedSub = ds.activeSubagents.get(event.toolCallId);
if (endedSub) {
endedSub.status = event.isError ? "error" : "completed";
endedSub.durationMs = event.durationMs;
endedSub.result = event.result;
}
break;
}
case "om_status": {
const w = event.windows;
ds.omProgress.pendingTokens = w.active.messages.tokens;
ds.omProgress.threshold = w.active.messages.threshold;
ds.omProgress.thresholdPercent = w.active.messages.threshold > 0 ? w.active.messages.tokens / w.active.messages.threshold * 100 : 0;
ds.omProgress.observationTokens = w.active.observations.tokens;
ds.omProgress.reflectionThreshold = w.active.observations.threshold;
ds.omProgress.reflectionThresholdPercent = w.active.observations.threshold > 0 ? w.active.observations.tokens / w.active.observations.threshold * 100 : 0;
ds.omProgress.buffered = {
observations: { ...w.buffered.observations },
reflection: { ...w.buffered.reflection }
};
ds.omProgress.generationCount = event.generationCount;
ds.omProgress.stepNumber = event.stepNumber;
ds.bufferingMessages = w.buffered.observations.status === "running";
ds.bufferingObservations = w.buffered.reflection.status === "running";
break;
}
case "om_observation_start":
ds.omProgress.status = "observing";
ds.omProgress.cycleId = event.cycleId;
ds.omProgress.startTime = Date.now();
break;
case "om_observation_end":
ds.omProgress.status = "idle";
ds.omProgress.cycleId = void 0;
ds.omProgress.startTime = void 0;
ds.omProgress.observationTokens = event.observationTokens;
ds.omProgress.pendingTokens = 0;
ds.omProgress.thresholdPercent = 0;
break;
case "om_observation_failed":
ds.omProgress.status = "idle";
ds.omProgress.cycleId = void 0;
ds.omProgress.startTime = void 0;
break;
case "om_reflection_start":
ds.omProgress.status = "reflecting";
ds.omProgress.cycleId = event.cycleId;
ds.omProgress.startTime = Date.now();
ds.omProgress.preReflectionTokens = ds.omProgress.observationTokens;
ds.omProgress.observationTokens = event.tokensToReflect;
ds.omProgress.reflectionThresholdPercent = ds.omProgress.reflectionThreshold > 0 ? event.tokensToReflect / ds.omProgress.reflectionThreshold * 100 : 0;
break;
case "om_reflection_end":
ds.omProgress.status = "idle";
ds.omProgress.cycleId = void 0;
ds.omProgress.startTime = void 0;
ds.omProgress.observationTokens = event.compressedTokens;
ds.omProgress.reflectionThresholdPercent = ds.omProgress.reflectionThreshold > 0 ? event.compressedTokens / ds.omProgress.reflectionThreshold * 100 : 0;
break;
case "om_reflection_failed":
ds.omProgress.status = "idle";
ds.omProgress.cycleId = void 0;
ds.omProgress.startTime = void 0;
break;
case "om_buffering_start":
if (event.operationType === "observation") ds.bufferingMessages = true;
else ds.bufferingObservations = true;
break;
case "om_buffering_end":
if (event.operationType === "observation") ds.bufferingMessages = false;
else ds.bufferingObservations = false;
break;
case "om_buffering_failed":
if (event.operationType === "observation") ds.bufferingMessages = false;
else ds.bufferingObservations = false;
break;
case "om_activation":
if (event.operationType === "observation") ds.bufferingMessages = false;
else ds.bufferingObservations = false;
break;
case "usage_update":
ds.tokenUsage = this.deps.getTokenUsage();
break;
case "task_updated":
ds.previousTasks = [...ds.tasks];
ds.tasks = event.tasks;
break;
case "follow_up_queued":
ds.queuedFollowUps = event.count;
break;
case "thread_changed":
this.resetThread();
ds.tokenUsage = this.deps.getTokenUsage();
break;
case "thread_created":
this.resetThread();
ds.tokenUsage = createEmptyTokenUsage();
break;
case "thread_deleted":
if (!this.deps.getThreadId()) {
this.resetThread();
ds.tokenUsage = createEmptyTokenUsage();
}
break;
case "state_changed": {
const keys = event.changedKeys;
if (keys.includes("observationThreshold")) {
const value = event.state.observationThreshold;
if (typeof value === "number") {
ds.omProgress.threshold = value;
ds.omProgress.thresholdPercent = value > 0 ? ds.omProgress.pendingTokens / value * 100 : 0;
}
}
if (keys.includes("reflectionThreshold")) {
const value = event.state.reflectionThreshold;
if (typeof value === "number") {
ds.omProgress.reflectionThreshold = value;
ds.omProgress.reflectionThresholdPercent = value > 0 ? ds.omProgress.observationTokens / value * 100 : 0;
}
}
break;
}
}
}
};
/**
* A session's event bus. Owns the listener list and the full emit pipeline:
* fold the event into the canonical display state, dispatch to this session's
* listeners, then fan out a synthetic `display_state_changed`. Each session
* has its own bus, so events never cross between sessions. Subsystems hold a
* reference to their session's bus and call {@link emit} directly.
*/
/**
* Event types emitted once per streamed chunk. Their display-state snapshots are
* coalesced, since a snapshot always carries the full state and intermediate
* ones are immediately superseded.
*/
const COALESCIBLE_DISPLAY_STATE_EVENTS = /* @__PURE__ */ new Set(["message_update", "tool_input_delta"]);
/** Upper bound on coalesced display-state snapshots: one per this many ms, plus a leading one. */
const DISPLAY_STATE_COALESCE_MS = 16;
var SessionBus = class {
#listeners = [];
#displayState;
/** Timer for the trailing snapshot of the current coalescing window. */
#displayStateTimer;
/** Whether a snapshot was withheld during the current window and still owes a dispatch. */
#displayStatePending = false;
/**
* The last workspace lifecycle event group emitted on this bus, replayed to
* subscribers that attach after the status changed so they receive the current
* workspace ready or error state.
*/
#lastWorkspaceEvents = [];
#lastOmStatus;
/** Attach the display-state reducer the bus folds events into. Set once by the Session. */
setDisplayState(displayState) {
this.#displayState = displayState;
}
subscribe(listener) {
for (const event of this.#lastWorkspaceEvents) try {
const result = listener(event);
if (result && typeof result === "object" && "catch" in result) result.catch((err) => console.error("Error in session event listener:", err));
} catch (err) {
console.error("Error in session event listener:", err);
}
this.#listeners.push(listener);
return () => {
const index = this.#listeners.indexOf(listener);
if (index !== -1) this.#listeners.splice(index, 1);
};
}
/** Whether anything is currently listening. Lets emitters skip snapshot work nobody reads. */
hasListeners() {
return this.#listeners.length > 0;
}
/** See {@link Session.initialStateEvents}. */
initialStateEvents() {
const events = [];
const { isRunning, currentMessage } = this.#displayState?.get() ?? {};
if (isRunning && currentMessage) events.push({
type: "message_start",
message: structuredClone(currentMessage)
});
if (this.#lastOmStatus) events.push(this.#lastOmStatus);
return events;
}
emit(event) {
if (event.type === "workspace_status_changed" || event.type === "workspace_ready" || event.type === "workspace_error") {
if (event.type === "workspace_status_changed") this.#lastWorkspaceEvents = [event];
else this.#lastWorkspaceEvents.push(event);
}
if (event.type === "om_status") this.#lastOmStatus = event;
else if (event.type === "thread_changed" || event.type === "thread_created" || event.type === "thread_deleted" && event.threadId === this.#lastOmStatus?.threadId) this.#lastOmStatus = void 0;
this.#displayState?.apply(event);
if (!COALESCIBLE_DISPLAY_STATE_EVENTS.has(event.type)) this.#flushDisplayState();
this.#dispatch(event);
if (event.type === "display_state_changed" || !this.#displayState) return;
if (COALESCIBLE_DISPLAY_STATE_EVENTS.has(event.type)) {
this.#scheduleDisplayState();
return;
}
this.#dispatch({
type: "display_state_changed",
displayState: this.#displayState.get()
});
}
/**
* Queue a display-state snapshot for a high-frequency event. Streaming a
* single message emits thousands of deltas, and dispatching a full snapshot
* per delta re-serializes the whole message (plus every completed tool's args
* and result) on each one. Snapshots are state-of-the-world rather than
* incremental, so dropping intermediate ones loses nothing: the trailing
* flush carries the latest state.
*
* The first delta of a burst dispatches immediately so UIs stay responsive;
* the rest collapse into one trailing snapshot per interval.
*/
#scheduleDisplayState() {
if (this.#displayStateTimer) {
this.#displayStatePending = true;
return;
}
this.#dispatch({
type: "display_state_changed",
displayState: this.#displayState.get()
});
this.#displayStateTimer = setTimeout(() => {
this.#displayStateTimer = void 0;
this.#flushDisplayState();
}, DISPLAY_STATE_COALESCE_MS);
this.#displayStateTimer.unref?.();
}
/** Dispatch any snapshot withheld by coalescing and clear the pending timer. */
#flushDisplayState() {
if (this.#displayStateTimer) {
clearTimeout(this.#displayStateTimer);
this.#displayStateTimer = void 0;
}
if (!this.#displayStatePending) return;
this.#displayStatePending = false;
if (this.#displayState) this.#dispatch({
type: "display_state_changed",
displayState: this.#displayState.get()
});
}
#dispatch(event) {
for (const listener of [...this.#listeners]) try {
const result = listener(event);
if (result && typeof result === "object" && "catch" in result) result.catch((err) => console.error("Error in session event listener:", err));
} catch (err) {
console.error("Error in session event listener:", err);
}
}
};
/**
* A process-local host for `{ id, resourceId, tags, active threadId }`.
* It is not the durable conversation record: mode, model, persisted state,
* token usage, pending runs, and display projections are re-derived from the
* active thread whenever one is created or selected. Custom `TState` fields
* that are not reserved thread settings are host-level configuration.
*/
var Session = class {
/** Every cancellation intent invalidates pending startup, even when teardown is already in progress. */
#abortGeneration = 0;
/** This session's event bus. Constructed first so every subsystem can route its events here. */
#bus = new SessionBus();
/** Process-local hooks that must finish before the session exposes a terminal agent event. */
#beforeAgentEndListeners = /* @__PURE__ */ new Set();
#endingRunId;
/** Tool categories granted "allow", bucketed by thread id (or the session-wide bucket). */
#grantedCategories = /* @__PURE__ */ new Map();
/** Individual tool names granted "allow", bucketed by thread id (or the session-wide bucket). */
#grantedTools = /* @__PURE__ */ new Map();
/** Running token-usage tally for the active thread. */
#tokenUsage = createEmptyTokenUsage();
/** Whether the in-flight abort teardown must stay local to this process. */
#localOnlyAbort = false;
/** Settles once the previous `sendMessage` carrying scopes is admitted, so scoped messages start in send order. */
#scopedSendTail = Promise.resolve();
#deferredAbortOrigin;
/** Thread-settings persistence handle, injected by the AgentController via {@link setStore}. */
#store;
/** Resolves a tool name to its category, injected by the AgentController via {@link setCategoryResolver} (the category map is AgentController config). */
#resolveCategory;
/** Resolves a subagent's display name from AgentController config, injected via {@link setSubagentNameResolver}. */
#resolveSubagentName;
/** AgentController-owned run machinery (agent, run/stream option builders, …), injected via {@link setMachinery}. */
#machinery;
/** The per-session agent run engine, constructed once machinery is wired via {@link setMachinery}. */
#engine;
/** The session's currently-selected model (source of truth). */
model;
/** The session's currently-selected mode. */
mode = new SessionMode(() => this.#store, this.#bus);
/** The session's observational-memory model selection (observer/reflector). */
om = new SessionOM(this.#bus);
/** The session's persisted tool-permission rules (per-category / per-tool). */
permissions = new SessionPermissions();
/** The session's subagent configuration (currently the subagent model). */
subagents = new SessionSubagents(this.#bus);
/** Transient run identity (run id, trace id, operation counter) for the active run. */
run = new SessionRun();
/** Tool-call answers currently holding {@link run} armed; see `#armRun`. */
#answerArms;
/** Live subscription to the active thread's agent event stream. */
stream = new SessionStream(() => ({
sessionId: this.identity.getId(),
runId: this.run.getRunId()
}));
/** Rebuildable resume mirror for suspensions on the active thread. */
suspensions;
/** Captured Agent queue scope for this session binding. */
#followUpBinding;
/** Follow-up preparation that can finish after the session's active run changes. */
#preparingFollowUps = /* @__PURE__ */ new Set();
/** Invalidates asynchronous follow-up preparation when the session unbinds. */
#followUpGeneration = 0;
/** The interactive tool-approval gate the current run parks on. */
approval = new SessionApproval();
/** The session's identity: the memory resourceId it reads/writes under. */
identity;
/** The session's thread domain: current binding + reads scoped to it. */
thread;
/** The canonical display state a UI renders, plus the reducer that maintains it. */
displayState;
/** The session-owned AgentController state domain. */
state;
/**
* Scoping tags for this session (e.g. `{ projectPath }`). Seeded at creation
* and stamped onto every thread this session creates so thread listings can be
* filtered back to the session's scope. Empty when the session is unscoped.
*/
#tags;
#workspace;
browser;
constructor({ resourceId, state, id, ownerId, tags, workspace, browser }) {
this.#tags = tags ? Object.fromEntries(Object.entries(tags).filter(([key]) => !isReservedThreadMetadataKey(key))) : {};
this.identity = new SessionIdentity({
resourceId,
id,
ownerId
});
this.thread = new SessionThread(() => this.identity.getResourceId());
this.suspensions = new SessionSuspensions(() => ({
resourceId: this.identity.getResourceId(),
threadId: this.thread.getId()
}));
this.displayState = new SessionDisplayState({
getTokenUsage: () => this.getTokenUsage(),
getSubagentDisplayName: (agentType) => this.#resolveSubagentName?.(agentType),
getThreadId: () => this.thread.getId(),
clearFollowUps: () => this.cleanupFollowUpBinding(),
getRunId: () => this.#endingRunId === void 0 ? this.run.getRunId() : this.#endingRunId
});
this.#bus.setDisplayState(this.displayState);
const sessionState = new SessionState(state ?? { initialState: {} }, this.#bus, () => {
const threadId = this.thread.getId();
if (threadId === null) return void 0;
return (args) => this.thread.setSettingOn({
threadId,
...args
});
}, () => ({
resourceId: this.identity.getResourceId(),
threadId: this.thread.getId()
}), () => ({
modeId: this.mode.get(),
modelId: this.model.get()
}));
this.state = sessionState;
this.model = new SessionModel(() => this.#store, this.#bus, (level, commit, isActive, applyModel) => sessionState.setWithCommit({ thinkingLevel: level }, commit, isActive, applyModel), () => {
const state = sessionState.get();
const level = state && typeof state === "object" && "thinkingLevel" in state ? state.thinkingLevel : void 0;
switch (level) {
case "off":
case "low":
case "medium":
case "high":
case "xhigh":
case "max": return level;
default: return;
}
});
if (workspace !== void 0 && !(workspace instanceof require_workspace.Workspace)) throw new Error(`A session workspace must be a valid Workspace instance.`);
this.#workspace = workspace;
this.browser = browser;
}
/**
* This session's scoping tags (e.g. `{ projectPath }`), stamped onto every
* thread it creates. Returns a copy; empty when the session is unscoped.
*/
getTags() {
return { ...this.#tags };
}
/** @internal Restore host defaults before hydrating another thread's selection. */
resetThreadSelection() {
this.state.captureSelection();
this.mode.reset();
this.model.reset();
}
/** @internal Reset state fields whose durable source is the active thread. */
resetThreadDerivedState() {
this.state.rebind(THREAD_DERIVED_STATE_KEYS);
}
/**
* The scope this session's threads carry: what `thread.create()` stamps and
* what thread selection filters on. Both must read it here — computing it on
* each side is what let selection drift off the controller-global state while
* creation stamped the session's own.
*/
getThreadScope() {
const tags = Object.fromEntries(Object.entries(this.#tags).filter(([key]) => !isReservedThreadMetadataKey(key)));
if (Object.keys(tags).length > 0) return tags;
const { projectPath } = this.state.get();
return projectPath ? { projectPath } : {};
}
/**
* The workspace resolved for this session, or `undefined` when the session
* runs without one. A workspace is optional: sessions that only need threads,
* state, and agent runs (chat-style usage) do not have to configure
* filesystem or sandbox access.
*
* Dynamic workspace factories are evaluated independently when each session
* is created. Use this accessor for operations that must stay bound to the
* session's workspace rather than resolving through controller-global state.
*/
getWorkspace() {
return this.#workspace;
}
/**
* Subscribe to this session's events. Returns an unsubscribe function.
* Listeners are scoped to this session: a session never delivers its events
* to another session's subscribers.
*/
subscribe(listener) {
return this.#bus.subscribe(listener);
}
/**
* The session's current state as events, for a subscriber that joins without
* `display_state_changed` snapshots: the message being streamed, as
* `message_start` so later `message_update` deltas apply to it, the active
* thread's latest `om_status`, and its token total as a `usage_update` with
* no step usage. Never emitted on the bus: deliver them to the joining
* subscriber only, right before {@link subscribe} in the same synchronous
* block, so no live event lands between.
*/
initialStateEvents() {
const total = this.getTokenUsage();
return [...this.#bus.initialStateEvents(), ...total.totalTokens > 0 ? [{
type: "usage_update",
usage: createEmptyTokenUsage(),
total
}] : []];
}
/** Subscribe to work that must complete before the terminal agent event is exposed. */
onBeforeAgentEnd(listener) {
this.#beforeAgentEndListeners.add(listener);
return () => this.#beforeAgentEndListeners.delete(listener);
}
/** Await terminal hooks, then emit the terminal event to subscribers. */
async finishAgentRun(reason, { abortReason } = {}) {
const event = {
type: "agent_end",
reason,
...abortReason ? { abortReason } : {}
};
const runId = this.run.getRunId();
for (const listener of this.#beforeAgentEndListeners) try {
await listener(event);
} catch (error) {
console.error("Error in before-agent-end listener:", error);
}
if (reason !== "suspended" && runId) this.#threadOwnerIdsByRunId.delete(runId);
this.#endingRunId = runId;
try {
this.emit(event);
} finally {
this.#endingRunId = void 0;
}
}
/** Await the terminal event for a specific accepted agent run. */
async waitForAcceptedRunCompletion(accepted, { waitForDelivery = true } = {}) {
const completedRunIds = /* @__PURE__ */ new Set();
let runId;
let resolveCompletion;
const completion = new Promise((resolve) => {
resolveCompletion = resolve;
});
const unsubscribe = this.onBeforeAgentEnd(() => {
const endingRunId = this.run.getRunId();
if (!endingRunId) return;
completedRunIds.add(endingRunId);
if (endingRunId === runId) resolveCompletion();
});
const waitersController = new AbortController();
const threadId = this.thread.getId();
let tornDown = false;
const teardown = this.stream.waitForTeardown(waitersController.signal).then(() => {
tornDown = true;
});
let aborted = false;
const abortRequest = this.run.waitForAbortRequest(waitersController.signal, { after: this.run.getAbortGeneration() }).then(() => {
aborted = true;
});
try {
const result = await accepted;
if (aborted) return;
if (result.action !== "wake" && !waitForDelivery) return;
runId = "runId" in result ? result.runId : void 0;
if (!runId || completedRunIds.has(runId)) return;
if (tornDown && (!this.stream.isOpen() || threadId !== null && this.thread.getId() !== threadId)) return;
const waits = [
completion,
this.stream.waitForConsumerFailure(waitersController.signal),
tornDown ? this.stream.waitForTeardown(waitersController.signal) : teardown,
abortRequest
];
await Promise.race(waits);
} finally {
waitersController.abort();
unsubscribe();
}
}
/**
* Emit an event on this session. Delegates to this session's bus, which folds
* the event into the canonical display state, dispatches to this session's
* listeners, then fans out a synthetic `display_state_changed`.
*/
emit(event) {
this.#bus.emit(event);
}
/**
* Whether this session has any event subscribers. Emitters use this to skip
* building per-event snapshots that nothing would read.
*/
hasListeners() {
return this.#bus.hasListeners();
}
/**
* Attach the thread-settings store the Session persists mode/model through.
* The AgentController calls this once storage is available; without it, mode/model
* state lives purely in memory.
*/
setStore(store) {
this.#store = store;
}
/**
* Attach the tool→category resolver used when a user picks "always allow
* category". The category map is AgentController config, so the AgentController injects this
* once; without it, an "always_allow_category" decision simply approves.
*/
setCategoryResolver(resolveCategory) {
this.#resolveCategory = resolveCategory;
}
/**
* Attach the subagent display-name resolver the display-state reducer uses to
* label active subagents. The subagent catalog is AgentController config, so the
* AgentController injects this once; without it, subagents render without a name.
*/
setSubagentNameResolver(resolveSubagentName) {
this.#resolveSubagentName = resolveSubagentName;
}
/**
* Attach the AgentController-owned run machinery this session leverages to drive agent
* runs (resolve the agent, build run/stream options + toolsets + request
* context, persist usage, generate ids). The AgentController injects this once when it
* constructs the session. The run loop, run state, and thread stream live on
* the session; this is the narrow set of shared capabilities it reaches back
* into the host for — see {@link SessionMachinery}.
*/
setMachinery(machinery) {
this.#machinery = machinery;
this.#engine = new SessionRunEngine(this, machinery);
}
/**
* The AgentController-owned run machinery injected via {@link setMachinery}, throwing
* when accessed before wiring (a run can never be driven without it).
*/
get machinery() {
if (!this.#machinery) throw new Error("Session run machinery has not been wired by the AgentController");
return this.#machinery;
}
/** The per-session run engine, throwing when accessed before machinery is wired. */
get runEngine() {
if (!this.#engine) throw new Error("Session run engine has not been wired by the AgentController");
return this.#engine;
}
/**
* Consume an agent stream response, folding chunks into this session's display
* messages and usage and driving tool approval. Delegates to the per-session
* run engine. Production runs go through `processSubscribedThreadStream`;
* only tests call this directly.
*/
processStream(response, requestContext) {
return this.runEngine.processStream(response, requestContext);
}
/**
* Drive the run loop for a subscribed thread stream: process each run's chunks
* and finalize it. Delegates to the per-session run engine.
*/
processSubscribedThreadStream(subscription) {
return this.runEngine.processSubscribedThreadStream(subscription);
}
/**
* The id of the run currently active on this session: the live subscription's
* active run id when it is streaming, falling back to the last run id the run
* tracker observed. Null when the session is idle.
*/
getCurrentRunId() {
return this.stream.activeRunId() ?? this.run.getRunId();
}
/**
* Abort the session's active run: drop any parked tool suspensions, abort the
* live subscription's in-flight run, and mark the run as aborting so the
* run-end path resolves its reason as 'aborted'.
*
* Dropping the parked suspensions matters because a run sitting in a tool
* `suspend()` (e.g. `ask_user` / `request_access`) is not actively streaming,
* so aborting the controller alone would leave it orphaned. The AgentController still
* clears its own display-state mirror of those suspensions separately.
*
* Releasing a parked tool-approval gate matters for the same reason: a run
* awaiting `approval.arm()` is not streaming, so we resolve it as a decline so
* the gated tool is rejected and the run can finalize rather than hang.
*/
abortRun(options = {}) {
this.#abortGeneration++;
if (this.run.isAbortRequested()) return;
const suspendedToolCalls = this.suspensions.clear();
for (const suspension of suspendedToolCalls) this.emit({
type: "tool_suspension_cancelled",
resourceId: suspension.resourceId,
threadId: suspension.threadId,
runId: suspension.runId,
toolCallId: suspension.toolCallId,
toolName: suspension.toolName,
reason: ABORTED_BY_USER_REASON
});
this.#localOnlyAbort = options.localOnly === true;
const abortThreadId = this.thread.getId() ?? void 0;
const wasGated = this.approval.isArmed({ threadId: abortThreadId });
if (wasGated && options.keepParked) this.displayState.clearPendingApprovals(this.approval.detach({ threadId: abortThreadId }));
else if (wasGated) {
const gatedRunId = this.run.getRunId();
this.run.requestAbort({ deferSignal: true });
this.#deferredAbortOrigin = {
bindingGeneration: this.run.bindingGeneration(),
localOnly: this.#localOnlyAbort
};
if (suspendedToolCalls.length === 0) {
this.#releaseApprovalGates({ threadId: abortThreadId });
return;
}
this.runEngine.settleSuspendedToolCallsAsDenied(suspendedToolCalls).catch((error) => this.emit({
type: "error",
error: require_error.getErrorFromUnknown(error)
})).finally(() => {
this.#releaseApprovalGates({ threadId: abortThreadId });
this.#releaseSuspendedRuns(suspendedToolCalls, gatedRunId);
});
return;
}
if (suspendedToolCalls.length > 0 && !options.keepParked) {
this.run.requestAbort({ deferSignal: true });
const origin = {
bindingGeneration: this.run.bindingGeneration(),
localOnly: this.#localOnlyAbort
};
this.runEngine.settleSuspendedToolCallsAsDenied(suspendedToolCalls).catch((error) => this.emit({
type: "error",
error: require_error.getErrorFromUnknown(error)
})).finally(() => {
this.completeDeferredAbort(origin);
this.#releaseSuspendedRuns(suspendedToolCalls);
});
return;
}
this.stream.abort({ localOnly: this.#localOnlyAbort });
this.run.requestAbort();
}
async #releaseSuspendedRuns(suspendedToolCalls, liveRunId) {
const runIds = new Set(suspendedToolCalls.map(({ runId }) => runId));
for (const runId of runIds) {
if (runId === liveRunId) continue;
try {
await this.machinery.releaseSuspendedRun(runId);
} catch (error) {
this.emit({
type: "error",
error: require_error.getErrorFromUnknown(error)
});
}
}
}
/**
* Take the origin captured when a gated abort was armed. The run engine
* claims it as soon as the gate releases, so a later abort of another run
* cannot overwrite the origin this run's teardown is checked against.
*/
takeDeferredAbortOrigin() {
const origin = this.#deferredAbortOrigin;
this.#deferredAbortOrigin = void 0;
return origin;
}
/**
* Fire the deferred abort teardown for a run that was aborted while parked on
* a tool-approval gate: abort the live subscription and the run's controller.
* Called by the run engine once the gated call's decline has been driven
* through the agent, so the denial is persisted before the run is torn down.
* When `origin` is present, the teardown is skipped if the session's binding
* was torn down since, because a successor run may now own the stream and
* run state. (The abort-requested flag is not a usable guard: the denial's
* own resumed run resets it before settlement resolves.)
*/
completeDeferredAbort(origin) {
if (origin && this.run.bindingGeneration() !== origin.bindingGeneration) return;
this.stream.abort({ localOnly: origin?.localOnly ?? this.#localOnlyAbort });
this.run.requestAbort();
}
/**
* Abort the session's active run and clear the display-state mirror of any
* parked tool suspensions. {@link abortRun} drops the parked suspensions (so a
* run sitting in a tool suspend() like ask_user / request_access isn't left
* orphaned), aborts the live subscription, and marks the run as aborting; this
* additionally clears the display-state mirror of those suspensions and
* notifies subscribers so stale suspension UI doesn't linger.
*/
abort(options = {}) {
const hadPendingSuspensions = this.displayState.get().pendingSuspensions.size > 0;
this.displayState.clearPendingSuspensions();
this.abortRun(options);
if (hadPendingSuspensions) this.emit({
type: "display_state_changed",
displayState: this.displayState.get()
});
}
/**
* Resolve the effective approval policy for a tool: explicit per-tool deny
* wins, then session-wide yolo, then an explicit per-tool policy, then a
* grant, then the tool's category grant/policy, falling back to "ask". Pure
* session state plus the injected category resolver.
*
* `scope` names the thread whose rules and grants apply. Pass a thread id to
* read that thread's grants against the session's current rules, or a run's
* request context to use the rules of the thread that run belongs to, which
* may not be the thread the session currently holds. Grants are checked
* against that thread (default: the current thread) plus the session-wide
* bucket, so a grant made from one thread's approval prompt is not inherited
* by every other thread in the session.
*/
resolveToolApproval(toolName, scope) {
const { threadId, state } = typeof scope === "string" || scope === void 0 ? {
threadId: scope,
state: this.state.get()
} : this.__getRunState(scope);
const rules = readPermissionRules(state);
const toolPolicy = rules.tools[toolName];
if (toolPolicy === "deny") return "deny";
if (state.yolo === true) return "allow";
if (toolPolicy) return toolPolicy;
if (this.hasToolGrant(toolName, threadId)) return "allow";
const category = this.#resolveCategory?.(toolName);
if (category) {
if (this.hasCategoryGrant(category, threadId)) return "allow";
const categoryPolicy = rules.categories[category];
if (categoryPolicy) return categoryPolicy;
}
return "ask";
}
/**
* @internal The thread and session state a run sees. Rules are thread-scoped
* state, so a run on a thread the session no longer holds reads its own
* thread's view from its request context. A run on the current thread reads
* the live state, which also covers a view whose source was released while
* the run was parked.
*/
__getRunState(requestContext) {
const context = requestContext?.get("controller");
const threadId = context?.threadId ?? this.thread.getId() ?? void 0;
const active = context?.isThreadActive ? context.isThreadActive() : threadId === (this.thread.getId() ?? void 0);
if (!context || active) return {
threadId,
state: this.state.get()
};
return {
threadId,
state: context.getState?.() ?? context.state ?? {}
};
}
/**
* Respond to the parked tool-approval gate named by `toolCallId` with the
* user's decision. The id is required: a response can only release the gate it
* names, so a stale or id-less response can never resolve a different pending
* gate. A no-op when that gate is not parked, or when the run is aborting and
* the gate belongs to the aborting thread.
* "always_allow_category" grants the gated tool's category to the thread that
* owns the gate (resolved via the injected {@link setCategoryResolver}) and then
* approves; "approve"/"decline" release the run as-is.
*/
respondToToolApproval({ decision, toolCallId, requestContext, declineContext }) {
if (this.run.isAbortRequested() && this.approval.isArmed({
toolCallId,
threadId: this.thread.getId() ?? void 0
})) return {
accepted: false,
reason: "aborting"
};
const result = this.approval.respond({
decision,
toolCallId,
requestContext,
declineContext,
onAlwaysAllow: (toolName, threadId) => {
const category = this.#resolveCategory?.(toolName);
if (category) this.grantCategory(category, threadId);
}
});
this.displayState.clearPendingApprovals([toolCallId]);
return result;
}
/**
* Decline every parked approval gate matching `filter` and drop the matching
* display entries. Used to release this thread's gate(s) on abort, or when a
* user message interrupts a run — never another thread's, so a background
* run's approval authority stays untouched.
*/
#releaseApprovalGates(filter = {}) {
this.displayState.clearPendingApprovals(this.approval.cancel(filter));
}
/**
* Whether a suspended run on the current thread is waiting on an approval for
* `toolCallId`. Lets callers reject stale answers before scheduling the resume.
*/
async hasPersistedToolApproval(toolCallId) {
const threadId = this.thread.getId();
if (!threadId) return false;
const resourceId = this.identity.getResourceId();
const { runs } = await this.machinery.getAgent().listSuspendedRuns({
threadId,
resourceId
});
return runs.some((run) => run.toolCalls.some((call) => call.requiresApproval && call.toolCallId === toolCallId));
}
/**
* Answer an approval that is stored with a suspended run but not parked on this
* session's gate, e.g. a card rebuilt from thread history after a restart.
* Resolves the run that owns `toolCallId` and resumes it by run id. Throws when
* no suspended run on the current thread is waiting on that tool call.
*/
async respondToPersistedToolApproval({ toolCallId, approved, alwaysAllowCategory, requestContext }) {
const threadId = this.thread.getId();
const resourceId = this.identity.getResourceId();
if (!threadId) throw new Error("Cannot answer a tool approval without a current thread");
const { runs } = await this.machinery.getAgent().listSuspendedRuns({
threadId,
resourceId
});
const run = runs.find((candidate) => candidate.toolCalls.some((call) => call.requiresApproval && call.toolCallId === toolCallId));
if (!run) throw new Error(`No suspended run is waiting on tool call ${toolCallId}`);
const identity = {
toolCallId,
requestContext,
runId: run.runId,
threadId,
resourceId
};
if (approved && alwaysAllowCategory) {
const toolName = run.toolCalls.find((call) => call.toolCallId === toolCallId)?.toolName;
const category = toolName ? this.#resolveCategory?.(toolName) : void 0;
if (category) this.grantCategory(category, threadId);
}
if (approved) await this.approveToolCall(identity);
else await this.declineToolCall(identity);
}
/**
* Answer parked approvals whose tool the current rules now allow or deny.
* The policy is otherwise read once, when the approval chunk streams past, so
* a rule set afterwards (a later `setForTool`, or a session-created hook on a
* process reopening a run parked elsewhere) would leave the call waiting for
* a click. Covers gates parked on this session and approvals stored with the
* current thread's suspended runs. Calls still resolving to `ask` stay parked.
*/
#parkedApprovalsCheck = Promise.resolve();
#answeredParkedApprovals = /* @__PURE__ */ new Set();
#parkedApprovalsRequestContext;
/** Resume calls released by a policy re-check under the context of the request that opened this session. */
setParkedApprovalsRequestContext(requestContext) {
this.#parkedApprovalsRequestContext = requestContext;
}
applyToolPolicyToParkedApprovals() {
const check = this.#parkedApprovalsCheck.then(() => this.#applyToolPolicyToParkedApprovalsSafely());
this.#parkedApprovalsCheck = check;
return check;
}
async #applyToolPolicyToParkedApprovalsSafely() {
try {
await this.#applyToolPolicyToParkedApprovals();
} catch (error) {
console.error("Re-checking parked tool approvals against the current policy failed:", error);
}
}
async #applyToolPolicyToParkedApprovals() {
const threadId = this.thread.getId();
if (!threadId) return;
const address = (runId, toolCallId) => `${runId ?? ""}:${toolCallId}`;
const handled = /* @__PURE__ */ new Set();
for (const gate of this.approval.list()) {
if (gate.threadId !== void 0 && gate.threadId !== threadId) continue;
handled.add(address(gate.runId, gate.toolCallId));
const policy = this.resolveToolApproval(gate.toolName, threadId);
if (policy === "ask") continue;
if (this.run.isAbortRequested()) continue;
this.approval.respond({
decision: policy === "allow" ? "approve" : "decline",
toolCallId: gate.toolCallId,
threadId: gate.threadId,
runId: gate.runId
});
this.displayState.clearPendingApprovals([gate.toolCallId]);
}
const agent = this.machinery.getAgent();
if (typeof agent.listSuspendedRuns !== "function") return;
let runs;
try {
({runs} = await agent.listSuspendedRuns({
threadId,
resourceId: this.identity.getResourceId()
}));
} catch (error) {
if (error instanceof require_error.MastraError && error.id === "AGENT_LIST_SUSPENDED_RUNS_NO_STORAGE") return;
throw error;
}
for (const run of runs) for (const call of run.toolCalls) {
const { toolCallId, toolName } = call;
if (!call.requiresApproval || !toolCallId || !toolName) continue;
const key = address(run.runId, toolCallId);
if (handled.has(key) || this.#answeredParkedApprovals.has(key)) continue;
const policy = this.resolveToolApproval(toolName, threadId);
if (policy === "ask") continue;
handled.add(key);
this.#answeredParkedApprovals.add(key);
const identity = {
toolCallId,
runId: run.runId,
threadId,
resourceId: this.identity.getResourceId(),
requestContext: this.#parkedApprovalsRequestContext
};
if (policy === "allow") await this.approveToolCall(identity);
else await this.declineToolCall(identity);
}
}
/**
* Build the agent message input for a user turn, attaching any files as
* additional message parts (text files inlined as fenced code, binary files
* as `file` parts). Returns the plain string when there are no files.
*/
createMessageInput({ content, files }) {
if (!files?.length) return content;
const fileParts = files.map((f) => {
if (f.mediaType.startsWith("text/") || f.mediaType === "application/json") {
let textContent = f.data;
const base64Match = f.data.match(/^data:[^;]*;base64,(.*)$/);
if (base64Match) try {
textContent = Buffer.from(base64Match[1], "base64").toString("utf-8");
} catch {}
const label = f.filename ? `[File: ${f.filename}]` : "[Attached file]";
const maxBacktickRun = Math.max(0, ...Array.from(textContent.matchAll(/`+/g), (match) => match[0].length));
const fence = "`".repeat(Math.max(3, maxBacktickRun + 1));
return {
type: "text",
text: `${label}\n${fence}\n${textContent}\n${fence}`
};
}
return {
type: "file",
data: f.data,
mediaType: f.mediaType,
...f.filename ? { filename: f.filename } : {}
};
});
return [{
type: "text",
text: content
}, ...fileParts];
}
/**
* Watch for the live subscription's next teardown (detach or cleanup). The run
* engine detaches an aborted subscription only after that run has ended, so
* work that must land on a fresh subscription waits for this first. Register
* it before awaiting anything, while the aborted handle is still attached.
*/
#watchStreamTeardown() {
const watcher = new AbortController();
const teardown = this.stream.waitForTeardown(watcher.signal);
return {
wait: async (timeoutMs) => {
let timer;
try {
await Promise.race([teardown, new Promise((resolve) => {
timer = setTimeout(resolve, timeoutMs);
})]);
} finally {
if (timer) clearTimeout(timer);
watcher.abort();
}
},
cancel: () => watcher.abort()
};
}
/**
* Resolve once this session's stream is fully idle.
*
* After `abort()` is called the run's status can still be `'running'` for a
* few microtasks while the underlying model stream finalizes. Callers that
* need to send a fresh signal after an abort (e.g. plan approval → mode
* switch → trigger reminder) should await this before calling `sendSignal`
* to avoid the new signal being queued onto the dying run, which would then
* be drained with the previous run's already-aborted abortSignal.
*/
async waitForStreamIdle(timeoutMs = 1e3) {
if (!this.stream.isActive() && this.run.getRunId() === null) return true;
let lifecycleWait;
let timeout;
const timeoutPromise = new Promise((resolve) => {
timeout = setTimeout(() => resolve("timeout"), timeoutMs);
});
try {
while (this.stream.isActive() || this.run.getRunId() !== null) {
lifecycleWait = new AbortController();
const result = await Promise.race([
this.stream.waitForTeardown(lifecycleWait.signal),
this.run.waitForTeardown(lifecycleWait.signal),
timeoutPromise
]);
lifecycleWait.abort();
lifecycleWait = void 0;
if (result === "timeout") return false;
}
} finally {
lifecycleWait?.abort();
if (timeout) clearTimeout(timeout);
}
return true;
}
/** Persist a signal to an explicit conversation without changing this session's current thread. */
sendSignalToThread(input, target, options) {
const signal = require_signals.createSignal(input);
const accepted = Promise.resolve().then(async () => {
await this.machinery.authorizeExecute?.(options?.requestContext);
const resourceId = this.identity.getResourceId();
const thread = target.resourceId === resourceId ? await this.thread.getById({ threadId: target.threadId }) : null;
if (!thread || thread.resourceId !== resourceId) throw new Error(`Thread not found: ${target.threadId}`);
const result = this.machinery.getAgent().sendSignal(signal, {
...target,
ifActive: { behavior: "persist" },
ifIdle: { behavior: "persist" }
});
if ((await result.accepted).action === "persist") {
await result.persisted;
if (this.identity.getResourceId() === target.resourceId && this.thread.getId() === target.threadId) {
const message = signal.toDBMessage(target);
this.emit({
type: "message_start",
message
});
this.emit({
type: "message_end",
id: message.id
});
}
}
return { accepted: true };
});
return {
id: signal.id,
type: signal.type,
accepted
};
}
/**
* Send a signal to this session's current agent/thread. Creates a thread when
* the session is not yet bound. When a run is already active the signal is
* dispatched onto it; otherwise the signal carries fresh stream options that
* start a new run.
*/
sendSignal(input, options) {
const settleRunId = async (result) => {
const settled = await result.accepted.catch(() => void 0);
return settled && "runId" in settled ? settled.runId : void 0;
};
const submittedAbortGeneration = this.#abortGeneration;
const assertNotCancelled = () => {
if (this.#abortGeneration !== submittedAbortGeneration) throw new SessionStartupCancelledError();
};
const contentOptions = "content" in input ? input : void 0;
const tracingContext = options?.tracingContext ?? contentOptions?.tracingContext;
const tracingOptions = options?.tracingOptions ?? contentOptions?.tracingOptions;
const requestContextInput = options?.requestContext ?? contentOptions?.requestContext;
const untilIdle = options?.untilIdle ?? contentOptions?.untilIdle;
const scopes = contentOptions?.scopes;
const requireDelivery = options?.requireDelivery ?? false;
const ifActive = options?.ifActive ?? ("content" in input ? input.ifActive : void 0);
const ifIdle = options?.ifIdle ?? ("content" in input ? input.ifIdle : void 0);
const submittedRunId = this.run.getRunId();
const submittedActiveRunId = this.stream.activeRunId();
const submittedIsRunning = this.run.isRunning();
const submittedAbortRequested = this.run.isAbortRequested();
const submittedWhileWorking = submittedIsRunning || submittedAbortRequested && Boolean(submittedRunId || submittedActiveRunId);
const abortedStreamTeardown = submittedAbortRequested && !submittedIsRunning && this.stream.isOpen() ? this.#watchStreamTeardown() : void 0;
const requestAuthor = readMessageAuthor(requestContextInput);
const submitted = require_signals.createSignal("content" in input ? {
type: "user",
tagName: "user",
contents: input.content,
author: input.author ?? requestAuthor,
providerOptions: withMessageAuthor(input.providerOptions, input.author ?? requestAuthor)
} : input);
const signal = submittedWhileWorking ? asInterjection(submitted) : submitted;
const accepted = Promise.resolve().then(async () => {
await this.machinery.authorizeExecute?.(requestContextInput);
const threadId = await this.thread.ensureId({ requestContext: requestContextInput });
const agent = this.machinery.getAgent();
await this.thread.ensureSubscription(threadId, agent, requestContextInput);
assertNotCancelled();
if (!submittedAbortRequested && submittedRunId && submittedActiveRunId && submittedIsRunning) {
if (signal.type === "user") this.#releaseApprovalGates({
threadId,
requestContext: requestContextInput,
declineContext: {
reason: "interrupted_by_user_message",
message: "The pending tool approval was declined because the user sent a new message."
}
});
const fallBackWhenIdle = (ifActive?.behavior ?? "deliver") === "deliver" && ifIdle?.behavior !== "discard";
const result = agent.sendSignal(signal, {
resourceId: this.identity.getResourceId(),
threadId,
ifActive,
ifIdle: fallBackWhenIdle ? {
...ifIdle,
behavior: "discard"
} : ifIdle,
...scopes ? { scopes } : {}
});
const settled = ifActive?.behavior === "persist" || ifIdle?.behavior === "persist" || requireDelivery ? await result.accepted : fallBackWhenIdle ? await result.accepted.catch(() => void 0) : void 0;
if (!(fallBackWhenIdle && settled?.action === "discard")) {
if (settled?.action === "persist") {
await result.persisted;
const message = signal.toDBMessage({
resourceId: this.identity.getResourceId(),
threadId
});
this.emit({
type: "message_start",
message
});
this.emit({
type: "message_end",
id: message.id
});
}
if (requireDelivery) {
const acceptedResult = settled ?? await result.accepted;
return {
accepted: true,
runId: "runId" in acceptedResult ? acceptedResult.runId : void 0,
action: acceptedResult.action,
..."reason" in acceptedResult ? { reason: acceptedResult.reason } : {}
};
}
return {
accepted: true,
runId: await settleRunId(result)
};
}
if (!await this.waitForStreamIdle()) this.thread.cleanupSubscription();
assertNotCancelled();
await this.thread.ensureSubscription(threadId, agent, requestContextInput);
assertNotCancelled();
}
if (submittedAbortRequested && (submittedRunId || submittedActiveRunId)) {
const teardownDeadline = Date.now() + POST_ABORT_TEARDOWN_TIMEOUT_MS;
const idle = await this.waitForStreamIdle(submittedIsRunning ? void 0 : POST_ABORT_TEARDOWN_TIMEOUT_MS);
assertNotCancelled();
if (idle && abortedStreamTeardown && this.run.isAbortRequested()) {
await abortedStreamTeardown.wait(Math.max(0, teardownDeadline - Date.now()));
assertNotCancelled();
}
if (!idle) this.thread.cleanupSubscription();
await this.thread.ensureSubscription(threadId, agent, requestContextInput);
assertNotCancelled();
} else if (abortedStreamTeardown) {
await abortedStreamTeardown.wait(1e3);
assertNotCancelled();
if (this.stream.isOpen() && this.run.isAbortRequested()) {
this.thread.cleanupSubscription();
this.run.reset();
}
await this.thread.ensureSubscription(threadId, agent, requestContextInput);
assertNotCancelled();
}
abortedStreamTeardown?.cancel();
const startupGeneration = this.run.bindingGeneration();
this.run.clearAbortRequested();
const startupSignal = this.run.ensureAbortController().signal;
const streamOptions = await this.machinery.buildStreamOptions({
requestContext: requestContextInput,
tracingContext,
tracingOptions,
untilIdle,
threadId,
abortSignal: startupSignal
}).catch((error) => {
if (this.run.bindingGeneration() === startupGeneration && this.run.getAbortSignal() === startupSignal && !this.run.getRunId() && !this.stream.activeRunId()) this.run.reset();
throw error;
});
assertNotCancelled();
if (startupSignal.aborted || this.run.bindingGeneration() !== startupGeneration) throw new SessionStartupCancelledError();
const result = agent.sendSignal(signal, {
resourceId: this.identity.getResourceId(),
threadId,
ifActive,
ifIdle: {
...ifIdle,
streamOptions
},
...scopes ? { scopes } : {}
});
result.accepted.then((settled) => {
if (settled.action !== "wake") return;
const runId = settled.runId;
const abort = () => this.#localOnlyAbort ? agent.abortThreadStream({
resourceId: this.identity.getResourceId(),
threadId,
expectedRunId: runId,
localOnly: true
}) : agent.abortRunStream(runId);
if (startupSignal.aborted) abort();
else startupSignal.addEventListener("abort", abort, { once: true });
}, () => {});
if (requireDelivery) {
const settled = await result.accepted;
return {
accepted: true,
runId: "runId" in settled ? settled.runId : void 0,
action: settled.action,
..."reason" in settled ? { reason: settled.reason } : {}
};
}
await Promise.race([result.accepted.then(() => void 0), new Promise((resolve) => setTimeout(resolve, 0))]);
result.accepted.catch(() => {});
if (ifIdle?.behavior === "persist") await result.persisted;
return {
accepted: true,
runId: void 0
};
});
return {
id: signal.id,
type: signal.type,
accepted: accepted.finally(() => abortedStreamTeardown?.cancel())
};
}
/**
* Send a notification signal to this session's current agent/thread.
*/
async sendNotificationSignal(input, options = {}) {
const { ifActive, ifIdle, requestContext: requestContextInput, tracingContext, tracingOptions, scopes } = options;
const scoped = scopes?.length ? { scopes } : {};
await this.machinery.authorizeExecute?.(requestContextInput);
const threadId = await this.thread.ensureId({ requestContext: requestContextInput });
const agent = this.machinery.getAgent();
await this.thread.ensureSubscription(threadId, agent, requestContextInput);
const streamOptions = await this.machinery.buildStreamOptions({
requestContext: requestContextInput,
tracingContext,
tracingOptions
});
return agent.sendNotificationSignal(input, {
resourceId: this.identity.getResourceId(),
threadId,
ifActive,
ifIdle: {
...ifIdle,
streamOptions
},
...scoped
});
}
async prepareMessageTarget({ requestContext, tracingContext, tracingOptions, untilIdle, abortSignal, includeStreamOptions = true }) {
const threadId = await this.thread.ensureId({ requestContext });
await this.thread.ensureSubscription(threadId, void 0, requestContext);
if (!includeStreamOptions) return {
resourceId: this.identity.getResourceId(),
threadId
};
const streamOptions = await this.machinery.buildStreamOptions({
requestContext,
tracingContext,
tracingOptions,
untilIdle,
abortSignal
});
return {
resourceId: this.identity.getResourceId(),
threadId,
ifIdle: { streamOptions }
};
}
/**
* Send a message to this session's current agent and await the run. Streams
* the response and emits events.
*
* `scopes` are the scopes the message's run holds. A run's scopes are fixed when it
* starts: a message whose scopes match the active run's joins it, and one whose scopes
* differ waits for that run to end and then starts its own run on the same thread.
* Messages carrying scopes start in the order they were sent.
*/
async sendMessage({ content, files, tracingContext, tracingOptions, requestContext: requestContextInput, untilIdle, author, scopes }) {
let admitted = () => {};
if (scopes) {
const previous = this.#scopedSendTail;
this.#scopedSendTail = new Promise((resolve) => {
admitted = resolve;
});
await previous;
}
try {
await this.#sendMessageUntilAdmitted({
content,
files,
tracingContext,
tracingOptions,
requestContext: requestContextInput,
untilIdle,
author,
scopes
}, () => admitted());
} finally {
admitted();
}
}
async #sendMessageUntilAdmitted(input, onAdmitted) {
const { content, files, scopes } = input;
let lastBlockingRunId;
while (true) {
const wasActive = this.stream.isActive();
const signal = this.sendSignal({
content: this.createMessageInput({
content,
files
}),
tracingContext: input.tracingContext,
tracingOptions: input.tracingOptions,
requestContext: input.requestContext,
untilIdle: input.untilIdle,
author: input.author,
...scopes ? { scopes } : {}
}, { requireDelivery: true });
let blocked;
const accepted = signal.accepted.then((settled) => {
if (settled.action !== "blocked") {
onAdmitted();
return settled;
}
blocked = {
reason: settled.reason ?? "thread-blocked",
runId: settled.runId
};
return { action: settled.action };
});
if (wasActive) await accepted;
else await this.waitForAcceptedRunCompletion(accepted);
if (blocked === void 0) return;
if (blocked.runId === lastBlockingRunId) {
this.emit({
type: "error",
error: /* @__PURE__ */ new Error("Your message wasn't sent: another run still holds this thread. Try again shortly.")
});
return;
}
lastBlockingRunId = blocked.runId;
const waited = await this.#waitForOtherAgentRun();
if (waited === "stopped") return;
if (waited === "suspended") {
this.emit({
type: "error",
error: /* @__PURE__ */ new Error(blocked.reason === "scope-mismatch" ? "Your message wasn't sent: the run on this thread, started with other scopes, is waiting for an answer to its own prompt." : "Your message wasn't sent: another agent's run on this thread is waiting for an answer to its own prompt.")
});
return;
}
}
}
/**
* Wait until no other run holds this session's thread and this session has
* seen it end, or until that run parks on a prompt (`'suspended'`).
* `'stopped'` when Stop is pressed while waiting.
*/
async #waitForOtherAgentRun() {
const threadId = this.thread.getId();
if (!threadId) return "free";
const agent = this.machinery.getAgent();
const waiters = new AbortController();
let aborted = false;
const abortRequest = this.run.waitForAbortRequest(waiters.signal, { after: this.run.getAbortGeneration() }).then(() => {
aborted = true;
});
try {
const outcome = await Promise.race([require_run_registry.agentThreadStreamRuntime.waitForCrossAgentThreadRun(agent, {
memory: {
thread: threadId,
resource: this.identity.getResourceId()
},
untilSuspended: true
}, agent.getPubSub()), abortRequest]);
if (aborted) return "stopped";
if (outcome === "suspended") return "suspended";
await this.waitForStreamIdle();
return aborted ? "stopped" : "free";
} finally {
waiters.abort();
}
}
/**
* Queue a message for the next run, or send it immediately when this session
* is idle. Queue ordering and retry behavior are owned by the Agent runtime.
*/
async queueMessage({ content, files, tracingContext, tracingOptions, requestContext: requestContextInput, author, scopes }) {
await this.machinery.authorizeExecute?.(requestContextInput);
const wasActive = this.stream.isActive();
const target = await this.prepareMessageTarget({
requestContext: requestContextInput,
tracingContext,
tracingOptions,
abortSignal: wasActive ? new AbortController().signal : void 0
});
const messageInput = this.createMessageInput({
content,
files
});
const messageAuthor = author ?? readMessageAuthor(requestContextInput);
const providerOptions = withMessageAuthor(void 0, messageAuthor);
const result = this.machinery.getAgent().queueMessage(messageAuthor || providerOptions ? {
contents: messageInput,
...messageAuthor ? { author: messageAuthor } : {},
providerOptions
} : messageInput, scopes?.length ? {
...target,
scopes
} : target);
if (wasActive) await result.accepted;
else await this.waitForAcceptedRunCompletion(result.accepted, { waitForDelivery: false });
}
/**
* Queue a typed signal for the next run, or send it immediately when this
* session is idle. Shares the Agent runtime queue used by `queueMessage()`.
* Unlike `queueMessage()`, no author is inferred from the request context:
* set `signal.author` when the signal is human-authored.
*/
async queueSignal(signal, { tracingContext, tracingOptions, requestContext: requestContextInput, scopes } = {}) {
await this.machinery.authorizeExecute?.(requestContextInput);
const wasActive = this.stream.isActive();
const target = await this.prepareMessageTarget({
requestContext: requestContextInput,
tracingContext,
tracingOptions,
abortSignal: wasActive ? new AbortController().signal : void 0
});
const result = this.machinery.getAgent().queueSignal(signal, scopes?.length ? {
...target,
scopes
} : target);
if (wasActive) await result.accepted;
else await this.waitForAcceptedRunCompletion(result.accepted, { waitForDelivery: false });
}
/** Abort the current run and send steering input without clearing queued follow-ups. */
async steer({ content, files, requestContext, author, scopes }) {
this.abort();
await this.sendMessage({
content,
files,
requestContext,
author,
...scopes?.length ? { scopes } : {}
});
}
ensureFollowUpBinding(agent, resourceId, threadId) {
const existing = this.#followUpBinding;
if (existing?.agent === agent && existing.resourceId === resourceId && existing.threadId === threadId) return existing;
this.cleanupFollowUpBinding();
const binding = {
agent,
resourceId,
threadId
};
this.#followUpBinding = binding;
try {
const unsubscribe = agent.subscribeThreadEvents({
resourceId,
threadId
}, (event) => {
if (event.type === "queue-count-changed" && this.#followUpBinding === binding) this.emit({
type: "follow_up_queued",
count: event.count
});
});
binding.unsubscribe = unsubscribe;
if (this.#followUpBinding !== binding) {
unsubscribe();
return;
}
return binding;
} catch (error) {
if (this.#followUpBinding === binding) this.#followUpBinding = void 0;
throw error;
}
}
/** Queue a follow-up through the Agent runtime, or send it immediately while idle. */
async followUp({ content, files, requestContext }) {
if (!this.run.isRunning()) return this.sendMessage({
content,
files,
requestContext
});
await this.machinery.authorizeExecute?.(requestContext);
const threadId = this.thread.getId();
if (!threadId) return;
const resourceId = this.identity.getResourceId();
const agent = this.machinery.getAgent();
if (!this.ensureFollowUpBinding(agent, resourceId, threadId)) return;
const operation = {
generation: this.#followUpGeneration,
controller: new AbortController()
};
this.#preparingFollowUps.add(operation);
try {
const streamOptions = await this.machinery.buildStreamOptions({
requestContext,
abortSignal: operation.controller.signal
});
if (operation.controller.signal.aborted || operation.generation !== this.#followUpGeneration) return;
this.#preparingFollowUps.delete(operation);
await agent.queueMessage({
contents: this.createMessageInput({
content,
files
}),
providerOptions: withMessageAuthor(void 0, readMessageAuthor(requestContext))
}, {
resourceId,
threadId,
ifIdle: { streamOptions }
}).accepted;
} finally {
this.#preparingFollowUps.delete(operation);
}
}
cleanupFollowUpBinding() {
this.#followUpGeneration += 1;
for (const operation of this.#preparingFollowUps) operation.controller.abort();
this.#preparingFollowUps.clear();
const binding = this.#followUpBinding;
this.#followUpBinding = void 0;
binding?.unsubscribe?.();
this.emit({
type: "follow_up_queued",
count: 0
});
}
/**
* Persist a system-reminder message to this session's current thread. Returns
* the saved message, or `null` when the session has no thread or no storage.
*/
async saveSystemReminderMessage({ message, reminderType, role = "user", metadata }) {
const threadId = this.thread.getId();
if (!threadId) return null;
return this.machinery.saveSystemReminder({
threadId,
resourceId: this.identity.getResourceId(),
message,
reminderType,
role,
metadata
});
}
/** Tool call ids whose response has been claimed and is still being applied. */
#claimedToolResponses = /* @__PURE__ */ new Set();
#suspensionAgents = /* @__PURE__ */ new WeakMap();
#threadOwnerIdsByRunId = /* @__PURE__ */ new Map();
/** @internal Capture the trusted owner snapshot while processing a run's stream. */
__captureRunThreadOwnerId(runId, requestContext) {
const threadOwnerId = requestContext.getRaw(THREAD_OWNER_ID_CONTEXT_KEY);
if (typeof threadOwnerId !== "string" || this.#threadOwnerIdsByRunId.has(runId)) return;
this.#threadOwnerIdsByRunId.set(runId, threadOwnerId);
const runScope = this.machinery.getRunScope(runId);
if (!runScope?.has(THREAD_OWNER_ID_RUN_SCOPE_KEY)) runScope?.set(THREAD_OWNER_ID_RUN_SCOPE_KEY, threadOwnerId);
}
/**
* The mode the suspended run executed in, read from its persisted request
* context, so a mode switch during the suspension does not change the tools
* the continuation sees. Runs suspended before the mode was recorded fall back
* to the mode of the run's source thread as `requestContext` resolves it.
*/
isConfiguredMode(modeId) {
try {
this.mode.resolveId(modeId);
return true;
} catch {
return false;
}
}
async resolveSuspendedRunModeId(agent, runId, requestContext) {
const persisted = await agent.__getSuspendedRunRequestContextValue({
runId,
key: RUN_MODE_ID_CONTEXT_KEY
});
const modeId = typeof persisted === "string" && this.isConfiguredMode(persisted) ? persisted : requestContext.get("controller")?.session.modeId;
if (modeId) requestContext.setRaw(RUN_MODE_ID_CONTEXT_KEY, modeId);
return modeId;
}
async resolveSuspendedThreadOwnerId(agent, { runId, threadId, resourceId }) {
const persisted = await agent.__getSuspendedRunRequestContextValue({
runId,
key: THREAD_OWNER_ID_CONTEXT_KEY
});
if (typeof persisted === "string") return persisted;
const runOwnerId = this.machinery.getRunScope(runId)?.get(THREAD_OWNER_ID_RUN_SCOPE_KEY) ?? this.#threadOwnerIdsByRunId.get(runId);
if (runOwnerId) return runOwnerId;
const thread = await this.thread.getById({ threadId });
if (thread) {
if (thread.resourceId !== resourceId) throw new Error(`Thread "${threadId}" does not belong to resource "${resourceId}"`);
return typeof thread.metadata?.ownerId === "string" ? thread.metadata.ownerId : this.identity.getOwnerId();
}
if (threadId === this.thread.getId() && resourceId === this.identity.getResourceId()) return this.identity.getOwnerId();
}
async resolveSuspensionAgent(address) {
let suspension = this.suspensions.get(address);
const scope = this.machinery.getRunScope(address.runId);
const warm = suspension && (scope?.get(SUSPENDED_RUN_AGENT_KEY) ?? this.#suspensionAgents.get(suspension));
if (warm) return warm;
const owners = /* @__PURE__ */ new Map();
for (const agent of this.machinery.getAgents?.() ?? [this.machinery.getAgent()]) {
const perPage = 100;
for (let page = 0;; page++) {
const { runs, total } = await agent.listSuspendedRuns({
threadId: address.threadId,
resourceId: address.resourceId,
page,
perPage
});
const call = runs.find((run) => run.runId === address.runId && run.threadId === address.threadId && run.resourceId === address.resourceId)?.toolCalls.find((call) => call.toolCallId === address.toolCallId);
if (call?.toolName) {
owners.set(agent, call.toolName);
break;
}
if ((page + 1) * perPage >= total) break;
}
}
if (owners.size !== 1) throw new Error("Cannot uniquely identify the suspended run's owning agent");
const [agent, toolName] = owners.entries().next().value;
if (!suspension) {
this.suspensions.register({
...address,
toolName
});
suspension = this.suspensions.get(address);
}
this.#suspensionAgents.set(suspension, agent);
scope?.set(SUSPENDED_RUN_AGENT_KEY, agent);
return agent;
}
/**
* Claim the right to answer `toolCallId` so concurrent requests cannot both be
* acknowledged for the same pending target. Synchronous, so a caller that
* claims and then starts the response without awaiting in between is atomic.
* Pair with {@link releaseToolResponse} once the response settles.
*/
claimToolResponse(toolCallId) {
if (this.#claimedToolResponses.has(toolCallId)) return false;
this.#claimedToolResponses.add(toolCallId);
return true;
}
/** Release a claim taken with {@link claimToolResponse}. */
releaseToolResponse(toolCallId) {
this.#claimedToolResponses.delete(toolCallId);
}
/**
* Register a suspension that lives only in storage, so {@link claimToolSuspension}
* can find it. A run parked by a process that has since gone away stays
* suspended in storage, but this session never saw it park. Only an exact
* `toolCallId` on the active thread is looked up, and only when exactly one
* stored, non-approval suspension matches. The scan is bounded so an unknown
* id can't make a reply read every stored run on the thread.
*/
async restoreStoredToolSuspension(toolCallId, runId) {
if (!toolCallId || this.suspensions.resolveAddress({
toolCallId,
runId
})) return;
const threadId = this.thread.getId();
if (!threadId) return;
const resourceId = this.identity.getResourceId();
const matches = [];
const perPage = 100;
const maxPages = 10;
scan: for (const agent of this.machinery.getAgents?.() ?? [this.machinery.getAgent()]) {
if (typeof agent.listSuspendedRuns !== "function") continue;
for (let page = 0; page < maxPages; page++) {
let result;
try {
result = await agent.listSuspendedRuns({
threadId,
resourceId,
page,
perPage
});
} catch (error) {
if (error instanceof require_error.MastraError && error.id === "AGENT_LIST_SUSPENDED_RUNS_NO_STORAGE") break;
throw error;
}
for (const run of result.runs) {
if (runId !== void 0 && run.runId !== runId) continue;
for (const call of run.toolCalls) {
if (call.toolCallId !== toolCallId || !call.toolName || call.requiresApproval) continue;
matches.push({
agent,
runId: run.runId,
toolName: call.toolName
});
if (matches.length > 1) break scan;
}
}
if ((page + 1) * perPage >= result.total) break;
}
}
if (matches.length !== 1) return;
if (this.suspensions.resolveAddress({
toolCallId,
runId
})) return;
const match = matches[0];
const address = {
threadId,
resourceId,
runId: match.runId,
toolCallId
};
this.suspensions.register({
...address,
toolName: match.toolName
});
this.#suspensionAgents.set(this.suspensions.get(address), match.agent);
}
/**
* Claim the parked suspension a {@link respondToToolSuspension} call would
* resume. Returns the resolved tool call id, or a rejection when nothing is
* pending or another response already claimed it.
*/
claimToolSuspension(toolCallId, runId) {
const address = this.suspensions.resolveAddress({
toolCallId,
runId
});
if (!address) return {
accepted: false,
reason: "no_pending_suspension"
};
const claimKey = getSuspensionAddressKey(address);
if (!this.claimToolResponse(claimKey)) return {
accepted: false,
reason: "not_pending"
};
return {
accepted: true,
toolCallId: address.toolCallId,
address,
claimKey
};
}
/**
* Respond to a pending tool suspension. Provides resume data so the suspended
* tool can continue. `toolCallId` selects which suspended tool to resume —
* required when more than one is suspended concurrently; when omitted it
* resolves to the sole pending suspension. `submit_plan` resumes are routed
* through the plan-approval path (approval switches to the default mode).
*/
async respondToToolSuspension({ resumeData, toolCallId, runId, address: inputAddress, requestContext }) {
const address = inputAddress ?? this.suspensions.resolveAddress({
toolCallId,
runId
});
if (!address) return;
try {
if (!this.suspensions.has(address) && inputAddress) await this.resolveSuspensionAgent(address);
const suspension = this.suspensions.get(address);
if (!suspension) return;
if (suspension.toolName === "submit_plan") {
await this.handlePlanApprovalResume({
address,
response: resumeData,
requestContext
});
return;
}
await this.resumeToolCall({
resumeData,
address,
requestContext
});
} catch (error) {
const err = require_error.getErrorFromUnknown(error);
if (!(address.threadId === this.thread.getId() && address.resourceId === this.identity.getResourceId())) throw err;
this.emit({
type: "error",
error: err
});
if (!this.suspensions.has(address) && this.getCurrentRunId() === address.runId) await this.finishAgentRun("error");
}
}
/**
* Respond to a suspended `submit_plan` tool call. Rejections resume the plan
* tool with feedback. Approvals switch to the transition mode when needed,
* then resume the same suspended tool so the approved tool result is persisted
* and the model continues naturally in the target mode.
*/
async handlePlanApprovalResume({ address, response, requestContext }) {
if (response.action === "rejected") {
await this.resumeToolCall({
resumeData: response,
address,
requestContext,
resolveOnToolEnd: true
});
return;
}
const agent = await this.resolveSuspensionAgent(address);
const threadOwnerId = await this.resolveSuspendedThreadOwnerId(agent, address);
let sourceRequestContext = await this.machinery.buildRequestContext(requestContext, {
...address,
threadOwnerId,
execution: true
});
const context = sourceRequestContext.get("controller");
const sourceModeId = await this.resolveSuspendedRunModeId(agent, address.runId, sourceRequestContext) ?? context.session.modeId;
let runModeId = sourceModeId;
const transitionModeId = this.machinery.resolveTransitionModeId(sourceModeId);
if (transitionModeId && transitionModeId !== sourceModeId) {
if (context.isThreadActive?.()) await this.mode.switch({ modeId: transitionModeId });
else await context.setThreadSetting?.({
key: MODE_ID_KEY,
value: transitionModeId
});
sourceRequestContext = await this.machinery.buildRequestContext(sourceRequestContext, {
...address,
modeId: transitionModeId,
execution: true
});
runModeId = transitionModeId;
}
await this.resumeToolCall({
resumeData: response,
address,
requestContext: sourceRequestContext,
modeId: runModeId
});
}
/**
* Approve a parked tool call: drive the agent to execute it. Throws when there
* is no active run.
*
* `runId`/`threadId`/`resourceId` resolve the call against the run that
* parked it rather than the session's current thread/run/resource. The run
* engine passes its stream state's own binding because the session can switch
* thread (or be re-scoped to another resource) while a run is still in
* flight, and the agent locates the suspended run by `threadId`/`resourceId`
* — resolving with the newly-bound identity would throw or land on the wrong
* thread.
*
* The owning agent is read from the run scope first (the
* {@link SUSPENDED_RUN_AGENT_KEY} invariant the resume path uses), then
* `agent` for callers that hold no run scope, then the session's current
* agent. `abortSignal` pins the run's own signal, because a successor run
* replaces the session's abort controller.
*/
async approveToolCall(input, onDispatch) {
await this.#disarmRunOnFailedStart((armed) => this.#approveToolCall(input, onDispatch, armed));
}
/**
* Arm the session run for an answer to a parked tool call. Records the arm in
* `armed` only when this call armed an idle run, or joined other answers that
* did, so a failed start can disarm it without touching a run another caller
* armed.
*/
#armRun(armed) {
const wasRunning = this.run.isRunning();
const armCountBefore = this.run.armCount();
const signal = this.run.ensureAbortController().signal;
if (!armed) return signal;
const arms = !wasRunning ? {
armCount: 0,
pending: 0,
dispatched: false
} : this.#answerArms?.armCount === armCountBefore ? this.#answerArms : void 0;
if (arms) {
arms.armCount = this.run.armCount();
arms.pending += 1;
this.#answerArms = arms;
armed.arms = arms;
}
return signal;
}
/**
* Run an answer to a parked tool call, resetting the run it armed when the
* answer fails before any run started (mirrors the `sendSignal` startup
* failure reset). Otherwise the session reports running with no run id.
*/
async #disarmRunOnFailedStart(answer) {
const armed = {};
try {
await answer(armed);
if (armed.arms) {
armed.arms.pending -= 1;
armed.arms.dispatched = true;
}
} catch (error) {
const arms = armed.arms;
if (arms) {
arms.pending -= 1;
if (arms.pending === 0 && !arms.dispatched && this.#answerArms === arms && this.run.armCount() === arms.armCount) {
this.#answerArms = void 0;
this.run.reset();
}
}
throw error;
}
}
/**
* Usage recorder for a resumed run. When the run's original stream continues
* across suspensions in this process, that stream's recorder already counts
* the resumed steps; otherwise the resume records them itself.
*/
#resumeUsageRecorder(agent, runId, requestContext) {
if (require_run_registry.agentThreadStreamRuntime.hasRunContinuation(runId, agent.getPubSub())) return void 0;
return this.machinery.buildSharedRunOptions(requestContext).onStepFinish;
}
async #approveToolCall({ toolCallId, requestContext: requestContextInput, runId: inputRunId, threadId: inputThreadId, resourceId = this.identity.getResourceId(), agent: inputAgent, abortSignal: inputAbortSignal }, onDispatch, armed) {
const runId = inputRunId ?? this.run.getRunId();
const threadId = inputThreadId ?? this.thread.getId();
if (!runId) throw new Error("No active run to approve tool call for");
const agent = this.machinery.getRunScope(runId)?.get(SUSPENDED_RUN_AGENT_KEY) ?? inputAgent ?? this.machinery.getAgent();
if (!threadId) throw new Error("Cannot approve a tool call without a current thread");
const threadOwnerId = await this.resolveSuspendedThreadOwnerId(agent, {
runId,
threadId,
resourceId
});
const abortSignal = inputAbortSignal ?? (this.thread.getId() === threadId && this.identity.getResourceId() === resourceId ? this.#armRun(armed) : new AbortController().signal);
const requestContext = await this.machinery.buildRequestContext(requestContextInput, {
threadId,
resourceId,
runId,
threadOwnerId,
abortSignal,
execution: true
});
const runModeId = await this.resolveSuspendedRunModeId(agent, runId, requestContext);
const toolsets = await this.machinery.buildToolsets(requestContext);
const activeTools = this.machinery.resolveModeActiveTools(runModeId, requestContext);
onDispatch?.();
await agent.sendToolApproval({
threadId,
resourceId,
runId,
toolCallId,
approved: true,
memory: {
thread: threadId,
resource: resourceId
},
abortSignal,
requestContext,
toolsets,
streamOptions: {
...this.machinery.buildSharedRunOptions(requestContext),
onStepFinish: this.#resumeUsageRecorder(agent, runId, requestContext),
...activeTools !== void 0 && { activeTools }
}
});
}
/**
* Decline a parked tool call: drive the agent to reject it. Throws when there
* is no active run.
*
* `runId`/`threadId`/`resourceId` follow the same contract as
* {@link approveToolCall}: the run engine resolves declined calls against the
* run that parked them, so a thread switch mid-run cannot redirect the
* decline to another thread.
*/
async declineToolCall(input, onDispatch) {
await this.#disarmRunOnFailedStart((armed) => this.#declineToolCall(input, onDispatch, armed));
}
async #declineToolCall({ toolCallId, requestContext: requestContextInput, declineContext, runId: inputRunId, threadId: inputThreadId, resourceId = this.identity.getResourceId(), agent: inputAgent, abortSignal: inputAbortSignal }, onDispatch, armed) {
const runId = inputRunId ?? this.run.getRunId();
const threadId = inputThreadId ?? this.thread.getId();
if (!runId) throw new Error("No active run to decline tool call for");
const agent = this.machinery.getRunScope(runId)?.get(SUSPENDED_RUN_AGENT_KEY) ?? inputAgent ?? this.machinery.getAgent();
if (!threadId) throw new Error("Cannot decline a tool call without a current thread");
const threadOwnerId = await this.resolveSuspendedThreadOwnerId(agent, {
runId,
threadId,
resourceId
});
const abortSignal = inputAbortSignal ?? (this.thread.getId() === threadId && this.identity.getResourceId() === resourceId ? this.#armRun(armed) : new AbortController().signal);
const requestContext = await this.machinery.buildRequestContext(requestContextInput, {
threadId,
resourceId,
runId,
threadOwnerId,
abortSignal,
execution: true
});
const runModeId = await this.resolveSuspendedRunModeId(agent, runId, requestContext);
const toolsets = await this.machinery.buildToolsets(requestContext);
const activeTools = this.machinery.resolveModeActiveTools(runModeId, requestContext);
onDispatch?.();
await agent.sendToolApproval({
threadId,
resourceId,
runId,
toolCallId,
approved: false,
declineContext,
memory: {
thread: threadId,
resource: resourceId
},
abortSignal,
requestContext,
toolsets,
streamOptions: {
...this.machinery.buildSharedRunOptions(requestContext),
onStepFinish: this.#resumeUsageRecorder(agent, runId, requestContext),
...activeTools !== void 0 && { activeTools }
}
});
}
createSubscribedResumeBoundaryWaiter({ toolCallId, resolveOnToolEnd = false }) {
let unsubscribe;
const lifecycleWait = new AbortController();
const cancel = () => {
unsubscribe?.();
lifecycleWait.abort();
};
const boundary = new Promise((resolve) => {
unsubscribe = this.subscribe((event) => {
const isTerminal = event.type === "tool_suspended" || event.type === "tool_approval_required" || event.type === "agent_end" || event.type === "error";
const completedResumedTool = resolveOnToolEnd && event.type === "tool_end" && event.toolCallId === toolCallId;
if (isTerminal || completedResumedTool) resolve();
});
});
return {
promise: Promise.race([
boundary,
this.stream.waitForTeardown(lifecycleWait.signal),
this.run.waitForTeardown(lifecycleWait.signal)
]).finally(cancel),
cancel
};
}
async observeSourceResume(agent, address, requestContext) {
const markerKey = "mastra.agentController.resumeAttempt";
const attempt = this.machinery.generateId();
const observerContext = new require_request_context.RequestContext(requestContext.entries());
let disposed = false;
let detach = () => {
disposed = true;
};
const removeDeletionListener = this.machinery.onSessionDeleted?.(() => detach());
const pubsub = agent.getPubSub();
const suspension = require_run_registry.agentThreadStreamRuntime.getResumableThreadRunSuspension(address, pubsub);
const subscription = await this.machinery.subscribeToThread({
agent,
...address,
requestContext: observerContext
}).catch((error) => {
removeDeletionListener?.();
throw error;
});
if (suspension && !require_run_registry.agentThreadStreamRuntime.getResumableThreadRun(address, pubsub)) require_run_registry.agentThreadStreamRuntime.__restoreThreadRunSuspension(address, suspension, pubsub);
detach = () => {
disposed = true;
subscription.unsubscribe();
};
if (disposed) {
detach();
removeDeletionListener?.();
throw new Error("Session was deleted during resume setup");
}
requestContext.set(markerKey, attempt);
const context = requestContext.get("controller");
context.abortSignal?.addEventListener("abort", detach, { once: true });
if (context.abortSignal?.aborted) detach();
let dispatched = false;
let cancelled = false;
const promise = (async () => {
try {
for await (const chunk of subscription.stream) {
const marker = subscription.__getCurrentRunRequestContext?.()?.get(markerKey);
const releasedRunChunk = dispatched && marker === void 0 && chunk.runId === address.runId;
if (marker !== attempt && !releasedRunChunk) continue;
if (chunk.runId && chunk.runId !== address.runId) continue;
dispatched = true;
if (chunk.type === "tool-call-approval") {
if (context.isThreadActive?.()) return;
const next = {
...address,
toolCallId: chunk.payload.toolCallId
};
if (this.approval.isArmed(next)) return;
const runScope = this.machinery.getRunScope(address.runId);
const ownedCalls = runScope?.get(SOURCE_APPROVAL_CALLS_KEY) ?? /* @__PURE__ */ new Set();
ownedCalls.add(next.toolCallId);
runScope?.set(SOURCE_APPROVAL_CALLS_KEY, ownedCalls);
const policy = this.resolveToolApproval(chunk.payload.toolName, requestContext);
const decision = policy === "ask" ? this.approval.arm({
...next,
toolName: chunk.payload.toolName
}) : Promise.resolve({ decision: policy === "allow" ? "approve" : "decline" });
let approvalDisposed = false;
let retainApprovalOwnership = false;
const removeApprovalDeletionListener = this.machinery.onSessionDeleted?.(() => {
approvalDisposed = true;
this.approval.cancel(next);
});
if (policy === "ask") context.emitEvent?.({
type: "tool_approval_required",
threadId: address.threadId,
toolCallId: next.toolCallId,
toolName: chunk.payload.toolName,
args: chunk.payload.args
});
(async () => {
let pendingDecision = decision;
while (!approvalDisposed) {
const approval = await pendingDecision;
if (approvalDisposed || approval.decision === "detached") return;
let observer;
let accepted = false;
let dispatchAttempted = false;
const deferredAbortOrigin = approval.decision === "decline" && context.isThreadActive?.() ? this.takeDeferredAbortOrigin() : void 0;
retainApprovalOwnership ||= deferredAbortOrigin !== void 0;
let abortCompleted = false;
try {
const continuation = await this.machinery.buildRequestContext(approval.requestContext ?? requestContext, {
...next,
execution: true,
abortSignal: context.abortSignal
});
if (approvalDisposed) return;
observer = await this.observeSourceResume(agent, next, continuation);
if (approvalDisposed) return;
const binding = {
...next,
agent,
requestContext: continuation,
abortSignal: context.abortSignal
};
const onDispatch = () => {
dispatchAttempted = true;
};
if (approval.decision === "approve") await this.#approveToolCall(binding, onDispatch);
else await this.#declineToolCall({
...binding,
declineContext: approval.declineContext
}, onDispatch);
accepted = true;
if (deferredAbortOrigin) {
this.completeDeferredAbort(deferredAbortOrigin);
abortCompleted = true;
}
await observer.promise;
return;
} catch (error) {
if (approvalDisposed) return;
if (deferredAbortOrigin && !dispatchAttempted) await this.declineToolCall({
...next,
agent,
requestContext,
abortSignal: context.abortSignal,
declineContext: {
reason: ABORTED_BY_USER_REASON,
message: ABORTED_BY_USER_REASON
}
});
retainApprovalOwnership ||= dispatchAttempted;
if (deferredAbortOrigin || context.abortSignal?.aborted || dispatchAttempted || accepted || observer?.dispatched()) throw error;
pendingDecision = this.approval.arm({
...next,
toolName: chunk.payload.toolName
});
context.emitEvent?.({
type: "tool_approval_required",
threadId: next.threadId,
toolCallId: next.toolCallId,
toolName: chunk.payload.toolName,
args: chunk.payload.args
});
} finally {
observer?.cancel();
if (deferredAbortOrigin && !abortCompleted) this.completeDeferredAbort(deferredAbortOrigin);
}
}
})().catch((error) => context.emitEvent?.({
type: "error",
error: require_error.getErrorFromUnknown(error)
})).finally(() => {
if (!retainApprovalOwnership) ownedCalls.delete(next.toolCallId);
if (!ownedCalls.size) runScope?.delete(SOURCE_APPROVAL_CALLS_KEY);
removeApprovalDeletionListener?.();
});
return;
}
if (chunk.type === "tool-call-suspended") {
const next = {
...address,
toolCallId: chunk.payload.toolCallId
};
if (!this.suspensions.has(next)) {
this.suspensions.register({
...next,
toolName: chunk.payload.toolName
});
this.#suspensionAgents.set(this.suspensions.get(next), agent);
context.emitEvent?.({
type: "tool_suspended",
...next,
toolName: chunk.payload.toolName,
args: chunk.payload.args,
suspendPayload: chunk.payload.suspendPayload,
resumeSchema: chunk.payload.resumeSchema
});
}
return;
}
if (chunk.type === "error" || chunk.type === "tripwire" || chunk.type === "abort") {
const error = require_error.getErrorFromUnknown(chunk.type === "error" ? chunk.payload.error : chunk.payload.reason ?? "Source run terminated");
for (const pending of this.suspensions.deleteForRun(address)) context.emitEvent?.({
type: "tool_suspension_cancelled",
...pending,
reason: error.message
});
throw error;
}
if (chunk.type === "finish") return;
}
if (!cancelled) throw new Error("Source resume subscription closed before a matching run boundary");
} finally {
context.abortSignal?.removeEventListener("abort", detach);
subscription.unsubscribe();
removeDeletionListener?.();
}
})();
promise.catch(() => void 0);
return {
promise,
cancel: () => {
cancelled = true;
subscription.unsubscribe();
},
dispatched: () => dispatched
};
}
/**
* Resume a suspended tool call through the active thread subscription.
* Re-supplies the shared run budget so the resumed run doesn't stop mid-task
* on the agent's small default maxSteps.
*
* The continuation keeps the run's approval policy. The resumed call itself
* is not gated again: the loop only gates calls that have not run yet or that
* were parked for approval, so an `ask_user` answer reaches the model as-is
* while later calls in the run still go through approval.
*/
async resumeToolCall(input) {
await this.#disarmRunOnFailedStart((armed) => this.#resumeToolCall(input, armed));
}
async #resumeToolCall({ resumeData, address, requestContext: requestContextInput, resolveOnToolEnd = false, modeId: inputModeId }, armed) {
const suspension = this.suspensions.get(address);
if (!suspension) throw new Error("No active suspension to resume");
const { toolCallId, threadId, resourceId } = address;
const agent = await this.resolveSuspensionAgent(address);
const threadOwnerId = await this.resolveSuspendedThreadOwnerId(agent, address);
const sourceIsActive = () => threadId === this.thread.getId() && resourceId === this.identity.getResourceId();
const abortSignal = sourceIsActive() ? this.#armRun(armed) : new AbortController().signal;
const requestContext = await this.machinery.buildRequestContext(requestContextInput, {
threadId,
resourceId,
runId: address.runId,
threadOwnerId,
abortSignal,
execution: true
});
if (inputModeId) requestContext.setRaw(RUN_MODE_ID_CONTEXT_KEY, inputModeId);
const modeId = inputModeId ?? await this.resolveSuspendedRunModeId(agent, address.runId, requestContext);
const toolsets = await this.machinery.buildToolsets(requestContext);
let resumedSubscriptionBoundary;
let restoreAbortedRun;
if (sourceIsActive()) {
await this.thread.ensureSubscription(threadId, agent, requestContext, resourceId, sourceIsActive);
restoreAbortedRun = this.stream.clearAbortedRun({ runId: suspension.runId });
if (sourceIsActive()) resumedSubscriptionBoundary = this.createSubscribedResumeBoundaryWaiter({
toolCallId,
resolveOnToolEnd
});
}
let observer;
const prompt = [...this.displayState.get().pendingSuspensions.values()].find((entry) => entry.toolCallId === toolCallId && entry.runId === address.runId && entry.threadId === threadId && entry.resourceId === resourceId);
try {
if (!sourceIsActive()) observer = await this.observeSourceResume(agent, address, requestContext);
this.suspensions.delete(address);
this.displayState.deletePendingSuspension(address);
const sharedOptions = this.machinery.buildSharedRunOptions(requestContext);
sharedOptions.onStepFinish = this.#resumeUsageRecorder(agent, suspension.runId, requestContext);
const activeTools = this.machinery.resolveModeActiveTools(modeId, requestContext);
await agent.sendStreamResume({
threadId,
resourceId,
runId: suspension.runId,
toolCallId,
resumeData,
streamOptions: {
...sharedOptions,
memory: {
thread: threadId,
resource: resourceId
},
abortSignal,
requestContext,
toolsets,
...activeTools !== void 0 && { activeTools }
}
});
restoreAbortedRun = void 0;
if (resumedSubscriptionBoundary) await resumedSubscriptionBoundary.promise;
else await observer?.promise;
} catch (error) {
restoreAbortedRun?.();
if (!observer?.dispatched()) {
this.suspensions.register({
...address,
toolName: suspension.toolName
});
this.#suspensionAgents.set(this.suspensions.get(address), agent);
if (prompt && sourceIsActive()) this.displayState.apply({
type: "tool_suspended",
...prompt
});
}
throw error;
} finally {
observer?.cancel();
resumedSubscriptionBoundary?.cancel();
}
}
/**
* Grant a tool category "allow". Scoped to `threadId` when given; a call that
* names no thread grants session-wide (every thread).
*/
grantCategory(category, threadId) {
this.#grantBucket(this.#grantedCategories, threadId).add(category);
}
/**
* Grant an individual tool "allow". Scoped to `threadId` when given; a call
* that names no thread grants session-wide (every thread).
*/
grantTool(toolName, threadId) {
this.#grantBucket(this.#grantedTools, threadId).add(toolName);
}
/**
* Whether the given tool category has been granted session-wide or for
* `threadId` (default: the current thread).
*/
hasCategoryGrant(category, threadId) {
return this.#hasGrant(this.#grantedCategories, category, threadId);
}
/**
* Whether the given tool has been granted session-wide or for `threadId`
* (default: the current thread).
*/
hasToolGrant(toolName, threadId) {
return this.#hasGrant(this.#grantedTools, toolName, threadId);
}
/**
* Snapshot of the grants that apply to `threadId` (default: the current
* thread): session-wide grants plus that thread's own.
*/
getGrants(threadId) {
return {
categories: [...this.#applicableGrants(this.#grantedCategories, threadId)],
tools: [...this.#applicableGrants(this.#grantedTools, threadId)]
};
}
#grantBucket(store, threadId) {
const key = threadId ?? SESSION_WIDE_GRANT_BUCKET;
let bucket = store.get(key);
if (!bucket) {
bucket = /* @__PURE__ */ new Set();
store.set(key, bucket);
}
return bucket;
}
#hasGrant(store, value, threadId) {
if (store.get(SESSION_WIDE_GRANT_BUCKET)?.has(value)) return true;
const thread = threadId ?? this.thread.getId();
return thread ? store.get(thread)?.has(value) ?? false : false;
}
#applicableGrants(store, threadId) {
const merged = new Set(store.get(SESSION_WIDE_GRANT_BUCKET) ?? []);
const thread = threadId ?? this.thread.getId();
if (thread) for (const value of store.get(thread) ?? []) merged.add(value);
return merged;
}
/** A copy of the running token-usage tally for the active thread. */
getTokenUsage() {
return { ...this.#tokenUsage };
}
/**
* Replace the running tally, e.g. when hydrating from persisted thread
* metadata on thread switch.
*/
setTokenUsage(usage) {
this.#tokenUsage = { ...usage };
}
/** Reset the running tally to zero, e.g. on a new/empty thread. */
resetTokenUsage() {
this.#tokenUsage = createEmptyTokenUsage();
}
/** Fold a single step's usage into the running tally. */
addUsage(stepUsage) {
this.#tokenUsage.promptTokens += stepUsage.promptTokens;
this.#tokenUsage.completionTokens += stepUsage.completionTokens;
this.#tokenUsage.totalTokens += stepUsage.totalTokens;
addOptionalUsageField(this.#tokenUsage, "reasoningTokens", stepUsage.reasoningTokens);
addOptionalUsageField(this.#tokenUsage, "cachedInputTokens", stepUsage.cachedInputTokens);
addOptionalUsageField(this.#tokenUsage, "cacheCreationInputTokens", stepUsage.cacheCreationInputTokens);
addOptionalUsageField(this.#tokenUsage, "cacheCreationInputTokens5m", stepUsage.cacheCreationInputTokens5m);
addOptionalUsageField(this.#tokenUsage, "cacheCreationInputTokens1h", stepUsage.cacheCreationInputTokens1h);
if (stepUsage.raw !== void 0) this.#tokenUsage.raw = stepUsage.raw;
}
};
// src/agent-controller/tools.ts
const FORKED_SUBAGENT_NESTING_NOTICE = "Do not call the `subagent` tool. You are currently running inside a forked subagent, and this is the maximum allowed subagent nesting level. Further subagent calls will return an error. Answer the task directly using the conversation history and the other tools available to you.";
const FORKED_SUBAGENT_TASK_NOTICE = "Do not call `task_write`, `task_update`, `task_complete`, or `task_check` inside a forked subagent. Forked subagents keep the parent task-tool schemas for prompt-cache stability, but the parent agent owns the visible task list. Track forked subagent work in your final answer instead.";
/**
* Creates a `subagent` tool from registered subagent definitions.
* The tool spawns a fresh Agent per invocation with constrained tools,
* streams the response, and forwards events to the controller.
*/
function createSubagentTool(opts) {
const { subagents, resolveModel, controllerTools, fallbackModelId, mastra } = opts;
if (subagents.length === 0) throw new Error("createSubagentTool requires at least one subagent");
const subagentIds = subagents.map((s) => s.id);
const typeDescriptions = subagents.map((s) => `- **${s.id}** (${s.name}): ${s.description}`).join("\n");
return require_tool.createTool({
id: "subagent",
description: `Delegate a focused task to a specialized subagent. The subagent runs independently with a constrained toolset, then returns its findings as text.
Available agent types:
${typeDescriptions}
By default the subagent runs in its own context — it does NOT see the parent conversation history. Write a clear, self-contained task description.
Set \`forked: true\` for context-dependent parallel work that needs the parent conversation, prior tool results, or the parent tool environment. Omit it for self-contained delegation. A forked subagent reuses the parent agent's instructions and tools so the prompt prefix stays cache-friendly.
Use this tool when:
- You want to run multiple investigations in parallel
- The task is self-contained and can be delegated`,
inputSchema: zod_v4.z.object({
agentType: zod_v4.z.enum(subagentIds).describe("Type of subagent to spawn"),
task: zod_v4.z.string().describe("Clear, self-contained description of what the subagent should do. For non-forked subagents include all relevant context — the subagent cannot see the parent conversation."),
modelId: zod_v4.z.string().optional().describe("Optional model ID override for this task. Ignored when `forked: true` (the parent agent's model is used)."),
forked: zod_v4.z.boolean().optional().describe("If true, fork the parent conversation: clone the parent thread and run with the parent agent's instructions/tools so prompt cache is preserved. Requires memory to be configured on the AgentController. Defaults to the subagent definition's `forked` setting.")
}),
execute: async (input, context) => {
const { agentType, modelId, forked } = input;
let { task } = input;
const displayTask = task;
const definition = subagents.find((s) => s.id === agentType);
if (!definition) return {
content: `Unknown agent type: ${agentType}. Valid types: ${subagentIds.join(", ")}`,
isError: true
};
const controllerCtx = context?.requestContext?.get("controller");
const emitEvent = controllerCtx?.emitEvent;
const abortSignal = controllerCtx?.abortSignal;
const toolCallId = context?.agent?.toolCallId ?? "unknown";
const workspace = context?.workspace;
const runAsForked = forked ?? definition.forked ?? false;
let subagentToRun;
let resolvedModelId;
let subagentRequestContext;
let streamMemory;
let streamMaxSteps;
let streamStopWhen;
let streamPrepareStep;
let forkedToolsets;
if (runAsForked) {
const parentAgent = opts.getParentAgent?.();
if (!parentAgent) return {
content: "Forked subagent requires a parent agent. None is configured on this AgentController.",
isError: true
};
const parentThreadId = controllerCtx?.threadId;
if (!parentThreadId) return {
content: "Forked subagent requires an active parent thread; none is set on the AgentController.",
isError: true
};
if (!opts.cloneThreadForFork) return {
content: "Forked subagent requires memory to be configured on the AgentController so the parent thread can be cloned.",
isError: true
};
await context?.agent?.flushMessages?.().catch(() => {});
let forkedThread;
try {
forkedThread = await opts.cloneThreadForFork({
sourceThreadId: parentThreadId,
resourceId: controllerCtx?.resourceId,
title: `Fork: ${definition.name} subagent`,
requestContext: context?.requestContext
});
} catch (err) {
return {
content: `Failed to clone parent thread for forked subagent: ${err instanceof Error ? err.message : String(err)}`,
isError: true
};
}
subagentToRun = parentAgent;
resolvedModelId = opts.getParentModelId?.() || "parent-agent";
task = `${task}\n\n${FORKED_SUBAGENT_NESTING_NOTICE}\n\n${FORKED_SUBAGENT_TASK_NOTICE}`;
streamMemory = {
thread: forkedThread.id,
resource: forkedThread.resourceId
};
streamMaxSteps = 1e3;
streamStopWhen = void 0;
streamPrepareStep = void 0;
if (context?.requestContext) {
subagentRequestContext = new require_request_context.RequestContext(context.requestContext.entries());
if (controllerCtx) subagentRequestContext.set("controller", {
...controllerCtx,
threadId: forkedThread.id,
resourceId: forkedThread.resourceId
});
subagentRequestContext.set(require_request_context.MASTRA_THREAD_ID_KEY, forkedThread.id);
subagentRequestContext.set(require_request_context.MASTRA_RESOURCE_ID_KEY, forkedThread.resourceId);
subagentRequestContext.delete(require_run_registry.CHAT_CHANNEL_RENDER_CONTEXT_KEY);
}
const inheritedToolsets = await opts.getParentToolsets?.(subagentRequestContext);
if (inheritedToolsets) {
forkedToolsets = {};
for (const [setName, setTools] of Object.entries(inheritedToolsets)) {
const patched = {};
for (const [toolId, tool] of Object.entries(setTools)) if (toolId === "subagent") patched[toolId] = patchSubagentToolForFork(tool);
else if (isForkedTaskToolId(toolId)) patched[toolId] = patchTaskToolForFork(tool, toolId);
else patched[toolId] = tool;
forkedToolsets[setName] = patched;
}
}
} else {
const mergedTools = { ...definition.tools };
if (definition.allowedControllerTools && controllerTools) {
for (const toolId of definition.allowedControllerTools) if (controllerTools[toolId] && !mergedTools[toolId]) mergedTools[toolId] = controllerTools[toolId];
}
const controllerModelId = controllerCtx?.getSubagentModelId?.({ agentType }) ?? void 0;
const maybeModelId = modelId ?? controllerModelId ?? definition.defaultModelId ?? fallbackModelId;
if (!maybeModelId) return {
content: "No model ID available for subagent. Configure defaultModelId.",
isError: true
};
resolvedModelId = maybeModelId;
if (context?.requestContext) {
subagentRequestContext = new require_request_context.RequestContext(context.requestContext.entries());
if (controllerCtx) subagentRequestContext.set("controller", {
...controllerCtx,
threadId: null,
resourceId: ""
});
subagentRequestContext.delete(require_request_context.MASTRA_THREAD_ID_KEY);
subagentRequestContext.delete(require_request_context.MASTRA_RESOURCE_ID_KEY);
}
let model;
try {
model = resolveModel(resolvedModelId, { requestContext: subagentRequestContext });
} catch (err) {
return {
content: `Failed to resolve model "${resolvedModelId}": ${err instanceof Error ? err.message : String(err)}`,
isError: true
};
}
subagentToRun = new require_run_registry.Agent({
id: `subagent-${definition.id}`,
name: `${definition.name} Subagent`,
instructions: definition.instructions,
model,
tools: mergedTools,
workspace,
mastra
});
const allowedWs = definition.allowedWorkspaceTools ? new Set(definition.allowedWorkspaceTools) : void 0;
const allWorkspaceToolNames = workspace && allowedWs ? new Set(Object.keys(await require_workspace.createWorkspaceTools(workspace, {
requestContext: context?.requestContext ?? {},
workspace
}))) : void 0;
streamMaxSteps = definition.maxSteps ?? (definition.stopWhen ? void 0 : 50);
streamStopWhen = definition.stopWhen;
streamPrepareStep = allowedWs && allWorkspaceToolNames ? ({ tools }) => ({ activeTools: Object.keys(tools ?? {}).filter((k) => !allWorkspaceToolNames.has(k) || allowedWs.has(k)) }) : void 0;
}
const startTime = Date.now();
emitEvent?.({
type: "subagent_start",
toolCallId,
agentType,
task: displayTask,
modelId: resolvedModelId,
forked: runAsForked
});
let partialText = "";
try {
const response = await subagentToRun.stream(task, {
maxSteps: streamMaxSteps,
stopWhen: streamStopWhen,
abortSignal,
requireToolApproval: false,
requestContext: subagentRequestContext,
...streamMemory && { memory: streamMemory },
...forkedToolsets && { toolsets: forkedToolsets },
...context?.tracingContext && { tracingContext: context.tracingContext },
prepareStep: streamPrepareStep
});
for await (const chunk of response.fullStream) switch (chunk.type) {
case "text-delta":
partialText += chunk.payload.text;
emitEvent?.({
type: "subagent_text_delta",
toolCallId,
agentType,
textDelta: chunk.payload.text
});
break;
case "tool-call":
if (!(runAsForked && chunk.payload.toolName === "subagent")) emitEvent?.({
type: "subagent_tool_start",
toolCallId,
agentType,
subToolName: chunk.payload.toolName,
subToolArgs: chunk.payload.args
});
break;
case "tool-result":
case "tool-error": {
const isErr = chunk.type === "tool-error" || isToolResultError(chunk.payload);
if (!(runAsForked && chunk.payload.toolName === "subagent")) emitEvent?.({
type: "subagent_tool_end",
toolCallId,
agentType,
subToolName: chunk.payload.toolName,
subToolResult: chunk.type === "tool-error" ? require_error.getErrorFromUnknown(chunk.payload.error).message : chunk.payload.result,
isError: isErr
});
break;
}
}
if (abortSignal?.aborted) {
const durationMs = Date.now() - startTime;
const abortResult = partialText ? `[Aborted by user]\n\nPartial output:\n${partialText}` : "[Aborted by user]";
emitEvent?.({
type: "subagent_end",
toolCallId,
agentType,
result: abortResult,
isError: false,
durationMs
});
return {
content: abortResult,
isError: false
};
}
const resultText = (await response.getFullOutput()).text || partialText;
const durationMs = Date.now() - startTime;
emitEvent?.({
type: "subagent_end",
toolCallId,
agentType,
result: resultText,
isError: false,
durationMs
});
return {
content: resultText,
isError: false
};
} catch (err) {
const isAbort = err instanceof Error && (err.name === "AbortError" || err.message?.includes("abort") || err.message?.includes("cancel"));
const durationMs = Date.now() - startTime;
if (isAbort) {
const abortResult = partialText ? `[Aborted by user]\n\nPartial output:\n${partialText}` : "[Aborted by user]";
emitEvent?.({
type: "subagent_end",
toolCallId,
agentType,
result: abortResult,
isError: false,
durationMs
});
return {
content: abortResult,
isError: false
};
}
const message = err instanceof Error ? err.message : String(err);
emitEvent?.({
type: "subagent_end",
toolCallId,
agentType,
result: message,
isError: true,
durationMs
});
return {
content: `Subagent "${definition.name}" failed: ${message}`,
isError: true
};
}
}
});
}
/**
* Returns a copy of the parent's `subagent` tool with `execute` replaced by a
* stub that refuses to dispatch a nested fork.
*
* Why patch instead of remove or replace wholesale:
* - Forked subagents reuse the parent Agent's `stream()` so the LLM request
* prefix (system prompt + tool list + tool schemas + tool descriptions)
* matches the parent byte-for-byte. This is what makes prompt-cache hits
* possible inside a fork, which is the whole reason forked mode exists.
* - Removing the `subagent` entry from the inherited toolset, or replacing
* its description / parameters with anything else, perturbs that prefix
* and invalidates the cache.
* - Replacing only `execute` is invisible to the LLM (execute lives in the
* runtime, not in the request payload) but lets us reject recursive
* invocations cleanly at runtime.
*
* The stub returns a tool-level error result with a clear human-readable
* recovery instruction. This does not fail the outer subagent run; the model
* receives the tool error and can continue with a direct answer.
*/
function patchSubagentToolForFork(tool) {
const stubExecute = async () => ({
content: FORKED_SUBAGENT_NESTING_NOTICE,
isError: true
});
return Object.assign({}, tool, { execute: stubExecute });
}
function isForkedTaskToolId(toolId) {
return toolId === "task_write" || toolId === "task_update" || toolId === "task_complete" || toolId === "task_check";
}
function patchTaskToolForFork(tool, toolId) {
const stubExecute = async () => {
const baseResult = {
content: FORKED_SUBAGENT_TASK_NOTICE,
tasks: [],
isError: true
};
if (toolId === "task_check") {
const taskCheck = require_state_processor.summarizeTaskCheck([]);
return {
...baseResult,
summary: taskCheck.summary,
incompleteTasks: taskCheck.incompleteTasks
};
}
return baseResult;
};
return Object.assign({}, tool, { execute: stubExecute });
}
/**
* Parse subagent metadata from a tool result string.
*
* Older persisted threads may have an internal `<subagent-meta />` tag
* appended to the subagent tool result content (carrying modelId / durationMs
* / sub-tool-call summary, used by history-render UIs to reconstruct the
* subagent activity box when live events aren't available).
*
* New runs no longer append the tag — the metadata leaked into model context
* and could be echoed back as visible assistant text — but this parser is
* retained so existing threads continue to render cleanly. It also strips the
* tag so callers never display it to users.
*
* Returns the cleaned text plus any parsed metadata.
*/
function parseSubagentMeta(content) {
const match = content.match(/\n<subagent-meta modelId="([^"]*)" durationMs="(\d+)" tools="([^"]*)" \/>$/);
if (!match) return { text: content };
return {
text: content.slice(0, match.index),
modelId: match[1],
durationMs: parseInt(match[2], 10),
toolCalls: match[3] ? match[3].split(",").filter(Boolean).map((entry) => {
const [name, status] = entry.split(":");
return {
name,
isError: status === "err"
};
}) : []
};
}
// src/agent-controller/agent-controller.ts
function validateModes(modes) {
const modeIds = /* @__PURE__ */ new Set();
for (const mode of modes) {
if (modeIds.has(mode.id)) throw new Error(`Duplicate mode id "${mode.id}" found when creating the AgentController`);
modeIds.add(mode.id);
const modeRecord = mode;
if (modeRecord.tools && modeRecord.additionalTools) throw new Error(`Mode "${modeRecord.id}" cannot set both "tools" and "additionalTools" - choose replace OR augment`);
}
for (const mode of modes) {
if (mode.transitionsTo === mode.id) throw new Error(`Mode "${mode.id}" transitionsTo cannot reference itself`);
if (mode.transitionsTo && !modeIds.has(mode.transitionsTo)) throw new Error(`Mode "${mode.id}" transitionsTo references unknown mode "${mode.transitionsTo}"`);
}
}
/**
* Build a user-facing message for a non-success stream finish reason.
*
* Anthropic's classifier blocks / model refusals (e.g. `claude-fable-5`) surface
* through the AI SDK as a `content-filter` finish reason, with details on
* `providerMetadata.anthropic.stopDetails`. Without explicit handling these
* runs end on an empty assistant message with no error, so the run appears to
* silently stop. Returning a message here lets the controller finalize the run
* into an explicit terminal error state.
*/
/**
* The Anthropic model that `claude-fable-5` runs are automatically retried on
* server-side when fable-5's safety classifiers block a turn. See
* {@link buildFableFallbackProviderOptions}.
*/
const FABLE_FALLBACK_MODEL = "claude-opus-4-8";
/**
* Step budget applied to every controller-driven agent run.
*
* This MUST be passed to both the initial stream and `resumeStream`: when a run
* suspends on an interactive tool (e.g. `ask_user`) and then resumes, the
* resumed call merges over the agent's *default* options, whose `maxSteps` is
* small (~5). Without re-supplying this budget the resumed run is silently
* capped and ends with `reason:"complete"` after a few steps — the agent stops
* mid-task even though it promised to continue. See {@link buildSharedRunOptions}.
*/
const CONTROLLER_MAX_STEPS = 1e3;
/**
* Returns Anthropic `providerOptions` that enable a server-side fallback to
* {@link FABLE_FALLBACK_MODEL} when the active model is `claude-fable-5`, and
* `undefined` otherwise.
*
* fable-5 can have a turn blocked server-side by its safety classifiers. With
* a fallback configured, Anthropic transparently retries the blocked turn on
* the fallback model and returns that model's answer instead of refusing. If
* the whole chain refuses, the run still ends on a `content-filter` finish
* reason, which is handled as a terminal error.
*
* The match is suffix-based so it covers `anthropic/claude-fable-5`, a bare
* `claude-fable-5`, and any pack/provider-prefixed form.
*/
function buildFableFallbackProviderOptions(modelId) {
if (!/(^|\/)claude-fable-5$/.test(modelId)) return;
return { anthropic: { fallbacks: [{ model: FABLE_FALLBACK_MODEL }] } };
}
/**
* Build a user-facing notice when a turn was served by an Anthropic
* server-side fallback model instead of the primary model.
*
* When the primary model's safety classifiers decline a turn and a fallback
* chain is configured (see {@link buildFableFallbackProviderOptions}), the API
* transparently retries on the fallback model and reports this via
* `fallback_message` entries in `providerMetadata.anthropic.iterations`.
* Without a notice the user has no way to tell that the response did not come
* from the model they selected.
*/
/** How much of the tail a rename reads: enough to say where the thread went, bounded so a long thread costs no more than a short one. */
const TITLE_WINDOW_MESSAGES = 20;
const THREAD_PAGE_FLOOR = 50;
/**
* The AgentController orchestrates multiple agent modes, shared state, memory, and storage.
* It's the core abstraction that a TUI (or other UI) controls.
*
* @example
* ```ts
* const controller = new AgentController({
* id: "my-coding-agent",
* storage: new LibSQLStore({ url: "file:./data.db" }),
* stateSchema: z.object({
* currentModelId: z.string().optional(),
* }),
* modes: [
* { id: "plan", name: "Plan", default: true, agent: planAgent },
* { id: "build", name: "Build", agent: buildAgent },
* ],
* })
*
* controller.subscribe((event) => {
* if (event.type === "message_update") appendText(event.id, event.event.delta)
* })
*
* await controller.init()
* await controller.sendMessage({ content: "Hello!" })
* ```
*/
var AgentController = class {
id;
config;
initPromise = void 0;
#metadataWriteQueues = /* @__PURE__ */ new Map();
#pendingTokenUsage = /* @__PURE__ */ new Map();
browser = void 0;
workspace = void 0;
intervalTimers = /* @__PURE__ */ new Map();
/**
* The mode every new session starts in. Resolved once at construction from
* `config.defaultModeId` (or the configured default/first mode) and reused by
* every {@link createSession} call. The AgentController itself holds no session.
*/
#defaultMode;
/**
* Live sessions created by {@link createSession}, keyed by session id. A
* session id maps to exactly one session per AgentController (get-or-create),
* and any number of sessions may share one resourceId. Stores the in-flight
* creation promise so concurrent calls share one session. Lets
* AgentController-external callers (e.g. notification delivery) resolve a
* session with {@link getSession} so a woken run uses that session's
* model/mode/state instead of an arbitrary one.
*/
#sessionsById = /* @__PURE__ */ new Map();
#sessionCreatedListeners = [];
#sessionDeletedListeners = [];
/**
* In-progress deletions keyed by session id, so {@link createSession} can
* wait for a concurrent deletion to finish before returning a (torn-down)
* session. Set synchronously before any await so the flag is visible to
* concurrent callers.
*/
#deletionsInProgress = /* @__PURE__ */ new Map();
/**
* Sessions currently being torn down, so {@link setResourceId} can skip a
* dying session and {@link createSession} can avoid returning one.
* Populated inside the deletion IIFE after `await pending` resolves the
* session.
*/
#sessionsBeingDeleted = /* @__PURE__ */ new WeakSet();
/**
* Per-session deletion promise (rejection-tolerant), keyed by the Session
* object so {@link createSession} and {@link setResourceId} can wait on a
* deletion they discovered via {@link #sessionsBeingDeleted}.
*/
#sessionDeletionPromises = /* @__PURE__ */ new WeakMap();
#executionViewKey = require_stream.createRunScopeKey("agent-controller.executionView");
#executionViews = /* @__PURE__ */ new WeakMap();
#instructions;
#internalMastra = void 0;
/** The application's event bus the backing agents share when the controller has none of its own. */
#applicationPubSub = void 0;
/**
* Set when this AgentController is registered on a parent Mastra (via
* {@link __registerMastra}). When present it is used in place of the
* lazily-created internal Mastra, so a server-hosted AgentController shares the
* server's storage/agents/gateways instead of spinning up its own.
*/
#externalMastra = void 0;
#gatewayManager = void 0;
#modelCatalog;
/** Last {@link listAvailableModels} result, reused while its inputs are unchanged. */
#availableModels;
#legacyAgentMode = {};
/** Chat channels running this controller inside messaging threads (from `config.channels`). */
#channels = null;
constructor(config) {
validateModes(config.modes);
this.id = config.id;
this.config = config;
this.#instructions = config.instructions;
if (config.channels) {
this.#channels = new require_channels.AgentControllerChannels(config.channels);
this.#channels.__setController(this);
}
this.#gatewayManager = new require_llm.GatewayManager([...config.gateways ?? [], ...require_llm.defaultGateways]);
const remoteGateways = new Set(require_llm.defaultGateways);
this.#modelCatalog = new ModelCatalogCache(this.#gatewayManager, (gateway) => remoteGateways.has(gateway));
const defaultMode = config.defaultModeId ? config.modes.find((mode) => mode.id === config.defaultModeId) : config.modes.find((mode) => mode.default || mode.metadata?.default === true) ?? config.modes[0];
if (!defaultMode) throw new Error(config.defaultModeId ? `Default mode not found: ${config.defaultModeId}` : "AgentController requires at least one agent mode");
this.#defaultMode = defaultMode;
this.workspace = config.workspace;
this.browser = config.browser;
}
/**
* Subscribe to process-local notifications for newly materialized sessions.
* Cached `createSession()` calls do not notify listeners again.
*
* Async listeners are fire-and-forget by default. Pass `blocking: true` to
* make `createSession()` await the listener before resolving — for setup that
* must land before the caller can start a run (e.g. seeding session state
* from storage). Blocking listeners run sequentially in registration order,
* before fire-and-forget listeners are notified. Failures are isolated and
* logged, never thrown — session creation stays best-effort with respect to
* listener setup. A blocking listener must not call `createSession()` for
* the same session id it is initializing: that lookup awaits the
* in-flight creation that is awaiting the listener, which deadlocks.
*/
onSessionCreated(listener, options) {
const entry = {
listener,
blocking: options?.blocking === true
};
this.#sessionCreatedListeners.push(entry);
return () => {
const index = this.#sessionCreatedListeners.indexOf(entry);
if (index !== -1) this.#sessionCreatedListeners.splice(index, 1);
};
}
async #notifySessionCreated(session) {
const entries = [...this.#sessionCreatedListeners];
for (const { listener, blocking } of entries) {
if (!blocking) continue;
try {
await listener(session);
} catch (error) {
console.error("Error in session-created listener:", error);
}
}
for (const { listener, blocking } of entries) {
if (blocking) continue;
try {
const result = listener(session);
if (result && typeof result === "object" && "catch" in result) result.catch((error) => console.error("Error in session-created listener:", error));
} catch (error) {
console.error("Error in session-created listener:", error);
}
}
}
/**
* Subscribe to process-local notifications after live sessions are torn
* down. Fires even when teardown cleanup fails — the session is
* deregistered either way.
*/
onSessionDeleted(listener) {
this.#sessionDeletedListeners.push(listener);
return () => {
const index = this.#sessionDeletedListeners.indexOf(listener);
if (index !== -1) this.#sessionDeletedListeners.splice(index, 1);
};
}
#notifySessionDeleted(session) {
for (const listener of [...this.#sessionDeletedListeners]) try {
const result = listener(session);
if (result && typeof result === "object" && "catch" in result) result.catch((error) => console.error("Error in session-deleted listener:", error));
} catch (error) {
console.error("Error in session-deleted listener:", error);
}
}
/**
* Wire a freshly-constructed {@link Session} to this AgentController: install the
* thread-settings store, resolvers (mode/model/om/permissions/subagents),
* thread data store, and seed the initial mode + model. Returns the same
* session for convenient assignment.
*
* The session owns its own event bus, so the AgentController no longer injects an
* `emit` callback — `#wireSession` only injects genuinely AgentController-owned
* dependencies (config catalog, resolvers, tracker, thread store). Extracted
* from the constructor so additional sessions can be wired the same way.
*/
#wireSession(session) {
const defaultMode = this.#defaultMode;
session.mode.setDefault({ modeId: defaultMode.id });
session.mode.set({ modeId: defaultMode.id });
session.setStore({
getAllOn: async (threadId) => (await session.thread.getById({ threadId }))?.metadata ?? {},
get: (key) => session.thread.getSetting({ key }),
getThreadId: () => session.thread.getId() ?? void 0,
set: (key, value) => session.thread.setSetting({
key,
value
}),
setOn: (threadId, key, value) => session.thread.setSettingOn({
threadId,
key,
value
}),
setModelOn: (threadId, settings) => this.writeThreadMetadataValues(threadId, settings)
});
session.setCategoryResolver((toolName) => this.getToolCategory({ toolName }));
session.setSubagentNameResolver((agentType) => this.getSubagentDisplayName(agentType));
session.mode.setResolver((modeId) => this.config.modes.find((m) => m.id === modeId) ?? null);
session.model.setResolver({
getCurrentModeId: () => session.mode.get(),
getModeIds: () => this.config.modes.map((mode) => mode.id),
trackModelUse: this.config.modelUseCountTracker
});
session.om.setResolver({
getState: () => session.state.get(),
getCurrentModelId: () => session.model.get() || void 0,
setState: (updates, event) => session.state.update(() => ({
updates,
events: event ? [event] : [],
result: void 0
})),
omConfig: this.config.omConfig,
gateways: this.config.gateways ?? []
});
session.permissions.setResolver({
getState: () => session.state.get(),
setState: (updates) => session.state.set(updates),
onChange: () => session.applyToolPolicyToParkedApprovals()
});
session.subagents.setResolver({
getState: () => session.state.get(),
setState: (updates, event) => session.state.update(() => ({
updates,
events: [event],
result: void 0
}))
});
session.thread.connect(this.createThreadDataStore(session), session);
session.setMachinery({
getAgent: () => this.getCurrentAgent(session),
getAgents: () => this.backingAgents(),
getRunScope: (runId) => this.getMastra()?.__getRunScope(runId),
releaseSuspendedRun: async (runId) => {
const mastra = this.getMastra();
if (!mastra) return;
mastra.__unregisterInternalWorkflow(require_run_registry.AGENTIC_LOOP_WORKFLOW_ID, runId);
const workflowsStore = await mastra.getStorage()?.getStore("workflows");
await Promise.all([
require_run_registry.AGENTIC_LOOP_WORKFLOW_ID,
require_run_registry.AGENTIC_EXECUTION_WORKFLOW_ID,
require_run_registry.DurableStepIds.AGENTIC_LOOP,
require_run_registry.DurableStepIds.AGENTIC_EXECUTION
].map((workflowName) => workflowsStore?.deleteWorkflowRunById({
runId,
workflowName
})));
},
subscribeToThread: async ({ agent, resourceId, threadId, requestContext }) => (agent ?? this.getCurrentAgent(session)).subscribeToThread({
resourceId,
threadId,
withInitialHistory: true,
requestContext: await this.buildRequestContext(session, requestContext)
}),
buildStreamOptions: (input) => this.buildAgentMessageStreamOptions({
session,
...input
}),
buildSharedRunOptions: (requestContext) => this.buildSharedRunOptions(session, requestContext),
resolveModeActiveTools: (modeId, requestContext) => this.resolveModeActiveTools(session, modeId, requestContext),
onSessionDeleted: (listener) => this.onSessionDeleted((deleted) => {
if (deleted === session) listener();
}),
buildToolsets: (requestContext) => this.buildToolsets(session, requestContext),
buildRequestContext: (requestContext, scope) => this.buildRequestContext(session, requestContext, scope),
authorizeExecute: (requestContext) => this.requireAgentControllerFGA({
permission: require_ee_iTj2bRDt.MastraFGAPermissions.AGENT_CONTROLLER_EXECUTE,
requestContext,
resourceId: session.identity.getResourceId(),
sessionId: session.identity.getId()
}),
generateId: () => this.generateId(),
resolveTransitionModeId: (modeId) => this.resolveTransitionModeId(session, modeId),
saveSystemReminder: (input) => this.saveSystemReminder(input)
});
const defaultModelId = this.config.initialState?.currentModelId || defaultMode.defaultModelId || "";
session.model.setDefault({ modelId: defaultModelId });
if (defaultModelId) session.model.set({ modelId: defaultModelId });
return session;
}
/**
* Create a new, fully-wired {@link Session} and bring it online: it starts in
* the default mode with the seeded model, is connected to the AgentController's shared
* machinery (agent, storage/lock, config catalog), and normally has a current
* thread (the most recent matching thread, or a freshly created one). When
* `createInitialThread` is false and no thread matches, the returned session
* has no current thread; the first operation that needs one (sending a
* message, {@link SessionThread.ensureId}) creates it.
*
* The AgentController owns no session of its own — every consumer creates its own
* session and drives all work through it (`session.sendMessage`,
* `session.mode.switch`, `session.thread.*`, `session.subscribe`, ...). In a
* server / multiplayer setting, each request / thread / user gets its own
* session, isolated from every other: independent event bus, mode, model,
* state, and current thread.
*
* Call {@link init} once before creating sessions so shared storage and
* workspace are ready.
*
* @param id - Stable session identifier (mirrors `SessionRecord.id`). Sessions are looked up by this id
* ({@link getSession}); several sessions may share one resourceId. Defaults to the resolved `resourceId`.
* @param ownerId - Stable session owner (mirrors `SessionRecord.ownerId`). Defaults to the controller `id`.
* @param resourceId - Memory resource to bind this session to. Defaults to the controller `resourceId` or `id`.
* @param createInitialThread - Create a thread when no existing thread matches. Defaults to true.
* @param resumeOnly - Only return a live session or recover one from a stored thread; never start a new conversation.
*/
async createSession({ resourceId, ownerId, id, tags, threadId, createInitialThread = true, resumeOnly = false, workspace, browser, requestContext } = {}) {
const effectiveResourceId = resourceId ?? this.config.resourceId ?? this.config.id;
const effectiveSessionId = id ?? effectiveResourceId;
const effectiveOwnerId = ownerId ?? this.config.id;
const registryKey = effectiveSessionId;
await this.requireAgentControllerFGA({
permission: require_ee_iTj2bRDt.MastraFGAPermissions.AGENT_CONTROLLER_EXECUTE,
requestContext,
resourceId: effectiveResourceId,
sessionId: effectiveSessionId
});
for (;;) {
let pendingDeletion = this.#deletionsInProgress.get(registryKey);
if (pendingDeletion) await pendingDeletion;
const existing = this.#sessionsById.get(registryKey);
if (existing) {
const session = await existing;
pendingDeletion = this.#deletionsInProgress.get(registryKey);
if (pendingDeletion) {
await pendingDeletion;
continue;
}
if (this.#sessionsBeingDeleted.has(session)) {
const sessionDeletion = this.#sessionDeletionPromises.get(session);
if (sessionDeletion) await sessionDeletion;
this.#sessionsById.delete(registryKey);
continue;
}
if (resourceId !== void 0 && session.identity.getResourceId() !== resourceId) throw new Error(`Session ${registryKey} belongs to another resource`);
if (resourceId === void 0 && session.identity.getResourceId() !== effectiveResourceId) await this.requireAgentControllerFGA({
permission: require_ee_iTj2bRDt.MastraFGAPermissions.AGENT_CONTROLLER_EXECUTE,
requestContext,
resourceId: session.identity.getResourceId(),
sessionId: effectiveSessionId
});
if (threadId && session.thread.getId() !== threadId) {
const existingThread = await session.thread.getById({ threadId });
if (existingThread) {
if (existingThread.resourceId !== session.identity.getResourceId()) throw new Error(`Thread not found: ${threadId}`);
await session.thread.switch({
threadId,
requestContext
});
} else await session.thread.create({
id: threadId,
requestContext
});
} else if (createInitialThread && !resumeOnly && session.thread.getId() === null) await session.thread.create({ requestContext });
pendingDeletion = this.#deletionsInProgress.get(registryKey);
if (pendingDeletion) {
await pendingDeletion;
continue;
}
if (this.#sessionsBeingDeleted.has(session)) {
const sessionDeletion = this.#sessionDeletionPromises.get(session);
if (sessionDeletion) await sessionDeletion;
this.#sessionsById.delete(registryKey);
continue;
}
return session;
}
const creation = this.#createSessionForResource(effectiveOwnerId, effectiveSessionId, effectiveResourceId, tags, {
threadId,
createInitialThread: resumeOnly ? false : createInitialThread,
resumeOnly,
workspace,
browser,
requestContext
});
this.#sessionsById.set(registryKey, creation);
try {
const session = await creation;
pendingDeletion = this.#deletionsInProgress.get(registryKey);
if (pendingDeletion) {
await pendingDeletion;
continue;
}
return session;
} catch (error) {
if (this.#sessionsById.get(registryKey) === creation) this.#sessionsById.delete(registryKey);
throw error;
}
}
}
async #createSessionForResource(ownerId, id, effectiveResourceId, tags, overrides) {
const requestContext = overrides?.requestContext ?? new require_request_context.RequestContext();
let initialState = structuredClone(this.config.initialState);
if (tags && Object.keys(tags).length > 0) initialState = {
...initialState,
...tags
};
if (overrides?.resumeOnly) await this.#requireRecoverableThread(effectiveResourceId, tags, initialState, overrides.threadId);
const defaultMode = this.#defaultMode;
requestContext.set("controller", {
controllerId: this.id,
harnessId: this.id,
state: initialState,
getState: () => initialState,
setState: (updates) => {
initialState = {
...initialState,
...updates
};
},
updateState: (updater) => {
return Promise.resolve(updater(initialState)).then((result) => {
if (result.updates) initialState = {
...initialState,
...result.updates
};
return result.result;
});
},
threadId: null,
resourceId: effectiveResourceId,
sessionId: id,
session: {
id,
ownerId,
resourceId: effectiveResourceId,
modeId: defaultMode.id,
modelId: defaultMode.defaultModelId ?? "",
state: {
get: () => initialState,
set: (updates) => {
initialState = {
...initialState,
...updates
};
return Promise.resolve();
},
update: (updater) => {
return Promise.resolve(updater(initialState)).then((result) => {
if (result.updates) initialState = {
...initialState,
...result.updates
};
return result.result;
});
}
}
},
getSubagentModelId: (params) => {
return (this.config.subagents?.find((s) => s.id === params?.agentType))?.defaultModelId ?? null;
}
});
let workspaceToConnect = overrides?.workspace ?? this.workspace;
if (typeof workspaceToConnect === "function") workspaceToConnect = await require_dynamic_argument.resolveDynamicArgument(workspaceToConnect, {
requestContext,
mastra: this.getMastra()
});
let browserToConnect = overrides?.browser ?? this.browser;
if (typeof browserToConnect === "function") browserToConnect = await require_dynamic_argument.resolveDynamicArgument(browserToConnect, {
requestContext,
mastra: this.getMastra()
});
const session = this.#wireSession(new Session({
resourceId: effectiveResourceId,
id,
ownerId,
tags,
state: {
initialState,
stateSchema: this.config.stateSchema
},
workspace: workspaceToConnect,
browser: browserToConnect
}));
if (overrides?.threadId) {
const existingThread = await session.thread.getById({ threadId: overrides.threadId });
if (existingThread) {
if (existingThread.resourceId !== effectiveResourceId) throw new Error(`Thread not found: ${overrides.threadId}`);
await this.config.threadLock?.acquire(existingThread.id);
session.thread.set({ threadId: existingThread.id });
await session.thread.loadMetadata({ preserveTokenUsageOnFailure: false });
await session.thread.ensureCurrentSubscription(requestContext);
} else await session.thread.create({
id: overrides.threadId,
requestContext
});
} else {
const scopeEntries = Object.entries(session.getThreadScope());
let metadata;
try {
if (scopeEntries.length > 0) metadata = require_run_registry.validateStorageMetadataFilter(Object.fromEntries(scopeEntries));
} catch {}
const candidates = await this.queryThreads({
resourceId: session.identity.getResourceId(),
metadata,
limit: scopeEntries.length > 0 && metadata === void 0 ? void 0 : 1,
matchesScope: (thread) => {
const values = thread.metadata ?? {};
return scopeEntries.every(([key, value]) => values[key] === value);
}
});
if (candidates.length === 0 && overrides?.createInitialThread !== false) await session.thread.create({ requestContext });
else if (candidates.length > 0) {
const mostRecent = [...candidates].sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())[0];
await this.config.threadLock?.acquire(mostRecent.id);
session.thread.set({ threadId: mostRecent.id });
await session.thread.loadMetadata({ preserveTokenUsageOnFailure: false });
await session.thread.ensureCurrentSubscription(requestContext);
}
}
session.setParkedApprovalsRequestContext(requestContext);
await this.#notifySessionCreated(session);
await session.applyToolPolicyToParkedApprovals();
return session;
}
/**
* Throw {@link SessionNotStartedError} unless a stored thread exists that a new session for this
* resource would bind to. Mirrors the scope matching in {@link AgentController.#createSessionForResource}.
*/
async #requireRecoverableThread(resourceId, tags, initialState, threadId) {
if (threadId) {
if ((await this.queryThreadById({ threadId }))?.resourceId === resourceId) return;
throw new SessionNotStartedError(resourceId);
}
const tagScope = Object.entries(tags ?? {}).filter(([key]) => !isReservedThreadMetadataKey(key));
const { projectPath } = initialState ?? {};
const scopeEntries = tagScope.length > 0 ? tagScope : projectPath ? [["projectPath", projectPath]] : [];
let metadata;
let filterable = true;
try {
if (scopeEntries.length > 0) metadata = require_run_registry.validateStorageMetadataFilter(Object.fromEntries(scopeEntries));
} catch {
filterable = false;
}
if ((await this.queryThreads({
resourceId,
metadata: filterable ? metadata : void 0,
limit: filterable ? 1 : void 0,
matchesScope: (thread) => {
const values = thread.metadata ?? {};
return scopeEntries.every(([key, value]) => values[key] === value);
}
})).length === 0) throw new SessionNotStartedError(resourceId);
}
/**
* Resolve a live session by its session id (the `id` passed to
* {@link createSession}, which defaults to the resourceId). Returns
* `undefined` when no live session has that id. Used by notification
* delivery to run woken signals as the session that owns the target thread,
* rather than an arbitrary session.
*/
async getSession(sessionId, requestContext) {
const session = await this.#sessionsById.get(sessionId);
await this.requireAgentControllerFGA({
permission: require_ee_iTj2bRDt.MastraFGAPermissions.AGENT_CONTROLLER_READ,
requestContext,
resourceId: session?.identity.getResourceId(),
sessionId
});
return session;
}
/**
* Tear down the live session with this session id.
* This only removes runtime state; persisted threads and messages remain.
* Returns `false` when no live session is registered.
*/
async deleteSession({ sessionId }) {
const registryKey = sessionId;
if (this.#deletionsInProgress.has(registryKey)) return false;
const pending = this.#sessionsById.get(registryKey);
if (!pending) return false;
const deletion = {};
const deletionPromise = (async () => {
const session = await pending;
this.#sessionsBeingDeleted.add(session);
this.#sessionDeletionPromises.set(session, deletion.tolerantPromise);
session.abort({ localOnly: true });
try {
await session.thread.clearAndReleaseLock();
} finally {
await this.#dropSessionFromRegistry(registryKey, session);
this.#notifySessionDeleted(session);
}
})();
const tolerantPromise = deletionPromise.then(() => void 0, () => void 0);
deletion.tolerantPromise = tolerantPromise;
this.#deletionsInProgress.set(registryKey, tolerantPromise);
try {
await deletionPromise;
return true;
} finally {
this.#deletionsInProgress.delete(registryKey);
}
}
/**
* Access the Mastra instance backing this AgentController.
*
* Returns the parent Mastra when this AgentController is registered on one (see
* {@link __registerMastra}); otherwise the internal Mastra created during
* `init()` when storage is configured.
*
* Useful for scorer registration, observability access, and eval tooling.
*/
getMastra() {
return this.#externalMastra ?? this.#internalMastra;
}
/** @internal */
async requireAgentControllerFGA({ permission, requestContext, resourceId, sessionId }) {
const fgaProvider = this.getMastra()?.getServer()?.fga;
if (!fgaProvider) return;
const user = requestContext?.get("user");
const actor = requestContext?.get("actor");
if (!user && !actor) return;
const { requireFGA } = await Promise.resolve().then(() => require("./auth/ee/fga-check.cjs"));
await requireFGA({
fgaProvider,
user,
resource: {
type: "agent-controller",
id: this.id
},
permission,
requestContext,
actor,
context: resourceId ? { resourceId } : void 0,
metadata: {
controllerId: this.id,
resourceId,
sessionId
}
});
}
/**
* Whether a workspace is configured on this AgentController (static instance, dynamic
* factory, or config object). Sessions without an explicit workspace override
* fall back to this.
*/
hasWorkspace() {
return this.workspace !== void 0;
}
/**
* Whether the AgentController-level static workspace has been explicitly initialized.
* Dynamic factory workspaces have no controller-level readiness state.
*/
isWorkspaceReady() {
if (typeof this.workspace === "function") return true;
return this.workspace?.status === "ready";
}
/**
* The AgentController-level workspace, if it is a static instance. Dynamic factory
* workspaces are not resolved here — use {@link resolveWorkspace} to resolve
* a factory against a session's request context.
*/
getWorkspace() {
return typeof this.workspace === "function" ? void 0 : this.workspace ?? void 0;
}
/**
* The workspace this session runs against, for code paths outside the request
* flow (e.g. slash commands). Sessions resolve their workspace once at
* creation — dynamic factories included — so this returns that instance
* rather than re-resolving, and only falls back to the factory for a session
* created without one.
*/
async resolveWorkspace({ session, requestContext }) {
const sessionWorkspace = session.getWorkspace();
if (sessionWorkspace) return sessionWorkspace;
if (typeof this.workspace !== "function") return this.workspace ?? void 0;
const ctx = await this.buildRequestContext(session, requestContext);
return await require_dynamic_argument.resolveDynamicArgument(this.workspace, {
requestContext: ctx,
mastra: this.getMastra()
}) ?? void 0;
}
/**
* Register this AgentController on a parent Mastra. Called by Mastra during
* construction when a harness is passed in its config. Once registered, the
* AgentController uses the parent Mastra (its storage, agents, gateways, and
* observability) instead of building its own internal one during `init()`.
*
* @internal
*/
__registerMastra(mastra) {
this.#externalMastra = mastra;
if (this.#internalMastra) {
this.#internalMastra.__unregisterHooks();
this.#internalMastra = void 0;
}
}
/**
* Resolve the storage this AgentController reads and writes through.
*
* When registered on a parent Mastra, the AgentController inherits that Mastra's
* configured storage so the host and its Harnesses persist to a single store.
* A standalone AgentController falls back to its own `config.storage`.
*/
#resolveStorage() {
return this.#externalMastra?.getStorage() ?? this.config.storage;
}
/**
* Sets or updates the harness-level browser and propagates it to mode agents.
*/
setBrowser(browser) {
this.browser = browser;
for (const agent of this.backingAgents()) agent.setBrowser(browser);
}
/**
* Initialize the harness by loading storage and propagating runtime services.
* Workspaces initialize lazily when used. Must be called before using the harness. Idempotent: repeated calls
* return the same in-flight/completed initialization instead of rebuilding
* the internal Mastra instance (which would orphan registered agents).
*/
async init() {
this.initPromise ??= this.runInit();
return this.initPromise;
}
/**
* Initialize only what read-only queries need: the storage layer (either a
* fresh internal Mastra wrapping the configured storage, or the inherited
* parent Mastra's storage). Skips workspace/sandbox provisioning entirely.
*
* Idempotent and safe to call from every read query; the underlying
* MastraCompositeStore init dedupes.
*/
async initStorage() {
this.#storageInitPromise ??= this.runStorageInit();
return this.#storageInitPromise;
}
#storageInitPromise;
async runStorageInit() {
if (!this.#externalMastra) {
const enabledGateways = this.config.gateways?.filter((gateway) => gateway.shouldEnable?.() ?? true);
const gateways = enabledGateways?.length ? Object.fromEntries(enabledGateways.map((gateway) => [gateway.id, gateway])) : void 0;
this.#internalMastra = new require_mastra.Mastra({
logger: false,
...this.config.storage ? { storage: this.config.storage } : {},
...this.config.backgroundTasks ? { backgroundTasks: this.config.backgroundTasks } : {},
...this.config.pubsub ? { pubsub: this.config.pubsub } : {},
...this.config.observability ? { observability: this.config.observability } : {},
...gateways ? { gateways } : {}
});
await this.#internalMastra.getStorage().init();
} else if (this.#externalMastra) await this.#externalMastra.getStorage()?.init();
}
async runInit() {
await this.initStorage();
if (this.#internalMastra && !this.config.pubsub) for (const agent of this.backingAgents()) {
const owner = agent.getMastraInstance();
if (owner && owner !== this.#internalMastra && !agent.hasOwnPubSub()) {
this.#applicationPubSub = owner.pubsub;
break;
}
}
for (const agent of this.backingAgents()) this.propagateRuntimeServicesToAgent(agent);
this.startIntervals();
}
async getMemoryStorage() {
const storage = this.#resolveStorage();
if (!storage) throw new Error("Storage is not configured on this AgentController");
const memoryStorage = await storage.getStore("memory");
if (!memoryStorage) throw new Error("Storage does not have a memory domain configured");
return memoryStorage;
}
/**
* The shared-host storage gateway the Session's thread domain reads/writes
* through. The Session owns the thread-domain logic; this adapter maps raw
* storage rows to AgentController types and uses the active session only when
* resolving configured memory for a clone.
*/
createThreadDataStore(session) {
return {
listThreads: ({ resourceId, includeForkedSubagents, metadata }) => this.queryThreads({
resourceId,
includeForkedSubagents,
metadata
}),
getById: ({ threadId }) => this.queryThreadById({ threadId }),
listMessages: async ({ threadId, limit }) => {
if (limit !== void 0) {
const result = await this.queryThreadMessages({
threadId,
perPage: limit,
page: 0,
orderBy: {
field: "createdAt",
direction: "DESC"
}
});
return {
...result,
messages: result.messages.reverse()
};
}
return this.queryThreadMessages({
threadId,
perPage: false,
orderBy: {
field: "createdAt",
direction: "ASC"
}
});
},
firstUserMessages: ({ threadIds }) => this.queryFirstUserMessages({ threadIds }),
getMetadata: ({ threadId, key }) => this.readThreadMetadataValue({
threadId,
key
}),
setMetadata: ({ threadId, key, value }) => this.writeThreadMetadataValue({
threadId,
key,
value
}),
deleteMetadata: ({ threadId, key }) => this.removeThreadMetadataValue({
threadId,
key
}),
hasStorage: () => !!this.#resolveStorage(),
saveThread: ({ thread }) => this.persistThreadRow(thread),
deleteThread: ({ threadId, requestContext }) => this.deleteThreadRow({
session,
threadId,
requestContext
}),
cloneThread: ({ sourceThreadId, resourceId, title, metadata, requestContext }) => this.cloneThreadRow({
session,
sourceThreadId,
resourceId,
title,
metadata,
requestContext
}),
acquireLock: (threadId) => this.config.threadLock?.acquire(threadId) ?? Promise.resolve(),
releaseLock: (threadId) => this.config.threadLock?.release(threadId) ?? Promise.resolve(),
getModeIds: () => this.config.modes.map((m) => m.id)
};
}
/** Persist a thread row to memory storage (gateway primitive for the Session thread domain). */
async persistThreadRow(thread) {
if (!this.#resolveStorage()) return;
await (await this.getMemoryStorage()).saveThread({ thread: {
id: thread.id,
resourceId: thread.resourceId,
title: thread.title ?? "",
createdAt: thread.createdAt,
updatedAt: thread.updatedAt,
metadata: thread.metadata
} });
}
/**
* Delete a thread from controller storage and, when memory is resolved per
* caller, from the caller's memory as well so a clone's messages are not
* left behind there (gateway primitive for the Session thread domain).
*/
async deleteThreadRow({ session, threadId, requestContext }) {
if (!this.#resolveStorage()) return;
if (this.config.memory) {
const memory = await this.resolveMemory(session, requestContext);
if (await memory.getThreadById({ threadId })) await memory.deleteThread(threadId);
}
const memoryStorage = await this.getMemoryStorage();
if (await memoryStorage.getThreadById({ threadId })) await memoryStorage.deleteThread({ threadId });
}
/** Clone a thread (and messages) via the host's memory (gateway primitive for the Session thread domain). */
async cloneThreadRow({ session, sourceThreadId, resourceId, title, metadata, requestContext }) {
const storage = this.#resolveStorage();
const callerMemory = this.config.memory ? await this.resolveMemory(session, requestContext) : void 0;
const memory = callerMemory ? callerMemory : storage ? await storage.getStore("memory") : void 0;
if (!memory) throw new Error(storage ? "Storage does not have a memory domain configured" : "Memory is not configured on this Harness");
const result = await memory.cloneThread({
sourceThreadId,
resourceId,
title,
metadata
});
const cloned = {
id: result.thread.id,
resourceId: result.thread.resourceId,
title: result.thread.title ?? "Cloned Thread",
createdAt: result.thread.createdAt,
updatedAt: result.thread.updatedAt,
metadata: result.thread.metadata
};
if (callerMemory) try {
await this.persistThreadRow(cloned);
} catch (error) {
await callerMemory.deleteThread(cloned.id).catch(() => {});
throw error;
}
return cloned;
}
async readThreadMetadataValue({ threadId, key }) {
if (!this.#resolveStorage()) return void 0;
try {
return ((await (await this.getMemoryStorage()).getThreadById({ threadId }))?.metadata)?.[key];
} catch {
return;
}
}
async writeThreadMetadataValues(threadId, values) {
if (!this.#resolveStorage()) return;
const run = (this.#metadataWriteQueues.get(threadId) ?? Promise.resolve()).catch(() => void 0).then(async () => {
const memoryStorage = await this.getMemoryStorage();
const thread = await memoryStorage.getThreadById({ threadId });
if (!thread) throw new Error(`Thread ${threadId} not found`);
const settings = typeof values === "function" ? values(thread.metadata ?? {}) : values;
const metadata = {
...thread.metadata,
...settings
};
for (const key of Object.keys(settings)) if (settings[key] === void 0) delete metadata[key];
await memoryStorage.saveThread({ thread: {
...thread,
metadata: Object.keys(metadata).length ? metadata : void 0,
updatedAt: /* @__PURE__ */ new Date()
} });
});
this.#metadataWriteQueues.set(threadId, run);
try {
await run;
} finally {
if (this.#metadataWriteQueues.get(threadId) === run) this.#metadataWriteQueues.delete(threadId);
}
}
async writeThreadMetadataValue({ threadId, key, value }) {
try {
await this.writeThreadMetadataValues(threadId, { [key]: value });
} catch {}
}
async removeThreadMetadataValue({ threadId, key }) {
try {
await this.writeThreadMetadataValues(threadId, { [key]: void 0 });
} catch {}
}
/**
* Read a single thread by id directly from storage, without constructing a
* {@link Session}. Read-only server endpoints use this so a GET request for a
* thread doesn't spin up a workspace/sandbox as a side effect of session
* creation. Returns `null` when the thread doesn't exist or no storage is
* configured.
*/
async queryThreadById({ threadId }) {
await this.initStorage();
if (!this.#resolveStorage()) return null;
const thread = await (await this.getMemoryStorage()).getThreadById({ threadId });
if (!thread) return null;
return {
id: thread.id,
resourceId: thread.resourceId,
title: thread.title,
createdAt: thread.createdAt,
updatedAt: thread.updatedAt,
metadata: thread.metadata
};
}
/**
* Switch the model of a resource's stored thread without creating a session.
* A live session bound to that thread switches immediately; otherwise the
* selection is persisted and applies when a session next loads the thread.
* Returns whether the switch reached a live session.
*/
async setThreadModel({ resourceId, threadId, modelId }) {
const thread = await this.queryThreadById({ threadId });
if (!thread || thread.resourceId !== resourceId) throw new Error("Thread not found for session.");
for (const pending of this.#sessionsById.values()) {
const live = await pending.catch(() => void 0);
if (live?.identity.getResourceId() === resourceId && live.thread.getId() === threadId) {
await live.model.switch(modelId);
return { live: true };
}
}
await runModelPersistenceOperation(threadId, () => this.writeThreadMetadataValues(threadId, {
currentModelId: modelId,
[MODEL_PERSISTENCE_VERSION_KEY]: 2
}));
return { live: false };
}
/**
* List threads directly from storage, without constructing a {@link Session}.
* Read-only server endpoints use this so a GET on `/threads` doesn't spin up
* a workspace/sandbox as a side effect of session creation.
*/
async queryThreads({ resourceId, includeForkedSubagents, metadata, limit, matchesScope }) {
await this.initStorage();
if (!this.#resolveStorage()) return [];
const memoryStorage = await this.getMemoryStorage();
const filter = resourceId === void 0 && metadata === void 0 ? void 0 : {
...resourceId === void 0 ? {} : { resourceId },
...metadata === void 0 ? {} : { metadata }
};
const keep = (thread) => (includeForkedSubagents || thread.metadata?.forkedSubagent !== true) && (!matchesScope || matchesScope(thread));
const boundedLimit = limit === void 0 ? void 0 : Math.max(0, Math.floor(limit));
if (boundedLimit === 0) return [];
let threads;
if (boundedLimit === void 0 || memoryStorage instanceof require_run_registry.InMemoryMemory || memoryStorage.listThreadsPaginatesInMemory) threads = (await memoryStorage.listThreads({
filter,
perPage: false,
orderBy: {
field: "updatedAt",
direction: "DESC"
}
})).threads.filter(keep).slice(0, boundedLimit);
else {
let size = Math.max(boundedLimit, THREAD_PAGE_FLOOR);
while (true) {
const result = await memoryStorage.listThreads({
filter,
perPage: size,
page: 0,
orderBy: {
field: "updatedAt",
direction: "DESC"
}
});
const candidates = result.threads.filter(keep);
if (candidates.length >= boundedLimit || !result.hasMore) {
threads = candidates.slice(0, boundedLimit);
break;
}
size *= 2;
}
}
return threads.map((thread) => ({
id: thread.id,
resourceId: thread.resourceId,
title: thread.title,
createdAt: thread.createdAt,
updatedAt: thread.updatedAt,
metadata: thread.metadata
}));
}
/**
* List messages for a thread directly from storage, without constructing a
* {@link Session}. The session thread-data adapter and read-only server
* endpoints use this shared path so message reads never provision a
* workspace/sandbox.
*/
async queryThreadMessages({ threadId, resourceId, perPage, page, orderBy = {
field: "createdAt",
direction: "DESC"
}, include, filter }) {
await this.initStorage();
if (!this.#resolveStorage()) return {
messages: [],
total: 0,
page: page ?? 0,
perPage: perPage ?? 40,
hasMore: false
};
const result = await (await this.getMemoryStorage()).listMessages({
threadId,
...resourceId !== void 0 ? { resourceId } : {},
...perPage !== void 0 ? { perPage } : {},
...page !== void 0 ? { page } : {},
...orderBy !== void 0 ? { orderBy } : {},
...include !== void 0 ? { include } : {},
...filter !== void 0 ? { filter } : {}
});
return {
...result,
messages: result.messages.map((msg) => this.convertToControllerMessage(msg))
};
}
async queryFirstUserMessages({ threadIds }) {
if (!this.#resolveStorage() || threadIds.length === 0) return /* @__PURE__ */ new Map();
const result = await (await this.getMemoryStorage()).listMessages({
threadId: threadIds,
perPage: false,
orderBy: {
field: "createdAt",
direction: "ASC"
}
});
const firstUserMessages = /* @__PURE__ */ new Map();
for (const message of result.messages) {
if (!require_signals.isUserAuthoredMessage(message) || !message.threadId || firstUserMessages.has(message.threadId)) continue;
firstUserMessages.set(message.threadId, this.convertToControllerMessage(message));
if (firstUserMessages.size === threadIds.length) break;
}
return firstUserMessages;
}
/**
* Name a thread from where its conversation went, with the model and
* instructions `generateTitle` gives the first-turn namer — so a title asked
* for by hand reads like one the thread would have been given on its own.
*
* Runs without constructing a {@link Session}: naming reads a window of recent
* messages and writes the thread row, so asking for a title never spins up a
* workspace or sandbox. A live session named by `sessionId` lends its agent, request
* context and event stream; otherwise the default mode answers — and with no
* session state to read, a `generateTitle.model` that resolves from it falls
* back to its own default, which is why hosts that store the choice elsewhere
* pass `model`. Resolves to the new title, or `undefined` when the model
* returns nothing and the current title stands.
*/
async generateThreadTitle({ threadId, sessionId, model, requestContext: callerContext }) {
const thread = await this.queryThreadById({ threadId });
if (!thread) throw new Error(`Thread not found: ${threadId}`);
const recent = await this.queryThreadMessages({
threadId,
perPage: TITLE_WINDOW_MESSAGES,
page: 0,
orderBy: {
field: "createdAt",
direction: "DESC"
}
});
const messages = new require_message_list.MessageList().add(recent.messages.reverse(), "memory").get.all.ui();
if (!messages.some((message) => message.role === "user")) throw new Error("This conversation has no message to name it from yet.");
const session = sessionId ? await this.getSession(sessionId, callerContext) : void 0;
const agent = session ? this.getCurrentAgent(session) : this.propagateRuntimeServicesToAgent(this.getAgentForMode(this.#defaultMode));
const requestContext = session ? await this.buildRequestContext(session, callerContext) : callerContext ?? new require_request_context.RequestContext();
const configured = (await agent.getMemory({ requestContext }))?.getMergedThreadConfig().generateTitle;
const titleConfig = typeof configured === "object" ? configured : void 0;
const overrideModel = model;
const configuredModel = titleConfig?.model;
const title = (await agent.generateTitleFromUserMessage({
messages,
requestContext,
model: overrideModel ?? configuredModel,
instructions: titleConfig?.instructions
}))?.trim();
if (!title) return void 0;
await this.persistThreadRow({
...thread,
title,
metadata: {
...thread.metadata,
[require_stream.TITLE_PINNED_THREAD_METADATA_KEY]: false
},
updatedAt: /* @__PURE__ */ new Date()
});
session?.emit({
type: "thread_title_updated",
threadId,
title
});
return title;
}
listModes() {
return this.config.modes;
}
getDefaultMode() {
return this.#defaultMode;
}
propagateRuntimeServicesToAgent(agent, _session) {
if (this.config.memory && !agent.hasOwnMemory()) agent.__setMemory(this.config.memory);
if (this.config.pubsub && !agent.hasOwnPubSub()) agent.__setPubSub(this.config.pubsub);
const mastra = this.getMastra();
if (mastra && agent.getMastraInstance() !== mastra) {
if (this.#applicationPubSub && !agent.hasOwnPubSub()) agent.__setPubSub(mastra === this.#internalMastra ? this.#applicationPubSub : mastra.pubsub);
if (!mastra.listAgents()[agent.id]) mastra.addAgent(agent);
}
if (this.workspace && typeof agent.hasOwnWorkspace === "function" && !agent.hasOwnWorkspace()) agent.__setWorkspace(this.workspace);
if (this.browser && typeof agent.hasOwnBrowser === "function" && !agent.hasOwnBrowser() && typeof this.browser !== "function") agent.setBrowser(this.browser);
if (this.#channels && agent.getChannels() !== this.#channels) agent.setChannels(this.#channels);
return agent;
}
/**
* Chat channels configured on this controller (from `config.channels`),
* or null when the controller has no channels.
*/
getChannels() {
return this.#channels;
}
/**
* Sets the AgentControllerChannels instance for this controller and
* propagates it onto every backing agent so their runs render back through
* the controller's adapters. Used by ChannelProvider implementations (e.g.
* SlackProvider) to inject channels they create for dynamic installations.
* Mirrors {@link setBrowser}: the instance is attached to the shared backing
* agent plus any per-mode agents via `Agent.setChannels`, and lazily-built
* mode agents pick it up on their first run via
* `propagateRuntimeServicesToAgent`.
*
* Replacing an existing instance is expected on provider reconnect (the
* provider rebuilds channels as a superset merge rather than mutating the
* live instance), so it logs at debug level only. Note the replaced
* instance's in-memory `autoApproveResourceIds` tracking is discarded with
* it — harmless, since it is refreshed on every inbound message.
* @internal
*/
setChannels(channels) {
if (this.#channels && this.#channels !== channels) this.getMastra()?.getLogger()?.debug(`[AgentController:${this.id}] Replacing existing AgentControllerChannels`);
this.#channels = channels;
channels.__setController(this);
for (const agent of this.backingAgents()) agent.setChannels(channels);
}
/** The distinct agents backing this controller: the shared one plus any deprecated per-mode agent. */
backingAgents() {
const agents = /* @__PURE__ */ new Set();
if (this.config.agent) agents.add(this.config.agent);
for (const mode of this.config.modes) if (mode.agent || !this.config.agent) agents.add(this.getAgentForMode(mode));
return agents;
}
getAgentForMode(mode) {
if (mode.agent) {
if (!this.#legacyAgentMode[mode.id]) this.#legacyAgentMode[mode.id] = mode.agent;
return this.#legacyAgentMode[mode.id];
}
if (this.config.agent) return this.config.agent;
if (!this.#legacyAgentMode[mode.id]) {
if (!mode.defaultModelId) throw new Error(`Mode ${mode.id} requires a defaultModelId when no backing agent is configured`);
const instructions = [this.#instructions ?? "", mode.instructions].filter(Boolean).join("\n");
const modeTools = {
...mode.tools,
...mode.additionalTools
};
const model = mode.defaultModelId;
this.#legacyAgentMode[mode.id] = new require_run_registry.Agent({
id: `${this.id}-agent`,
name: `Harness ${this.id} agent`,
model,
instructions,
tools: modeTools
});
}
return this.#legacyAgentMode[mode.id];
}
/**
* Resolve the combined instructions for the current mode: harness-level
* instructions + mode-specific instructions. Passed at call time via
* `buildAgentMessageStreamOptions` so the agent's own instructions are
* never mutated.
*/
resolveCurrentModeInstructions(session) {
const mode = session.mode.resolve();
return [this.#instructions ?? "", mode?.instructions ?? ""].filter(Boolean).join("\n") || void 0;
}
/**
* Convert AgentInstructions (string | string[] | system message objects) to
* a plain string for combining with mode instructions.
*/
instructionsToString(instructions) {
if (typeof instructions === "string") return instructions;
if (Array.isArray(instructions)) return instructions.map((msg) => typeof msg === "string" ? msg : typeof msg.content === "string" ? msg.content : "").filter(Boolean).join("\n\n");
return typeof instructions.content === "string" ? instructions.content : "";
}
/**
* Get the agent for the current mode.
*/
/**
* Resolve the Agent backing the current mode, with runtime services (storage,
* pubsub, telemetry) propagated. Public so consumers like MastraCode's
* GoalManager can drive the agent's native objective methods
* (`setObjective`/`getObjective`/`clearObjective`/`updateObjectiveOptions`),
* which read/write the durable `threadState` `'goal'` slot.
*/
getCurrentAgent(session) {
const mode = session.mode.resolve();
return this.propagateRuntimeServicesToAgent(this.getAgentForMode(mode), session);
}
listActiveThreadRuns() {
const byRunId = /* @__PURE__ */ new Map();
for (const agent of this.backingAgents()) for (const run of this.propagateRuntimeServicesToAgent(agent).listActiveThreadRuns()) byRunId.set(run.runId, run);
return [...byRunId.values()];
}
/**
* Check if the current model's provider has authentication configured.
* Delegates to the {@link GatewayManager} auth chain (the same resolution
* the model router uses at run time). Returns `hasAuth: true` only when no
* model is selected; gateway-chain failures return `hasAuth: false` so the
* auth-status endpoint stays stable instead of erroring.
*/
async getCurrentModelAuthStatus(session) {
const modelId = session.model.get();
if (!modelId) return { hasAuth: true };
let hasAuth = true;
try {
hasAuth = this.#gatewayManager ? await this.#gatewayManager.hasAuth(modelId) : true;
} catch {
hasAuth = false;
}
if (hasAuth) return { hasAuth: true };
try {
const currentModel = (await this.listAvailableModels()).find((model) => model.id === modelId);
if (currentModel) return {
hasAuth: false,
apiKeyEnvVar: currentModel.apiKeyEnvVar
};
} catch {}
return { hasAuth: false };
}
/**
* Get available models from the configured gateways with use counts applied.
*
* Remote catalogs (models.dev, Netlify) are served from their last good
* download and refreshed in the background once it is a few minutes old;
* calls wait for one only until it has downloaded once.
* Configured gateways and auth are checked again after a few seconds, or on
* the next call after {@link invalidateAvailableModelsCache}.
*/
async listAvailableModels() {
const catalog = await this.#modelCatalog.list();
const useCounts = this.config.modelUseCountProvider?.() ?? {};
const useCountsKey = JSON.stringify(useCounts);
const previous = this.#availableModels;
if (previous?.catalog === catalog && previous.useCountsKey === useCountsKey) return previous.models.slice();
const modelsById = /* @__PURE__ */ new Map();
for (const model of catalog) {
if (!model.id || !model.provider || !model.modelName) continue;
modelsById.set(model.id, {
...model,
useCount: useCounts[model.id] ?? 0
});
}
const models = [...modelsById.values()];
this.#availableModels = {
catalog,
useCountsKey,
models
};
return models.slice();
}
/**
* Make the next {@link listAvailableModels} call check configured gateways and
* auth again, and download remote catalogs again in the background. Call it
* after credentials or custom providers change.
*/
invalidateAvailableModelsCache() {
this.#modelCatalog.invalidate();
}
/**
* Point the session at a different memory resourceId. The resourceId itself
* lives on the session (`session.identity`); the AgentController orchestrates the
* surrounding teardown — dropping the current thread subscription and clearing
* the active thread — since those are AgentController-owned.
*
* The session stays registered under its session id, so {@link getSession}
* keeps resolving it. A session that is being deleted is left alone.
*/
async setResourceId(session, { resourceId }) {
if (this.#sessionsBeingDeleted.has(session)) return;
const deletion = this.#deletionsInProgress.get(session.identity.getId());
if (deletion) {
await deletion;
if (this.#sessionsBeingDeleted.has(session)) return;
}
await session.thread.setResourceId({ resourceId });
}
/**
* Remove `registryKey` from the registry only if it still resolves to
* `session`.
*/
async #dropSessionFromRegistry(registryKey, session) {
const pending = this.#sessionsById.get(registryKey);
if (!pending) return;
if (await pending.catch(() => void 0) === session && this.#sessionsById.get(registryKey) === pending) this.#sessionsById.delete(registryKey);
}
async getKnownResourceIds(session) {
const threads = await session.thread.list({ allResources: true });
return [...new Set(threads.map((t) => t.resourceId))].sort();
}
/**
* Load observational memory progress for the current thread.
* Reconstructs status from the durable OM record, then emits an `om_status` event for the UI.
*/
async loadOMProgress(session, isCurrent = () => true) {
const threadId = session.thread.getId();
if (!threadId) return;
try {
const record = await (await this.getMemoryStorage()).getObservationalMemory(threadId, session.identity.getResourceId());
if (!record) return;
const config = record.config;
const getThreshold = (val, fallback) => {
if (!val) return fallback;
if (typeof val === "number") return val;
return val.max;
};
const observationThreshold = getThreshold(config?._overrides?.observation?.messageTokens ?? config?.observation?.messageTokens, 3e4);
const reflectionThreshold = getThreshold(config?._overrides?.reflection?.observationTokens ?? config?.reflection?.observationTokens, 4e4);
const messageTokens = record.pendingMessageTokens ?? 0;
const observationTokens = record.observationTokenCount ?? 0;
const rawChunks = record.bufferedObservationChunks;
let bufferedChunks = [];
if (Array.isArray(rawChunks)) bufferedChunks = rawChunks;
else if (typeof rawChunks === "string") try {
const parsed = JSON.parse(rawChunks);
if (Array.isArray(parsed)) bufferedChunks = parsed;
} catch {
bufferedChunks = [];
}
const bufferedMessageTokens = Math.min(bufferedChunks.reduce((sum, chunk) => sum + (chunk.messageTokens ?? 0), 0), messageTokens);
const bufferedObservationTokens = bufferedChunks.reduce((sum, chunk) => sum + (chunk.tokenCount ?? 0), 0);
const bufferedObs = {
status: record.isBufferingObservation ? "running" : bufferedChunks.length ? "complete" : "idle",
chunks: bufferedChunks.length,
messageTokens: bufferedMessageTokens,
projectedMessageRemoval: 0,
observationTokens: bufferedObservationTokens
};
const bufferedRef = {
status: record.isBufferingReflection ? "running" : record.bufferedReflection ? "complete" : "idle",
inputObservationTokens: record.bufferedReflectionInputTokens ?? 0,
observationTokens: record.bufferedReflectionTokens ?? 0
};
const generationCount = record.generationCount ?? 0;
const stepNumber = 0;
if (!isCurrent()) return;
session.emit({
type: "om_status",
windows: {
active: {
messages: {
tokens: messageTokens,
threshold: observationThreshold
},
observations: {
tokens: observationTokens,
threshold: reflectionThreshold
}
},
buffered: {
observations: bufferedObs,
reflection: bufferedRef
}
},
recordId: record.id ?? "",
threadId,
stepNumber,
generationCount
});
} catch {}
}
async getObservationalMemoryRecord(session) {
if (!session.thread.getId()) return null;
try {
return await (await this.getMemoryStorage()).getObservationalMemory(session.thread.getId(), session.identity.getResourceId());
} catch {
return null;
}
}
getToolCategory({ toolName }) {
return this.config.toolCategoryResolver?.(toolName) ?? null;
}
/**
* Resolve the `activeTools` allowlist for the current mode's run.
*
* Returns `undefined` when the mode has no `availableTools` configured
* (no restriction — all tools visible). When the mode declares
* `availableTools`, returns that list filtered to remove tools whose
* permission category is denied.
*
* Per-tool `deny` is already handled by `buildToolsets` (denied tools are
* deleted from the toolsets), so those tools won't exist at execution time
* regardless of whether they appear in the allowlist.
*
* The returned list uses the same exposed tool names the execution pipeline
* checks against (e.g. `view`, `write_file`, `ask_user`), which matches the
* names workspace tools are renamed to via `TOOL_NAME_OVERRIDES`.
*
* Pass the run's `requestContext` to filter with the rules of the run's own
* thread rather than the thread the session currently holds.
*/
resolveModeActiveTools(session, modeId, requestContext) {
const availableTools = (modeId ? session.mode.resolveId(modeId) : session.mode.resolve())?.availableTools;
if (!availableTools) return;
if (availableTools.length === 0) return [];
const permissionRules = readPermissionRules(session.__getRunState(requestContext).state);
const deniedTools = new Set(Object.entries(permissionRules.tools).filter(([, policy]) => policy === "deny").map(([tool]) => tool));
const deniedCategories = new Set(Object.entries(permissionRules.categories).filter(([, policy]) => policy === "deny").map(([cat]) => cat));
if (deniedTools.size === 0 && deniedCategories.size === 0) return availableTools;
return availableTools.filter((toolName) => {
if (deniedTools.has(toolName)) return false;
const category = this.getToolCategory({ toolName });
return !category || !deniedCategories.has(category);
});
}
async buildAgentMessageStreamOptions({ session, requestContext: requestContextInput, tracingContext, tracingOptions, untilIdle, abortSignal, threadId }) {
const runThreadId = threadId ?? session.thread.getId();
if (!runThreadId) throw new Error("Cannot build stream options without a current thread");
const resourceId = session.identity.getResourceId();
const modeId = session.mode.get();
const threadOwnerId = await session.thread.getOwner({ threadId: runThreadId });
if (!abortSignal) session.run.clearAbortRequested();
await session.model.syncFromPersisted();
const requestContext = await this.buildRequestContext(session, requestContextInput, {
abortSignal,
resourceId,
threadId: runThreadId,
threadOwnerId,
modeId,
execution: true
});
let callTimeInstructions;
if (this.config.agent) {
const modeInstructions = this.resolveCurrentModeInstructions(session);
if (modeInstructions) {
const agentInstructions = await this.getCurrentAgent(session).getInstructions({ requestContext });
callTimeInstructions = [this.instructionsToString(agentInstructions), modeInstructions].filter(Boolean).join("\n") || void 0;
}
}
const streamOptions = {
...this.buildSharedRunOptions(session, requestContext),
memory: {
thread: runThreadId,
resource: resourceId,
onTitleGenerated: (title) => session.emit({
type: "thread_title_updated",
threadId: runThreadId,
title
})
},
abortSignal: abortSignal ?? session.run.ensureAbortController().signal,
requestContext,
outputWriter: async (chunk) => {
if (chunk.type !== "data-mastracode-tool-progress") return;
const data = chunk.data;
if (!data?.toolCallId || data.progress === void 0) return;
session.emit({
type: "tool_update",
threadId: runThreadId,
toolCallId: data.toolCallId,
partialResult: data.progress
});
const output = this.formatToolProgressOutput(data.progress);
if (output) session.emit({
type: "shell_output",
threadId: runThreadId,
toolCallId: data.toolCallId,
output,
stream: "stdout"
});
},
...tracingContext && { tracingContext },
...tracingOptions && { tracingOptions },
untilIdle: untilIdle ?? true,
...callTimeInstructions && { instructions: callTimeInstructions }
};
streamOptions.toolsets = await this.buildToolsets(session, requestContext);
const activeTools = this.resolveModeActiveTools(session, void 0, requestContext);
if (activeTools !== void 0) streamOptions.activeTools = activeTools;
return streamOptions;
}
formatToolProgressOutput(progress) {
if (typeof progress === "string") return progress.endsWith("\n") ? progress : `${progress}\n`;
if (typeof progress !== "object" || progress === null) return `${String(progress)}\n`;
const record = progress;
const parts = [record.status, record.detail].filter((part) => typeof part === "string" && part.length > 0);
return parts.length > 0 ? `${parts.join(": ")}\n` : "";
}
/**
* Options that every harness-driven agent run must carry — the initial stream
* AND every `resumeStream`. Centralized so the two paths can't drift: a
* missing `maxSteps` on resume silently caps the resumed run at the agent's
* small default and ends it mid-task (see {@link HARNESS_MAX_STEPS}).
*/
buildSharedRunOptions(session, requestContext) {
const context = requestContext?.get("controller");
const isYolo = session.state.get().yolo === true;
const channelAutoApprove = this.#channels?.__isAutoApproveResource(context?.resourceId ?? session.identity.getResourceId()) === true;
const shared = {
maxSteps: CONTROLLER_MAX_STEPS,
savePerStep: false,
requireToolApproval: isYolo || channelAutoApprove ? false : ({ toolName }) => session.resolveToolApproval(toolName, requestContext) !== "allow",
toolCallConcurrency: { strategy: "called" },
onStepFinish: this.createUsageRecorder(context?.threadId ?? session.thread.getId())
};
const fableFallback = buildFableFallbackProviderOptions(context?.session.modelId ?? session.model.get());
if (fableFallback) shared.providerOptions = { anthropic: { ...fableFallback.anthropic } };
return shared;
}
/**
* Persist a system-reminder message for a thread (host-owned storage). Throws
* when no storage is configured — the Session guards the no-thread case before
* calling. Returns the saved {@link MastraDBMessage}.
*/
async saveSystemReminder({ threadId, resourceId, message, reminderType, role, metadata }) {
if (!this.#resolveStorage()) return null;
const memoryStorage = await this.getMemoryStorage();
const dbMessage = {
id: globalThis.crypto.randomUUID(),
role,
threadId,
resourceId,
createdAt: /* @__PURE__ */ new Date(),
content: {
format: 2,
parts: [],
content: "",
metadata: { systemReminder: {
type: reminderType,
message,
...metadata
} }
}
};
const saved = (await memoryStorage.saveMessages({ messages: [dbMessage] })).messages[0] ?? dbMessage;
return this.convertToControllerMessage(saved);
}
/**
* Resolve the mode the session transitions to when a plan is approved: the
* source mode's `transitionsTo`, else the configured default mode. The mode
* catalog is AgentController config, so this is host-owned. Returns `undefined` when
* no default mode is configured.
*/
resolveTransitionModeId(session, modeId) {
const transitionModeId = session.mode.resolveId(modeId).transitionsTo ?? this.config.defaultModeId ?? this.config.modes.find((mode) => mode.default || mode.metadata?.default === true)?.id ?? this.config.modes[0]?.id;
return this.listModes().find((mode) => mode.id === transitionModeId)?.id;
}
convertToControllerMessage(msg) {
return {
id: msg.id,
role: msg.role,
createdAt: msg.createdAt,
...msg.threadId !== void 0 ? { threadId: msg.threadId } : {},
...msg.resourceId !== void 0 ? { resourceId: msg.resourceId } : {},
...msg.type !== void 0 ? { type: msg.type } : {},
content: msg.content
};
}
getSubagentDisplayName(agentType) {
return this.config.subagents?.find((subagent) => subagent.id === agentType)?.name;
}
/**
* Build the toolsets object that includes built-in harness tools (ask_user, submit_plan,
* and optionally subagent) plus any user-configured tools.
* Used by sendMessage, handleToolApprove, and handleToolDecline.
*/
async buildToolsets(session, requestContext) {
const context = requestContext.get("controller");
const runModeId = requestContext.getRaw(RUN_MODE_ID_CONTEXT_KEY);
const resolveMode = () => session.mode.resolveId((typeof runModeId === "string" ? runModeId : void 0) ?? context?.session.modeId ?? session.mode.get());
const builtInTools = {
ask_user: require_tools.askUserTool,
submit_plan: require_tools.submitPlanTool,
task_write: require_state_processor.taskWriteTool,
task_update: require_state_processor.taskUpdateTool,
task_complete: require_state_processor.taskCompleteTool,
task_check: require_state_processor.taskCheckTool
};
let resolvedControllerTools = void 0;
if (this.config.tools) {
const tools = await require_dynamic_argument.resolveDynamicArgument(this.config.tools, { requestContext });
if (tools) resolvedControllerTools = { ...tools };
}
if (this.config.subagents?.length) {
const currentMode = resolveMode();
const hasMemory = Boolean(this.config.memory);
builtInTools.subagent = createSubagentTool({
subagents: this.config.subagents,
resolveModel: this.config.resolveSubagentModel ?? ((modelId) => modelId),
mastra: this.getMastra(),
controllerTools: resolvedControllerTools,
fallbackModelId: currentMode?.defaultModelId,
getParentModelId: () => context?.session.modelId ?? session.model.get(),
getParentAgent: () => {
try {
return this.getAgentForMode(resolveMode());
} catch {
return;
}
},
cloneThreadForFork: hasMemory ? async ({ sourceThreadId, resourceId, title, requestContext }) => {
const result = await (await this.resolveMemory(session, requestContext)).copyThread({
sourceThreadId,
resourceId: resourceId ?? session.identity.getResourceId(),
title,
metadata: {
forkedSubagent: true,
parentThreadId: sourceThreadId
}
});
return {
id: result.thread.id,
resourceId: result.thread.resourceId
};
} : void 0,
getParentToolsets: (forkRequestContext) => this.buildToolsets(session, forkRequestContext ?? requestContext)
});
}
if (this.config.disableBuiltinTools?.length) for (const toolId of this.config.disableBuiltinTools) delete builtInTools[toolId];
const permissionRules = readPermissionRules(session.__getRunState(requestContext).state);
for (const [toolId, policy] of Object.entries(permissionRules.tools)) if (policy === "deny") {
delete builtInTools[toolId];
delete resolvedControllerTools?.[toolId];
}
const result = { controllerBuiltIn: builtInTools };
if (resolvedControllerTools) result.controller = resolvedControllerTools;
if (this.config.agent) {
const currentMode = resolveMode();
const modeTools = currentMode.tools ?? currentMode.additionalTools;
if (modeTools) result.modeTools = modeTools;
}
return result;
}
/**
* Build request context for agent execution.
* Tools can access controller state via requestContext.get('controller').
*/
async buildRequestContext(session, requestContext, scope) {
const inheritedControllerContext = requestContext?.get("controller");
const persistedThreadOwnerId = requestContext?.getRaw(THREAD_OWNER_ID_CONTEXT_KEY);
requestContext = new require_request_context.RequestContext(requestContext?.entries());
const inheritedContext = requestContext.get("controller");
const inherited = inheritedContext && this.#executionViews.get(inheritedContext);
const threadId = scope?.threadId ?? inherited?.view.threadId ?? session.thread.getId();
const resourceId = scope?.resourceId ?? inherited?.view.resourceId ?? session.identity.getResourceId();
const runScope = scope?.runId ? this.getMastra()?.__getRunScope(scope.runId) : void 0;
const cached = runScope?.get(this.#executionViewKey) ?? inherited;
const retained = Boolean(scope?.execution || scope?.runId || cached?.retained);
const matches = cached?.session === session && cached.view.threadId === threadId && cached.view.resourceId === resourceId && (!retained || cached.retained);
const readMetadata = async () => {
if (!threadId || !this.#resolveStorage()) return {};
const thread = await session.thread.getById({ threadId });
if (!thread || thread.resourceId !== resourceId) throw new Error("Source thread is missing or belongs to another resource");
return thread.metadata ?? {};
};
const persistSetting = async ({ key, value }) => {
if (!threadId) return;
await readMetadata();
await this.writeThreadMetadataValues(threadId, { [key]: value });
};
let view = matches ? cached.view : void 0;
if (!view) {
const state = session.state;
if (session.thread.getId() === threadId && session.identity.getResourceId() === resourceId) view = state.retain(void 0, retained);
else {
if (!threadId) throw new Error("Cannot build an execution view without a source thread");
const metadata = await readMetadata();
const modeId = typeof metadata.currentModeId === "string" && this.config.modes.some((mode) => mode.id === metadata.currentModeId) ? metadata.currentModeId : session.mode.getDefault();
const modelId = await migratePersistedModelSelection({
metadata,
modeId,
threadId,
validModeIds: this.config.modes.map((mode) => mode.id),
set: (key, value) => persistSetting({
key,
value
})
}) ?? session.model.getDefault();
view = state.retain({
resourceId,
threadId,
preferences: metadata,
selection: {
modeId,
modelId
},
persistSetting
}, retained);
}
}
if (scope?.runId && scope.modeId) view.setSelection({
...view.selection(),
modeId: scope.modeId
});
const executionView = {
session,
view,
retained
};
runScope?.set(this.#executionViewKey, executionView);
const threadOwnerId = scope && Object.prototype.hasOwnProperty.call(scope, "threadOwnerId") ? scope.threadOwnerId : inheritedControllerContext?.threadOwnerId ?? (typeof persistedThreadOwnerId === "string" ? persistedThreadOwnerId : void 0);
const controllerContext = {
controllerId: this.id,
harnessId: this.id,
state: view.get(),
getState: view.get,
setState: view.set,
updateState: view.update,
getThreadSetting: async (key) => (await readMetadata())[key],
setThreadSetting: persistSetting,
isThreadActive: () => session.thread.getId() === threadId && session.identity.getResourceId() === resourceId,
threadId,
threadOwnerId,
resourceId,
sessionId: session.identity.getId(),
session: {
id: session.identity.getId(),
ownerId: session.identity.getOwnerId(),
get modeId() {
return view.selection().modeId;
},
get modelId() {
return view.selection().modelId;
},
state: {
get: view.get,
set: view.set,
update: view.update
}
},
abortSignal: scope?.abortSignal ?? (view.isActive() ? session.run.getAbortSignal() : void 0),
emitEvent: view.emit,
getSubagentModelId: (params) => {
const state = view.get();
const perType = params?.agentType ? state[`subagentModelId_${params.agentType}`] : void 0;
if (typeof perType === "string") return perType;
return typeof state.subagentModelId === "string" ? state.subagentModelId : null;
}
};
this.#executionViews.set(controllerContext, executionView);
requestContext.set("controller", controllerContext);
if (threadOwnerId !== void 0) requestContext.setRaw(THREAD_OWNER_ID_CONTEXT_KEY, threadOwnerId);
if (scope?.modeId) requestContext.setRaw(RUN_MODE_ID_CONTEXT_KEY, scope.modeId);
if (resourceId) requestContext.set(require_request_context.MASTRA_RESOURCE_ID_KEY, resourceId);
if (threadId) requestContext.set(require_request_context.MASTRA_THREAD_ID_KEY, threadId);
return requestContext;
}
/**
* Resolve memory from config — handles both static instances and dynamic factory functions.
* Pass the caller's context so a dynamic factory sees the caller's user.
*/
async resolveMemory(session, callerContext) {
const mem = this.config.memory;
if (!mem) throw new Error("Memory is not configured on this AgentController");
if (typeof mem !== "function") return mem;
const requestContext = await this.buildRequestContext(session, callerContext);
const resolved = await require_dynamic_argument.resolveDynamicArgument(mem, {
requestContext,
mastra: this.getMastra()
});
if (!resolved) throw new Error("Dynamic memory factory returned empty value");
return resolved;
}
/**
* Execution-side usage recorder for one run. Stream subscribers only project
* usage for display; the run that spends the tokens folds each step into its
* thread's persisted total exactly once.
*/
createUsageRecorder(threadId) {
return async (step) => {
const usage = toStepTokenUsage(step.usage);
if (!threadId || !usage || !this.#resolveStorage()) return;
let pending = this.#pendingTokenUsage.get(threadId);
if (!pending) {
pending = {
usage: createEmptyTokenUsage(),
revision: 0
};
this.#pendingTokenUsage.set(threadId, pending);
}
pending.usage = addTokenUsage(pending.usage, usage);
if (pending.total) pending.total = addTokenUsage(pending.total, usage);
pending.revision++;
const measurement = pending;
let savedRevision = 0;
try {
await this.writeThreadMetadataValues(threadId, (metadata) => {
measurement.total ??= addTokenUsage({
...createEmptyTokenUsage(),
...metadata.tokenUsage
}, measurement.usage);
savedRevision = measurement.revision;
return { tokenUsage: { ...measurement.total } };
});
if (measurement.revision === savedRevision && this.#pendingTokenUsage.get(threadId) === measurement) this.#pendingTokenUsage.delete(threadId);
} catch {}
};
}
startIntervals() {
const handlers = [...this.config.intervalHandlers ?? []];
if (!handlers.length) return;
for (const iv of handlers) {
if (this.intervalTimers.has(iv.id)) continue;
const run = async () => {
try {
await iv.handler();
} catch (error) {
console.error(`[Interval:${iv.id}] failed:`, error);
}
};
if (iv.immediate !== false) run();
const timer = setInterval(run, iv.intervalMs);
timer.unref();
this.intervalTimers.set(iv.id, {
timer,
shutdown: iv.shutdown
});
}
}
registerInterval(handler) {
this.removeInterval({ id: handler.id });
const run = async () => {
try {
await handler.handler();
} catch (error) {
console.error(`[Interval:${handler.id}] failed:`, error);
}
};
if (handler.immediate !== false) run();
const timer = setInterval(run, handler.intervalMs);
timer.unref();
this.intervalTimers.set(handler.id, {
timer,
shutdown: handler.shutdown
});
}
async removeInterval({ id }) {
const entry = this.intervalTimers.get(id);
if (entry) {
clearInterval(entry.timer);
this.intervalTimers.delete(id);
try {
await entry.shutdown?.();
} catch (error) {
console.error(`[Interval:${id}] shutdown failed:`, error);
}
}
}
async stopIntervals() {
const entries = [...this.intervalTimers.entries()];
this.intervalTimers.clear();
for (const [id, entry] of entries) {
clearInterval(entry.timer);
try {
await entry.shutdown?.();
} catch (error) {
console.error(`[Interval:${id}] shutdown failed:`, error);
}
}
}
async destroy() {
await this.stopIntervals();
}
generateId() {
if (this.config.idGenerator) return this.config.idGenerator();
return globalThis.crypto.randomUUID();
}
};
Object.defineProperty(exports, "AgentController", {
enumerable: true,
get: function() {
return AgentController;
}
});
Object.defineProperty(exports, "MODEL_PERSISTENCE_VERSION", {
enumerable: true,
get: function() {
return MODEL_PERSISTENCE_VERSION;
}
});
Object.defineProperty(exports, "MODEL_PERSISTENCE_VERSION_KEY", {
enumerable: true,
get: function() {
return MODEL_PERSISTENCE_VERSION_KEY;
}
});
Object.defineProperty(exports, "Session", {
enumerable: true,
get: function() {
return Session;
}
});
Object.defineProperty(exports, "SessionNotStartedError", {
enumerable: true,
get: function() {
return SessionNotStartedError;
}
});
Object.defineProperty(exports, "SessionStartupCancelledError", {
enumerable: true,
get: function() {
return SessionStartupCancelledError;
}
});
Object.defineProperty(exports, "defaultDisplayState", {
enumerable: true,
get: function() {
return defaultDisplayState;
}
});
Object.defineProperty(exports, "defaultOMProgressState", {
enumerable: true,
get: function() {
return defaultOMProgressState;
}
});
Object.defineProperty(exports, "getSuspensionAddressKey", {
enumerable: true,
get: function() {
return getSuspensionAddressKey;
}
});
Object.defineProperty(exports, "isSessionNotStartedError", {
enumerable: true,
get: function() {
return isSessionNotStartedError;
}
});
Object.defineProperty(exports, "isSessionStartupCancelledError", {
enumerable: true,
get: function() {
return isSessionStartupCancelledError;
}
});
Object.defineProperty(exports, "migratePersistedModelSelection", {
enumerable: true,
get: function() {
return migratePersistedModelSelection;
}
});
Object.defineProperty(exports, "parseSubagentMeta", {
enumerable: true,
get: function() {
return parseSubagentMeta;
}
});
//# sourceMappingURL=agent-controller-BCFa_YF3.cjs.map