@mastra/code-sdk 1.11.0-alpha.8 → 1.11.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/acp/agent.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,KAAK,EACL,mBAAmB,EACnB,mBAAmB,EAEnB,iBAAiB,EACjB,kBAAkB,EAClB,iBAAiB,EACjB,kBAAkB,EAClB,aAAa,EACb,cAAc,EACd,kBAAkB,EAClB,YAAY,EAEZ,6BAA6B,EAC7B,8BAA8B,EAE/B,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,eAAe,EAAE,mBAAmB,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAInG,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAO3D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE7C,MAAM,WAAW,iBAAiB;IAChC,UAAU,EAAE,eAAe,CAAC;IAC5B,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,EAAE,mBAAmB,EAAE,CAAC;IAC7B,gBAAgB,CAAC,EAAE,MAAM,oBAAoB,CAAC;IAC9C,SAAS,CAAC,EAAE,MAAM,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC,CAAC;IACjD,OAAO,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/B;AAED,MAAM,MAAM,iBAAiB,GAAG,CAAC,OAAO,EAAE,iBAAiB,KAAK,OAAO,CAAC,iBAAiB,CAAC,CAAC;AA6E3F,yFAAyF;AACzF,qBAAa,kBAAmB,YAAW,KAAK;IAQ5C,OAAO,CAAC,QAAQ,CAAC,UAAU;IAC3B,OAAO,CAAC,QAAQ,CAAC,aAAa;IARhC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAmC;IAC5D,OAAO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WAAW,GAAG,YAAY,GAAG,mBAAmB,GAAG,SAAS,CAW3E"}
package/dist/acp/agent.js CHANGED
@@ -162,7 +162,7 @@ var MastraCodeAcpAgent = class {
162
162
  const thread = await runtime.session.thread.create();
163
163
  await runtime.session.thread.switch({ threadId: thread.id });
164
164
  const defaultModelId = credentialedDefaultModel(available, runtime.session.model.get() ?? "");
165
- if (defaultModelId) await runtime.session.model.switch({ modelId: defaultModelId });
165
+ if (defaultModelId) await runtime.session.model.switch(defaultModelId);
166
166
  const models = {
167
167
  currentModelId: runtime.session.model.get() ?? "",
168
168
  availableModels: includeCurrentModel([...new Map(available.filter((model) => model.hasApiKey || model.id === runtime.session.model.get()).map((model) => [model.id, {
@@ -282,9 +282,9 @@ var MastraCodeAcpAgent = class {
282
282
  });
283
283
  return options;
284
284
  }
285
- thinkingLevel(entry) {
285
+ thinkingLevel(entry, modelId = entry.session.model.get() ?? "") {
286
286
  const level = entry.getThinkingLevel?.() ?? "off";
287
- return getAvailableThinkingLevelsForModel(entry.session.model.get() ?? "").includes(level) ? level : "xhigh";
287
+ return getAvailableThinkingLevelsForModel(modelId).includes(level) ? level : "xhigh";
288
288
  }
289
289
  async setSessionConfigOption(params) {
290
290
  const entry = this.getSession(params.sessionId);
@@ -292,8 +292,10 @@ var MastraCodeAcpAgent = class {
292
292
  this.getSession(params.sessionId);
293
293
  const option = this.configOptions(entry).find((option) => option.id === params.configId);
294
294
  if (!option || option.type !== "select" || !option.options.some((item) => "value" in item && item.value === params.value)) throw RequestError.invalidParams(void 0, "Unknown session configuration selection");
295
- if (params.configId === "model") await entry.session.model.switch({ modelId: String(params.value) });
296
- else if (params.configId === "mode") await entry.session.mode.switch({ modeId: String(params.value) });
295
+ if (params.configId === "model") {
296
+ const modelId = String(params.value);
297
+ await entry.session.model.switch(modelId, { ...entry.getThinkingLevel ? { thinkingLevel: this.thinkingLevel(entry, modelId) } : {} });
298
+ } else if (params.configId === "mode") await entry.session.mode.switch({ modeId: String(params.value) });
297
299
  else if (isThinkingLevelSetting(params.value)) await entry.session.state.set({ thinkingLevel: params.value });
298
300
  if (entry.getThinkingLevel && entry.getThinkingLevel() !== this.thinkingLevel(entry)) await entry.session.state.set({ thinkingLevel: this.thinkingLevel(entry) });
299
301
  return { configOptions: this.configOptions(entry) };
@@ -388,7 +390,7 @@ var MastraCodeAcpAgent = class {
388
390
  await this.enqueue(entry, async () => {
389
391
  if (this.disposed) return;
390
392
  if (!includeCurrentModel(entry.models, entry.session.model.get() ?? "").some((model) => model.modelId === params.modelId)) throw RequestError.invalidParams(void 0, "Model is unavailable or its provider is not configured. Refresh the model list.");
391
- await entry.session.model.switch({ modelId: params.modelId });
393
+ await entry.session.model.switch(params.modelId);
392
394
  });
393
395
  }
394
396
  };
@@ -1 +1 @@
1
- {"version":3,"file":"agent.js","names":[],"sources":["../../src/acp/agent.ts"],"sourcesContent":["import { isAbsolute } from 'node:path';\nimport { PROTOCOL_VERSION, RequestError } from '@agentclientprotocol/sdk';\nimport type {\n Agent,\n AgentSideConnection,\n AuthenticateRequest,\n AuthMethod,\n InitializeRequest,\n InitializeResponse,\n NewSessionRequest,\n NewSessionResponse,\n PromptRequest,\n PromptResponse,\n CancelNotification,\n ContentBlock,\n SessionConfigOption,\n SetSessionConfigOptionRequest,\n SetSessionConfigOptionResponse,\n AvailableCommand,\n} from '@agentclientprotocol/sdk';\nimport type { AgentController, AgentControllerMode, Session } from '@mastra/core/agent-controller';\nimport { AuthStorage, getOAuthProviders, PROVIDER_DEFAULT_MODELS } from '../auth/storage.js';\nimport { seedProviderOMDefault } from '../onboarding/om-settings.js';\nimport { getAvailableThinkingLevelsForModel, isThinkingLevelSetting } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nimport { openUrlInBrowser } from '../utils/open-url.js';\nimport { getCurrentVersion } from '../utils/update-check.js';\nimport { withCleanupFailure } from './errors.js';\nimport { handleAgentControllerEvent } from './event-mapper.js';\nimport type { PromptState } from './event-mapper.js';\nimport { expandSkillCommand, listSkillCommands } from './skills.js';\nimport type { AcpSkills } from './skills.js';\n\nexport interface AcpSessionRuntime {\n controller: AgentController;\n session: Session;\n modes: AgentControllerMode[];\n getThinkingLevel?: () => ThinkingLevelSetting;\n getSkills?: () => Promise<AcpSkills | undefined>;\n cleanup?: () => Promise<void>;\n}\n\nexport type AcpSessionFactory = (request: NewSessionRequest) => Promise<AcpSessionRuntime>;\n\ninterface SessionEntry extends AcpSessionRuntime {\n models: { modelId: string; name: string }[];\n state: PromptState | null;\n queue: Promise<void>;\n turns: Set<{ cancelled: boolean }>;\n unsubscribe: () => void;\n commands?: AvailableCommand[];\n}\n\nconst TERMINAL_LOGIN_METHOD_ID = 'mastracode-login';\nconst BROWSER_LOGIN_PROVIDER_IDS = ['openai-codex', 'kimi-for-coding', 'xai'];\nconst TERMINAL_LOGIN_PROVIDER_IDS = ['anthropic', 'github-copilot'];\n\nfunction terminalLogin(id: string, name: string, description: string, loginArgs: string[]): AuthMethod {\n return {\n id,\n name,\n description,\n type: 'terminal',\n args: loginArgs,\n _meta: {\n 'terminal-auth': {\n command: process.execPath,\n args: [...process.argv.slice(1, 2), ...loginArgs],\n label: name,\n },\n },\n };\n}\n\nfunction listAuthMethods({ auth, _meta }: InitializeRequest['clientCapabilities'] = {}): AuthMethod[] {\n const providers = getOAuthProviders();\n const methods: AuthMethod[] = providers\n .filter(provider => BROWSER_LOGIN_PROVIDER_IDS.includes(provider.id))\n .map(provider => ({\n id: provider.id,\n name: `Log in with ${provider.name}`,\n description: 'Opens your browser to sign in',\n }));\n if (!auth?.terminal && _meta?.['terminal-auth'] !== true) return methods;\n return [\n ...methods,\n ...providers\n .filter(provider => TERMINAL_LOGIN_PROVIDER_IDS.includes(provider.id))\n .map(provider =>\n terminalLogin(provider.id, `Log in with ${provider.name}`, 'Sign in from a terminal', [\n 'login',\n '--provider',\n provider.id,\n ]),\n ),\n terminalLogin(\n TERMINAL_LOGIN_METHOD_ID,\n 'Log in with Mastra Code',\n 'Sign in to another provider or add an API key from a terminal',\n ['login'],\n ),\n ];\n}\n\nfunction hasUsableModel(available: { id: string; hasApiKey: boolean }[], currentModelId: string): boolean {\n if (available.some(model => model.hasApiKey)) return true;\n return currentModelId !== '' && !available.some(model => model.id === currentModelId);\n}\n\nfunction credentialedDefaultModel(\n available: { id: string; hasApiKey: boolean }[],\n currentModelId: string,\n): string | undefined {\n const current = available.find(model => model.id === currentModelId);\n if (!current || current.hasApiKey) return undefined;\n const credentialed = new Set(available.filter(model => model.hasApiKey).map(model => model.id));\n return Object.values(PROVIDER_DEFAULT_MODELS).find(modelId => credentialed.has(modelId));\n}\n\n/** One ACP connection, with an independent Mastra Code runtime for each conversation. */\nexport class MastraCodeAcpAgent implements Agent {\n private readonly sessions = new Map<string, SessionEntry>();\n private readonly pendingCreations = new Set<Promise<NewSessionResponse>>();\n private readonly startupCleanupFailures: unknown[] = [];\n private disposed = false;\n private disposal?: Promise<void>;\n\n constructor(\n private readonly connection: AgentSideConnection,\n private readonly createSession: AcpSessionFactory,\n ) {}\n\n private getSession(sessionId: string): SessionEntry {\n const entry = this.sessions.get(sessionId);\n if (!entry || this.disposed) throw RequestError.invalidParams({ sessionId }, 'Unknown ACP session');\n return entry;\n }\n\n private enqueue<T>(entry: SessionEntry, operation: () => Promise<T>): Promise<T> {\n const result = entry.queue.then(operation);\n entry.queue = result.then(\n () => {},\n () => {},\n );\n return result;\n }\n\n dispose(): Promise<void> {\n if (this.disposal) return this.disposal;\n this.disposed = true;\n const entries = [...this.sessions.values()];\n this.sessions.clear();\n const cleanup = Promise.allSettled([\n // A runtime under construction owns its cleanup until it joins sessions.\n Promise.allSettled([...this.pendingCreations]),\n ...entries.map(async entry => {\n for (const turn of entry.turns) turn.cancelled = true;\n if (entry.state) {\n entry.state.cancelled = true;\n entry.session.abort();\n entry.state?.resolve('aborted');\n }\n entry.unsubscribe();\n await entry.cleanup?.();\n }),\n ]).then(results => {\n const failures = results.filter(result => result.status === 'rejected').map(result => result.reason);\n failures.push(...this.startupCleanupFailures);\n if (failures.length) throw new AggregateError(failures, 'ACP session cleanup failed');\n });\n // A provider or MCP startup can stall. Keep its cleanup ownership, but let\n // the host terminate the connection if shutdown cannot finish in time.\n this.disposal = new Promise<void>((resolve, reject) => {\n const timeout = setTimeout(() => reject(new Error('ACP shutdown timed out after 10 seconds')), 10_000);\n void cleanup.then(resolve, reject).finally(() => clearTimeout(timeout));\n });\n return this.disposal;\n }\n\n async initialize({ clientCapabilities }: InitializeRequest): Promise<InitializeResponse> {\n return {\n protocolVersion: PROTOCOL_VERSION,\n agentInfo: { name: 'mastracode', title: 'Mastra Code', version: getCurrentVersion() },\n agentCapabilities: { loadSession: false, mcpCapabilities: { http: true, sse: false } },\n authMethods: listAuthMethods(clientCapabilities),\n };\n }\n\n async authenticate({ methodId }: AuthenticateRequest): Promise<void> {\n if (methodId === TERMINAL_LOGIN_METHOD_ID || TERMINAL_LOGIN_PROVIDER_IDS.includes(methodId)) return;\n if (!BROWSER_LOGIN_PROVIDER_IDS.includes(methodId)) {\n throw RequestError.invalidParams(undefined, `Unknown authentication method: ${methodId}`);\n }\n const needsTerminal = () =>\n RequestError.internalError(\n undefined,\n \"Browser sign-in can't finish on its own. Run `mastracode login` in a terminal to sign in.\",\n );\n await new AuthStorage().login(methodId, {\n authMode: 'browser',\n onAuth: ({ url, userCode }) => {\n if (userCode && !url.includes(userCode)) throw needsTerminal();\n process.stderr.write(`Open ${url} to sign in\\n`);\n openUrlInBrowser(url);\n },\n onPrompt: async () => {\n throw needsTerminal();\n },\n });\n try {\n seedProviderOMDefault(methodId);\n } catch (error) {\n process.stderr.write(`[acp] memory model unchanged after sign-in: ${error}\\n`);\n }\n }\n\n newSession(request: NewSessionRequest): Promise<NewSessionResponse> {\n const creating = Promise.resolve().then(() => this.createNewSession(request));\n this.pendingCreations.add(creating);\n void creating.then(\n () => this.pendingCreations.delete(creating),\n () => this.pendingCreations.delete(creating),\n );\n return creating;\n }\n\n private async createNewSession(request: NewSessionRequest): Promise<NewSessionResponse> {\n if (this.disposed) throw RequestError.internalError(undefined, 'ACP connection is closed');\n if (!isAbsolute(request.cwd)) throw RequestError.invalidParams(undefined, 'cwd must be an absolute path');\n const runtime = await this.createSession(request);\n try {\n if (this.disposed) throw RequestError.internalError(undefined, 'ACP connection is closed');\n const available = await runtime.controller.listAvailableModels();\n if (!hasUsableModel(available, runtime.session.model.get() ?? '')) {\n throw RequestError.authRequired(undefined, 'Sign in to a model provider or add an API key to use Mastra Code');\n }\n const thread = await runtime.session.thread.create();\n await runtime.session.thread.switch({ threadId: thread.id });\n const defaultModelId = credentialedDefaultModel(available, runtime.session.model.get() ?? '');\n if (defaultModelId) await runtime.session.model.switch({ modelId: defaultModelId });\n const models: NewSessionResponse['models'] = {\n currentModelId: runtime.session.model.get() ?? '',\n availableModels: includeCurrentModel(\n [\n ...new Map(\n available\n .filter(model => model.hasApiKey || model.id === runtime.session.model.get())\n .map(\n model =>\n [\n model.id,\n {\n modelId: model.id,\n name: model.hasApiKey ? model.id : `${model.id} (provider not configured)`,\n },\n ] as const,\n ),\n ).values(),\n ],\n runtime.session.model.get() ?? '',\n ),\n };\n if (this.disposed) throw RequestError.internalError(undefined, 'ACP connection is closed');\n const entry: SessionEntry = {\n ...runtime,\n models: models.availableModels,\n state: null,\n queue: Promise.resolve(),\n turns: new Set(),\n unsubscribe: () => {},\n commands: [],\n };\n if (this.disposed) throw RequestError.internalError(undefined, 'ACP connection is closed');\n entry.unsubscribe = runtime.session.subscribe(event => {\n handleAgentControllerEvent(event, entry.state, this.connection, entry.session);\n if (event.type === 'mode_changed') {\n void this.connection\n .sessionUpdate({\n sessionId: thread.id,\n update: { sessionUpdate: 'current_mode_update', currentModeId: entry.session.mode.get() },\n })\n .catch(error => process.stderr.write(`[acp] mode update failed: ${error}\\n`));\n }\n if (\n event.type === 'mode_changed' ||\n event.type === 'model_changed' ||\n (event.type === 'state_changed' && event.changedKeys.includes('thinkingLevel'))\n ) {\n void this.connection\n .sessionUpdate({\n sessionId: thread.id,\n update: { sessionUpdate: 'config_option_update', configOptions: this.configOptions(entry) },\n })\n .catch(error => process.stderr.write(`[acp] configuration update failed: ${error}\\n`));\n }\n });\n const response: NewSessionResponse = {\n sessionId: thread.id,\n modes: {\n currentModeId: runtime.session.mode.get(),\n availableModes: runtime.modes.map(mode => ({ id: mode.id, name: mode.name ?? mode.id })),\n },\n models,\n configOptions: this.configOptions(entry),\n };\n this.sessions.set(thread.id, entry);\n // Let the SDK send session/new before clients receive updates for this ID.\n setImmediate(() => {\n void this.enqueue(entry, async () => {\n if (!this.disposed) await this.refreshCommands(thread.id, entry);\n }).catch(error => process.stderr.write(`[acp] command discovery failed: ${error}\\n`));\n });\n return response;\n } catch (error) {\n try {\n await runtime.cleanup?.();\n } catch (cleanupError) {\n if (this.disposed) this.startupCleanupFailures.push(cleanupError);\n throw withCleanupFailure(error, cleanupError);\n }\n throw error;\n }\n }\n\n private async refreshCommands(sessionId: string, entry: SessionEntry): Promise<AcpSkills | undefined> {\n const skills = await entry.getSkills?.();\n const commands = await listSkillCommands(skills);\n if (JSON.stringify(commands) !== JSON.stringify(entry.commands)) {\n await this.connection.sessionUpdate({\n sessionId,\n update: { sessionUpdate: 'available_commands_update', availableCommands: commands },\n });\n entry.commands = commands;\n }\n return skills;\n }\n\n private configOptions(entry: SessionEntry): SessionConfigOption[] {\n const modelId = entry.session.model.get() ?? '';\n const options: SessionConfigOption[] = [];\n const models = includeCurrentModel(entry.models, modelId);\n if (models.length)\n options.push({\n id: 'model',\n name: 'Model',\n category: 'model',\n type: 'select',\n currentValue: modelId,\n options: models.map(model => ({ value: model.modelId, name: model.name })),\n });\n options.push({\n id: 'mode',\n name: 'Mode',\n category: 'mode',\n type: 'select',\n currentValue: entry.session.mode.get(),\n options: entry.modes.map(mode => ({ value: mode.id, name: mode.name ?? mode.id })),\n });\n if (entry.getThinkingLevel)\n options.push({\n id: 'thought_level',\n name: 'Reasoning effort',\n category: 'thought_level',\n type: 'select',\n description: 'Requested reasoning level. The provider may adjust it for the selected model.',\n currentValue: this.thinkingLevel(entry),\n options: getAvailableThinkingLevelsForModel(modelId).map(value => ({\n value,\n name: value[0]!.toUpperCase() + value.slice(1),\n })),\n });\n return options;\n }\n\n private thinkingLevel(entry: SessionEntry): ThinkingLevelSetting {\n const level = entry.getThinkingLevel?.() ?? 'off';\n const levels = getAvailableThinkingLevelsForModel(entry.session.model.get() ?? '');\n return levels.includes(level) ? level : 'xhigh';\n }\n\n async setSessionConfigOption(params: SetSessionConfigOptionRequest): Promise<SetSessionConfigOptionResponse> {\n const entry = this.getSession(params.sessionId);\n return this.enqueue(entry, async () => {\n this.getSession(params.sessionId);\n const option = this.configOptions(entry).find(option => option.id === params.configId);\n if (\n !option ||\n option.type !== 'select' ||\n !option.options.some(item => 'value' in item && item.value === params.value)\n ) {\n throw RequestError.invalidParams(undefined, 'Unknown session configuration selection');\n }\n if (params.configId === 'model') {\n await entry.session.model.switch({ modelId: String(params.value) });\n } else if (params.configId === 'mode') {\n await entry.session.mode.switch({ modeId: String(params.value) });\n } else if (isThinkingLevelSetting(params.value)) {\n await entry.session.state.set({ thinkingLevel: params.value });\n }\n if (entry.getThinkingLevel && entry.getThinkingLevel() !== this.thinkingLevel(entry)) {\n await entry.session.state.set({ thinkingLevel: this.thinkingLevel(entry) });\n }\n return { configOptions: this.configOptions(entry) };\n });\n }\n\n async prompt(request: PromptRequest): Promise<PromptResponse> {\n const entry = this.getSession(request.sessionId);\n const content = extractTextFromContentBlocks(request.prompt);\n const turn = { cancelled: false };\n entry.turns.add(turn);\n try {\n return await this.enqueue(entry, async () => {\n if (turn.cancelled || this.disposed) return { stopReason: 'cancelled' };\n const usage: PromptState['usage'] = { promptTokens: 0, completionTokens: 0, totalTokens: 0 };\n let complete!: PromptState['resolve'];\n const completion = new Promise<Parameters<PromptState['resolve']>[0]>(resolve => {\n complete = resolve;\n });\n const state: PromptState = {\n sessionId: request.sessionId,\n usage,\n resolve: reason => {\n state.finished = true;\n complete(reason);\n },\n };\n entry.state = state;\n try {\n const skills = await this.refreshCommands(request.sessionId, entry);\n const expanded = await expandSkillCommand(content, skills, entry.commands ?? []);\n if (turn.cancelled || this.disposed) return { stopReason: 'cancelled' };\n await entry.session.sendMessage({ content: expanded });\n const reason = await completion;\n if (reason === 'error' && !state.cancelled && !state.stopReason) {\n throw RequestError.internalError(undefined, state.error?.message ?? 'Mastra Code turn failed');\n }\n return {\n stopReason: state.cancelled ? 'cancelled' : (state.stopReason ?? mapStopReason(reason)),\n usage: {\n inputTokens: usage.promptTokens,\n outputTokens: usage.completionTokens,\n totalTokens: usage.totalTokens,\n thoughtTokens: usage.reasoningTokens,\n cachedReadTokens: usage.cachedInputTokens,\n cachedWriteTokens: usage.cacheCreationInputTokens,\n },\n };\n } catch (error) {\n if (state.cancelled) return { stopReason: 'cancelled' };\n if (error instanceof RequestError) throw error;\n throw RequestError.internalError(\n undefined,\n error instanceof Error ? error.message : 'Mastra Code turn failed',\n );\n } finally {\n state.finished = true;\n if (entry.state === state) entry.state = null;\n }\n });\n } finally {\n entry.turns.delete(turn);\n }\n }\n\n async cancel(notification: CancelNotification): Promise<void> {\n const entry = this.sessions.get(notification.sessionId);\n if (!entry) return;\n for (const turn of entry.turns) turn.cancelled = true;\n if (entry.state && !entry.state.finished && !entry.state.cancelled) {\n const state = entry.state;\n state.cancelled = true;\n // Persist denial before aborting, otherwise a parked snapshot can replay on the next turn.\n for (const deny of state.cancelSuspensions?.values() ?? []) {\n try {\n await deny();\n } catch {\n /* Still abort if the suspended run is no longer available. */\n }\n }\n state.cancelSuspensions?.clear();\n if (entry.state !== state) return;\n entry.session.abort();\n // A suspended run has already ended and will not emit another agent_end.\n if (entry.state?.suspended) {\n entry.session.stream.detach();\n entry.state.resolve('aborted');\n }\n }\n }\n\n async setSessionMode(params: { sessionId: string; modeId: string }): Promise<void> {\n const entry = this.getSession(params.sessionId);\n if (!entry.modes.some(mode => mode.id === params.modeId))\n throw RequestError.invalidParams(undefined, 'Unknown mode');\n await this.enqueue(entry, async () => {\n if (this.disposed) return;\n await entry.session.mode.switch({ modeId: params.modeId });\n });\n }\n\n async unstable_setSessionModel(params: { sessionId: string; modelId: string }): Promise<void> {\n const entry = this.getSession(params.sessionId);\n await this.enqueue(entry, async () => {\n if (this.disposed) return;\n if (\n !includeCurrentModel(entry.models, entry.session.model.get() ?? '').some(\n model => model.modelId === params.modelId,\n )\n ) {\n throw RequestError.invalidParams(\n undefined,\n 'Model is unavailable or its provider is not configured. Refresh the model list.',\n );\n }\n await entry.session.model.switch({ modelId: params.modelId });\n });\n }\n}\n\nfunction includeCurrentModel(models: SessionEntry['models'], currentModelId: string): SessionEntry['models'] {\n // Saved/custom model IDs may work even when discovery only returns a gateway-qualified alias.\n return currentModelId && !models.some(model => model.modelId === currentModelId)\n ? [{ modelId: currentModelId, name: currentModelId }, ...models]\n : models;\n}\n\nexport function extractTextFromContentBlocks(blocks: ContentBlock[]): string {\n const parts: string[] = [];\n for (const block of blocks) {\n if (block.type === 'text') {\n parts.push(block.text);\n } else if (block.type === 'resource_link') {\n parts.push(`[resource: ${block.uri}]`);\n } else if (block.type === 'resource') {\n parts.push(`[resource: ${block.resource.uri}]`);\n if (!('text' in block.resource))\n throw RequestError.invalidParams(undefined, 'Binary prompt resources are not supported');\n parts.push(block.resource.text);\n } else {\n throw RequestError.invalidParams(undefined, `Unsupported prompt content: ${block.type}`);\n }\n }\n return parts.join('\\n');\n}\n\nexport function mapStopReason(\n reason: 'complete' | 'aborted' | 'error' | 'suspended',\n): 'end_turn' | 'cancelled' | 'max_tokens' | 'max_turn_requests' | 'refusal' {\n switch (reason) {\n case 'complete':\n return 'end_turn';\n case 'aborted':\n return 'cancelled';\n case 'error':\n throw RequestError.internalError(undefined, 'Mastra Code turn failed');\n case 'suspended':\n return 'end_turn';\n }\n}\n"],"mappings":";;;;;;;;;;;AAqDA,MAAM,2BAA2B;AACjC,MAAM,6BAA6B;CAAC;CAAgB;CAAmB;AAAK;AAC5E,MAAM,8BAA8B,C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 'node:path';\nimport { PROTOCOL_VERSION, RequestError } from '@agentclientprotocol/sdk';\nimport type {\n Agent,\n AgentSideConnection,\n AuthenticateRequest,\n AuthMethod,\n InitializeRequest,\n InitializeResponse,\n NewSessionRequest,\n NewSessionResponse,\n PromptRequest,\n PromptResponse,\n CancelNotification,\n ContentBlock,\n SessionConfigOption,\n SetSessionConfigOptionRequest,\n SetSessionConfigOptionResponse,\n AvailableCommand,\n} from '@agentclientprotocol/sdk';\nimport type { AgentController, AgentControllerMode, Session } from '@mastra/core/agent-controller';\nimport { AuthStorage, getOAuthProviders, PROVIDER_DEFAULT_MODELS } from '../auth/storage.js';\nimport { seedProviderOMDefault } from '../onboarding/om-settings.js';\nimport { getAvailableThinkingLevelsForModel, isThinkingLevelSetting } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nimport { openUrlInBrowser } from '../utils/open-url.js';\nimport { getCurrentVersion } from '../utils/update-check.js';\nimport { withCleanupFailure } from './errors.js';\nimport { handleAgentControllerEvent } from './event-mapper.js';\nimport type { PromptState } from './event-mapper.js';\nimport { expandSkillCommand, listSkillCommands } from './skills.js';\nimport type { AcpSkills } from './skills.js';\n\nexport interface AcpSessionRuntime {\n controller: AgentController;\n session: Session;\n modes: AgentControllerMode[];\n getThinkingLevel?: () => ThinkingLevelSetting;\n getSkills?: () => Promise<AcpSkills | undefined>;\n cleanup?: () => Promise<void>;\n}\n\nexport type AcpSessionFactory = (request: NewSessionRequest) => Promise<AcpSessionRuntime>;\n\ninterface SessionEntry extends AcpSessionRuntime {\n models: { modelId: string; name: string }[];\n state: PromptState | null;\n queue: Promise<void>;\n turns: Set<{ cancelled: boolean }>;\n unsubscribe: () => void;\n commands?: AvailableCommand[];\n}\n\nconst TERMINAL_LOGIN_METHOD_ID = 'mastracode-login';\nconst BROWSER_LOGIN_PROVIDER_IDS = ['openai-codex', 'kimi-for-coding', 'xai'];\nconst TERMINAL_LOGIN_PROVIDER_IDS = ['anthropic', 'github-copilot'];\n\nfunction terminalLogin(id: string, name: string, description: string, loginArgs: string[]): AuthMethod {\n return {\n id,\n name,\n description,\n type: 'terminal',\n args: loginArgs,\n _meta: {\n 'terminal-auth': {\n command: process.execPath,\n args: [...process.argv.slice(1, 2), ...loginArgs],\n label: name,\n },\n },\n };\n}\n\nfunction listAuthMethods({ auth, _meta }: InitializeRequest['clientCapabilities'] = {}): AuthMethod[] {\n const providers = getOAuthProviders();\n const methods: AuthMethod[] = providers\n .filter(provider => BROWSER_LOGIN_PROVIDER_IDS.includes(provider.id))\n .map(provider => ({\n id: provider.id,\n name: `Log in with ${provider.name}`,\n description: 'Opens your browser to sign in',\n }));\n if (!auth?.terminal && _meta?.['terminal-auth'] !== true) return methods;\n return [\n ...methods,\n ...providers\n .filter(provider => TERMINAL_LOGIN_PROVIDER_IDS.includes(provider.id))\n .map(provider =>\n terminalLogin(provider.id, `Log in with ${provider.name}`, 'Sign in from a terminal', [\n 'login',\n '--provider',\n provider.id,\n ]),\n ),\n terminalLogin(\n TERMINAL_LOGIN_METHOD_ID,\n 'Log in with Mastra Code',\n 'Sign in to another provider or add an API key from a terminal',\n ['login'],\n ),\n ];\n}\n\nfunction hasUsableModel(available: { id: string; hasApiKey: boolean }[], currentModelId: string): boolean {\n if (available.some(model => model.hasApiKey)) return true;\n return currentModelId !== '' && !available.some(model => model.id === currentModelId);\n}\n\nfunction credentialedDefaultModel(\n available: { id: string; hasApiKey: boolean }[],\n currentModelId: string,\n): string | undefined {\n const current = available.find(model => model.id === currentModelId);\n if (!current || current.hasApiKey) return undefined;\n const credentialed = new Set(available.filter(model => model.hasApiKey).map(model => model.id));\n return Object.values(PROVIDER_DEFAULT_MODELS).find(modelId => credentialed.has(modelId));\n}\n\n/** One ACP connection, with an independent Mastra Code runtime for each conversation. */\nexport class MastraCodeAcpAgent implements Agent {\n private readonly sessions = new Map<string, SessionEntry>();\n private readonly pendingCreations = new Set<Promise<NewSessionResponse>>();\n private readonly startupCleanupFailures: unknown[] = [];\n private disposed = false;\n private disposal?: Promise<void>;\n\n constructor(\n private readonly connection: AgentSideConnection,\n private readonly createSession: AcpSessionFactory,\n ) {}\n\n private getSession(sessionId: string): SessionEntry {\n const entry = this.sessions.get(sessionId);\n if (!entry || this.disposed) throw RequestError.invalidParams({ sessionId }, 'Unknown ACP session');\n return entry;\n }\n\n private enqueue<T>(entry: SessionEntry, operation: () => Promise<T>): Promise<T> {\n const result = entry.queue.then(operation);\n entry.queue = result.then(\n () => {},\n () => {},\n );\n return result;\n }\n\n dispose(): Promise<void> {\n if (this.disposal) return this.disposal;\n this.disposed = true;\n const entries = [...this.sessions.values()];\n this.sessions.clear();\n const cleanup = Promise.allSettled([\n // A runtime under construction owns its cleanup until it joins sessions.\n Promise.allSettled([...this.pendingCreations]),\n ...entries.map(async entry => {\n for (const turn of entry.turns) turn.cancelled = true;\n if (entry.state) {\n entry.state.cancelled = true;\n entry.session.abort();\n entry.state?.resolve('aborted');\n }\n entry.unsubscribe();\n await entry.cleanup?.();\n }),\n ]).then(results => {\n const failures = results.filter(result => result.status === 'rejected').map(result => result.reason);\n failures.push(...this.startupCleanupFailures);\n if (failures.length) throw new AggregateError(failures, 'ACP session cleanup failed');\n });\n // A provider or MCP startup can stall. Keep its cleanup ownership, but let\n // the host terminate the connection if shutdown cannot finish in time.\n this.disposal = new Promise<void>((resolve, reject) => {\n const timeout = setTimeout(() => reject(new Error('ACP shutdown timed out after 10 seconds')), 10_000);\n void cleanup.then(resolve, reject).finally(() => clearTimeout(timeout));\n });\n return this.disposal;\n }\n\n async initialize({ clientCapabilities }: InitializeRequest): Promise<InitializeResponse> {\n return {\n protocolVersion: PROTOCOL_VERSION,\n agentInfo: { name: 'mastracode', title: 'Mastra Code', version: getCurrentVersion() },\n agentCapabilities: { loadSession: false, mcpCapabilities: { http: true, sse: false } },\n authMethods: listAuthMethods(clientCapabilities),\n };\n }\n\n async authenticate({ methodId }: AuthenticateRequest): Promise<void> {\n if (methodId === TERMINAL_LOGIN_METHOD_ID || TERMINAL_LOGIN_PROVIDER_IDS.includes(methodId)) return;\n if (!BROWSER_LOGIN_PROVIDER_IDS.includes(methodId)) {\n throw RequestError.invalidParams(undefined, `Unknown authentication method: ${methodId}`);\n }\n const needsTerminal = () =>\n RequestError.internalError(\n undefined,\n \"Browser sign-in can't finish on its own. Run `mastracode login` in a terminal to sign in.\",\n );\n await new AuthStorage().login(methodId, {\n authMode: 'browser',\n onAuth: ({ url, userCode }) => {\n if (userCode && !url.includes(userCode)) throw needsTerminal();\n process.stderr.write(`Open ${url} to sign in\\n`);\n openUrlInBrowser(url);\n },\n onPrompt: async () => {\n throw needsTerminal();\n },\n });\n try {\n seedProviderOMDefault(methodId);\n } catch (error) {\n process.stderr.write(`[acp] memory model unchanged after sign-in: ${error}\\n`);\n }\n }\n\n newSession(request: NewSessionRequest): Promise<NewSessionResponse> {\n const creating = Promise.resolve().then(() => this.createNewSession(request));\n this.pendingCreations.add(creating);\n void creating.then(\n () => this.pendingCreations.delete(creating),\n () => this.pendingCreations.delete(creating),\n );\n return creating;\n }\n\n private async createNewSession(request: NewSessionRequest): Promise<NewSessionResponse> {\n if (this.disposed) throw RequestError.internalError(undefined, 'ACP connection is closed');\n if (!isAbsolute(request.cwd)) throw RequestError.invalidParams(undefined, 'cwd must be an absolute path');\n const runtime = await this.createSession(request);\n try {\n if (this.disposed) throw RequestError.internalError(undefined, 'ACP connection is closed');\n const available = await runtime.controller.listAvailableModels();\n if (!hasUsableModel(available, runtime.session.model.get() ?? '')) {\n throw RequestError.authRequired(undefined, 'Sign in to a model provider or add an API key to use Mastra Code');\n }\n const thread = await runtime.session.thread.create();\n await runtime.session.thread.switch({ threadId: thread.id });\n const defaultModelId = credentialedDefaultModel(available, runtime.session.model.get() ?? '');\n if (defaultModelId) await runtime.session.model.switch(defaultModelId);\n const models: NewSessionResponse['models'] = {\n currentModelId: runtime.session.model.get() ?? '',\n availableModels: includeCurrentModel(\n [\n ...new Map(\n available\n .filter(model => model.hasApiKey || model.id === runtime.session.model.get())\n .map(\n model =>\n [\n model.id,\n {\n modelId: model.id,\n name: model.hasApiKey ? model.id : `${model.id} (provider not configured)`,\n },\n ] as const,\n ),\n ).values(),\n ],\n runtime.session.model.get() ?? '',\n ),\n };\n if (this.disposed) throw RequestError.internalError(undefined, 'ACP connection is closed');\n const entry: SessionEntry = {\n ...runtime,\n models: models.availableModels,\n state: null,\n queue: Promise.resolve(),\n turns: new Set(),\n unsubscribe: () => {},\n commands: [],\n };\n if (this.disposed) throw RequestError.internalError(undefined, 'ACP connection is closed');\n entry.unsubscribe = runtime.session.subscribe(event => {\n handleAgentControllerEvent(event, entry.state, this.connection, entry.session);\n if (event.type === 'mode_changed') {\n void this.connection\n .sessionUpdate({\n sessionId: thread.id,\n update: { sessionUpdate: 'current_mode_update', currentModeId: entry.session.mode.get() },\n })\n .catch(error => process.stderr.write(`[acp] mode update failed: ${error}\\n`));\n }\n if (\n event.type === 'mode_changed' ||\n event.type === 'model_changed' ||\n (event.type === 'state_changed' && event.changedKeys.includes('thinkingLevel'))\n ) {\n void this.connection\n .sessionUpdate({\n sessionId: thread.id,\n update: { sessionUpdate: 'config_option_update', configOptions: this.configOptions(entry) },\n })\n .catch(error => process.stderr.write(`[acp] configuration update failed: ${error}\\n`));\n }\n });\n const response: NewSessionResponse = {\n sessionId: thread.id,\n modes: {\n currentModeId: runtime.session.mode.get(),\n availableModes: runtime.modes.map(mode => ({ id: mode.id, name: mode.name ?? mode.id })),\n },\n models,\n configOptions: this.configOptions(entry),\n };\n this.sessions.set(thread.id, entry);\n // Let the SDK send session/new before clients receive updates for this ID.\n setImmediate(() => {\n void this.enqueue(entry, async () => {\n if (!this.disposed) await this.refreshCommands(thread.id, entry);\n }).catch(error => process.stderr.write(`[acp] command discovery failed: ${error}\\n`));\n });\n return response;\n } catch (error) {\n try {\n await runtime.cleanup?.();\n } catch (cleanupError) {\n if (this.disposed) this.startupCleanupFailures.push(cleanupError);\n throw withCleanupFailure(error, cleanupError);\n }\n throw error;\n }\n }\n\n private async refreshCommands(sessionId: string, entry: SessionEntry): Promise<AcpSkills | undefined> {\n const skills = await entry.getSkills?.();\n const commands = await listSkillCommands(skills);\n if (JSON.stringify(commands) !== JSON.stringify(entry.commands)) {\n await this.connection.sessionUpdate({\n sessionId,\n update: { sessionUpdate: 'available_commands_update', availableCommands: commands },\n });\n entry.commands = commands;\n }\n return skills;\n }\n\n private configOptions(entry: SessionEntry): SessionConfigOption[] {\n const modelId = entry.session.model.get() ?? '';\n const options: SessionConfigOption[] = [];\n const models = includeCurrentModel(entry.models, modelId);\n if (models.length)\n options.push({\n id: 'model',\n name: 'Model',\n category: 'model',\n type: 'select',\n currentValue: modelId,\n options: models.map(model => ({ value: model.modelId, name: model.name })),\n });\n options.push({\n id: 'mode',\n name: 'Mode',\n category: 'mode',\n type: 'select',\n currentValue: entry.session.mode.get(),\n options: entry.modes.map(mode => ({ value: mode.id, name: mode.name ?? mode.id })),\n });\n if (entry.getThinkingLevel)\n options.push({\n id: 'thought_level',\n name: 'Reasoning effort',\n category: 'thought_level',\n type: 'select',\n description: 'Requested reasoning level. The provider may adjust it for the selected model.',\n currentValue: this.thinkingLevel(entry),\n options: getAvailableThinkingLevelsForModel(modelId).map(value => ({\n value,\n name: value[0]!.toUpperCase() + value.slice(1),\n })),\n });\n return options;\n }\n\n private thinkingLevel(entry: SessionEntry, modelId = entry.session.model.get() ?? ''): ThinkingLevelSetting {\n const level = entry.getThinkingLevel?.() ?? 'off';\n const levels = getAvailableThinkingLevelsForModel(modelId);\n return levels.includes(level) ? level : 'xhigh';\n }\n\n async setSessionConfigOption(params: SetSessionConfigOptionRequest): Promise<SetSessionConfigOptionResponse> {\n const entry = this.getSession(params.sessionId);\n return this.enqueue(entry, async () => {\n this.getSession(params.sessionId);\n const option = this.configOptions(entry).find(option => option.id === params.configId);\n if (\n !option ||\n option.type !== 'select' ||\n !option.options.some(item => 'value' in item && item.value === params.value)\n ) {\n throw RequestError.invalidParams(undefined, 'Unknown session configuration selection');\n }\n if (params.configId === 'model') {\n const modelId = String(params.value);\n await entry.session.model.switch(modelId, {\n ...(entry.getThinkingLevel ? { thinkingLevel: this.thinkingLevel(entry, modelId) } : {}),\n });\n } else if (params.configId === 'mode') {\n await entry.session.mode.switch({ modeId: String(params.value) });\n } else if (isThinkingLevelSetting(params.value)) {\n await entry.session.state.set({ thinkingLevel: params.value });\n }\n if (entry.getThinkingLevel && entry.getThinkingLevel() !== this.thinkingLevel(entry)) {\n await entry.session.state.set({ thinkingLevel: this.thinkingLevel(entry) });\n }\n return { configOptions: this.configOptions(entry) };\n });\n }\n\n async prompt(request: PromptRequest): Promise<PromptResponse> {\n const entry = this.getSession(request.sessionId);\n const content = extractTextFromContentBlocks(request.prompt);\n const turn = { cancelled: false };\n entry.turns.add(turn);\n try {\n return await this.enqueue(entry, async () => {\n if (turn.cancelled || this.disposed) return { stopReason: 'cancelled' };\n const usage: PromptState['usage'] = { promptTokens: 0, completionTokens: 0, totalTokens: 0 };\n let complete!: PromptState['resolve'];\n const completion = new Promise<Parameters<PromptState['resolve']>[0]>(resolve => {\n complete = resolve;\n });\n const state: PromptState = {\n sessionId: request.sessionId,\n usage,\n resolve: reason => {\n state.finished = true;\n complete(reason);\n },\n };\n entry.state = state;\n try {\n const skills = await this.refreshCommands(request.sessionId, entry);\n const expanded = await expandSkillCommand(content, skills, entry.commands ?? []);\n if (turn.cancelled || this.disposed) return { stopReason: 'cancelled' };\n await entry.session.sendMessage({ content: expanded });\n const reason = await completion;\n if (reason === 'error' && !state.cancelled && !state.stopReason) {\n throw RequestError.internalError(undefined, state.error?.message ?? 'Mastra Code turn failed');\n }\n return {\n stopReason: state.cancelled ? 'cancelled' : (state.stopReason ?? mapStopReason(reason)),\n usage: {\n inputTokens: usage.promptTokens,\n outputTokens: usage.completionTokens,\n totalTokens: usage.totalTokens,\n thoughtTokens: usage.reasoningTokens,\n cachedReadTokens: usage.cachedInputTokens,\n cachedWriteTokens: usage.cacheCreationInputTokens,\n },\n };\n } catch (error) {\n if (state.cancelled) return { stopReason: 'cancelled' };\n if (error instanceof RequestError) throw error;\n throw RequestError.internalError(\n undefined,\n error instanceof Error ? error.message : 'Mastra Code turn failed',\n );\n } finally {\n state.finished = true;\n if (entry.state === state) entry.state = null;\n }\n });\n } finally {\n entry.turns.delete(turn);\n }\n }\n\n async cancel(notification: CancelNotification): Promise<void> {\n const entry = this.sessions.get(notification.sessionId);\n if (!entry) return;\n for (const turn of entry.turns) turn.cancelled = true;\n if (entry.state && !entry.state.finished && !entry.state.cancelled) {\n const state = entry.state;\n state.cancelled = true;\n // Persist denial before aborting, otherwise a parked snapshot can replay on the next turn.\n for (const deny of state.cancelSuspensions?.values() ?? []) {\n try {\n await deny();\n } catch {\n /* Still abort if the suspended run is no longer available. */\n }\n }\n state.cancelSuspensions?.clear();\n if (entry.state !== state) return;\n entry.session.abort();\n // A suspended run has already ended and will not emit another agent_end.\n if (entry.state?.suspended) {\n entry.session.stream.detach();\n entry.state.resolve('aborted');\n }\n }\n }\n\n async setSessionMode(params: { sessionId: string; modeId: string }): Promise<void> {\n const entry = this.getSession(params.sessionId);\n if (!entry.modes.some(mode => mode.id === params.modeId))\n throw RequestError.invalidParams(undefined, 'Unknown mode');\n await this.enqueue(entry, async () => {\n if (this.disposed) return;\n await entry.session.mode.switch({ modeId: params.modeId });\n });\n }\n\n async unstable_setSessionModel(params: { sessionId: string; modelId: string }): Promise<void> {\n const entry = this.getSession(params.sessionId);\n await this.enqueue(entry, async () => {\n if (this.disposed) return;\n if (\n !includeCurrentModel(entry.models, entry.session.model.get() ?? '').some(\n model => model.modelId === params.modelId,\n )\n ) {\n throw RequestError.invalidParams(\n undefined,\n 'Model is unavailable or its provider is not configured. Refresh the model list.',\n );\n }\n await entry.session.model.switch(params.modelId);\n });\n }\n}\n\nfunction includeCurrentModel(models: SessionEntry['models'], currentModelId: string): SessionEntry['models'] {\n // Saved/custom model IDs may work even when discovery only returns a gateway-qualified alias.\n return currentModelId && !models.some(model => model.modelId === currentModelId)\n ? [{ modelId: currentModelId, name: currentModelId }, ...models]\n : models;\n}\n\nexport function extractTextFromContentBlocks(blocks: ContentBlock[]): string {\n const parts: string[] = [];\n for (const block of blocks) {\n if (block.type === 'text') {\n parts.push(block.text);\n } else if (block.type === 'resource_link') {\n parts.push(`[resource: ${block.uri}]`);\n } else if (block.type === 'resource') {\n parts.push(`[resource: ${block.resource.uri}]`);\n if (!('text' in block.resource))\n throw RequestError.invalidParams(undefined, 'Binary prompt resources are not supported');\n parts.push(block.resource.text);\n } else {\n throw RequestError.invalidParams(undefined, `Unsupported prompt content: ${block.type}`);\n }\n }\n return parts.join('\\n');\n}\n\nexport function mapStopReason(\n reason: 'complete' | 'aborted' | 'error' | 'suspended',\n): 'end_turn' | 'cancelled' | 'max_tokens' | 'max_turn_requests' | 'refusal' {\n switch (reason) {\n case 'complete':\n return 'end_turn';\n case 'aborted':\n return 'cancelled';\n case 'error':\n throw RequestError.internalError(undefined, 'Mastra Code turn failed');\n case 'suspended':\n return 'end_turn';\n }\n}\n"],"mappings":";;;;;;;;;;;AAqDA,MAAM,2BAA2B;AACjC,MAAM,6BAA6B;CAAC;CAAgB;CAAmB;AAAK;AAC5E,MAAM,8BAA8B,CAAC,aAAa,gBAAgB;AAElE,SAAS,cAAc,IAAY,MAAc,aAAqB,WAAiC;CACrG,OAAO;EACL;EACA;EACA;EACA,MAAM;EACN,MAAM;EACN,OAAO,EACL,iBAAiB;GACf,SAAS,QAAQ;GACjB,MAAM,CAAC,GAAG,QAAQ,KAAK,MAAM,GAAG,CAAC,GAAG,GAAG,SAAS;GAChD,OAAO;EACT,EACF;CACF;AACF;AAEA,SAAS,gBAAgB,EAAE,MAAM,UAAmD,CAAC,GAAiB;CACpG,MAAM,YAAY,kBAAkB;CACpC,MAAM,UAAwB,UAC3B,QAAO,aAAY,2BAA2B,SAAS,SAAS,EAAE,CAAC,CAAC,CACpE,KAAI,cAAa;EAChB,IAAI,SAAS;EACb,MAAM,eAAe,SAAS;EAC9B,aA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AAY,cAAc,IAC3E,CAAC;EAAE,SAAS;EAAgB,MAAM;CAAe,GAAG,GAAG,MAAM,IAC7D;AACN;AAEA,SAAgB,6BAA6B,QAAgC;CAC3E,MAAM,QAAkB,CAAC;CACzB,KAAK,MAAM,SAAS,QAClB,IAAI,MAAM,SAAS,QACjB,MAAM,KAAK,MAAM,IAAI;MAChB,IAAI,MAAM,SAAS,iBACxB,MAAM,KAAK,cAAc,MAAM,IAAI,EAAE;MAChC,IAAI,MAAM,SAAS,YAAY;EACpC,MAAM,KAAK,cAAc,MAAM,SAAS,IAAI,EAAE;EAC9C,IAAI,EAAE,UAAU,MAAM,WACpB,MAAM,aAAa,cAAc,KAAA,GAAW,2CAA2C;EACzF,MAAM,KAAK,MAAM,SAAS,IAAI;CAChC,OACE,MAAM,aAAa,cAAc,KAAA,GAAW,+BAA+B,MAAM,MAAM;CAG3F,OAAO,MAAM,KAAK,IAAI;AACxB;AAEA,SAAgB,cACd,QAC2E;CAC3E,QAAQ,QAAR;EACE,KAAK,YACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,SACH,MAAM,aAAa,cAAc,KAAA,GAAW,yBAAyB;EACvE,KAAK,aACH,OAAO;CACX;AACF"}
@@ -24,7 +24,9 @@ export declare function hasSubconsciousTools(vector: MastraVector | undefined, s
24
24
  * Reads OM thresholds from controller state via requestContext.
25
25
  * Model functions also read from requestContext (no mutable bridge needed).
26
26
  */
27
- export declare function getDynamicMemory(storage: MastraCompositeStore, vector?: MastraVector, settingsPath?: string): ({ requestContext }: {
27
+ export declare function getDynamicMemory(storage: MastraCompositeStore, vector?: MastraVector, settingsPath?: string, options?: {
28
+ disableSettingsOmSeed?: boolean;
29
+ }): ({ requestContext }: {
28
30
  requestContext: RequestContext;
29
31
  }) => Memory;
30
32
  //# sourceMappingURL=memory.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../src/agents/memory.ts"],"names":[],"mappings":"AAEA,OAAO,K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G;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,YAAY,GAAG,SAAS,GAAG,OAAO,CAE/E;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,YAAY,GAAG,SAAS,EAAE,KAAK,EAAE,eAAe,GAAG,SAAS,GAAG,OAAO,CAElH;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,oBAAoB,EAC7B,MAAM,CAAC,EAAE,YAAY,EACrB,YAAY,CAAC,EAAE,MAAM,EACrB,OAAO,CAAC,EAAE;IAAE,qBAAqB,CAAC,EAAE,OAAO,CAAA;CAAE,IAgBrC,oBAAoB;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,YA0G/D"}
@@ -3,21 +3,12 @@ import { getOmScope } from "../utils/project.js";
3
3
  import { loadSettings } from "../onboarding/settings.js";
4
4
  import { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeScopeIdentity } from "../knowledge-scope.js";
5
5
  import "../providers/anthropic-prompt-cache.js";
6
- import { resolveModel, resolvePackMemoryModelChain } from "./model.js";
6
+ import { resolveModel } from "./model.js";
7
7
  import { fastembed } from "@mastra/fastembed";
8
8
  import { Memory, Subconscious } from "@mastra/memory";
9
9
  //#region src/agents/memory.ts
10
- /**
11
- * Resolve one OM role's model for this invocation. Lookup order:
12
- * 1. The explicit role override (`observerModelOverride` / `reflectorModelOverride`).
13
- * 2. The active mode pack's optional `models.memory`, walking the pack's fallback
14
- * chain so OM fails over alongside (and independently of) the main agent.
15
- * The pending pack-hop marker wins over the settled pack id so an immediate
16
- * retrigger observes on the landed pack.
17
- * 3. The standalone OM configuration seeded into controller state
18
- * (`observerModelId` / `reflectorModelId`), then the default OM model.
19
- */
20
- function resolveOmRoleModelForRequest(role, requestContext, settingsPath) {
10
+ /** Resolve one OM role's model for this invocation. */
11
+ function resolveOmRoleModelForRequest(role, requestContext, settingsPath, options) {
21
12
  const controller = requestContext.get("controller");
22
13
  const state = controller?.getState();
23
14
  const resolveOptions = {
@@ -25,15 +16,35 @@ function resolveOmRoleModelForRequest(role, requestContext, settingsPath) {
25
16
  requestContext,
26
17
  anthropicPromptCacheScope: "system"
27
18
  };
28
- const settings = loadSettings(settingsPath);
29
- const roleOverride = role === "observer" ? settings.models?.observerModelOverride : settings.models?.reflectorModelOverride;
30
- if (roleOverride) return resolveModel(roleOverride, resolveOptions);
31
- const pendingState = state?.mastracodePendingPackFallback;
32
- const packId = (pendingState && (pendingState.threadId === void 0 || pendingState.threadId === controller?.threadId) && typeof pendingState.toPackId === "string" && pendingState.toPackId.length > 0 ? pendingState.toPackId : void 0) ?? state?.activeModelPackId ?? settings.models?.activeModelPackId;
33
- if (typeof packId === "string" && packId.length > 0) {
34
- const chained = resolvePackMemoryModelChain(settings, packId, resolveOptions);
35
- if (chained) return chained;
19
+ if (!options?.disableSettingsOmSeed) {
20
+ const settings = loadSettings(settingsPath);
21
+ const roleOverride = role === "observer" ? settings.models?.observerModelOverride : settings.models?.reflectorModelOverride;
22
+ if (roleOverride) return resolveModel(roleOverride, resolveOptions);
23
+ }
24
+ const pending = state?.mastracodePendingModelFallback;
25
+ const sameThreadPending = pending && (pending.threadId === void 0 || pending.threadId === controller?.threadId) ? pending : void 0;
26
+ const routeEntries = state?.modelRoute?.entries?.slice(0, 32) ?? [];
27
+ const pendingIndex = sameThreadPending ? routeEntries.findIndex((entry) => entry.id === sameThreadPending.toEntryId) : -1;
28
+ const memoryRoute = pendingIndex >= 0 ? routeEntries.slice(pendingIndex) : routeEntries;
29
+ const seenModelIds = /* @__PURE__ */ new Set();
30
+ const appearances = /* @__PURE__ */ new Map();
31
+ const entries = [];
32
+ for (const entry of memoryRoute) {
33
+ if (!entry.memoryModelId || seenModelIds.has(entry.memoryModelId)) continue;
34
+ seenModelIds.add(entry.memoryModelId);
35
+ const occurrence = (appearances.get(entry.id) ?? 0) + 1;
36
+ appearances.set(entry.id, occurrence);
37
+ try {
38
+ entries.push({
39
+ id: `${entry.id}:memory${occurrence === 1 ? "" : `#${occurrence}`}`,
40
+ model: resolveModel(entry.memoryModelId, resolveOptions)
41
+ });
42
+ } catch {
43
+ break;
44
+ }
36
45
  }
46
+ if (entries.length === 1) return entries[0].model;
47
+ if (entries.length > 1) return entries;
37
48
  return resolveModel((role === "observer" ? state?.observerModelId : state?.reflectorModelId) ?? DEFAULT_OM_MODEL_ID, resolveOptions);
38
49
  }
39
50
  const DYNAMIC_AGENTS_MD_INSTRUCTION = "Messages wrapped in <system-reminder type=\"dynamic-agents-md\" ...>...</system-reminder> are ephemeral project-context instructions injected from files on disk. Do NOT observe or extract information from these messages — they are reloaded automatically when needed and should not be stored in memory.";
@@ -94,11 +105,11 @@ function hasSubconsciousTools(vector, state) {
94
105
  * Reads OM thresholds from controller state via requestContext.
95
106
  * Model functions also read from requestContext (no mutable bridge needed).
96
107
  */
97
- function getDynamicMemory(storage, vector, settingsPath) {
108
+ function getDynamicMemory(storage, vector, settingsPath, options) {
98
109
  let cachedMemory = null;
99
110
  let cachedMemoryKey = null;
100
- const getObserverModel = ({ requestContext }) => resolveOmRoleModelForRequest("observer", requestContext, settingsPath);
101
- const getReflectorModel = ({ requestContext }) => resolveOmRoleModelForRequest("reflector", requestContext, settingsPath);
111
+ const getObserverModel = ({ requestContext }) => resolveOmRoleModelForRequest("observer", requestContext, settingsPath, options);
112
+ const getReflectorModel = ({ requestContext }) => resolveOmRoleModelForRequest("reflector", requestContext, settingsPath, options);
102
113
  return ({ requestContext }) => {
103
114
  const controller = requestContext.get("controller");
104
115
  const state = controller?.getState();
@@ -1 +1 @@
1
- {"version":3,"file":"memory.js","names":[],"sources":["../../src/agents/memory.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { GatewayLanguageModel } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { fastembed } from '@mastra/fastembed';\nimport { Memory, Subconscious } from '@mastra/memory';\nimport { DEFAULT_OM_MODEL_ID, DEFAULT_OBS_THRESHOLD, DEFAULT_REF_THRESHOLD } from '../constants.js';\nimport { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeScopeIdentity } from '../knowledge-scope.js';\nimport { loadSettings } from '../onboarding/settings.js';\nimport { ANTHROPIC_PROMPT_CACHE_TTL } from '../providers/anthropic-prompt-cache.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { getOmScope } from '../utils/project.js';\nimport { resolveModel, resolvePackMemoryModelChain } from './model.js';\nimport type { PackMemoryModelChainEntry } from './model.js';\n\n/**\n * Resolve one OM role's model for this invocation. Lookup order:\n * 1. The explicit role override (`observerModelOverride` / `reflectorModelOverride`).\n * 2. The active mode pack's optional `models.memory`, walking the pack's fallback\n * chain so OM fails over alongside (and independently of) the main agent.\n * The pending pack-hop marker wins over the settled pack id so an immediate\n * retrigger observes on the landed pack.\n * 3. The standalone OM configuration seeded into controller state\n * (`observerModelId` / `reflectorModelId`), then the default OM model.\n */\nfunction resolveOmRoleModelForRequest(\n role: 'observer' | 'reflector',\n requestContext: RequestContext,\n settingsPath?: string,\n): GatewayLanguageModel | PackMemoryModelChainEntry[] {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n // OM calls send different content every time, so only their shared instructions are worth caching.\n const resolveOptions = { remapForCodexOAuth: true, requestContext, anthropicPromptCacheScope: 'system' } as const;\n\n // The configured settings file, not the default one: a caller that points the\n // agent at another settings path must get the same pack/override resolution\n // for observational memory as it does for the main model.\n const settings = loadSettings(settingsPath);\n const roleOverride =\n role === 'observer' ? settings.models?.observerModelOverride : settings.models?.reflectorModelOverride;\n if (roleOverride) return resolveModel(roleOverride, resolveOptions);\n\n const pendingState = state?.mastracodePendingPackFallback as\n | { toPackId?: unknown; threadId?: unknown }\n | null\n | undefined;\n const pendingPackId =\n pendingState &&\n (pendingState.threadId === undefined || pendingState.threadId === controller?.threadId) &&\n typeof pendingState.toPackId === 'string' &&\n pendingState.toPackId.length > 0\n ? pendingState.toPackId\n : undefined;\n const packId = pendingPackId ?? state?.activeModelPackId ?? settings.models?.activeModelPackId;\n if (typeof packId === 'string' && packId.length > 0) {\n const chained = resolvePackMemoryModelChain(settings, packId, resolveOptions);\n if (chained) return chained;\n }\n\n const stateModelId = role === 'observer' ? state?.observerModelId : state?.reflectorModelId;\n return resolveModel(stateModelId ?? DEFAULT_OM_MODEL_ID, resolveOptions);\n}\n\nconst DYNAMIC_AGENTS_MD_INSTRUCTION =\n 'Messages wrapped in <system-reminder type=\"dynamic-agents-md\" ...>...</system-reminder> are ephemeral project-context instructions injected from files on disk. Do NOT observe or extract information from these messages — they are reloaded automatically when needed and should not be stored in memory.';\n\n// Derived from https://github.com/JuliusBrussee/caveman and adapted for OM use with fixed full-level compression.\nconst CAVEMAN_OM_INSTRUCTION = `Respond terse like smart caveman. All technical substance stay. Only fluff die.\n\nUse full caveman compression style.\n\nDrop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not \"implement a solution for\"). Technical terms exact. Code blocks unchanged. Errors quoted exact. Leave out the words \"agent\" and \"assistant\" at the start of each observation line, it is assumed each line is referring to the assistant unless it specifically says it was about the user. Leave out parenthesis and other text characters like * that would not contribute to understanding the observations.\n\nPattern: \\`[thing] [action] [reason]. [next step]\\`\n\nNot: \"Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by...\"\nYes: \"Bug in auth middleware. Token expiry check use < not <=. Fix:\"\n\nExample 1\n🔴 14:31 user asks why React component rerenders\n🟡 14:32 saw inline object prop create new ref each render, cause rerender\n✅ 14:34 fixed render issue by wrap object in useMemo\n\nExample 2\n🟡 15:10 explained pool reuse DB connections, skip repeat handshake overhead\n\nDon't say \"Agent did x\", say \"did x\". It will be assumed the agent did what was observed. The who should only be specified for the user or other third parties: \"user asked x\"\n\nDrop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question, and anything that requires remembering verbatim content. Resume caveman after clear part done`;\n\nexport { LOCAL_KNOWLEDGE_ORG_ID };\n\n// One error per session, not per memory resolution. Keyed on the session id\n// rather than the controller object: the controller is read off the request\n// context on every resolution, so it is a fresh object per request and would\n// dedupe nothing. Bounded so a long-running Factory process cannot grow this\n// without limit — refusing sessions are rare, and losing the oldest ids only\n// costs one extra log line.\nconst REPORTED_ORG_UNRESOLVED_LIMIT = 500;\nconst reportedOrgUnresolved = new Set<string>();\n\nfunction reportOrgUnresolved(\n controller: AgentControllerRequestContext<MastraCodeState> | undefined,\n factoryProjectId: string | undefined,\n reason?: string,\n) {\n const sessionId = controller?.session?.id;\n if (sessionId) {\n if (reportedOrgUnresolved.has(sessionId)) return;\n if (reportedOrgUnresolved.size >= REPORTED_ORG_UNRESOLVED_LIMIT) {\n reportedOrgUnresolved.delete(reportedOrgUnresolved.values().next().value as string);\n }\n reportedOrgUnresolved.add(sessionId);\n }\n const session = controller?.session;\n console.error(\n `[Subconscious] Knowledge curation disabled: no organization resolved for session ${session?.id ?? 'unknown'} (project ${factoryProjectId ?? 'none'})${reason ? `: ${reason}` : ''}. Knowledge is not written rather than written where it cannot be read.`,\n );\n}\n\n/**\n * Whether the experimental subconscious (knowledge graph + reminder sidekick)\n * is switched on for this process: it needs a vector store and the opt-in flag.\n */\nexport function isSubconsciousEnabled(vector: MastraVector | undefined): boolean {\n return Boolean(vector) && process.env.MASTRACODE_EXPERIMENTAL_SUBCONSCIOUS === '1';\n}\n\n/**\n * Whether the subconscious tools (`knowledge_*`, `ask_memory`) are registered\n * for a given session. Beyond the process-level switch, a Factory-owned\n * session that cannot resolve its org refuses the subconscious entirely (see\n * `getDynamicMemory`, which applies the same two checks inline because it also\n * needs the resolved identity). The system prompt's tool guidance calls here so\n * it never advertises tools that `getDynamicMemory` did not register.\n */\nexport function hasSubconsciousTools(vector: MastraVector | undefined, state: MastraCodeState | undefined): boolean {\n return isSubconsciousEnabled(vector) && resolveKnowledgeScopeIdentity(state).resolved;\n}\n\n/**\n * Dynamic memory factory function.\n * Reads OM thresholds from controller state via requestContext.\n * Model functions also read from requestContext (no mutable bridge needed).\n */\nexport function getDynamicMemory(storage: MastraCompositeStore, vector?: MastraVector, settingsPath?: string) {\n // Cache is scoped per storage instance (per getDynamicMemory call) so a\n // Memory bound to one storage is never reused after storage changes.\n let cachedMemory: Memory | null = null;\n let cachedMemoryKey: string | null = null;\n\n // Observer/reflector model functions — read the current model ID from\n // controller state via requestContext (propagated by OM's agent.generate).\n // Bound here so the configured settings path reaches role overrides and pack\n // memory-model resolution.\n const getObserverModel = ({ requestContext }: { requestContext: RequestContext }) =>\n resolveOmRoleModelForRequest('observer', requestContext, settingsPath);\n const getReflectorModel = ({ requestContext }: { requestContext: RequestContext }) =>\n resolveOmRoleModelForRequest('reflector', requestContext, settingsPath);\n\n return ({ requestContext }: { requestContext: RequestContext }) => {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n const subconsciousEnabled = isSubconsciousEnabled(vector);\n const factoryProjectId = state?.factoryProjectId;\n const isFactory = typeof factoryProjectId === 'string' && factoryProjectId.trim().length > 0;\n\n // A Factory-owned session that could not resolve its org refuses to curate:\n // writing under a substituted identity produces knowledge the fail-closed\n // read path can never see.\n let orgUnresolvedRefusal = false;\n\n if (subconsciousEnabled) {\n const identity = resolveKnowledgeScopeIdentity(state);\n if (identity.resolved) {\n requestContext.set('organizationId', identity.organizationId);\n } else {\n orgUnresolvedRefusal = true;\n reportOrgUnresolved(controller, identity.knowledgeResourceId, identity.reason);\n }\n if (identity.knowledgeResourceId) {\n requestContext.set('knowledgeResourceId', identity.knowledgeResourceId);\n }\n }\n\n const subconsciousAvailable = subconsciousEnabled && !orgUnresolvedRefusal;\n\n const omScope = state?.omScope ?? getOmScope(state?.projectPath);\n\n const obsThreshold = state?.observationThreshold ?? DEFAULT_OBS_THRESHOLD;\n const refThreshold = state?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD;\n const caveman = state?.cavemanObservations ?? false;\n\n const observerPreviousObservationTokens = 1000;\n const observeAttachments = state?.observeAttachments;\n // Factory sessions get a factory-only Subconscious config, so the cache key\n // carries a factory presence bit to keep the two configs from cross-serving.\n const cacheKey = `${obsThreshold}:${refThreshold}:${omScope}:${observerPreviousObservationTokens}:${caveman ? 1 : 0}:${observeAttachments}:${isFactory ? 1 : 0}:${subconsciousAvailable ? 1 : 0}`;\n if (cachedMemory && cachedMemoryKey === cacheKey) {\n return cachedMemory;\n }\n\n // Async buffering is not supported with resource scope — disable it\n const isResourceScope = omScope === 'resource';\n\n const observerInstruction = caveman\n ? `${DYNAMIC_AGENTS_MD_INSTRUCTION}\\n\\n${CAVEMAN_OM_INSTRUCTION}`\n : DYNAMIC_AGENTS_MD_INSTRUCTION;\n const reflectionInstruction = caveman ? CAVEMAN_OM_INSTRUCTION : undefined;\n\n cachedMemory = new Memory({\n storage,\n vector: vector || false,\n embedder: vector ? fastembed.small : undefined,\n options: {\n // Generate a durable title from the first user message. Every client uses\n // the same title in its thread list and active-session chrome. Title\n // generation takes the primary OM model only — its model field does not\n // accept fallback arrays.\n generateTitle: {\n model: ({ requestContext }) => {\n const resolved = getObserverModel({ requestContext });\n return Array.isArray(resolved) ? resolved[0]!.model : resolved;\n },\n },\n observationalMemory: {\n enabled: true,\n temporalMarkers: true,\n retrieval: vector ? { vector: true } : true,\n experimental_subconscious: subconsciousAvailable\n ? new Subconscious({\n defaultScope: 'resource',\n maxScope: 'resource',\n pins: true,\n ...(isFactory ? { maxSteps: 25 } : {}),\n })\n : undefined,\n scope: omScope,\n // The main agent writes Anthropic cache entries with this TTL; 'auto' can't see it.\n activateAfterIdle: { default: 'auto', anthropic: ANTHROPIC_PROMPT_CACHE_TTL },\n activateOnProviderChange: true,\n observation: {\n bufferTokens: isResourceScope ? false : 1 / 5,\n bufferActivation: isResourceScope ? undefined : 2000,\n model: getObserverModel,\n messageTokens: obsThreshold,\n blockAfter: 2,\n previousObserverTokens: observerPreviousObservationTokens,\n threadTitle: true,\n instruction: observerInstruction,\n observeAttachments,\n },\n reflection: {\n bufferActivation: isResourceScope ? undefined : 1 / 2,\n blockAfter: 1.1,\n model: getReflectorModel,\n observationTokens: refThreshold,\n instruction: reflectionInstruction,\n },\n },\n },\n });\n cachedMemoryKey = cacheKey;\n\n return cachedMemory;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA0BA,SAAS,6BACP,MACA,gBACA,cACoD;CACpD,MAAM,aAAa,eAAe,IAAI,YAAY;CAClD,MAAM,QAAQ,YAAY,SAAS;CAEnC,MAAM,iBAAiB;EAAE,oBAAoB;EAAM;EAAgB,2BAA2B;CAAS;CAKvG,MAAM,WAAW,aAAa,YAAY;CAC1C,MAAM,eACJ,SAAS,aAAa,SAAS,QAAQ,wBAAwB,SAAS,QAAQ;CAClF,IAAI,cAAc,OAAO,aAAa,cAAc,cAAc;CAElE,MAAM,eAAe,OAAO;CAW5B,MAAM,UANJ,iBACC,aAAa,aAAa,KAAA,KAAa,aAAa,aAAa,YAAY,aAC9E,OAAO,aAAa,aAAa,YACjC,aAAa,SAAS,SAAS,IAC3B,aAAa,WACb,KAAA,MAC0B,OAAO,qBAAqB,SAAS,QAAQ;CAC7E,IAAI,OAAO,WAAW,YAAY,OAAO,SAAS,GAAG;EACnD,MAAM,UAAU,4BAA4B,UAAU,QAAQ,cAAc;EAC5E,IAAI,SAAS,OAAO;CACtB;CAGA,OAAO,cADc,SAAS,aAAa,OAAO,kBAAkB,OAAO,qBACvC,qBAAqB,cAAc;AACzE;AAEA,MAAM,gCACJ;AAGF,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;;;;;AA+B/B,MAAM,gCAAgC;AACtC,MAAM,wCAAwB,IAAI,IAAY;AAE9C,SAAS,oBACP,YACA,kBACA,QACA;CACA,MAAM,YAAY,YAAY,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;MACZ,wBAAwB;MACxB,aAAa;MACb,aAAa;MACb;KACF;KACA,YAAY;MACV,kBAAkB,kBAAkB,KAAA,IAAY,IAAI;MACpD,YAAY;MACZ,OAAO;MACP,mBAAmB;MACnB,aAAa;KACf;IACF;GACF;EACF,CAAC;EACD,kBAAkB;EAElB,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"memory.js","names":[],"sources":["../../src/agents/memory.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { GatewayLanguageModel } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { fastembed } from '@mastra/fastembed';\nimport { Memory, Subconscious } from '@mastra/memory';\nimport {\n DEFAULT_OM_MODEL_ID,\n DEFAULT_OBS_THRESHOLD,\n DEFAULT_REF_THRESHOLD,\n MODEL_ROUTE_MAX_ENTRIES,\n} from '../constants.js';\nimport { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeScopeIdentity } from '../knowledge-scope.js';\nimport { loadSettings } from '../onboarding/settings.js';\nimport { ANTHROPIC_PROMPT_CACHE_TTL } from '../providers/anthropic-prompt-cache.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { getOmScope } from '../utils/project.js';\nimport { resolveModel } from './model.js';\n\n/** Route-backed OM fallback entry. */\ntype MemoryModelRouteEntry = { id: string; model: GatewayLanguageModel };\n\n/** Resolve one OM role's model for this invocation. */\nfunction resolveOmRoleModelForRequest(\n role: 'observer' | 'reflector',\n requestContext: RequestContext,\n settingsPath?: string,\n options?: { disableSettingsOmSeed?: boolean },\n): GatewayLanguageModel | MemoryModelRouteEntry[] {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n const resolveOptions = { remapForCodexOAuth: true, requestContext, anthropicPromptCacheScope: 'system' } as const;\n\n if (!options?.disableSettingsOmSeed) {\n const settings = loadSettings(settingsPath);\n const roleOverride =\n role === 'observer' ? settings.models?.observerModelOverride : settings.models?.reflectorModelOverride;\n if (roleOverride) return resolveModel(roleOverride, resolveOptions);\n }\n\n const pending = state?.mastracodePendingModelFallback;\n const sameThreadPending =\n pending && (pending.threadId === undefined || pending.threadId === controller?.threadId) ? pending : undefined;\n const routeEntries = state?.modelRoute?.entries?.slice(0, MODEL_ROUTE_MAX_ENTRIES) ?? [];\n const pendingIndex = sameThreadPending\n ? routeEntries.findIndex(entry => entry.id === sameThreadPending.toEntryId)\n : -1;\n const memoryRoute = pendingIndex >= 0 ? routeEntries.slice(pendingIndex) : routeEntries;\n const seenModelIds = new Set<string>();\n const appearances = new Map<string, number>();\n const entries: MemoryModelRouteEntry[] = [];\n for (const entry of memoryRoute) {\n if (!entry.memoryModelId || seenModelIds.has(entry.memoryModelId)) continue;\n seenModelIds.add(entry.memoryModelId);\n const occurrence = (appearances.get(entry.id) ?? 0) + 1;\n appearances.set(entry.id, occurrence);\n try {\n entries.push({\n id: `${entry.id}:memory${occurrence === 1 ? '' : `#${occurrence}`}`,\n model: resolveModel(entry.memoryModelId, resolveOptions),\n });\n } catch {\n break;\n }\n }\n if (entries.length === 1) return entries[0]!.model;\n if (entries.length > 1) return entries;\n\n const stateModelId = role === 'observer' ? state?.observerModelId : state?.reflectorModelId;\n return resolveModel(stateModelId ?? DEFAULT_OM_MODEL_ID, resolveOptions);\n}\n\nconst DYNAMIC_AGENTS_MD_INSTRUCTION =\n 'Messages wrapped in <system-reminder type=\"dynamic-agents-md\" ...>...</system-reminder> are ephemeral project-context instructions injected from files on disk. Do NOT observe or extract information from these messages — they are reloaded automatically when needed and should not be stored in memory.';\n\n// Derived from https://github.com/JuliusBrussee/caveman and adapted for OM use with fixed full-level compression.\nconst CAVEMAN_OM_INSTRUCTION = `Respond terse like smart caveman. All technical substance stay. Only fluff die.\n\nUse full caveman compression style.\n\nDrop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not \"implement a solution for\"). Technical terms exact. Code blocks unchanged. Errors quoted exact. Leave out the words \"agent\" and \"assistant\" at the start of each observation line, it is assumed each line is referring to the assistant unless it specifically says it was about the user. Leave out parenthesis and other text characters like * that would not contribute to understanding the observations.\n\nPattern: \\`[thing] [action] [reason]. [next step]\\`\n\nNot: \"Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by...\"\nYes: \"Bug in auth middleware. Token expiry check use < not <=. Fix:\"\n\nExample 1\n🔴 14:31 user asks why React component rerenders\n🟡 14:32 saw inline object prop create new ref each render, cause rerender\n✅ 14:34 fixed render issue by wrap object in useMemo\n\nExample 2\n🟡 15:10 explained pool reuse DB connections, skip repeat handshake overhead\n\nDon't say \"Agent did x\", say \"did x\". It will be assumed the agent did what was observed. The who should only be specified for the user or other third parties: \"user asked x\"\n\nDrop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question, and anything that requires remembering verbatim content. Resume caveman after clear part done`;\n\nexport { LOCAL_KNOWLEDGE_ORG_ID };\n\n// One error per session, not per memory resolution. Keyed on the session id\n// rather than the controller object: the controller is read off the request\n// context on every resolution, so it is a fresh object per request and would\n// dedupe nothing. Bounded so a long-running Factory process cannot grow this\n// without limit — refusing sessions are rare, and losing the oldest ids only\n// costs one extra log line.\nconst REPORTED_ORG_UNRESOLVED_LIMIT = 500;\nconst reportedOrgUnresolved = new Set<string>();\n\nfunction reportOrgUnresolved(\n controller: AgentControllerRequestContext<MastraCodeState> | undefined,\n factoryProjectId: string | undefined,\n reason?: string,\n) {\n const sessionId = controller?.session?.id;\n if (sessionId) {\n if (reportedOrgUnresolved.has(sessionId)) return;\n if (reportedOrgUnresolved.size >= REPORTED_ORG_UNRESOLVED_LIMIT) {\n reportedOrgUnresolved.delete(reportedOrgUnresolved.values().next().value as string);\n }\n reportedOrgUnresolved.add(sessionId);\n }\n const session = controller?.session;\n console.error(\n `[Subconscious] Knowledge curation disabled: no organization resolved for session ${session?.id ?? 'unknown'} (project ${factoryProjectId ?? 'none'})${reason ? `: ${reason}` : ''}. Knowledge is not written rather than written where it cannot be read.`,\n );\n}\n\n/**\n * Whether the experimental subconscious (knowledge graph + reminder sidekick)\n * is switched on for this process: it needs a vector store and the opt-in flag.\n */\nexport function isSubconsciousEnabled(vector: MastraVector | undefined): boolean {\n return Boolean(vector) && process.env.MASTRACODE_EXPERIMENTAL_SUBCONSCIOUS === '1';\n}\n\n/**\n * Whether the subconscious tools (`knowledge_*`, `ask_memory`) are registered\n * for a given session. Beyond the process-level switch, a Factory-owned\n * session that cannot resolve its org refuses the subconscious entirely (see\n * `getDynamicMemory`, which applies the same two checks inline because it also\n * needs the resolved identity). The system prompt's tool guidance calls here so\n * it never advertises tools that `getDynamicMemory` did not register.\n */\nexport function hasSubconsciousTools(vector: MastraVector | undefined, state: MastraCodeState | undefined): boolean {\n return isSubconsciousEnabled(vector) && resolveKnowledgeScopeIdentity(state).resolved;\n}\n\n/**\n * Dynamic memory factory function.\n * Reads OM thresholds from controller state via requestContext.\n * Model functions also read from requestContext (no mutable bridge needed).\n */\nexport function getDynamicMemory(\n storage: MastraCompositeStore,\n vector?: MastraVector,\n settingsPath?: string,\n options?: { disableSettingsOmSeed?: boolean },\n) {\n // Cache is scoped per storage instance (per getDynamicMemory call) so a\n // Memory bound to one storage is never reused after storage changes.\n let cachedMemory: Memory | null = null;\n let cachedMemoryKey: string | null = null;\n\n // Observer/reflector model functions — read the current model ID from\n // controller state via requestContext (propagated by OM's agent.generate).\n // Bound here so the configured settings path reaches role overrides and pack\n // memory-model resolution.\n const getObserverModel = ({ requestContext }: { requestContext: RequestContext }) =>\n resolveOmRoleModelForRequest('observer', requestContext, settingsPath, options);\n const getReflectorModel = ({ requestContext }: { requestContext: RequestContext }) =>\n resolveOmRoleModelForRequest('reflector', requestContext, settingsPath, options);\n\n return ({ requestContext }: { requestContext: RequestContext }) => {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n const subconsciousEnabled = isSubconsciousEnabled(vector);\n const factoryProjectId = state?.factoryProjectId;\n const isFactory = typeof factoryProjectId === 'string' && factoryProjectId.trim().length > 0;\n\n // A Factory-owned session that could not resolve its org refuses to curate:\n // writing under a substituted identity produces knowledge the fail-closed\n // read path can never see.\n let orgUnresolvedRefusal = false;\n\n if (subconsciousEnabled) {\n const identity = resolveKnowledgeScopeIdentity(state);\n if (identity.resolved) {\n requestContext.set('organizationId', identity.organizationId);\n } else {\n orgUnresolvedRefusal = true;\n reportOrgUnresolved(controller, identity.knowledgeResourceId, identity.reason);\n }\n if (identity.knowledgeResourceId) {\n requestContext.set('knowledgeResourceId', identity.knowledgeResourceId);\n }\n }\n\n const subconsciousAvailable = subconsciousEnabled && !orgUnresolvedRefusal;\n\n const omScope = state?.omScope ?? getOmScope(state?.projectPath);\n\n const obsThreshold = state?.observationThreshold ?? DEFAULT_OBS_THRESHOLD;\n const refThreshold = state?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD;\n const caveman = state?.cavemanObservations ?? false;\n\n const observerPreviousObservationTokens = 1000;\n const observeAttachments = state?.observeAttachments;\n // Factory sessions get a factory-only Subconscious config, so the cache key\n // carries a factory presence bit to keep the two configs from cross-serving.\n const cacheKey = `${obsThreshold}:${refThreshold}:${omScope}:${observerPreviousObservationTokens}:${caveman ? 1 : 0}:${observeAttachments}:${isFactory ? 1 : 0}:${subconsciousAvailable ? 1 : 0}`;\n if (cachedMemory && cachedMemoryKey === cacheKey) {\n return cachedMemory;\n }\n\n // Async buffering is not supported with resource scope — disable it\n const isResourceScope = omScope === 'resource';\n\n const observerInstruction = caveman\n ? `${DYNAMIC_AGENTS_MD_INSTRUCTION}\\n\\n${CAVEMAN_OM_INSTRUCTION}`\n : DYNAMIC_AGENTS_MD_INSTRUCTION;\n const reflectionInstruction = caveman ? CAVEMAN_OM_INSTRUCTION : undefined;\n\n cachedMemory = new Memory({\n storage,\n vector: vector || false,\n embedder: vector ? fastembed.small : undefined,\n options: {\n // Generate a durable title from the first user message. Every client uses\n // the same title in its thread list and active-session chrome. Title\n // generation takes the primary OM model only — its model field does not\n // accept fallback arrays.\n generateTitle: {\n model: ({ requestContext }) => {\n const resolved = getObserverModel({ requestContext });\n return Array.isArray(resolved) ? resolved[0]!.model : resolved;\n },\n },\n observationalMemory: {\n enabled: true,\n temporalMarkers: true,\n retrieval: vector ? { vector: true } : true,\n experimental_subconscious: subconsciousAvailable\n ? new Subconscious({\n defaultScope: 'resource',\n maxScope: 'resource',\n pins: true,\n ...(isFactory ? { maxSteps: 25 } : {}),\n })\n : undefined,\n scope: omScope,\n // The main agent writes Anthropic cache entries with this TTL; 'auto' can't see it.\n activateAfterIdle: { default: 'auto', anthropic: ANTHROPIC_PROMPT_CACHE_TTL },\n activateOnProviderChange: true,\n observation: {\n bufferTokens: isResourceScope ? false : 1 / 5,\n bufferActivation: isResourceScope ? undefined : 2000,\n model: getObserverModel,\n messageTokens: obsThreshold,\n blockAfter: 2,\n previousObserverTokens: observerPreviousObservationTokens,\n threadTitle: true,\n instruction: observerInstruction,\n observeAttachments,\n },\n reflection: {\n bufferActivation: isResourceScope ? undefined : 1 / 2,\n blockAfter: 1.1,\n model: getReflectorModel,\n observationTokens: refThreshold,\n instruction: reflectionInstruction,\n },\n },\n },\n });\n cachedMemoryKey = cacheKey;\n\n return cachedMemory;\n };\n}\n"],"mappings":";;;;;;;;;;AAwBA,SAAS,6BACP,MACA,gBACA,cACA,SACgD;CAChD,MAAM,aAAa,eAAe,IAAI,YAAY;CAClD,MAAM,QAAQ,YAAY,SAAS;CACnC,MAAM,iBAAiB;EAAE,oBAAoB;EAAM;EAAgB,2BAA2B;CAAS;CAEvG,IAAI,CAAC,SAAS,uBAAuB;EACnC,MAAM,WAAW,aAAa,YAAY;EAC1C,MAAM,eACJ,SAAS,aAAa,SAAS,QAAQ,wBAAwB,SAAS,QAA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b;KACF;KACA,YAAY;MACV,kBAAkB,kBAAkB,KAAA,IAAY,IAAI;MACpD,YAAY;MACZ,OAAO;MACP,mBAAmB;MACnB,aAAa;KACf;IACF;GACF;EACF,CAAC;EACD,kBAAkB;EAElB,OAAO;CACT;AACF"}
@@ -2,7 +2,6 @@ import type { ModelWithRetries } from '@mastra/core/agent';
2
2
  import type { GatewayLanguageModel, MastraModelGatewayInterface } from '@mastra/core/llm';
3
3
  import type { RequestContext } from '@mastra/core/request-context';
4
4
  import type { CredentialStore } from '../auth/types.js';
5
- import { loadSettings } from '../onboarding/settings.js';
6
5
  import type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';
7
6
  import type { ThinkingLevelSetting } from '../thinking.js';
8
7
  import { MastraCodeGateway } from './mastracode-gateway.js';
@@ -60,49 +59,15 @@ export interface ThinkingRequestContext {
60
59
  * (rule-driven) Factory runs that nobody ever opens interactively.
61
60
  */
62
61
  export declare function resolveRequestThinkingLevel(agentControllerContext: ThinkingRequestContext | undefined, settingsPath?: string): ThinkingLevelSetting;
63
- /** Structural pack shape for fallback resolution (custom pack models are partial by nature). */
64
- export interface ResolvableModePack {
65
- id: string;
66
- name: string;
67
- models: Record<string, string>;
68
- }
69
- /** All packs a fallback chain may reference: every builtin plus saved customs. */
70
- export declare function listResolvableModePacks(settings: ReturnType<typeof loadSettings>): ResolvableModePack[];
71
62
  /**
72
- * Dynamic model function that reads the current model from controller state.
73
- * This allows runtime model switching via the /models picker.
74
- *
75
- * When the session's model came from a pack with a fallback chain configured
76
- * (`settings.models.packFallbacks`), returns core's `ModelWithRetries[]`
77
- * fallback array instead of a bare model: the active pack's model first, then
78
- * each fallback pack's model for the same mode. Core advances the array when
79
- * the error processors decline to retry (pool exhausted / persistent outage —
80
- * see AccountRotationProcessor). Entry ids are unique per occurrence — the
81
- * one allowed revisit of a pack gets `<packId>#2` — because core re-resolves
82
- * the active fallback index by id across agentic steps.
63
+ * Dynamic model function that reads the current model and optional ordered
64
+ * fallback route from controller state. Route entry ids are opaque host-owned
65
+ * identifiers; repeated ids receive occurrence suffixes because core tracks the
66
+ * active fallback index by id across agentic steps.
83
67
  */
84
68
  export declare function getDynamicModel({ requestContext }: {
85
69
  requestContext: RequestContext;
86
70
  }, settingsPath?: string): ResolvedModel | ModelWithRetries[];
87
- /** OM fallback-chain entry: a pack's OM model resolved through the gateway. Assignable to `ModelWithRetries`. */
88
- export type PackMemoryModelChainEntry = {
89
- id: string;
90
- model: GatewayLanguageModel;
91
- };
92
- /**
93
- * Resolve the observational-memory model for the active mode pack, walking the
94
- * pack's fallback chain (`settings.models.packFallbacks`) and collecting each
95
- * pack's optional `models.memory` entry. Packs without an OM model are skipped
96
- * (the field is optional, so absence must not truncate the chain); duplicate
97
- * model ids collapse so an A⇄B cycle never retries an identical OM model.
98
- *
99
- * Returns a bare model for a single entry, a fallback array for multiple
100
- * entries (OM's internal agents run the same agentic loop, so the array gives
101
- * OM its own cross-pack failover), or `undefined` when no pack in the chain
102
- * defines an OM model — callers then fall back to the standalone OM
103
- * configuration.
104
- */
105
- export declare function resolvePackMemoryModelChain(settings: ReturnType<typeof loadSettings>, startPackId: string, resolveOptions: Parameters<typeof resolveModel>[1]): GatewayLanguageModel | PackMemoryModelChainEntry[] | undefined;
106
71
  /**
107
72
  * Goal judge model resolver for the agent's `goal.judge` config. Resolves the
108
73
  * configured goal judge model through mastracode's gateway so provider
@@ -1 +1 @@
1
- {"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../src/agents/model.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAE3D,OAAO,KAAK,EAAE,oBAAoB,EAAE,2BAA2B,EAAE,MAAM,kBAAkB,CAAC;AAC1F,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAGnE,OAAO,KAAK,EAAE,eAAe,EAAsB,MAAM,kBAAkB,CAAC;AAE5E,OAAO,EAEL,YAAY,EAIb,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