@mastra/code-sdk 1.14.0-alpha.1 → 1.14.0-alpha.2

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.
@@ -3,56 +3,60 @@
3
3
  *
4
4
  * Locally, model resolution reads the server-global file-backed `AuthStorage`.
5
5
  * A deployed web host registers a {@link CredentialStoreProvider} at boot; from
6
- * then on `resolveModel` derives the calling tenant from the request context
7
- * (the web auth gate stashes the authenticated user under the `user` key) and
8
- * resolves credentials through the tenant's own store — user credentials over
9
- * org credentials over server env vars, with OAuth refresh owned by the store.
6
+ * then on `resolveModel` uses the host's trusted execution policy, never mutable
7
+ * session state. Factory scope reads organization credentials only. User scope reads
8
+ * the Factory session owner's credentials only, or the authenticated principal
9
+ * for project-less personal sessions.
10
10
  *
11
11
  * When no provider is registered (TUI, local web), everything falls through to
12
12
  * the existing global behavior unchanged.
13
13
  */
14
14
  import type { RequestContext } from '@mastra/core/request-context';
15
15
  import type { CredentialStore } from '../auth/types.js';
16
- /** The identity a credential lookup is scoped to. */
16
+ export type CredentialScope = 'factory' | 'user';
17
+ /** The identity and exclusive scope a credential lookup is resolved against. */
17
18
  export interface CredentialTenant {
18
19
  /** Org tenant; absent for personal accounts (store impls may synthesize one). */
19
20
  orgId?: string;
20
- /** Stable user id from the web auth adapter. */
21
+ /** Stable user id used for user-scoped credentials and tenant cache keys. */
21
22
  userId: string;
22
- /**
23
- * Resolve org-shared credentials over the user's personal ones. Set by
24
- * trusted server code for automated (factory) runs so they ride the org's
25
- * shared keys first and only fall back to the acting user's credentials.
26
- */
27
- orgFirst?: boolean;
23
+ /** Exclusive credential scope for this request. */
24
+ credentialScope: CredentialScope;
28
25
  }
29
26
  /**
30
- * Returns a tenant-scoped {@link CredentialStore}, or `undefined` to fall back
31
- * to the global store (e.g. tenant storage temporarily unavailable). Must be
32
- * synchronous — implementations serve from a primed snapshot and do
33
- * authoritative async work inside `getApiKey`.
27
+ * Returns a tenant-scoped {@link CredentialStore}, or `undefined` when tenant
28
+ * storage is unavailable. Must be synchronous — implementations serve from a
29
+ * primed snapshot and do authoritative async work inside `getApiKey`.
34
30
  */
35
31
  export type CredentialStoreProvider = (tenant: CredentialTenant) => CredentialStore | undefined;
32
+ export type CredentialTenantResolver = (requestContext: RequestContext) => Promise<CredentialTenant | undefined>;
36
33
  /** Register (or clear) the tenant credential store provider. Deployed-web only. */
37
- export declare function setCredentialStoreProvider(provider: CredentialStoreProvider | undefined): void;
34
+ export declare function setCredentialStoreProvider(provider: CredentialStoreProvider | undefined, resolveTenant?: CredentialTenantResolver): void;
35
+ /** Refresh authority before a fresh model invocation; cloned contexts inherit only an opaque token. */
36
+ export declare function prepareCredentialTenant(requestContext?: RequestContext): Promise<void>;
37
+ export declare function withCredentialTenantPreparation<T>(resolve: (ctx: {
38
+ requestContext: RequestContext;
39
+ }) => T): (ctx: {
40
+ requestContext: RequestContext;
41
+ }) => Promise<T>;
38
42
  /**
39
43
  * Whether a tenant provider is registered. Used to disable the
40
44
  * `loadStoredApiKeysIntoEnv` side-channel in deployed mode — per-tenant
41
45
  * credentials must never leak into process-global env vars.
42
46
  */
43
47
  export declare function hasCredentialStoreProvider(): boolean;
48
+ export declare function hasCredentialTenantResolver(): boolean;
49
+ export declare function resolveCredentialScope(requestContext?: RequestContext): CredentialScope;
44
50
  /**
45
51
  * Derive the calling tenant from a request context, if an authenticated web
46
52
  * user was stashed on it. Mirrors the web layer's stable-id resolution
47
53
  * (`workosId` falling back to the provider `id`).
48
54
  *
49
- * The value under `user` is whatever the active auth provider's
50
- * `authenticateToken` returned, so its shape follows the provider: a flat user
51
- * (WorkOS) or a `{ session, user }` wrapper (better-auth). Reading only the
52
- * flat shape resolves no tenant at all for the wrapper, which in deployed mode
53
- * fails closed to an empty credential store.
55
+ * Session state and HTTP-supplied policy values never establish credential authority.
54
56
  */
55
57
  export declare function resolveTenantFromRequestContext(requestContext?: RequestContext): CredentialTenant | undefined;
58
+ /** Authenticated principal only, for hosts resolving durable session ownership. */
59
+ export declare function resolveAuthenticatedCredentialTenant(requestContext?: RequestContext): CredentialTenant | undefined;
56
60
  /**
57
61
  * Resolve the credential store for a request. Local mode returns `undefined`
58
62
  * and keeps the global `AuthStorage` behavior. Once deployed web registers a
@@ -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,CAsBnG"}
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,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B,oCAAoC,CAAC,cAAc,CAAC,EAAE,cAAc,GAAG,gBAAgB,GAAG,SAAS,CAclH;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,cAAc,CAAC,EAAE,cAAc,GAAG,eAAe,GAAG,SAAS,CAsBnG"}
@@ -1,5 +1,8 @@
1
1
  //#region src/agents/credential-resolver.ts
2
+ const CREDENTIAL_POLICY_KEY = "mastracode__credentialPolicy";
2
3
  let credentialStoreProvider;
4
+ let credentialTenantResolver;
5
+ let trustedTenants = /* @__PURE__ */ new WeakMap();
3
6
  const unavailableTenantCredentialStore = {
4
7
  allowEnvironmentFallback: false,
5
8
  reload() {},
@@ -8,8 +11,34 @@ const unavailableTenantCredentialStore = {
8
11
  async getApiKey() {}
9
12
  };
10
13
  /** Register (or clear) the tenant credential store provider. Deployed-web only. */
11
- function setCredentialStoreProvider(provider) {
14
+ function setCredentialStoreProvider(provider, resolveTenant) {
12
15
  credentialStoreProvider = provider;
16
+ credentialTenantResolver = provider ? resolveTenant : void 0;
17
+ trustedTenants = /* @__PURE__ */ new WeakMap();
18
+ }
19
+ /** Refresh authority before a fresh model invocation; cloned contexts inherit only an opaque token. */
20
+ async function prepareCredentialTenant(requestContext) {
21
+ if (!credentialTenantResolver) return;
22
+ if (!requestContext) throw new Error("Tenant model resolution requires a request context.");
23
+ const inheritedToken = requestContext.get(CREDENTIAL_POLICY_KEY);
24
+ const inheritedPolicy = inheritedToken && typeof inheritedToken === "object" ? trustedTenants.get(inheritedToken) : void 0;
25
+ const sourceController = inheritedPolicy?.sourceContext.get("controller");
26
+ const sourceContext = inheritedPolicy && sourceController?.resourceId ? inheritedPolicy.sourceContext : requestContext;
27
+ const token = {};
28
+ requestContext.set(CREDENTIAL_POLICY_KEY, token);
29
+ trustedTenants.set(token, { sourceContext });
30
+ const tenant = await credentialTenantResolver(sourceContext);
31
+ if (!tenant) throw new Error("Tenant model credential policy could not be resolved.");
32
+ trustedTenants.set(token, {
33
+ tenant,
34
+ sourceContext
35
+ });
36
+ }
37
+ function withCredentialTenantPreparation(resolve) {
38
+ return async (ctx) => {
39
+ await prepareCredentialTenant(ctx.requestContext);
40
+ return resolve(ctx);
41
+ };
13
42
  }
14
43
  /**
15
44
  * Whether a tenant provider is registered. Used to disable the
@@ -19,47 +48,38 @@ function setCredentialStoreProvider(provider) {
19
48
  function hasCredentialStoreProvider() {
20
49
  return credentialStoreProvider !== void 0;
21
50
  }
22
- /**
23
- * Whether the request context belongs to a run on a factory-owned session.
24
- *
25
- * The agent controller stamps the session's state onto the request context
26
- * under `controller`, and only trusted factory server code ever writes
27
- * `factoryProjectId` into session state (board-run creation) — interactive
28
- * chat sessions never carry it. Runs on such sessions resolve credentials
29
- * org > user regardless of who sent the message: a board run continued
30
- * interactively, or a model switch inside it, is still org work.
31
- */
32
- function isFactorySessionContext(requestContext) {
33
- const controller = requestContext?.get("controller");
34
- if (!controller || typeof controller !== "object") return false;
35
- const factoryProjectId = controller.state?.factoryProjectId;
36
- return typeof factoryProjectId === "string" && factoryProjectId.length > 0;
51
+ function hasCredentialTenantResolver() {
52
+ return credentialTenantResolver !== void 0;
53
+ }
54
+ function resolveCredentialScope(requestContext) {
55
+ return resolveTenantFromRequestContext(requestContext)?.credentialScope ?? "user";
37
56
  }
38
57
  /**
39
58
  * Derive the calling tenant from a request context, if an authenticated web
40
59
  * user was stashed on it. Mirrors the web layer's stable-id resolution
41
60
  * (`workosId` falling back to the provider `id`).
42
61
  *
43
- * The value under `user` is whatever the active auth provider's
44
- * `authenticateToken` returned, so its shape follows the provider: a flat user
45
- * (WorkOS) or a `{ session, user }` wrapper (better-auth). Reading only the
46
- * flat shape resolves no tenant at all for the wrapper, which in deployed mode
47
- * fails closed to an empty credential store.
62
+ * Session state and HTTP-supplied policy values never establish credential authority.
48
63
  */
49
64
  function resolveTenantFromRequestContext(requestContext) {
65
+ if (!credentialTenantResolver) return resolveAuthenticatedCredentialTenant(requestContext);
66
+ const token = requestContext?.get(CREDENTIAL_POLICY_KEY);
67
+ return token && typeof token === "object" ? trustedTenants.get(token)?.tenant : void 0;
68
+ }
69
+ /** Authenticated principal only, for hosts resolving durable session ownership. */
70
+ function resolveAuthenticatedCredentialTenant(requestContext) {
50
71
  const raw = requestContext?.get("user");
51
72
  if (!raw || typeof raw !== "object") return void 0;
52
73
  const wrapped = Boolean(raw.user && typeof raw.user === "object" && raw.session && typeof raw.session === "object");
53
74
  const user = wrapped ? raw.user : raw;
54
- const orgId = wrapped ? raw.session?.activeOrganizationId : user.organizationId;
55
- const userId = user.workosId ?? user.id;
56
- if (typeof userId !== "string" || !userId) return void 0;
57
- if (orgId !== void 0 && typeof orgId !== "string") return void 0;
58
- const orgFirst = raw.orgFirstCredentials === true || user.orgFirstCredentials === true || isFactorySessionContext(requestContext);
75
+ const principalOrgId = wrapped ? raw.session?.activeOrganizationId : user.organizationId;
76
+ const principalUserId = user.workosId ?? user.id;
77
+ if (typeof principalUserId !== "string" || !principalUserId) return void 0;
78
+ if (principalOrgId !== void 0 && typeof principalOrgId !== "string") return void 0;
59
79
  return {
60
- orgId,
61
- userId,
62
- ...orgFirst ? { orgFirst } : {}
80
+ orgId: principalOrgId,
81
+ userId: principalUserId,
82
+ credentialScope: "user"
63
83
  };
64
84
  }
65
85
  /**
@@ -74,9 +94,8 @@ function resolveCredentialStore(requestContext) {
74
94
  if (!tenant) {
75
95
  const rawUser = requestContext?.get("user");
76
96
  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)
97
+ reason: rawUser === void 0 ? "missing-user-context" : "credential-policy-unavailable",
98
+ hasRequestContext: requestContext !== void 0
80
99
  });
81
100
  return unavailableTenantCredentialStore;
82
101
  }
@@ -85,13 +104,14 @@ function resolveCredentialStore(requestContext) {
85
104
  console.warn("[MastraCode] Tenant credential resolution failed closed", {
86
105
  reason: "credential-store-unavailable",
87
106
  hasOrganization: tenant.orgId !== void 0,
88
- orgFirst: tenant.orgFirst === true
107
+ credentialScope: tenant.credentialScope,
108
+ ownerResolved: tenant.credentialScope === "factory" || tenant.userId !== void 0
89
109
  });
90
110
  return unavailableTenantCredentialStore;
91
111
  }
92
112
  return store;
93
113
  }
94
114
  //#endregion
95
- export { hasCredentialStoreProvider, resolveCredentialStore, resolveTenantFromRequestContext, setCredentialStoreProvider };
115
+ export { hasCredentialStoreProvider, hasCredentialTenantResolver, prepareCredentialTenant, resolveAuthenticatedCredentialTenant, resolveCredentialScope, resolveCredentialStore, resolveTenantFromRequestContext, setCredentialStoreProvider, withCredentialTenantPreparation };
96
116
 
97
117
  //# sourceMappingURL=credential-resolver.js.map
@@ -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) {\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;CACpD,OAAO,4BAA4B,KAAA;AACrC;;;;;;;;;;;AA8BA,SAAS,wBAAwB,gBAA0C;CACzE,MAAM,aAAa,gBAAgB,IAAI,YAAY;CACnD,IAAI,CAAC,cAAc,OAAO,eAAe,UAAU,OAAO;CAC1D,MAAM,mBAAmB,WAAW,OAAO;CAC3C,OAAO,OAAO,qBAAqB,YAAY,iBAAiB,SAAS;AAC3E;;;;;;;;;;;;AAaA,SAAgB,gCAAgC,gBAA+D;CAC7G,MAAM,MAAM,gBAAgB,IAAI,MAAM;CACtC,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU,OAAO,KAAA;CAK5C,MAAM,UAAU,QAAQ,IAAI,QAAQ,OAAO,IAAI,SAAS,YAAY,IAAI,WAAW,OAAO,IAAI,YAAY,QAAQ;CAClH,MAAM,OAAO,UAAW,IAAI,OAA8B;CAC1D,MAAM,QAAQ,UAAU,IAAI,SAAS,uBAAuB,KAAK;CACjE,MAAM,SAAS,KAAK,YAAY,KAAK;CAIrC,IAAI,OAAO,WAAW,YAAY,CAAC,QAAQ,OAAO,KAAA;CAClD,IAAI,UAAU,KAAA,KAAa,OAAO,UAAU,UAAU,OAAO,KAAA;CAI7D,MAAM,WACJ,IAAI,wBAAwB,QAAQ,KAAK,wBAAwB,QAAQ,wBAAwB,cAAc;CACjH,OAAO;EAAE;EAAO;EAAQ,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;CAAG;AAC5D;;;;;;;AAQA,SAAgB,uBAAuB,gBAA8D;CACnG,IAAI,CAAC,yBAAyB,OAAO,KAAA;CACrC,MAAM,SAAS,gCAAgC,cAAc;CAC7D,IAAI,CAAC,QAAQ;EACX,MAAM,UAAU,gBAAgB,IAAI,MAAM;EAC1C,QAAQ,KAAK,2DAA2D;GACtE,QAAQ,YAAY,KAAA,IAAY,yBAAyB;GACzD,mBAAmB,mBAAmB,KAAA;GACtC,gBAAgB,wBAAwB,cAAc;EACxD,CAAC;EACD,OAAO;CACT;CACA,MAAM,QAAQ,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"}
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` uses the host's trusted execution policy, never mutable\n * session state. Factory scope reads organization credentials only. User scope reads\n * the Factory session owner's credentials only, or the authenticated principal\n * for project-less personal sessions.\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\nexport type CredentialScope = 'factory' | 'user';\n\n/** The identity and exclusive scope a credential lookup is resolved against. */\nexport interface CredentialTenant {\n /** Org tenant; absent for personal accounts (store impls may synthesize one). */\n orgId?: string;\n /** Stable user id used for user-scoped credentials and tenant cache keys. */\n userId: string;\n /** Exclusive credential scope for this request. */\n credentialScope: CredentialScope;\n}\n\n/**\n * Returns a tenant-scoped {@link CredentialStore}, or `undefined` when tenant\n * storage is unavailable. Must be synchronous — implementations serve from a\n * primed snapshot and do authoritative async work inside `getApiKey`.\n */\nexport type CredentialStoreProvider = (tenant: CredentialTenant) => CredentialStore | undefined;\n\nexport type CredentialTenantResolver = (requestContext: RequestContext) => Promise<CredentialTenant | undefined>;\n\nconst CREDENTIAL_POLICY_KEY = 'mastracode__credentialPolicy';\nlet credentialStoreProvider: CredentialStoreProvider | undefined;\nlet credentialTenantResolver: CredentialTenantResolver | undefined;\nlet trustedTenants = new WeakMap<object, { tenant?: CredentialTenant; sourceContext: RequestContext }>();\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(\n provider: CredentialStoreProvider | undefined,\n resolveTenant?: CredentialTenantResolver,\n): void {\n credentialStoreProvider = provider;\n credentialTenantResolver = provider ? resolveTenant : undefined;\n trustedTenants = new WeakMap();\n}\n\n/** Refresh authority before a fresh model invocation; cloned contexts inherit only an opaque token. */\nexport async function prepareCredentialTenant(requestContext?: RequestContext): Promise<void> {\n if (!credentialTenantResolver) return;\n if (!requestContext) throw new Error('Tenant model resolution requires a request context.');\n const inheritedToken = requestContext.get(CREDENTIAL_POLICY_KEY);\n const inheritedPolicy =\n inheritedToken && typeof inheritedToken === 'object' ? trustedTenants.get(inheritedToken) : undefined;\n // Subagents and internal memory contexts can strip the controller's thread identity.\n // Keep their billing origin outside those mutable context fields.\n const sourceController = inheritedPolicy?.sourceContext.get('controller') as { resourceId?: string } | undefined;\n const sourceContext =\n inheritedPolicy && sourceController?.resourceId ? inheritedPolicy.sourceContext : requestContext;\n const token = {};\n requestContext.set(CREDENTIAL_POLICY_KEY, token);\n trustedTenants.set(token, { sourceContext });\n const tenant = await credentialTenantResolver(sourceContext);\n if (!tenant) throw new Error('Tenant model credential policy could not be resolved.');\n trustedTenants.set(token, { tenant, sourceContext });\n}\n\nexport function withCredentialTenantPreparation<T>(resolve: (ctx: { requestContext: RequestContext }) => T) {\n return async (ctx: { requestContext: RequestContext }): Promise<T> => {\n await prepareCredentialTenant(ctx.requestContext);\n return resolve(ctx);\n };\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\nexport function hasCredentialTenantResolver(): boolean {\n return credentialTenantResolver !== 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}\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\nexport function resolveCredentialScope(requestContext?: RequestContext): CredentialScope {\n return resolveTenantFromRequestContext(requestContext)?.credentialScope ?? 'user';\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 * Session state and HTTP-supplied policy values never establish credential authority.\n */\nexport function resolveTenantFromRequestContext(requestContext?: RequestContext): CredentialTenant | undefined {\n if (!credentialTenantResolver) return resolveAuthenticatedCredentialTenant(requestContext);\n const token = requestContext?.get(CREDENTIAL_POLICY_KEY);\n return token && typeof token === 'object' ? trustedTenants.get(token)?.tenant : undefined;\n}\n\n/** Authenticated principal only, for hosts resolving durable session ownership. */\nexport function resolveAuthenticatedCredentialTenant(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.\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 principalOrgId = wrapped ? raw.session?.activeOrganizationId : user.organizationId;\n const principalUserId = user.workosId ?? user.id;\n if (typeof principalUserId !== 'string' || !principalUserId) return undefined;\n if (principalOrgId !== undefined && typeof principalOrgId !== 'string') return undefined;\n\n return { orgId: principalOrgId, userId: principalUserId, credentialScope: 'user' };\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' : 'credential-policy-unavailable',\n hasRequestContext: requestContext !== undefined,\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 credentialScope: tenant.credentialScope,\n ownerResolved: tenant.credentialScope === 'factory' || tenant.userId !== undefined,\n });\n return unavailableTenantCredentialStore;\n }\n return store;\n}\n"],"mappings":";AAsCA,MAAM,wBAAwB;AAC9B,IAAI;AACJ,IAAI;AACJ,IAAI,iCAAiB,IAAI,QAA8E;AAEvG,MAAM,mCAAoD;CACxD,0BAA0B;CAC1B,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E,MAAM,sBAAsB,CAAC;AACjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,MAAM,EAAgB,MAAM,gBAAgB,CAAC;AAEtD,OAAO,EAAE,sBAAsB,EAAiC,MAAM,uBAAuB,CAAC;AAI9F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAsLpD,OAAO,EAAE,sBAAsB,EAAE,CAAC;AA8BlC;;;GAGG;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,EAC7C,SAAS,CAAC,EAAE,SAAS,yBAsBsB;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE;IAmJ3E;;;OAGG;eACc,OAAO,CAAC,IAAI,CAAC;EAKjC"}
@@ -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 { Knowledge } from '@mastra/core/knowledge';\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_OBS_THRESHOLD, DEFAULT_REF_THRESHOLD } from '../constants.js';\nimport { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeScopeIdentity } from '../knowledge-scope.js';\nimport { MASTRACODE_AUTO_OM_MODELS, resolveAutoOMModelId } from '../onboarding/packs.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 { getActiveMemoryRoute, resolveModel } from './model.js';\n\n/** Route-backed OM fallback entry. */\ntype MemoryModelRouteEntry = { id: string; model: GatewayLanguageModel };\n\n/**\n * Resolve the active model route's memory models, starting at a same-thread\n * pending fallback hop. Returns `'auto'` when the route's first memory model is\n * Auto, and `undefined` when the route sets no memory model.\n */\nfunction resolveRouteMemoryModels(\n state: MastraCodeState | undefined,\n threadId: string | null | undefined,\n resolve: (modelId: string) => GatewayLanguageModel,\n): MemoryModelRouteEntry[] | 'auto' | undefined {\n const memoryRoute = getActiveMemoryRoute(state, threadId);\n if (memoryRoute[0]?.memoryModelId === 'auto') return 'auto';\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 || entry.memoryModelId === 'auto' || 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: resolve(entry.memoryModelId),\n });\n } catch {\n break;\n }\n }\n return entries.length > 0 ? entries : undefined;\n}\n\n/**\n * The authoritative per-caller Factory memory-settings row, placed on the request\n * context before Factory's model-dependent processors run. `null` means the row\n * exists but is empty (every role auto). An unavailable sentinel or a missing\n * value on a Factory-owned session falls back to Auto roles and default\n * thresholds/attachments, so memory keeps working while Factory reports the error.\n */\ninterface FactoryMemorySettings {\n observerModelId: string | null;\n reflectorModelId: string | null;\n observationThreshold: number | null;\n reflectionThreshold: number | null;\n observeAttachments: 'auto' | boolean | null;\n}\n\ntype FactoryMemorySettingsContext =\n | FactoryMemorySettings\n | null\n | { status: 'unavailable'; reason: string }\n | undefined;\n\nfunction getFactoryMemorySettingsContext(requestContext: RequestContext): FactoryMemorySettingsContext {\n return requestContext.get('mastra__factoryMemorySettings') as FactoryMemorySettingsContext;\n}\n\nfunction isFactoryMemorySettingsUnavailable(\n settings: FactoryMemorySettingsContext,\n): settings is { status: 'unavailable'; reason: string } {\n return settings !== null && typeof settings === 'object' && 'status' in settings && settings.status === 'unavailable';\n}\n\nfunction getMainModelId(requestContext: RequestContext): string | undefined {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n return controller?.session.modelId || (controller?.getState()?.currentModelId as string | undefined);\n}\n\n/**\n * Resolve one OM role's model for this invocation. Returns `'auto'` for Memory's\n * auto policy, or a concrete model. Factory's DB row is authoritative for\n * Factory sessions (an unreadable row falls back to auto). Otherwise the active\n * model route's memory models win, then the per-role selection, then legacy\n * concrete settings.\n */\nfunction resolveOmRoleModelForRequest(\n role: 'observer' | 'reflector',\n requestContext: RequestContext,\n settingsPath?: string,\n options?: { disableSettingsOmSeed?: boolean },\n): 'auto' | 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 const factorySettingsContext = getFactoryMemorySettingsContext(requestContext);\n const isFactory = typeof state?.factoryProjectId === 'string';\n\n const useModel = (modelId: string) => {\n requestContext.set(`om.${role}.selectionMode`, 'model');\n requestContext.set(`om.${role}.effectiveModelId`, modelId);\n return resolveModel(modelId, resolveOptions);\n };\n const useAuto = () => {\n requestContext.set(`om.${role}.selectionMode`, 'auto');\n // These two keys are declared in the span-context allowlist\n // (`mastracode/sdk/src/index.ts`), so traces can report intent separately from\n // the effective concrete model without either being mistaken for a model ID.\n requestContext.set(`om.${role}.effectiveModelId`, resolveAutoOMModelId(getMainModelId(requestContext)));\n return 'auto' as const;\n };\n\n if (\n isFactoryMemorySettingsUnavailable(factorySettingsContext) ||\n (factorySettingsContext === undefined && isFactory)\n ) {\n return useAuto();\n }\n if (factorySettingsContext !== undefined) {\n const factoryModelId = factorySettingsContext?.[`${role}ModelId`];\n return factoryModelId ? useModel(factoryModelId) : useAuto();\n }\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 override resolution for\n // observational memory as it does for the main model. Hosts that disable the\n // settings seed never read it.\n const settings = options?.disableSettingsOmSeed ? undefined : loadSettings(settingsPath);\n const routeMemory = resolveRouteMemoryModels(state, controller?.threadId, modelId =>\n resolveModel(modelId, resolveOptions),\n );\n if (routeMemory === 'auto') return useAuto();\n if (routeMemory) {\n requestContext.set(`om.${role}.selectionMode`, 'model');\n requestContext.set(`om.${role}.effectiveModelId`, routeMemory[0]?.model.modelId);\n return routeMemory.length === 1 ? routeMemory[0]!.model : routeMemory;\n }\n\n const selection: unknown = state?.[`${role}ModelSelection`];\n if (selection === 'auto') return useAuto();\n if (typeof selection === 'string' && selection) return useModel(selection);\n if (\n selection &&\n typeof selection === 'object' &&\n 'modelId' in selection &&\n typeof selection.modelId === 'string' &&\n selection.modelId\n ) {\n return useModel(selection.modelId);\n }\n\n const roleOverride =\n role === 'observer' ? settings?.models?.observerModelOverride : settings?.models?.reflectorModelOverride;\n if (roleOverride) return useModel(roleOverride);\n const legacyModelId = state?.[`${role}ModelId`];\n if (typeof legacyModelId === 'string' && legacyModelId) return useModel(legacyModelId);\n return useAuto();\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 knowledge?: Knowledge,\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 // Instances replaced by a config change may still have background work in flight.\n const retiredMemories = new Set<Memory>();\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 // Routes the concrete model Memory's `'auto'` picks through Mastra Code's\n // credential-aware resolver, like every other Mastra Code model.\n const resolveMemoryModel = (modelId: string, { requestContext }: { requestContext?: RequestContext }) =>\n resolveModel(modelId, { remapForCodexOAuth: true, requestContext, anthropicPromptCacheScope: 'system' });\n\n const resolveMemory = ({ 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 // The Factory row is authoritative and read per invocation, so a stored\n // threshold/attachment change reaches the running Memory without a session.\n const factorySettingsContext = getFactoryMemorySettingsContext(requestContext);\n const factorySettingsUnavailable =\n isFactoryMemorySettingsUnavailable(factorySettingsContext) || (factorySettingsContext === undefined && isFactory);\n const factorySettings = factorySettingsUnavailable ? null : factorySettingsContext;\n const obsThreshold =\n factorySettings !== undefined\n ? (factorySettings?.observationThreshold ?? DEFAULT_OBS_THRESHOLD)\n : (state?.observationThreshold ?? DEFAULT_OBS_THRESHOLD);\n const refThreshold =\n factorySettings !== undefined\n ? (factorySettings?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD)\n : (state?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD);\n const caveman = state?.cavemanObservations ?? false;\n\n const observerPreviousObservationTokens = 1000;\n // The row is authoritative: an absent value means the user left it on Auto,\n // which the config API reports as 'auto' and Memory resolves by model\n // capability.\n const observeAttachments =\n factorySettings !== undefined ? (factorySettings?.observeAttachments ?? 'auto') : state?.observeAttachments;\n // Factory sessions get a factory-only Subconscious config, so the cache key\n // carries Factory presence and settings availability to keep those configs\n // 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 if (cachedMemory) {\n const retired = cachedMemory;\n retiredMemories.add(retired);\n // settled() rejects if the instance's OM engine failed to start; that must not surface as\n // an unhandled rejection from a background retirement.\n void retired\n .settled()\n .catch(() => {})\n .finally(() => retiredMemories.delete(retired));\n }\n\n cachedMemory = new Memory({\n storage,\n ...(knowledge ? { knowledge } : {}),\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 process.env.MASTRACODE_DISABLE_TITLE_GENERATION === '1'\n ? false\n : {\n model: ({ requestContext }) => {\n const resolved = getObserverModel({ requestContext });\n if (resolved === 'auto') {\n return resolveMemoryModel(resolveAutoOMModelId(getMainModelId(requestContext)), { requestContext });\n }\n return Array.isArray(resolved) ? resolved[0]!.model : resolved;\n },\n },\n observationalMemory:\n process.env.MASTRACODE_DISABLE_OBSERVATIONAL_MEMORY === '1'\n ? false\n : {\n enabled: true,\n autoModels: MASTRACODE_AUTO_OM_MODELS,\n resolveModel: resolveMemoryModel,\n temporalMarkers: true,\n retrieval: vector ? { vector: true } : true,\n experimental_subconscious: subconsciousAvailable\n ? new Subconscious({\n defaultScope: '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 return Object.assign(resolveMemory, {\n /**\n * Wait for background memory work (buffered observations, reflections, indexing) in every\n * instance this factory created. Await before closing storage.\n */\n async settled(): Promise<void> {\n // Drain every instance even if one rejects, so teardown can still close storage.\n await Promise.allSettled([cachedMemory?.settled(), ...[...retiredMemories].map(memory => memory.settled())]);\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAyBA,SAAS,yBACP,OACA,UACA,SAC8C;C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B,MAAM,QAAQ,WAAW,CAAC,cAAc,QAAQ,GAAG,GAAG,CAAC,GAAG,eAAe,CAAC,CAAC,KAAI,WAAU,OAAO,QAAQ,CAAC,CAAC,CAAC;CAC7G,EACF,CAAC;AACH"}
1
+ {"version":3,"file":"memory.js","names":[],"sources":["../../src/agents/memory.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { Knowledge } from '@mastra/core/knowledge';\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_OBS_THRESHOLD, DEFAULT_REF_THRESHOLD } from '../constants.js';\nimport { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeScopeIdentity } from '../knowledge-scope.js';\nimport { MASTRACODE_AUTO_OM_MODELS, resolveAutoOMModelId } from '../onboarding/packs.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 { getActiveMemoryRoute, resolveModel } from './model.js';\n\n/** Route-backed OM fallback entry. */\ntype MemoryModelRouteEntry = { id: string; model: ReturnType<typeof resolveModel> };\n\n/**\n * Resolve the active model route's memory models, starting at a same-thread\n * pending fallback hop. Returns `'auto'` when the route's first memory model is\n * Auto, and `undefined` when the route sets no memory model.\n */\nfunction resolveRouteMemoryModels(\n state: MastraCodeState | undefined,\n threadId: string | null | undefined,\n resolve: (modelId: string) => ReturnType<typeof resolveModel>,\n): MemoryModelRouteEntry[] | 'auto' | undefined {\n const memoryRoute = getActiveMemoryRoute(state, threadId);\n if (memoryRoute[0]?.memoryModelId === 'auto') return 'auto';\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 || entry.memoryModelId === 'auto' || 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: resolve(entry.memoryModelId),\n });\n } catch {\n break;\n }\n }\n return entries.length > 0 ? entries : undefined;\n}\n\n/**\n * The authoritative per-caller Factory memory-settings row, placed on the request\n * context before Factory's model-dependent processors run. `null` means the row\n * exists but is empty (every role auto). An unavailable sentinel or a missing\n * value on a Factory-owned session falls back to Auto roles and default\n * thresholds/attachments, so memory keeps working while Factory reports the error.\n */\ninterface FactoryMemorySettings {\n observerModelId: string | null;\n reflectorModelId: string | null;\n observationThreshold: number | null;\n reflectionThreshold: number | null;\n observeAttachments: 'auto' | boolean | null;\n}\n\ntype FactoryMemorySettingsContext =\n | FactoryMemorySettings\n | null\n | { status: 'unavailable'; reason: string }\n | undefined;\n\nfunction getFactoryMemorySettingsContext(requestContext: RequestContext): FactoryMemorySettingsContext {\n return requestContext.get('mastra__factoryMemorySettings') as FactoryMemorySettingsContext;\n}\n\nfunction isFactoryMemorySettingsUnavailable(\n settings: FactoryMemorySettingsContext,\n): settings is { status: 'unavailable'; reason: string } {\n return settings !== null && typeof settings === 'object' && 'status' in settings && settings.status === 'unavailable';\n}\n\nfunction getMainModelId(requestContext: RequestContext): string | undefined {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n return controller?.session.modelId || (controller?.getState()?.currentModelId as string | undefined);\n}\n\n/**\n * Resolve one OM role's model for this invocation. Returns `'auto'` for Memory's\n * auto policy, or a concrete model. Factory's DB row is authoritative for\n * Factory sessions (an unreadable row falls back to auto). Otherwise the active\n * model route's memory models win, then the per-role selection, then legacy\n * concrete settings.\n */\nfunction resolveOmRoleModelForRequest(\n role: 'observer' | 'reflector',\n requestContext: RequestContext,\n settingsPath?: string,\n options?: { disableSettingsOmSeed?: boolean },\n): 'auto' | ReturnType<typeof resolveModel> | 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 const factorySettingsContext = getFactoryMemorySettingsContext(requestContext);\n const isFactory = typeof state?.factoryProjectId === 'string';\n\n const useModel = (modelId: string) => {\n requestContext.set(`om.${role}.selectionMode`, 'model');\n requestContext.set(`om.${role}.effectiveModelId`, modelId);\n return resolveModel(modelId, resolveOptions);\n };\n const useAuto = () => {\n requestContext.set(`om.${role}.selectionMode`, 'auto');\n // These two keys are declared in the span-context allowlist\n // (`mastracode/sdk/src/index.ts`), so traces can report intent separately from\n // the effective concrete model without either being mistaken for a model ID.\n requestContext.set(`om.${role}.effectiveModelId`, resolveAutoOMModelId(getMainModelId(requestContext)));\n return 'auto' as const;\n };\n\n if (\n isFactoryMemorySettingsUnavailable(factorySettingsContext) ||\n (factorySettingsContext === undefined && isFactory)\n ) {\n return useAuto();\n }\n if (factorySettingsContext !== undefined) {\n const factoryModelId = factorySettingsContext?.[`${role}ModelId`];\n return factoryModelId ? useModel(factoryModelId) : useAuto();\n }\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 override resolution for\n // observational memory as it does for the main model. Hosts that disable the\n // settings seed never read it.\n const settings = options?.disableSettingsOmSeed ? undefined : loadSettings(settingsPath);\n const routeMemory = resolveRouteMemoryModels(state, controller?.threadId, modelId =>\n resolveModel(modelId, resolveOptions),\n );\n if (routeMemory === 'auto') return useAuto();\n if (routeMemory) {\n requestContext.set(`om.${role}.selectionMode`, 'model');\n requestContext.set(`om.${role}.effectiveModelId`, routeMemory[0]?.model.modelId);\n return routeMemory.length === 1 ? routeMemory[0]!.model : routeMemory;\n }\n\n const selection: unknown = state?.[`${role}ModelSelection`];\n if (selection === 'auto') return useAuto();\n if (typeof selection === 'string' && selection) return useModel(selection);\n if (\n selection &&\n typeof selection === 'object' &&\n 'modelId' in selection &&\n typeof selection.modelId === 'string' &&\n selection.modelId\n ) {\n return useModel(selection.modelId);\n }\n\n const roleOverride =\n role === 'observer' ? settings?.models?.observerModelOverride : settings?.models?.reflectorModelOverride;\n if (roleOverride) return useModel(roleOverride);\n const legacyModelId = state?.[`${role}ModelId`];\n if (typeof legacyModelId === 'string' && legacyModelId) return useModel(legacyModelId);\n return useAuto();\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 knowledge?: Knowledge,\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 // Instances replaced by a config change may still have background work in flight.\n const retiredMemories = new Set<Memory>();\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 // Routes the concrete model Memory's `'auto'` picks through Mastra Code's\n // credential-aware resolver, like every other Mastra Code model.\n const resolveMemoryModel = (modelId: string, { requestContext }: { requestContext?: RequestContext }) =>\n resolveModel(modelId, { remapForCodexOAuth: true, requestContext, anthropicPromptCacheScope: 'system' });\n\n const resolveMemory = ({ 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 // The Factory row is authoritative and read per invocation, so a stored\n // threshold/attachment change reaches the running Memory without a session.\n const factorySettingsContext = getFactoryMemorySettingsContext(requestContext);\n const factorySettingsUnavailable =\n isFactoryMemorySettingsUnavailable(factorySettingsContext) || (factorySettingsContext === undefined && isFactory);\n const factorySettings = factorySettingsUnavailable ? null : factorySettingsContext;\n const obsThreshold =\n factorySettings !== undefined\n ? (factorySettings?.observationThreshold ?? DEFAULT_OBS_THRESHOLD)\n : (state?.observationThreshold ?? DEFAULT_OBS_THRESHOLD);\n const refThreshold =\n factorySettings !== undefined\n ? (factorySettings?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD)\n : (state?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD);\n const caveman = state?.cavemanObservations ?? false;\n\n const observerPreviousObservationTokens = 1000;\n // The row is authoritative: an absent value means the user left it on Auto,\n // which the config API reports as 'auto' and Memory resolves by model\n // capability.\n const observeAttachments =\n factorySettings !== undefined ? (factorySettings?.observeAttachments ?? 'auto') : state?.observeAttachments;\n // Factory sessions get a factory-only Subconscious config, so the cache key\n // carries Factory presence and settings availability to keep those configs\n // 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 if (cachedMemory) {\n const retired = cachedMemory;\n retiredMemories.add(retired);\n // settled() rejects if the instance's OM engine failed to start; that must not surface as\n // an unhandled rejection from a background retirement.\n void retired\n .settled()\n .catch(() => {})\n .finally(() => retiredMemories.delete(retired));\n }\n\n cachedMemory = new Memory({\n storage,\n ...(knowledge ? { knowledge } : {}),\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 process.env.MASTRACODE_DISABLE_TITLE_GENERATION === '1'\n ? false\n : {\n model: ({ requestContext }) => {\n const resolved = getObserverModel({ requestContext });\n if (resolved === 'auto') {\n return resolveMemoryModel(resolveAutoOMModelId(getMainModelId(requestContext)), { requestContext });\n }\n return Array.isArray(resolved) ? resolved[0]!.model : resolved;\n },\n },\n observationalMemory:\n process.env.MASTRACODE_DISABLE_OBSERVATIONAL_MEMORY === '1'\n ? false\n : {\n enabled: true,\n autoModels: MASTRACODE_AUTO_OM_MODELS,\n resolveModel: resolveMemoryModel,\n temporalMarkers: true,\n retrieval: vector ? { vector: true } : true,\n experimental_subconscious: subconsciousAvailable\n ? new Subconscious({\n defaultScope: '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 return Object.assign(resolveMemory, {\n /**\n * Wait for background memory work (buffered observations, reflections, indexing) in every\n * instance this factory created. Await before closing storage.\n */\n async settled(): Promise<void> {\n // Drain every instance even if one rejects, so teardown can still close storage.\n await Promise.allSettled([cachedMemory?.settled(), ...[...retiredMemories].map(memory => memory.settled())]);\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwBA,SAAS,yBACP,OACA,UACA,SAC8C;CAC9C,MAAM,cAAc,qBAAqB,OAAO,QAAQ;CACxD,IAAI,YAAY,EAAE,EAAE,kBAAkB,QAAQ,OAAO;CACrD,MAAM,+BAAe,IAAI,IAAY;CACrC,MAAM,8BAAc,IAAI,IAAoB;CAC5C,MAAM,UAAmC,CAAC;CAC1C,KAAK,MAAM,SAAS,aAAa;EAC/B,IAAI,CAAC,MAAM,iBAAiB,MAAM,kBAAkB,UAAU,aAAa,IAAI,MAAM,aAAa,GAAG;EACrG,aAAa,IAAI,MAAM,aAAa;EACpC,MAAM,cAAc,YAAY,IAAI,MAAM,EAAE,KAAK,KAAK;EACtD,YAAY,IAAI,MAAM,IAAI,UAAU;EACpC,IAAI;GACF,QAAQ,KAAK;IACX,IAAI,GAAG,MAAM,GAAG,SAAS,eAAe,IAAI,KAAK,IAAI;IACrD,OAAO,QAAQ,MAAM,aAAa;GACpC,CAAC;EACH,QAAQ;GACN;EACF;CACF;CACA,OAAO,QAAQ,SAAS,IAAI,UAAU,KAAA;AACxC;AAuBA,SAAS,gCAAgC,gBAA8D;CACrG,OAAO,eAAe,IAAI,+BAA+B;AAC3D;AAEA,SAAS,mCACP,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N,GAAI,YAAY,EAAE,UAAU,GAAG,IAAI,CAAC;KACtC,CAAC,IACD,KAAA;KACJ,OAAO;KAEP,mBAAmB;MAAE,SAAS;MAAQ,WAAA;KAAsC;KAC5E,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;GACR;EACF,CAAC;EACD,kBAAkB;EAElB,OAAO;CACT;CAEA,OAAO,OAAO,OAAO,eAAe;;;;;AAKlC,MAAM,UAAyB;EAE7B,MAAM,QAAQ,WAAW,CAAC,cAAc,QAAQ,GAAG,GAAG,CAAC,GAAG,eAAe,CAAC,CAAC,KAAI,WAAU,OAAO,QAAQ,CAAC,CAAC,CAAC;CAC7G,EACF,CAAC;AACH"}
@@ -1,6 +1,7 @@
1
1
  import type { ModelWithRetries } from '@mastra/core/agent';
2
+ import { ModelRouterLanguageModel } from '@mastra/core/llm';
2
3
  import type { GatewayLanguageModel, IdentifiedModelConfig, MastraModelGatewayInterface } from '@mastra/core/llm';
3
- import type { RequestContext } from '@mastra/core/request-context';
4
+ import { RequestContext } from '@mastra/core/request-context';
4
5
  import type { CredentialStore } from '../auth/types.js';
5
6
  import type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';
6
7
  import type { ThinkingLevelSetting } from '../thinking.js';
@@ -12,7 +13,7 @@ export { setCredentialStoreProvider, hasCredentialStoreProvider, resolveTenantFr
12
13
  export type { CredentialTenant, CredentialStoreProvider } from './credential-resolver.js';
13
14
  export { setCustomProvidersSource, hasCustomProvidersSource, resolveCustomProviders, } from './custom-provider-source.js';
14
15
  export type { CustomProvidersSource } from './custom-provider-source.js';
15
- type ResolvedModel = GatewayLanguageModel;
16
+ type ResolvedModel = GatewayLanguageModel | ModelRouterLanguageModel;
16
17
  export declare function createRequestScopedCredentialStore(base: CredentialStore, requestContext?: RequestContext): CredentialStore;
17
18
  export declare function createMastraCodeGateway(options: MastraCodeGatewayOptions): MastraCodeGateway;
18
19
  export declare function createMastraCodeModelCatalogProvider(gateway: MastraModelGatewayInterface): import("@mastra/core/harness").CustomModelCatalogProvider;
@@ -36,7 +37,7 @@ export declare function resolveModel(modelId: string, options?: {
36
37
  remapForCodexOAuth?: boolean;
37
38
  requestContext?: RequestContext;
38
39
  anthropicPromptCacheScope?: AnthropicPromptCacheScope;
39
- }): GatewayLanguageModel;
40
+ }): ResolvedModel;
40
41
  export interface ThinkingRequestContext {
41
42
  state?: {
42
43
  thinkingLevel?: unknown;
@@ -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,qBAAqB,EAAE,2BAA2B,EAAE,MAAM,kBAAkB,CAAC;AACjH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAGnE,OAAO,KAAK,EAAE,eAAe,EAAsB,MAAM,kBAAkB,CAAC;AAS5E,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAC;AAGxF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAG3D,OAAO,EAGL,iBAAiB,EAIlB,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AAExE,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,qBAAqB,EACrB,iBAAiB,EACjB,6BAA6B,EAC7B,WAAW,GACZ,MAAM,yBAAyB,CAAC;AACjC,YAAY,EAAE,wBAAwB,EA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E,KAAK,CAAC;YAAE,EAAE,CAAC,EAAE,OAAO,CAAC;YAAC,aAAa,CAAC,EAAE,OAAO,CAAA;SAAE,CAAC,CAAA;KAAE,CAAC;IAC5E,8BAA8B,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,OAAO,CAAC;QAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI,CAAC;CACrF,CAAC;AAEF;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,SAAS;IAAE,EAAE,CAAC,EAAE,OAAO,CAAC;IAAC,aAAa,CAAC,EAAE,OAAO,CAAA;CAAE,EAC3F,KAAK,EACD;IACE,UAAU,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC;IACpC,8BAA8B,CAAC,EAAE,gBAAgB,CAAC,gCAAgC,CAAC,CAAC;CACrF,GACD,SAAS,EACb,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GACvB,MAAM,EAAE,CASV;AAED;;;;GAIG;AACH,wBAAgB,2BAA2B,CACzC,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,SAAS,EACpD,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GACvB,MAAM,GAAG,SAAS,CAQpB;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"}
@@ -4,11 +4,13 @@ import { isThinkingLevelSetting } from "../thinking.js";
4
4
  import { ProviderAuthRequiredError } from "../auth/provider-auth-error.js";
5
5
  import { toMemoryModelId } from "../onboarding/packs.js";
6
6
  import { loadSettings, resolveDefaultThinkingLevel, stripMastraCodeCustomProviderPrefix } from "../onboarding/settings.js";
7
- import { hasCredentialStoreProvider, resolveCredentialStore, resolveTenantFromRequestContext, setCredentialStoreProvider } from "./credential-resolver.js";
7
+ import { hasCredentialStoreProvider, hasCredentialTenantResolver, prepareCredentialTenant, resolveCredentialStore, resolveTenantFromRequestContext, setCredentialStoreProvider } from "./credential-resolver.js";
8
8
  import { getRequestAccountSelection, isRequestAccountRoutingExhausted } from "../auth/account-routing-context.js";
9
9
  import { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from "../providers/amazon-bedrock-gateway.js";
10
10
  import { hasCustomProvidersSource, resolveCustomProviders, setCustomProvidersSource } from "./custom-provider-source.js";
11
11
  import { MASTRACODE_GATEWAY_ID, MastraCodeGateway, getAnthropicApiKey, getGlobalAuthStorage, getOpenAIApiKey, reloadAuthStorage, resolveAuth } from "./mastracode-gateway.js";
12
+ import { ModelRouterLanguageModel } from "@mastra/core/llm";
13
+ import { RequestContext } from "@mastra/core/request-context";
12
14
  //#region src/agents/model.ts
13
15
  function getAgentControllerHeaders(requestContext) {
14
16
  const agentControllerContext = requestContext?.get("controller");
@@ -78,6 +80,38 @@ function resolveModelId(modelId) {
78
80
  * - For all other providers: Uses Mastra's model router (models.dev gateway)
79
81
  */
80
82
  function resolveModel(modelId, options) {
83
+ if (!hasCredentialTenantResolver()) return resolveModelForRequest(modelId, options);
84
+ const createRequestModel = () => {
85
+ const requestContext = options?.requestContext ? new RequestContext(options.requestContext.entries()) : void 0;
86
+ return new ModelRouterLanguageModel({ id: `${MASTRACODE_GATEWAY_ID}/${modelId}` }, [{
87
+ id: MASTRACODE_GATEWAY_ID,
88
+ name: "Request-scoped MastraCode",
89
+ fetchProviders: async () => ({}),
90
+ buildUrl: () => void 0,
91
+ getApiKey: async () => "",
92
+ resolveAuth: () => ({ apiKey: "request-scoped" }),
93
+ resolveLanguageModel: async () => {
94
+ await prepareCredentialTenant(requestContext);
95
+ return resolveModelForRequest(modelId, {
96
+ ...options,
97
+ requestContext
98
+ });
99
+ }
100
+ }]);
101
+ };
102
+ let currentModel = createRequestModel();
103
+ return new Proxy(currentModel, { get(_target, property) {
104
+ if (property === "supportedUrls") return createRequestModel().supportedUrls;
105
+ if (property === "doStream" || property === "doGenerate") return async (...args) => {
106
+ const refreshed = createRequestModel();
107
+ currentModel = refreshed;
108
+ return Reflect.apply(Reflect.get(refreshed, property), refreshed, args);
109
+ };
110
+ const value = Reflect.get(currentModel, property, currentModel);
111
+ return typeof value === "function" ? value.bind(currentModel) : value;
112
+ } });
113
+ }
114
+ function resolveModelForRequest(modelId, options) {
81
115
  reloadAuthStorage();
82
116
  const headers = getAgentControllerHeaders(options?.requestContext);
83
117
  const settings = loadSettings();