@mastra/code-sdk 1.6.0-alpha.0 → 1.6.0-alpha.10

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.
package/README.md CHANGED
@@ -24,128 +24,14 @@ const { mastra, controller } = await mountAgentControllerOnMastra({
24
24
  });
25
25
  ```
26
26
 
27
- To construct the `Mastra` instance yourself (e.g. in a deployable `mastra` entry file), use `prepareAgentControllerMount`:
27
+ ## Documentation
28
28
 
29
- ```ts
30
- import { Mastra } from '@mastra/core/mastra';
31
- import { prepareAgentControllerMount } from '@mastra/code-sdk';
32
-
33
- const prepared = await prepareAgentControllerMount({ cwd: process.cwd() });
34
-
35
- export const mastra = new Mastra(prepared.mastraArgs);
36
-
37
- await prepared.finalize();
38
- ```
39
-
40
- ### Add input processors
41
-
42
- Embedding surfaces can prepend stateless input processors without replacing Mastra Code's required policy and compatibility processors:
43
-
44
- ```ts
45
- const phaseProcessor = {
46
- id: 'current-phase',
47
- async processInputStep({ messages }) {
48
- await reconcileCompletedTools(messages);
49
- },
50
- };
51
-
52
- const prepared = await prepareAgentControllerMount({
53
- cwd: process.cwd(),
54
- inputProcessors: [phaseProcessor],
55
- });
56
- ```
57
-
58
- Configured processors run before Mastra Code's built-in input processors. Keep processor instances stateless because the mounted agent shares them across sessions and runs.
59
-
60
- ## Process memory diagnostics
61
-
62
- Use `ProcessMemoryDiagnostics` to collect low-perturbation memory evidence from a long-running Node.js process. The service records process memory, V8 heap-space statistics, naturally occurring garbage collection (GC) events, and sampled allocation profiles. It doesn't force GC or write heap snapshots.
63
-
64
- > **Warning:** Allocation profiles can contain prompts, credentials, file contents, and tool arguments. Store them in a restricted location, don't upload them as telemetry, and delete them when you finish the investigation.
65
-
66
- The environment factory applies the supported defaults and validation rules:
67
-
68
- ```ts
69
- import {
70
- createProcessMemoryDiagnosticsFromEnvironment,
71
- startConfiguredProcessMemoryDiagnostics,
72
- } from '@mastra/code-sdk/process-memory-diagnostics';
73
-
74
- const setup = createProcessMemoryDiagnosticsFromEnvironment(process.env);
75
- const diagnostics = await startConfiguredProcessMemoryDiagnostics(setup, warning => {
76
- console.warn(warning);
77
- });
78
-
79
- try {
80
- // Create and run your Mastra Code process adapter.
81
- } finally {
82
- await diagnostics.stop();
83
- }
84
- ```
85
-
86
- Construct and start diagnostics before creating Mastra Code. Stop work-producing services first during shutdown, then await `diagnostics.stop()` to write the final process sample and allocation profile.
29
+ - [@mastra/code-sdk documentation](https://mastra.ai/reference/code-sdk/mount-agent-controller)
87
30
 
88
- ### Configuration
89
-
90
- | Environment variable | Default | Minimum | Description |
91
- | ---------------------------------------------- | --------------------------------- | ------- | ----------------------------------------------------------- |
92
- | `MASTRACODE_PROFILE` | Disabled | N/A | Enables startup profiling for `1`, `true`, `yes`, or `on` |
93
- | `MASTRACODE_PROFILE_DIR` | `<Mastra Code app-data>/profiles` | N/A | Parent directory for private, unique run directories |
94
- | `MASTRACODE_PROFILE_SAMPLE_INTERVAL_MS` | `10000` | `1000` | Process and V8 sample interval in milliseconds |
95
- | `MASTRACODE_PROFILE_CAPTURE_INTERVAL_MS` | `300000` | `10000` | Durable allocation-profile capture interval in milliseconds |
96
- | `MASTRACODE_PROFILE_ALLOCATION_INTERVAL_BYTES` | `524288` | `32768` | V8 allocation-sampling interval in bytes |
97
-
98
- Truthy values are case-insensitive and may contain surrounding whitespace. Other values leave startup profiling disabled. Invalid numeric values produce an actionable error instead of starting a higher-overhead profiler.
99
-
100
- ### Artifacts
101
-
102
- Each run directory contains:
103
-
104
- - `metadata.json`: Immutable runtime and configuration metadata
105
- - `process-samples.jsonl`: Append-only RSS, JavaScript heap, external memory, ArrayBuffer memory, resource usage, and V8 heap-space samples
106
- - `gc-events.jsonl`: Append-only GC kind, flags, duration, and nearby memory values when V8 emits GC performance entries. A run can contain zero events.
107
- - `allocation-<sequence>-<timestamp>.heapprofile`: Atomic Chrome allocation-sampling profiles. Each capture closes one sampling epoch and immediately starts the next.
108
-
109
- The service requests mode `0700` for run directories and `0600` for files on POSIX systems. Other platforms may apply permissions differently.
110
-
111
- Compare JavaScript heap growth with resident set size (RSS). Rising heap-space usage points to retained JavaScript objects. Rising RSS with a stable JavaScript heap can point to external buffers, ArrayBuffers, native libraries, memory-mapped files, or allocator behavior. Allocation profiles include objects collected by major and minor GC, which helps distinguish sustained retention from transient allocation pressure.
112
-
113
- Sampling and periodic writes add overhead. Larger allocation intervals and longer capture intervals reduce it. A manual or periodic capture rotates allocation sampling without triggering a heap snapshot or forced GC.
114
-
115
- Atomically completed captures survive later `SIGINT`, `SIGTERM`, `SIGHUP`, `SIGKILL`, or native crashes. Awaited shutdown can write a final capture for graceful signals and application errors. JavaScript can't guarantee a final capture after immediate `SIGKILL`, a native crash, or power loss, so use periodic captures for those cases.
116
-
117
- Delete a run after analysis with your platform's file-removal tools. Never commit captured profiles.
118
-
119
- ## Dynamic workflows
120
-
121
- The local controller registers the Workflow Builder before workers start. In build mode, users can ask the code agent to create a workflow in natural language. The builder discovers registered agents, tools, and workflows, validates a complete definition, then persists and registers it immediately.
122
-
123
- Use the workflow service to manage saved workflows from a custom SDK surface:
124
-
125
- ```ts
126
- import { deleteWorkflow, getWorkflow, listWorkflows, runWorkflow } from '@mastra/code-sdk/workflows/service';
127
-
128
- const { workflows } = await listWorkflows(mastra);
129
- const firstWorkflow = workflows[0];
130
- if (!firstWorkflow) throw new Error('No Dynamic Workflows are available.');
131
-
132
- const definition = await getWorkflow(mastra, firstWorkflow.id);
133
- if (!definition) throw new Error(`Workflow "${firstWorkflow.id}" was not found.`);
134
-
135
- const result = await runWorkflow(mastra, definition.id, { topic: 'dynamic workflows' });
136
- await deleteWorkflow(mastra, definition.id);
137
- ```
138
-
139
- Pass the session request context to `runWorkflow` when workflow agent steps need the session-selected model. You can also pass an event callback as the fifth argument to render workflow step progress.
140
-
141
- Deep modules are available as subpath imports, e.g.:
142
-
143
- ```ts
144
- import { loadSettings } from '@mastra/code-sdk/onboarding/settings';
145
- ```
31
+ ## Changelog
146
32
 
147
- > The subpath API surface is still evolving and may change between minor releases while the package is pre-1.0.
33
+ See the [package changelog](https://github.com/mastra-ai/mastra/blob/main/mastracode/sdk/CHANGELOG.md) for version history and release notes.
148
34
 
149
- ## License
35
+ ## Support
150
36
 
151
- Apache-2.0
37
+ We have an [open community Discord](https://discord.gg/mastra-ai). Come and say hello and let us know if you have any questions or need any help getting things running.
@@ -1 +1 @@
1
- {"version":3,"file":"credential-resolver.d.ts","sourceRoot":"","sources":["../../src/agents/credential-resolver.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAExD,qDAAqD;AACrD,MAAM,WAAW,gBAAgB;IAC/B,iFAAiF;IACjF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,MAAM,EAAE,MAAM,CAAC;IACf;;;;OAIG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED;;;;;GAKG;AACH,MAAM,MAAM,uBAAuB,GAAG,CAAC,MAAM,EAAE,gBAAgB,KAAK,eAAe,GAAG,SAAS,CAAC;AAkBhG,mFAAmF;AACnF,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,uBAAuB,GAAG,SAAS,GAAG,IAAI,CAE9F;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,IAAI,OAAO,CAEpD;AAqCD;;;;;;;;;;GAUG;AACH,wBAAgB,+BAA+B,CAAC,cAAc,CAAC,EAAE,cAAc,GAAG,gBAAgB,GAAG,SAAS,CAsB7G;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,cAAc,CAAC,EAAE,cAAc,GAAG,eAAe,GAAG,SAAS,CAKnG"}
1
+ {"version":3,"file":"credential-resolver.d.ts","sourceRoot":"","sources":["../../src/agents/credential-resolver.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAExD,qDAAqD;AACrD,MAAM,WAAW,gBAAgB;IAC/B,iFAAiF;IACjF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,MAAM,EAAE,MAAM,CAAC;IACf;;;;OAIG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED;;;;;GAKG;AACH,MAAM,MAAM,uBAAuB,GAAG,CAAC,MAAM,EAAE,gBAAgB,KAAK,eAAe,GAAG,SAAS,CAAC;AAkBhG,mFAAmF;AACnF,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,uBAAuB,GAAG,SAAS,GAAG,IAAI,CAE9F;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,IAAI,OAAO,CAEpD;AAqCD;;;;;;;;;;GAUG;AACH,wBAAgB,+BAA+B,CAAC,cAAc,CAAC,EAAE,cAAc,GAAG,gBAAgB,GAAG,SAAS,CAsB7G;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,cAAc,CAAC,EAAE,cAAc,GAAG,eAAe,GAAG,SAAS,CAsBnG"}
@@ -71,8 +71,25 @@ function resolveTenantFromRequestContext(requestContext) {
71
71
  function resolveCredentialStore(requestContext) {
72
72
  if (!credentialStoreProvider) return void 0;
73
73
  const tenant = resolveTenantFromRequestContext(requestContext);
74
- if (!tenant) return unavailableTenantCredentialStore;
75
- return credentialStoreProvider(tenant) ?? unavailableTenantCredentialStore;
74
+ if (!tenant) {
75
+ const rawUser = requestContext?.get("user");
76
+ console.warn("[MastraCode] Tenant credential resolution failed closed", {
77
+ reason: rawUser === void 0 ? "missing-user-context" : "invalid-principal-shape",
78
+ hasRequestContext: requestContext !== void 0,
79
+ factorySession: isFactorySessionContext(requestContext)
80
+ });
81
+ return unavailableTenantCredentialStore;
82
+ }
83
+ const store = credentialStoreProvider(tenant);
84
+ if (!store) {
85
+ console.warn("[MastraCode] Tenant credential resolution failed closed", {
86
+ reason: "credential-store-unavailable",
87
+ hasOrganization: tenant.orgId !== void 0,
88
+ orgFirst: tenant.orgFirst === true
89
+ });
90
+ return unavailableTenantCredentialStore;
91
+ }
92
+ return store;
76
93
  }
77
94
  //#endregion
78
95
  export { hasCredentialStoreProvider, resolveCredentialStore, resolveTenantFromRequestContext, setCredentialStoreProvider };
@@ -1 +1 @@
1
- {"version":3,"file":"credential-resolver.js","names":[],"sources":["../../src/agents/credential-resolver.ts"],"sourcesContent":["/**\n * Per-tenant credential resolution seam for deployed (multi-user) servers.\n *\n * Locally, model resolution reads the server-global file-backed `AuthStorage`.\n * A deployed web host registers a {@link CredentialStoreProvider} at boot; from\n * then on `resolveModel` derives the calling tenant from the request context\n * (the web auth gate stashes the authenticated user under the `user` key) and\n * resolves credentials through the tenant's own store — user credentials over\n * org credentials over server env vars, with OAuth refresh owned by the store.\n *\n * When no provider is registered (TUI, local web), everything falls through to\n * the existing global behavior unchanged.\n */\n\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { CredentialStore } from '../auth/types.js';\n\n/** The identity a credential lookup is scoped to. */\nexport interface CredentialTenant {\n /** Org tenant; absent for personal accounts (store impls may synthesize one). */\n orgId?: string;\n /** Stable user id from the web auth adapter. */\n userId: string;\n /**\n * Resolve org-shared credentials over the user's personal ones. Set by\n * trusted server code for automated (factory) runs so they ride the org's\n * shared keys first and only fall back to the acting user's credentials.\n */\n orgFirst?: boolean;\n}\n\n/**\n * Returns a tenant-scoped {@link CredentialStore}, or `undefined` to fall back\n * to the global store (e.g. tenant storage temporarily unavailable). Must be\n * synchronous — implementations serve from a primed snapshot and do\n * authoritative async work inside `getApiKey`.\n */\nexport type CredentialStoreProvider = (tenant: CredentialTenant) => CredentialStore | undefined;\n\nlet credentialStoreProvider: CredentialStoreProvider | undefined;\n\nconst unavailableTenantCredentialStore: CredentialStore = {\n allowEnvironmentFallback: false,\n reload() {},\n get() {\n return undefined;\n },\n getStoredApiKey() {\n return undefined;\n },\n async getApiKey() {\n return undefined;\n },\n};\n\n/** Register (or clear) the tenant credential store provider. Deployed-web only. */\nexport function setCredentialStoreProvider(provider: CredentialStoreProvider | undefined): void {\n credentialStoreProvider = provider;\n}\n\n/**\n * Whether a tenant provider is registered. Used to disable the\n * `loadStoredApiKeysIntoEnv` side-channel in deployed mode — per-tenant\n * credentials must never leak into process-global env vars.\n */\nexport function hasCredentialStoreProvider(): boolean {\n return credentialStoreProvider !== undefined;\n}\n\n/** Shape the web auth gate stashes on the request context under `user`. */\ninterface RequestContextUser {\n workosId?: string;\n id?: string;\n organizationId?: string;\n /** Trusted server code marks automated runs to resolve org > user credentials. */\n orgFirstCredentials?: boolean;\n}\n\n/**\n * Session-shaped `authenticateToken` results (better-auth) arrive as a wrapper\n * whose active org lives on the session half rather than on the user.\n */\ninterface RequestContextSession {\n user?: RequestContextUser;\n session?: { activeOrganizationId?: string };\n}\n\n/**\n * Whether the request context belongs to a run on a factory-owned session.\n *\n * The agent controller stamps the session's state onto the request context\n * under `controller`, and only trusted factory server code ever writes\n * `factoryProjectId` into session state (board-run creation) — interactive\n * chat sessions never carry it. Runs on such sessions resolve credentials\n * org > user regardless of who sent the message: a board run continued\n * interactively, or a model switch inside it, is still org work.\n */\nfunction isFactorySessionContext(requestContext?: RequestContext): boolean {\n const controller = requestContext?.get('controller') as { state?: { factoryProjectId?: unknown } } | undefined;\n if (!controller || typeof controller !== 'object') return false;\n const factoryProjectId = controller.state?.factoryProjectId;\n return typeof factoryProjectId === 'string' && factoryProjectId.length > 0;\n}\n\n/**\n * Derive the calling tenant from a request context, if an authenticated web\n * user was stashed on it. Mirrors the web layer's stable-id resolution\n * (`workosId` falling back to the provider `id`).\n *\n * The value under `user` is whatever the active auth provider's\n * `authenticateToken` returned, so its shape follows the provider: a flat user\n * (WorkOS) or a `{ session, user }` wrapper (better-auth). Reading only the\n * flat shape resolves no tenant at all for the wrapper, which in deployed mode\n * fails closed to an empty credential store.\n */\nexport function resolveTenantFromRequestContext(requestContext?: RequestContext): CredentialTenant | undefined {\n const raw = requestContext?.get('user') as (RequestContextUser & RequestContextSession) | undefined;\n if (!raw || typeof raw !== 'object') return undefined;\n\n // Precedence matches `toFactoryAuthUser` in `@mastra/factory`: a wrapper's org\n // comes from the session half only, never from the inner user. The two parsers\n // cannot share code across the package boundary, so they must agree by rule.\n const wrapped = Boolean(raw.user && typeof raw.user === 'object' && raw.session && typeof raw.session === 'object');\n const user = wrapped ? (raw.user as RequestContextUser) : raw;\n const orgId = wrapped ? raw.session?.activeOrganizationId : user.organizationId;\n const userId = user.workosId ?? user.id;\n // The slot holds whatever the provider returned, so the declared string\n // types are hopes, not guarantees. A non-string id must refuse the tenant\n // (fail closed), not flow onward as a mistyped key.\n if (typeof userId !== 'string' || !userId) return undefined;\n if (orgId !== undefined && typeof orgId !== 'string') return undefined;\n // Only an exact `true` flips precedence — anything else keeps user > org.\n // Server code stamps the flag on the stashed value itself, so read it from\n // the top level as well as the unwrapped user (better-auth wrapper shape).\n const orgFirst =\n raw.orgFirstCredentials === true || user.orgFirstCredentials === true || isFactorySessionContext(requestContext);\n return { orgId, userId, ...(orgFirst ? { orgFirst } : {}) };\n}\n\n/**\n * Resolve the credential store for a request. Local mode returns `undefined`\n * and keeps the global `AuthStorage` behavior. Once deployed web registers a\n * provider, missing tenant identity or unavailable tenant storage fails closed\n * through an empty store that also disables process-environment fallback.\n */\nexport function resolveCredentialStore(requestContext?: RequestContext): CredentialStore | undefined {\n if (!credentialStoreProvider) return undefined;\n const tenant = resolveTenantFromRequestContext(requestContext);\n if (!tenant) return unavailableTenantCredentialStore;\n return credentialStoreProvider(tenant) ?? unavailableTenantCredentialStore;\n}\n"],"mappings":";AAuCA,IAAI;AAEJ,MAAM,mCAAoD;CACxD,0BAA0B;CAC1B,SAAS,CAAC;CACV,MAAM,CAEN;CACA,kBAAkB,CAElB;CACA,MAAM,YAAY,CAElB;AACF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Per-tenant credential resolution seam for deployed (multi-user) servers.\n *\n * Locally, model resolution reads the server-global file-backed `AuthStorage`.\n * A deployed web host registers a {@link CredentialStoreProvider} at boot; from\n * then on `resolveModel` derives the calling tenant from the request context\n * (the web auth gate stashes the authenticated user under the `user` key) and\n * resolves credentials through the tenant's own store — user credentials over\n * org credentials over server env vars, with OAuth refresh owned by the store.\n *\n * When no provider is registered (TUI, local web), everything falls through to\n * the existing global behavior unchanged.\n */\n\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { CredentialStore } from '../auth/types.js';\n\n/** The identity a credential lookup is scoped to. */\nexport interface CredentialTenant {\n /** Org tenant; absent for personal accounts (store impls may synthesize one). */\n orgId?: string;\n /** Stable user id from the web auth adapter. */\n userId: string;\n /**\n * Resolve org-shared credentials over the user's personal ones. Set by\n * trusted server code for automated (factory) runs so they ride the org's\n * shared keys first and only fall back to the acting user's credentials.\n */\n orgFirst?: boolean;\n}\n\n/**\n * Returns a tenant-scoped {@link CredentialStore}, or `undefined` to fall back\n * to the global store (e.g. tenant storage temporarily unavailable). Must be\n * synchronous — implementations serve from a primed snapshot and do\n * authoritative async work inside `getApiKey`.\n */\nexport type CredentialStoreProvider = (tenant: CredentialTenant) => CredentialStore | undefined;\n\nlet credentialStoreProvider: CredentialStoreProvider | undefined;\n\nconst unavailableTenantCredentialStore: CredentialStore = {\n allowEnvironmentFallback: false,\n reload() {},\n get() {\n return undefined;\n },\n getStoredApiKey() {\n return undefined;\n },\n async getApiKey() {\n return undefined;\n },\n};\n\n/** Register (or clear) the tenant credential store provider. Deployed-web only. */\nexport function setCredentialStoreProvider(provider: CredentialStoreProvider | undefined): void {\n credentialStoreProvider = provider;\n}\n\n/**\n * Whether a tenant provider is registered. Used to disable the\n * `loadStoredApiKeysIntoEnv` side-channel in deployed mode — per-tenant\n * credentials must never leak into process-global env vars.\n */\nexport function hasCredentialStoreProvider(): boolean {\n return credentialStoreProvider !== undefined;\n}\n\n/** Shape the web auth gate stashes on the request context under `user`. */\ninterface RequestContextUser {\n workosId?: string;\n id?: string;\n organizationId?: string;\n /** Trusted server code marks automated runs to resolve org > user credentials. */\n orgFirstCredentials?: boolean;\n}\n\n/**\n * Session-shaped `authenticateToken` results (better-auth) arrive as a wrapper\n * whose active org lives on the session half rather than on the user.\n */\ninterface RequestContextSession {\n user?: RequestContextUser;\n session?: { activeOrganizationId?: string };\n}\n\n/**\n * Whether the request context belongs to a run on a factory-owned session.\n *\n * The agent controller stamps the session's state onto the request context\n * under `controller`, and only trusted factory server code ever writes\n * `factoryProjectId` into session state (board-run creation) — interactive\n * chat sessions never carry it. Runs on such sessions resolve credentials\n * org > user regardless of who sent the message: a board run continued\n * interactively, or a model switch inside it, is still org work.\n */\nfunction isFactorySessionContext(requestContext?: RequestContext): boolean {\n const controller = requestContext?.get('controller') as { state?: { factoryProjectId?: unknown } } | undefined;\n if (!controller || typeof controller !== 'object') return false;\n const factoryProjectId = controller.state?.factoryProjectId;\n return typeof factoryProjectId === 'string' && factoryProjectId.length > 0;\n}\n\n/**\n * Derive the calling tenant from a request context, if an authenticated web\n * user was stashed on it. Mirrors the web layer's stable-id resolution\n * (`workosId` falling back to the provider `id`).\n *\n * The value under `user` is whatever the active auth provider's\n * `authenticateToken` returned, so its shape follows the provider: a flat user\n * (WorkOS) or a `{ session, user }` wrapper (better-auth). Reading only the\n * flat shape resolves no tenant at all for the wrapper, which in deployed mode\n * fails closed to an empty credential store.\n */\nexport function resolveTenantFromRequestContext(requestContext?: RequestContext): CredentialTenant | undefined {\n const raw = requestContext?.get('user') as (RequestContextUser & RequestContextSession) | undefined;\n if (!raw || typeof raw !== 'object') return undefined;\n\n // Precedence matches `toFactoryAuthUser` in `@mastra/factory`: a wrapper's org\n // comes from the session half only, never from the inner user. The two parsers\n // cannot share code across the package boundary, so they must agree by rule.\n const wrapped = Boolean(raw.user && typeof raw.user === 'object' && raw.session && typeof raw.session === 'object');\n const user = wrapped ? (raw.user as RequestContextUser) : raw;\n const orgId = wrapped ? raw.session?.activeOrganizationId : user.organizationId;\n const userId = user.workosId ?? user.id;\n // The slot holds whatever the provider returned, so the declared string\n // types are hopes, not guarantees. A non-string id must refuse the tenant\n // (fail closed), not flow onward as a mistyped key.\n if (typeof userId !== 'string' || !userId) return undefined;\n if (orgId !== undefined && typeof orgId !== 'string') return undefined;\n // Only an exact `true` flips precedence — anything else keeps user > org.\n // Server code stamps the flag on the stashed value itself, so read it from\n // the top level as well as the unwrapped user (better-auth wrapper shape).\n const orgFirst =\n raw.orgFirstCredentials === true || user.orgFirstCredentials === true || isFactorySessionContext(requestContext);\n return { orgId, userId, ...(orgFirst ? { orgFirst } : {}) };\n}\n\n/**\n * Resolve the credential store for a request. Local mode returns `undefined`\n * and keeps the global `AuthStorage` behavior. Once deployed web registers a\n * provider, missing tenant identity or unavailable tenant storage fails closed\n * through an empty store that also disables process-environment fallback.\n */\nexport function resolveCredentialStore(requestContext?: RequestContext): CredentialStore | undefined {\n if (!credentialStoreProvider) return undefined;\n const tenant = resolveTenantFromRequestContext(requestContext);\n if (!tenant) {\n const rawUser = requestContext?.get('user');\n console.warn('[MastraCode] Tenant credential resolution failed closed', {\n reason: rawUser === undefined ? 'missing-user-context' : 'invalid-principal-shape',\n hasRequestContext: requestContext !== undefined,\n factorySession: isFactorySessionContext(requestContext),\n });\n return unavailableTenantCredentialStore;\n }\n const store = credentialStoreProvider(tenant);\n if (!store) {\n console.warn('[MastraCode] Tenant credential resolution failed closed', {\n reason: 'credential-store-unavailable',\n hasOrganization: tenant.orgId !== undefined,\n orgFirst: tenant.orgFirst === true,\n });\n return unavailableTenantCredentialStore;\n }\n return store;\n}\n"],"mappings":";AAuCA,IAAI;AAEJ,MAAM,mCAAoD;CACxD,0BAA0B;CAC1B,SAAS,CAAC;CACV,MAAM,CAEN;CACA,kBAAkB,CAElB;CACA,MAAM,YAAY,CAElB;AACF;;AAGA,SAAgB,2BAA2B,UAAqD;CAC9F,0BAA0B;AAC5B;;;;;;AAOA,SAAgB,6BAAsC;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,wBAAwB,MAAM;CAC5C,IAAI,CAAC,OAAO;EACV,QAAQ,KAAK,2DAA2D;GACtE,QAAQ;GACR,iBAAiB,OAAO,UAAU,KAAA;GAClC,UAAU,OAAO,aAAa;EAChC,CAAC;EACD,OAAO;CACT;CACA,OAAO;AACT"}
@@ -3,7 +3,7 @@ import type { MastraCompositeStore } from '@mastra/core/storage';
3
3
  import type { MastraVector } from '@mastra/core/vector';
4
4
  import { Memory } from '@mastra/memory';
5
5
  /**
6
- * The organization rung local (TUI/studio) knowledge is captured under. A fixed
6
+ * The organization rung local (TUI/studio) knowledge is curated under. A fixed
7
7
  * literal on purpose: deriving it from a hostname or path would fragment local
8
8
  * knowledge per checkout into scopes nothing ever reads.
9
9
  */
@@ -1 +1 @@
1
- {"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../src/agents/memory.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AACjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,MAAM,EAAgB,MAAM,gBAAgB,CAAC;AAkEtD;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,UAAU,CAAC;AA6B9C;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,oBAAoB,EAAE,MAAM,CAAC,EAAE,YAAY,IAM3E,oBAAoB;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,YAmH/D"}
1
+ {"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../src/agents/memory.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AACjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,MAAM,EAAgB,MAAM,gBAAgB,CAAC;AAkEtD;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,UAAU,CAAC;AA6B9C;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,oBAAoB,EAAE,MAAM,CAAC,EAAE,YAAY,IAM3E,oBAAoB;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,YA0G/D"}
@@ -55,7 +55,7 @@ Don't say "Agent did x", say "did x". It will be assumed the agent did what was
55
55
 
56
56
  Drop 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`;
57
57
  /**
58
- * The organization rung local (TUI/studio) knowledge is captured under. A fixed
58
+ * The organization rung local (TUI/studio) knowledge is curated under. A fixed
59
59
  * literal on purpose: deriving it from a hostname or path would fragment local
60
60
  * knowledge per checkout into scopes nothing ever reads.
61
61
  */
@@ -70,7 +70,7 @@ function reportOrgUnresolved(controller, factoryProjectId) {
70
70
  reportedOrgUnresolved.add(sessionId);
71
71
  }
72
72
  const session = controller?.session;
73
- console.error(`[Subconscious] Knowledge capture disabled: no organization resolved for session ${session?.id ?? "unknown"} (project ${factoryProjectId ?? "none"}). Knowledge is not written rather than written where it cannot be read.`);
73
+ console.error(`[Subconscious] Knowledge curation disabled: no organization resolved for session ${session?.id ?? "unknown"} (project ${factoryProjectId ?? "none"}). Knowledge is not written rather than written where it cannot be read.`);
74
74
  }
75
75
  /**
76
76
  * Dynamic memory factory function.
@@ -97,14 +97,14 @@ function getDynamicMemory(storage, vector) {
97
97
  } else requestContext.set("organizationId", LOCAL_KNOWLEDGE_ORG_ID);
98
98
  if (isFactory) requestContext.set("knowledgeResourceId", factoryProjectId);
99
99
  }
100
- const captureEnabled = subconsciousEnabled && !orgUnresolvedRefusal;
100
+ const subconsciousAvailable = subconsciousEnabled && !orgUnresolvedRefusal;
101
101
  const omScope = state?.omScope ?? getOmScope(state?.projectPath);
102
102
  const obsThreshold = state?.observationThreshold ?? 3e4;
103
103
  const refThreshold = state?.reflectionThreshold ?? 4e4;
104
104
  const caveman = state?.cavemanObservations ?? false;
105
105
  const observerPreviousObservationTokens = 1e3;
106
106
  const observeAttachments = state?.observeAttachments;
107
- const cacheKey = `${obsThreshold}:${refThreshold}:${omScope}:${observerPreviousObservationTokens}:${caveman ? 1 : 0}:${observeAttachments}:${isFactory ? 1 : 0}:${captureEnabled ? 1 : 0}`;
107
+ const cacheKey = `${obsThreshold}:${refThreshold}:${omScope}:${observerPreviousObservationTokens}:${caveman ? 1 : 0}:${observeAttachments}:${isFactory ? 1 : 0}:${subconsciousAvailable ? 1 : 0}`;
108
108
  if (cachedMemory && cachedMemoryKey === cacheKey) return cachedMemory;
109
109
  const isResourceScope = omScope === "resource";
110
110
  const observerInstruction = caveman ? `${DYNAMIC_AGENTS_MD_INSTRUCTION}\n\n${CAVEMAN_OM_INSTRUCTION}` : DYNAMIC_AGENTS_MD_INSTRUCTION;
@@ -114,16 +114,15 @@ function getDynamicMemory(storage, vector) {
114
114
  vector: vector || false,
115
115
  embedder: vector ? fastembed.small : void 0,
116
116
  options: {
117
- ...isFactory ? { generateTitle: { model: getObserverModel } } : {},
117
+ generateTitle: { model: getObserverModel },
118
118
  observationalMemory: {
119
119
  enabled: true,
120
120
  temporalMarkers: true,
121
121
  retrieval: vector ? { vector: true } : true,
122
- experimental_subconscious: captureEnabled ? new Subconscious({
122
+ experimental_subconscious: subconsciousAvailable ? new Subconscious({
123
123
  defaultScope: "resource",
124
124
  maxScope: "resource",
125
- pins: isFactory ? { capturePinning: true } : true,
126
- ...isFactory ? { curationCadence: 3 } : {},
125
+ pins: true,
127
126
  ...isFactory ? { maxSteps: 25 } : {}
128
127
  }) : void 0,
129
128
  scope: omScope,
@@ -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 { 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 type { MastraCodeState } from '../schema.js';\nimport { getOmScope } from '../utils/project.js';\nimport { resolveModel } from './model.js';\n\n/**\n * Read controller state from requestContext.\n * Used by both the memory factory and the OM model functions.\n */\nfunction getAgentControllerState(requestContext: RequestContext): MastraCodeState | undefined {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n return ctx?.getState() as MastraCodeState | undefined;\n}\n\n/**\n * Observer model function — reads the current observer model ID from\n * controller state via requestContext (now propagated by OM's agent.generate).\n */\nfunction getObserverModel({ requestContext }: { requestContext: RequestContext }) {\n const state = getAgentControllerState(requestContext);\n return resolveModel(state?.observerModelId ?? DEFAULT_OM_MODEL_ID, {\n remapForCodexOAuth: true,\n requestContext,\n });\n}\n\n/**\n * Reflector model function — reads the current reflector model ID from\n * controller state via requestContext (now propagated by OM's agent.generate).\n */\nfunction getReflectorModel({ requestContext }: { requestContext: RequestContext }) {\n const state = getAgentControllerState(requestContext);\n return resolveModel(state?.reflectorModelId ?? DEFAULT_OM_MODEL_ID, {\n remapForCodexOAuth: true,\n requestContext,\n });\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\n/**\n * The organization rung local (TUI/studio) knowledge is captured under. A fixed\n * literal on purpose: deriving it from a hostname or path would fragment local\n * knowledge per checkout into scopes nothing ever reads.\n */\nexport const LOCAL_KNOWLEDGE_ORG_ID = 'local';\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) {\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 capture disabled: no organization resolved for session ${session?.id ?? 'unknown'} (project ${factoryProjectId ?? 'none'}). Knowledge is not written rather than written where it cannot be read.`,\n );\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) {\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 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 = Boolean(vector) && process.env.MASTRACODE_EXPERIMENTAL_SUBCONSCIOUS === '1';\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 capture:\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 // Factory seeds the authoritative org id into session state. There is no\n // fallback: a session owner is a USER id, never an organization.\n const factoryOrgId = state?.factoryOrgId;\n const factoryOwned = isFactory || state?.factoryOrgUnresolved === true;\n if (typeof factoryOrgId === 'string' && factoryOrgId.trim()) {\n requestContext.set('organizationId', factoryOrgId);\n } else if (factoryOwned) {\n orgUnresolvedRefusal = true;\n reportOrgUnresolved(controller, factoryProjectId);\n } else {\n // TUI/studio: an explicit, named scope rather than a cascaded identity.\n requestContext.set('organizationId', LOCAL_KNOWLEDGE_ORG_ID);\n }\n // Factory runs share one knowledge graph per project: anchor the\n // subconscious knowledge scope's resource rung on the project id.\n if (isFactory) {\n requestContext.set('knowledgeResourceId', factoryProjectId);\n }\n }\n\n const captureEnabled = 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}:${captureEnabled ? 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 // The factory sidebar shows a session the moment it exists, so it needs a\n // name on the first turn. The TUI names its threads from OM's `threadTitle`\n // as they grow and would only pay for an extra call here.\n ...(isFactory ? { generateTitle: { model: getObserverModel } } : {}),\n observationalMemory: {\n enabled: true,\n temporalMarkers: true,\n retrieval: vector ? { vector: true } : true,\n experimental_subconscious: captureEnabled\n ? new Subconscious({\n defaultScope: 'resource',\n maxScope: 'resource',\n // Capture-time pinning is a factory-only opinion; every other\n // client keeps plain curator-maintained pins.\n pins: isFactory ? { capturePinning: true } : true,\n // Factory sessions run the curator every 3 observation runs;\n // other clients leave the cadence trigger dormant.\n ...(isFactory ? { curationCadence: 3 } : {}),\n // Real curation over a factory worklist needs tool room: the\n // default 5-step budget exhausts mid-batch and the curator never\n // reaches its cursor acknowledgment (observed live 2026-08-13).\n ...(isFactory ? { maxSteps: 25 } : {}),\n })\n : undefined,\n scope: omScope,\n activateAfterIdle: 'auto',\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":";;;;;;;;;;AAeA,SAAS,wBAAwB,gBAA6D;CAE5F,OADY,eAAe,IAAI,YACtB,CAAC,EAAE,SAAS;AACvB;;;;;AAMA,SAAS,iBAAiB,EAAE,kBAAsD;CAEhF,OAAO,aADO,wBAAwB,cACd,CAAC,EAAE,mBAAmB,qBAAqB;EACjE,oBAAoB;EACpB;CACF,CAAC;AACH;;;;;AAMA,SAAS,kBAAkB,EAAE,kBAAsD;CAEjF,OAAO,aADO,wBAAwB,cACd,CAAC,EAAE,oBAAoB,qBAAqB;EAClE,oBAAoB;EACpB;CACF,CAAC;AACH;AAEA,MAAM,gCACJ;AAGF,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4B/B,MAAa,yBAAyB;AAQtC,MAAM,gCAAgC;AACtC,MAAM,wCAAwB,IAAI,IAAY;AAE9C,SAAS,oBACP,YACA,kBACA;CACA,MAAM,YAAY,YAAY,SAAS;CACvC,IAAI,WAAW;EACb,IAAI,sBAAsB,IAAI,SAAS,GAAG;EAC1C,IAAI,sBAAsB,QAAQ,+BAChC,sBAAsB,OAAO,sB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AG,iBAAiB,IAAI;EACvL,IAAI,gBAAgB,oBAAoB,UACtC,OAAO;EAIT,MAAM,kBAAkB,YAAY;EAEpC,MAAM,sBAAsB,UACxB,GAAG,8BAA8B,MAAM,2BACvC;EACJ,MAAM,wBAAwB,UAAU,yBAAyB,KAAA;EAEjE,eAAe,IAAI,OAAO;GACxB;GACA,QAAQ,UAAU;GAClB,UAAU,SAAS,UAAU,QAAQ,KAAA;GACrC,SAAS;IAIP,GAAI,YAAY,EAAE,eAAe,EAAE,OAAO,iBAAiB,EAAE,IAAI,CAAC;IAClE,qBAAqB;KACnB,SAAS;KACT,iBAAiB;KACjB,WAAW,SAAS,EAAE,QAAQ,KAAK,IAAI;KACvC,2BAA2B,iBACvB,IAAI,aAAa;MACf,cAAc;MACd,UAAU;MAGV,MAAM,YAAY,EAAE,gBAAgB,KAAK,IAAI;MAG7C,GAAI,YAAY,EAAE,iBAAiB,EAAE,IAAI,CAAC;MAI1C,GAAI,YAAY,EAAE,UAAU,GAAG,IAAI,CAAC;KACtC,CAAC,IACD,KAAA;KACJ,OAAO;KACP,mBAAmB;KACnB,0BAA0B;KAC1B,aAAa;MACX,cAAc,kBAAkB,QAAQ,IAAI;MAC5C,kBAAkB,kBAAkB,KAAA,IAAY;MAChD,OAAO;MACP,eAAe;MACf,YAAY;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 { 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 type { MastraCodeState } from '../schema.js';\nimport { getOmScope } from '../utils/project.js';\nimport { resolveModel } from './model.js';\n\n/**\n * Read controller state from requestContext.\n * Used by both the memory factory and the OM model functions.\n */\nfunction getAgentControllerState(requestContext: RequestContext): MastraCodeState | undefined {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n return ctx?.getState() as MastraCodeState | undefined;\n}\n\n/**\n * Observer model function — reads the current observer model ID from\n * controller state via requestContext (now propagated by OM's agent.generate).\n */\nfunction getObserverModel({ requestContext }: { requestContext: RequestContext }) {\n const state = getAgentControllerState(requestContext);\n return resolveModel(state?.observerModelId ?? DEFAULT_OM_MODEL_ID, {\n remapForCodexOAuth: true,\n requestContext,\n });\n}\n\n/**\n * Reflector model function — reads the current reflector model ID from\n * controller state via requestContext (now propagated by OM's agent.generate).\n */\nfunction getReflectorModel({ requestContext }: { requestContext: RequestContext }) {\n const state = getAgentControllerState(requestContext);\n return resolveModel(state?.reflectorModelId ?? DEFAULT_OM_MODEL_ID, {\n remapForCodexOAuth: true,\n requestContext,\n });\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\n/**\n * The organization rung local (TUI/studio) knowledge is curated under. A fixed\n * literal on purpose: deriving it from a hostname or path would fragment local\n * knowledge per checkout into scopes nothing ever reads.\n */\nexport const LOCAL_KNOWLEDGE_ORG_ID = 'local';\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) {\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'}). Knowledge is not written rather than written where it cannot be read.`,\n );\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) {\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 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 = Boolean(vector) && process.env.MASTRACODE_EXPERIMENTAL_SUBCONSCIOUS === '1';\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 // Factory seeds the authoritative org id into session state. There is no\n // fallback: a session owner is a USER id, never an organization.\n const factoryOrgId = state?.factoryOrgId;\n const factoryOwned = isFactory || state?.factoryOrgUnresolved === true;\n if (typeof factoryOrgId === 'string' && factoryOrgId.trim()) {\n requestContext.set('organizationId', factoryOrgId);\n } else if (factoryOwned) {\n orgUnresolvedRefusal = true;\n reportOrgUnresolved(controller, factoryProjectId);\n } else {\n // TUI/studio: an explicit, named scope rather than a cascaded identity.\n requestContext.set('organizationId', LOCAL_KNOWLEDGE_ORG_ID);\n }\n // Factory runs share one knowledge graph per project: anchor the\n // subconscious knowledge scope's resource rung on the project id.\n if (isFactory) {\n requestContext.set('knowledgeResourceId', factoryProjectId);\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.\n generateTitle: { model: getObserverModel },\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 activateAfterIdle: 'auto',\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":";;;;;;;;;;AAeA,SAAS,wBAAwB,gBAA6D;CAE5F,OADY,eAAe,IAAI,YACtB,CAAC,EAAE,SAAS;AACvB;;;;;AAMA,SAAS,iBAAiB,EAAE,kBAAsD;CAEhF,OAAO,aADO,wBAAwB,cACd,CAAC,EAAE,mBAAmB,qBAAqB;EACjE,oBAAoB;EACpB;CACF,CAAC;AACH;;;;;AAMA,SAAS,kBAAkB,EAAE,kBAAsD;CAEjF,OAAO,aADO,wBAAwB,cACd,CAAC,EAAE,oBAAoB,qBAAqB;EAClE,oBAAoB;EACpB;CACF,CAAC;AACH;AAEA,MAAM,gCACJ;AAGF,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4B/B,MAAa,yBAAyB;AAQtC,MAAM,gCAAgC;AACtC,MAAM,wCAAwB,IAAI,IAAY;AAE9C,SAAS,oBACP,YACA,kBACA;CACA,MAAM,YAAY,YAAY,SAAS;CACvC,IAAI,WAAW;EACb,IAAI,sBAAsB,IAAI,SAAS,GAAG;EAC1C,IAAI,sBAAsB,QAAQ,+BAChC,sBAAsB,OAAO,sBAAsB,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,KAAe;EAEpF,sBAAsB,IAAI,SAAS;CACrC;CACA,MAAM,UAAU,YAAY;CAC5B,QAAQ,MACN,oFAAoF,SAAS,MAAM,UAAU,YAAY,oBAAoB,OAAO,yEACtJ;AACF;;;;;;AAOA,SAAgB,iBAAiB,SAA+B,QAAuB;CAGrF,IAAI,eAA8B;CAClC,IAAI,kBAAiC;CAErC,QAAQ,EAAE,qBAAyD;EACjE,MAAM,aAAa,eAAe,IAAI,YAAY;EAClD,MAAM,QAAQ,YAAY,SAAS;EACnC,MAAM,sBAAsB,QAAQ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,CAAC;IAAC,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAAC,cAAc,CAAC,EAAE,cAAc,CAAA;CAAE,GAChH,oBAAoB,CAqFtB;AAED,MAAM,WAAW,sBAAsB;IACrC,KAAK,CAAC,EAAE;QAAE,aAAa,CAAC,EAAE,OAAO,CAAA;KAAE,CAAC;IACpC,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAC/B;AACD;;;;;;;;;;;;GAYG;AAEH,wBAAgB,2BAA2B,CACzC,sBAAsB,EAAE,sBAAsB,GAAG,SAAS,EAC1D,YAAY,CAAC,EAAE,MAAM,GACpB,oBAAoB,CAKtB;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAC7B,EAAE,cAAc,EAAE,EAAE;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,EACtD,YAAY,CAAC,EAAE,MAAM,GACpB,aAAa,CAoBf;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAC/B,EAAE,cAAc,EAAE,EAAE;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,EACtD,YAAY,CAAC,EAAE,MAAM,GACpB,aAAa,GAAG,SAAS,CAI3B"}
@@ -83,6 +83,7 @@ function resolveModel(modelId, options) {
83
83
  modelId: bareModelId,
84
84
  routerId
85
85
  });
86
+ if (!auth && credentialStore?.allowEnvironmentFallback === false) throw new Error(`No usable ${providerId} credential is configured for this signed-in Factory account. Connect the provider or add an organization credential, then try again.`);
86
87
  return gateway.resolveLanguageModel({
87
88
  providerId,
88
89
  modelId: bareModelId,
@@ -1 +1 @@
1
- {"version":3,"file":"model.js","names":[],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { GatewayLanguageModel, MastraModelGatewayInterface } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport {\n loadSettings,\n resolveDefaultThinkingLevel,\n stripMastraCodeCustomProviderPrefix,\n} from '../onboarding/settings.js';\nimport { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from '../providers/amazon-bedrock-gateway.js';\nimport { isThinkingLevelSetting } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nimport { resolveCredentialStore } from './credential-resolver.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\nimport {\n MASTRA_GATEWAY_PREFIX,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n reloadAuthStorage,\n stripMastraGatewayPrefix,\n} from './mastracode-gateway.js';\nimport type { MastraCodeGatewayOptions } from './mastracode-gateway.js';\n\nexport {\n getAnthropicApiKey,\n getOpenAIApiKey,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n remapOpenAIModelForCodexOAuth,\n resolveAuth,\n} from './mastracode-gateway.js';\nexport type { MastraCodeCustomProvider, MastraCodeGatewayOptions } from './mastracode-gateway.js';\nexport {\n setCredentialStoreProvider,\n hasCredentialStoreProvider,\n resolveTenantFromRequestContext,\n} from './credential-resolver.js';\nexport type { CredentialTenant, CredentialStoreProvider } from './credential-resolver.js';\nexport {\n setCustomProvidersSource,\n hasCustomProvidersSource,\n resolveCustomProviders,\n} from './custom-provider-source.js';\nexport type { CustomProvidersSource } from './custom-provider-source.js';\n\ntype ResolvedModel = GatewayLanguageModel;\ntype ModelRequestHeaders = Record<string, string>;\n\nfunction getAgentControllerHeaders(requestContext?: RequestContext): ModelRequestHeaders | undefined {\n const agentControllerContext = requestContext?.get('controller') as AgentControllerRequestContext<any> | undefined;\n const headers = {\n ...(agentControllerContext?.threadId ? { 'x-thread-id': agentControllerContext.threadId } : {}),\n ...(agentControllerContext?.resourceId ? { 'x-resource-id': agentControllerContext.resourceId } : {}),\n };\n\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nexport function createMastraCodeGateway(options: MastraCodeGatewayOptions): MastraCodeGateway {\n return new MastraCodeGateway(options);\n}\n\nexport function createMastraCodeModelCatalogProvider(gateway: MastraModelGatewayInterface) {\n return gateway instanceof MastraCodeGateway\n ? gateway.createModelCatalogProvider()\n : MastraCodeGateway.createModelCatalogProvider(gateway);\n}\n\n/**\n * Placeholder for future model ID normalization.\n * Currently returns the input unchanged, but exists as a seam\n * for aliasing, casing fixes, or validation in the future.\n */\nexport function resolveModelId(modelId: string): string {\n return modelId;\n}\n\n/**\n * Resolve a model ID to the correct provider instance.\n * Shared by the main agent, observer, and reflector.\n *\n * - For anthropic/* models: Uses stored OAuth credentials when present, otherwise direct API key\n * - For openai/* models: Uses OAuth when configured, otherwise direct API key from AuthStorage\n * - For moonshotai/* models: Uses Moonshot AI Anthropic-compatible endpoint\n * - For all other providers: Uses Mastra's model router (models.dev gateway)\n */\nexport function resolveModel(\n modelId: string,\n options?: { thinkingLevel?: ThinkingLevelSetting; remapForCodexOAuth?: boolean; requestContext?: RequestContext },\n): GatewayLanguageModel {\n reloadAuthStorage();\n const headers = getAgentControllerHeaders(options?.requestContext);\n const settings = loadSettings();\n // Bedrock was previously cataloged under the MastraCode gateway namespace\n // (`mastracode/amazon-bedrock/<model>`). Normalize any legacy saved ids to the\n // standalone `amazon-bedrock/<model>` form so they resolve through the\n // dedicated Bedrock gateway.\n const bedrockLegacyPrefix = `${MASTRACODE_GATEWAY_ID}/amazon-bedrock/`;\n const bedrockNormalizedInput = modelId.startsWith(bedrockLegacyPrefix)\n ? modelId.slice(MASTRACODE_GATEWAY_ID.length + 1)\n : modelId;\n // Deployed web registers a custom providers source (DB-backed, tenant\n // scoped); when registered it is authoritative and settings.json custom\n // providers are ignored. Undefined = local settings-based behavior.\n const customProviders = resolveCustomProviders(options?.requestContext) ?? settings.customProviders;\n // Ids selected from the shared /models catalog were previously persisted in\n // the gateway-qualified `mastracode/<customProviderId>/<model>` form, which\n // parses the provider as `mastracode` and breaks provider config lookup.\n // Normalize at resolution time (in addition to stripping at selection time)\n // so already-saved ids and any surface that persists the raw catalog id\n // still resolve to the custom provider.\n const normalizedInput = stripMastraCodeCustomProviderPrefix(bedrockNormalizedInput, customProviders);\n const isMastraGatewayModel = normalizedInput.startsWith(MASTRA_GATEWAY_PREFIX);\n const normalizedModelId = stripMastraGatewayPrefix(normalizedInput);\n const [providerId, ...modelParts] = normalizedModelId.split('/');\n const bareModelId = modelParts.join('/');\n if (!providerId || !bareModelId) {\n throw new Error(`Invalid model id: ${modelId}`);\n }\n\n if (providerId === AMAZON_BEDROCK_GATEWAY_ID) {\n const bedrockGateway = createAmazonBedrockGateway();\n const routerId = `${AMAZON_BEDROCK_GATEWAY_ID}/${bareModelId}`;\n const auth = bedrockGateway.resolveAuth({\n gatewayId: AMAZON_BEDROCK_GATEWAY_ID,\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n routerId,\n });\n return bedrockGateway.resolveLanguageModel({\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n }\n\n const routerId = `${MASTRACODE_GATEWAY_ID}/${normalizedModelId}`;\n\n const mgApiKey = MastraCodeGateway.getMastraGatewayApiKey();\n const rawGatewayBase =\n settings.memoryGateway?.baseUrl ?? process.env['MASTRA_GATEWAY_URL'] ?? 'https://gateway-api.mastra.ai';\n // Deployed web registers a per-tenant credential store provider; when the\n // request carries an authenticated tenant, resolve credentials through the\n // caller's own store (user > org > env). Undefined = global AuthStorage.\n const credentialStore = resolveCredentialStore(options?.requestContext);\n const gateway = createMastraCodeGateway({\n mastraGatewayBaseUrl: rawGatewayBase.replace(/\\/+$/, '').replace(/\\/v1$/, ''),\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: Boolean(mgApiKey && isMastraGatewayModel),\n thinkingLevel: options?.thinkingLevel,\n customProviders,\n credentialStore,\n });\n\n const auth = gateway.resolveAuth({\n gatewayId: MASTRACODE_GATEWAY_ID,\n providerId,\n modelId: bareModelId,\n routerId,\n });\n\n return gateway.resolveLanguageModel({\n providerId,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n}\n\nexport interface ThinkingRequestContext {\n state?: { thinkingLevel?: unknown };\n session?: { modeId?: string };\n}\n/**\n * Resolve the effective thinking level for the current request.\n *\n * Precedence:\n * 1. Session override (`state.thinkingLevel`, set via /think or the session\n * settings panel).\n * 2. Per-mode default from settings (`models.modeThinkingDefaults[mode]`).\n * 3. Global default (`preferences.thinkingLevel`).\n *\n * Resolved per-request (not seeded at session start) so configuration changes\n * apply to the next request of every session — including automated\n * (rule-driven) Factory runs that nobody ever opens interactively.\n */\n\nexport function resolveRequestThinkingLevel(\n agentControllerContext: ThinkingRequestContext | undefined,\n settingsPath?: string,\n): ThinkingLevelSetting {\n const override = agentControllerContext?.state?.thinkingLevel;\n if (isThinkingLevelSetting(override)) return override;\n const modeId = agentControllerContext?.session?.modeId;\n return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;\n}\n\n/**\n * Dynamic model function that reads the current model from controller state.\n * This allows runtime model switching via the /models picker.\n */\nexport function getDynamicModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel {\n const agentControllerContext = requestContext.get('controller') as AgentControllerRequestContext<any> | undefined;\n\n const modelId = agentControllerContext?.session?.modelId;\n if (!modelId) {\n // A missing controller context means the run was started without session\n // request context at all (e.g. a signal delivered to an idle thread) —\n // \"use /models\" would mislead there, the user's selection was never the\n // problem.\n if (!agentControllerContext) {\n throw new Error(\n 'No model available: this run started without a controller session context, so no model selection could be resolved.',\n );\n }\n throw new Error('No model selected. Use /models to select a model first.');\n }\n\n const thinkingLevel = resolveRequestThinkingLevel(agentControllerContext, settingsPath);\n\n return resolveModel(modelId, { thinkingLevel, remapForCodexOAuth: true, requestContext });\n}\n\n/**\n * Goal judge model resolver for the agent's `goal.judge` config. Resolves the\n * configured goal judge model through mastracode's gateway so provider\n * credentials (stored in auth storage, not just env) are injected — a bare model\n * id handed to core's default model router would fail to find the API key.\n *\n * Returns `undefined` when no judge model is configured, which keeps the goal\n * step a complete no-op (the goal mechanism requires a judge to do anything).\n *\n * `settingsPath` must be the same source `createMastraCode()` reads from so the\n * judge model and the goal budget (`goalMaxTurns`) come from one config — with a\n * custom `settingsPath` a bare `loadSettings()` here could read a different file\n * and silently turn the goal step into a no-op.\n */\nexport function getGoalJudgeModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | undefined {\n const judgeModelId = loadSettings(settingsPath).models.goalJudgeModel;\n if (!judgeModelId) return undefined;\n return resolveModel(judgeModelId, { remapForCodexOAuth: true, requestContext });\n}\n"],"mappings":";;;;;;;AA+CA,SAAS,0BAA0B,gBAAkE;CACnG,MAAM,yBAAyB,gBAAgB,IAAI,YAAY;CAC/D,MAAM,UAAU;EACd,GAAI,wBAAwB,WAAW,EAAE,eAAe,uBAAuB,SAAS,IAAI,CAAC;EAC7F,GAAI,wBAAwB,aAAa,EAAE,iBAAiB,uBAAuB,WAAW,IAAI,CAAC;CACrG;CAEA,OAAO,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,IAAI,UAAU,KAAA;AACrD;AAEA,SAAgB,wBAAwB,SAAsD;CAC5F,OAAO,IAAI,kBAAkB,OAAO;AACtC;AAEA,SAAgB,qCAAqC,SAAsC;CACzF,OAAO,mBAAmB,oBACtB,QAAQ,2BAA2B,IACnC,kBAAkB,2BAA2B,OAAO;AAC1D;;;;;;AAOA,SAAgB,eAAe,SAAyB;CACtD,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,aACd,SACA,SACsB;CACtB,kBAAkB;CAClB,MAAM,UAAU,0BAA0B,SAAS,cAAc;CACjE,MAAM,WAAW,aAAa;CAK9B,MAAM,sBAAsB,GAAG,sBAAsB;CACrD,MAAM,yBAAyB,QAAQ,WAAW,mBAAmB,IACjE,QAAQ,MAAM,sBAAsB,SAAS,CAAC,IAC9C;CAIJ,MAAM,kBAAkB,uBAAuB,SAAS,cAAc,KAAK,SAAS;CAOpF,MAAM,kBAAkB,oCAAoC,wBAA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a,YAAY,GAAG,MAAM,CAAC,CAAC;AACzE;;;;;AAMA,SAAgB,gBACd,EAAE,kBACF,cACe;CACf,MAAM,yBAAyB,eAAe,IAAI,YAAY;CAE9D,MAAM,UAAU,wBAAwB,SAAS;CACjD,IAAI,CAAC,SAAS;EAKZ,IAAI,CAAC,wBACH,MAAM,IAAI,MACR,qHACF;EAEF,MAAM,IAAI,MAAM,yDAAyD;CAC3E;CAIA,OAAO,aAAa,SAAS;EAAE,eAFT,4BAA4B,wBAAwB,YAE/B;EAAG,oBAAoB;EAAM;CAAe,CAAC;AAC1F;;;;;;;;;;;;;;;AAgBA,SAAgB,kBACd,EAAE,kBACF,cAC2B;CAC3B,MAAM,eAAe,aAAa,YAAY,CAAC,CAAC,OAAO;CACvD,IAAI,CAAC,cAAc,OAAO,KAAA;CAC1B,OAAO,aAAa,cAAc;EAAE,oBAAoB;EAAM;CAAe,CAAC;AAChF"}
1
+ {"version":3,"file":"model.js","names":[],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { GatewayLanguageModel, MastraModelGatewayInterface } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport {\n loadSettings,\n resolveDefaultThinkingLevel,\n stripMastraCodeCustomProviderPrefix,\n} from '../onboarding/settings.js';\nimport { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from '../providers/amazon-bedrock-gateway.js';\nimport { isThinkingLevelSetting } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nimport { resolveCredentialStore } from './credential-resolver.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\nimport {\n MASTRA_GATEWAY_PREFIX,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n reloadAuthStorage,\n stripMastraGatewayPrefix,\n} from './mastracode-gateway.js';\nimport type { MastraCodeGatewayOptions } from './mastracode-gateway.js';\n\nexport {\n getAnthropicApiKey,\n getOpenAIApiKey,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n remapOpenAIModelForCodexOAuth,\n resolveAuth,\n} from './mastracode-gateway.js';\nexport type { MastraCodeCustomProvider, MastraCodeGatewayOptions } from './mastracode-gateway.js';\nexport {\n setCredentialStoreProvider,\n hasCredentialStoreProvider,\n resolveTenantFromRequestContext,\n} from './credential-resolver.js';\nexport type { CredentialTenant, CredentialStoreProvider } from './credential-resolver.js';\nexport {\n setCustomProvidersSource,\n hasCustomProvidersSource,\n resolveCustomProviders,\n} from './custom-provider-source.js';\nexport type { CustomProvidersSource } from './custom-provider-source.js';\n\ntype ResolvedModel = GatewayLanguageModel;\ntype ModelRequestHeaders = Record<string, string>;\n\nfunction getAgentControllerHeaders(requestContext?: RequestContext): ModelRequestHeaders | undefined {\n const agentControllerContext = requestContext?.get('controller') as AgentControllerRequestContext<any> | undefined;\n const headers = {\n ...(agentControllerContext?.threadId ? { 'x-thread-id': agentControllerContext.threadId } : {}),\n ...(agentControllerContext?.resourceId ? { 'x-resource-id': agentControllerContext.resourceId } : {}),\n };\n\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nexport function createMastraCodeGateway(options: MastraCodeGatewayOptions): MastraCodeGateway {\n return new MastraCodeGateway(options);\n}\n\nexport function createMastraCodeModelCatalogProvider(gateway: MastraModelGatewayInterface) {\n return gateway instanceof MastraCodeGateway\n ? gateway.createModelCatalogProvider()\n : MastraCodeGateway.createModelCatalogProvider(gateway);\n}\n\n/**\n * Placeholder for future model ID normalization.\n * Currently returns the input unchanged, but exists as a seam\n * for aliasing, casing fixes, or validation in the future.\n */\nexport function resolveModelId(modelId: string): string {\n return modelId;\n}\n\n/**\n * Resolve a model ID to the correct provider instance.\n * Shared by the main agent, observer, and reflector.\n *\n * - For anthropic/* models: Uses stored OAuth credentials when present, otherwise direct API key\n * - For openai/* models: Uses OAuth when configured, otherwise direct API key from AuthStorage\n * - For moonshotai/* models: Uses Moonshot AI Anthropic-compatible endpoint\n * - For all other providers: Uses Mastra's model router (models.dev gateway)\n */\nexport function resolveModel(\n modelId: string,\n options?: { thinkingLevel?: ThinkingLevelSetting; remapForCodexOAuth?: boolean; requestContext?: RequestContext },\n): GatewayLanguageModel {\n reloadAuthStorage();\n const headers = getAgentControllerHeaders(options?.requestContext);\n const settings = loadSettings();\n // Bedrock was previously cataloged under the MastraCode gateway namespace\n // (`mastracode/amazon-bedrock/<model>`). Normalize any legacy saved ids to the\n // standalone `amazon-bedrock/<model>` form so they resolve through the\n // dedicated Bedrock gateway.\n const bedrockLegacyPrefix = `${MASTRACODE_GATEWAY_ID}/amazon-bedrock/`;\n const bedrockNormalizedInput = modelId.startsWith(bedrockLegacyPrefix)\n ? modelId.slice(MASTRACODE_GATEWAY_ID.length + 1)\n : modelId;\n // Deployed web registers a custom providers source (DB-backed, tenant\n // scoped); when registered it is authoritative and settings.json custom\n // providers are ignored. Undefined = local settings-based behavior.\n const customProviders = resolveCustomProviders(options?.requestContext) ?? settings.customProviders;\n // Ids selected from the shared /models catalog were previously persisted in\n // the gateway-qualified `mastracode/<customProviderId>/<model>` form, which\n // parses the provider as `mastracode` and breaks provider config lookup.\n // Normalize at resolution time (in addition to stripping at selection time)\n // so already-saved ids and any surface that persists the raw catalog id\n // still resolve to the custom provider.\n const normalizedInput = stripMastraCodeCustomProviderPrefix(bedrockNormalizedInput, customProviders);\n const isMastraGatewayModel = normalizedInput.startsWith(MASTRA_GATEWAY_PREFIX);\n const normalizedModelId = stripMastraGatewayPrefix(normalizedInput);\n const [providerId, ...modelParts] = normalizedModelId.split('/');\n const bareModelId = modelParts.join('/');\n if (!providerId || !bareModelId) {\n throw new Error(`Invalid model id: ${modelId}`);\n }\n\n if (providerId === AMAZON_BEDROCK_GATEWAY_ID) {\n const bedrockGateway = createAmazonBedrockGateway();\n const routerId = `${AMAZON_BEDROCK_GATEWAY_ID}/${bareModelId}`;\n const auth = bedrockGateway.resolveAuth({\n gatewayId: AMAZON_BEDROCK_GATEWAY_ID,\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n routerId,\n });\n return bedrockGateway.resolveLanguageModel({\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n }\n\n const routerId = `${MASTRACODE_GATEWAY_ID}/${normalizedModelId}`;\n\n const mgApiKey = MastraCodeGateway.getMastraGatewayApiKey();\n const rawGatewayBase =\n settings.memoryGateway?.baseUrl ?? process.env['MASTRA_GATEWAY_URL'] ?? 'https://gateway-api.mastra.ai';\n // Deployed web registers a per-tenant credential store provider; when the\n // request carries an authenticated tenant, resolve credentials through the\n // caller's own store (user > org > env). Undefined = global AuthStorage.\n const credentialStore = resolveCredentialStore(options?.requestContext);\n const gateway = createMastraCodeGateway({\n mastraGatewayBaseUrl: rawGatewayBase.replace(/\\/+$/, '').replace(/\\/v1$/, ''),\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: Boolean(mgApiKey && isMastraGatewayModel),\n thinkingLevel: options?.thinkingLevel,\n customProviders,\n credentialStore,\n });\n\n const auth = gateway.resolveAuth({\n gatewayId: MASTRACODE_GATEWAY_ID,\n providerId,\n modelId: bareModelId,\n routerId,\n });\n\n if (!auth && credentialStore?.allowEnvironmentFallback === false) {\n throw new Error(\n `No usable ${providerId} credential is configured for this signed-in Factory account. Connect the provider or add an organization credential, then try again.`,\n );\n }\n\n return gateway.resolveLanguageModel({\n providerId,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n}\n\nexport interface ThinkingRequestContext {\n state?: { thinkingLevel?: unknown };\n session?: { modeId?: string };\n}\n/**\n * Resolve the effective thinking level for the current request.\n *\n * Precedence:\n * 1. Session override (`state.thinkingLevel`, set via /think or the session\n * settings panel).\n * 2. Per-mode default from settings (`models.modeThinkingDefaults[mode]`).\n * 3. Global default (`preferences.thinkingLevel`).\n *\n * Resolved per-request (not seeded at session start) so configuration changes\n * apply to the next request of every session — including automated\n * (rule-driven) Factory runs that nobody ever opens interactively.\n */\n\nexport function resolveRequestThinkingLevel(\n agentControllerContext: ThinkingRequestContext | undefined,\n settingsPath?: string,\n): ThinkingLevelSetting {\n const override = agentControllerContext?.state?.thinkingLevel;\n if (isThinkingLevelSetting(override)) return override;\n const modeId = agentControllerContext?.session?.modeId;\n return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;\n}\n\n/**\n * Dynamic model function that reads the current model from controller state.\n * This allows runtime model switching via the /models picker.\n */\nexport function getDynamicModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel {\n const agentControllerContext = requestContext.get('controller') as AgentControllerRequestContext<any> | undefined;\n\n const modelId = agentControllerContext?.session?.modelId;\n if (!modelId) {\n // A missing controller context means the run was started without session\n // request context at all (e.g. a signal delivered to an idle thread) —\n // \"use /models\" would mislead there, the user's selection was never the\n // problem.\n if (!agentControllerContext) {\n throw new Error(\n 'No model available: this run started without a controller session context, so no model selection could be resolved.',\n );\n }\n throw new Error('No model selected. Use /models to select a model first.');\n }\n\n const thinkingLevel = resolveRequestThinkingLevel(agentControllerContext, settingsPath);\n\n return resolveModel(modelId, { thinkingLevel, remapForCodexOAuth: true, requestContext });\n}\n\n/**\n * Goal judge model resolver for the agent's `goal.judge` config. Resolves the\n * configured goal judge model through mastracode's gateway so provider\n * credentials (stored in auth storage, not just env) are injected — a bare model\n * id handed to core's default model router would fail to find the API key.\n *\n * Returns `undefined` when no judge model is configured, which keeps the goal\n * step a complete no-op (the goal mechanism requires a judge to do anything).\n *\n * `settingsPath` must be the same source `createMastraCode()` reads from so the\n * judge model and the goal budget (`goalMaxTurns`) come from one config — with a\n * custom `settingsPath` a bare `loadSettings()` here could read a different file\n * and silently turn the goal step into a no-op.\n */\nexport function getGoalJudgeModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | undefined {\n const judgeModelId = loadSettings(settingsPath).models.goalJudgeModel;\n if (!judgeModelId) return undefined;\n return resolveModel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E,QAAQ,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/B,CAAC,CA0CD;AAED;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,iCAA2B,CAAC;AACzD,cAAc,0BAA0B,CAAC;AAEzC;;;;GAIG;AACH,OAAO,EACL,KAAK,EACL,QAAQ,EACR,eAAe,EACf,iBAAiB,EACjB,UAAU,EACV,sBAAsB,EACtB,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;AAC7B,YAAY,EACV,YAAY,EACZ,WAAW,EACX,WAAW,EACX,UAAU,EACV,aAAa,EACb,eAAe,EACf,UAAU,EACV,kBAAkB,EAClB,KAAK,EACL,gBAAgB,EAChB,cAAc,GACf,MAAM,qBAAqB,CAAC"}
package/dist/index.js CHANGED
@@ -383,6 +383,7 @@ async function createMastraCodeAgentController(config) {
383
383
  };
384
384
  const githubSignals = globalSettings.signals?.experimentalGithubSignals && !config?.disableGithubSignals ? new GithubSignals({
385
385
  cwd: project.rootPath,
386
+ pollIntervalMs: globalSettings.signals.githubPollIntervalMs,
386
387
  gitcrawlCommand: process.env.MASTRACODE_GITCRAWL_BIN ?? process.env.GITCRAWL_BIN ?? process.env.MASTRACODE_GITCRAWL_COMMAND ?? process.env.GITCRAWL_COMMAND,
387
388
  getNotificationStreamOptions
388
389
  }) : void 0;