@mastra/factory 0.28.0-alpha.4 → 0.28.0-alpha.5

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.
Files changed (62) hide show
  1. package/dist/auth.d.ts.map +1 -1
  2. package/dist/auth.js +7 -1
  3. package/dist/auth.js.map +1 -1
  4. package/dist/factory.d.ts.map +1 -1
  5. package/dist/factory.js +4 -16
  6. package/dist/factory.js.map +1 -1
  7. package/dist/feed-events.d.ts +3 -2
  8. package/dist/feed-events.d.ts.map +1 -1
  9. package/dist/feed-events.js +3 -2
  10. package/dist/feed-events.js.map +1 -1
  11. package/dist/integrations/slack/run-error-card.js +1 -0
  12. package/dist/integrations/slack/run-error-card.js.map +1 -1
  13. package/dist/provider-display-name.d.ts.map +1 -1
  14. package/dist/provider-display-name.js +1 -0
  15. package/dist/provider-display-name.js.map +1 -1
  16. package/dist/routes/config.d.ts +7 -1
  17. package/dist/routes/config.d.ts.map +1 -1
  18. package/dist/routes/config.js +105 -22
  19. package/dist/routes/config.js.map +1 -1
  20. package/dist/routes/mastra-gateway.d.ts +19 -0
  21. package/dist/routes/mastra-gateway.d.ts.map +1 -0
  22. package/dist/routes/mastra-gateway.js +120 -0
  23. package/dist/routes/mastra-gateway.js.map +1 -0
  24. package/dist/routes/provider-credentials.d.ts +6 -1
  25. package/dist/routes/provider-credentials.d.ts.map +1 -1
  26. package/dist/routes/provider-credentials.js +32 -2
  27. package/dist/routes/provider-credentials.js.map +1 -1
  28. package/dist/routes/route.d.ts +6 -0
  29. package/dist/routes/route.d.ts.map +1 -1
  30. package/dist/routes/route.js.map +1 -1
  31. package/dist/routes/tenant-credentials.d.ts.map +1 -1
  32. package/dist/routes/tenant-credentials.js +5 -1
  33. package/dist/routes/tenant-credentials.js.map +1 -1
  34. package/dist/run-error.d.ts +1 -1
  35. package/dist/run-error.d.ts.map +1 -1
  36. package/dist/run-error.js +38 -5
  37. package/dist/run-error.js.map +1 -1
  38. package/dist/session/live-sessions.d.ts +11 -4
  39. package/dist/session/live-sessions.d.ts.map +1 -1
  40. package/dist/session/live-sessions.js +31 -10
  41. package/dist/session/live-sessions.js.map +1 -1
  42. package/dist/storage/domains/comments/base.d.ts.map +1 -1
  43. package/dist/storage/domains/comments/base.js +2 -2
  44. package/dist/storage/domains/comments/base.js.map +1 -1
  45. package/dist/storage/domains/comments/routes.d.ts.map +1 -1
  46. package/dist/storage/domains/comments/routes.js +4 -2
  47. package/dist/storage/domains/comments/routes.js.map +1 -1
  48. package/dist/storage/domains/work-items/base.d.ts +6 -9
  49. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  50. package/dist/storage/domains/work-items/base.js +33 -33
  51. package/dist/storage/domains/work-items/base.js.map +1 -1
  52. package/dist/storage/domains/work-items/board-version.d.ts +6 -2
  53. package/dist/storage/domains/work-items/board-version.d.ts.map +1 -1
  54. package/dist/storage/domains/work-items/board-version.js +20 -9
  55. package/dist/storage/domains/work-items/board-version.js.map +1 -1
  56. package/factory-skills/factory-gitlab-rereview/SKILL.md +4 -4
  57. package/factory-skills/factory-gitlab-review/SKILL.md +5 -5
  58. package/factory-skills/factory-rereview/SKILL.md +68 -22
  59. package/factory-skills/factory-review/SKILL.md +68 -22
  60. package/factory-skills/factory-self-review/SKILL.md +5 -6
  61. package/factory-skills/factory-triage/SKILL.md +8 -20
  62. package/package.json +8 -8
@@ -0,0 +1,120 @@
1
+ import { z } from "zod";
2
+ // src/routes/mastra-gateway.ts
3
+ const MASTRA_PROJECTS_URL = process.env.MASTRA_PROJECTS_URL || "https://projects.mastra.ai";
4
+ /** The Starter plan's gateway credit pool, used when the customer names none. */
5
+ const STARTER_CREDIT_POOL = "gateway_credits";
6
+ /**
7
+ * Provisions a Gateway project with a v1 key, which the live gateway accepts. Organization (v2) keys
8
+ * aren't released yet, so Factory doesn't ask for one (the CLI does the same).
9
+ */
10
+ const GATEWAY_PROVISION_PATH = "/gateway/projects/provision";
11
+ const PLATFORM_TIMEOUT_MS = 15e3;
12
+ const PLATFORM_UNREACHABLE = "Could not reach Mastra. Try again.";
13
+ const MASTRA_SIGN_IN_REQUIRED = "The Mastra Gateway needs a Factory signed in with a Mastra account.";
14
+ var MastraGatewayError = class extends Error {
15
+ status;
16
+ constructor(status, message) {
17
+ super(message);
18
+ this.status = status;
19
+ }
20
+ };
21
+ function platformUnavailable(message) {
22
+ return new MastraGatewayError(502, message);
23
+ }
24
+ async function platformFetch(auth, c, path, init = {}, unreachable = PLATFORM_UNREACHABLE) {
25
+ if (!auth.fetchPlatformAsUser) throw new MastraGatewayError(400, MASTRA_SIGN_IN_REQUIRED);
26
+ let res;
27
+ try {
28
+ res = await auth.fetchPlatformAsUser(c, path, {
29
+ ...init,
30
+ signal: AbortSignal.timeout(PLATFORM_TIMEOUT_MS)
31
+ });
32
+ } catch {
33
+ throw platformUnavailable(unreachable);
34
+ }
35
+ if (!res || res.status === 401) throw new MastraGatewayError(400, "Your Mastra sign-in expired. Sign in again.");
36
+ return res;
37
+ }
38
+ async function readJson(res, schema, failure) {
39
+ const parsed = schema.safeParse(await res.json().catch(() => void 0));
40
+ if (!parsed.success) throw platformUnavailable(failure);
41
+ return parsed.data;
42
+ }
43
+ const PlatformMe = z.object({
44
+ organizationId: z.string().nullish(),
45
+ role: z.string().nullish(),
46
+ user: z.object({ email: z.string().nullish() }).nullish()
47
+ });
48
+ /**
49
+ * The signed-in user on Mastra, once their session is confirmed to be on this
50
+ * Factory's organization. Platform keys and billing follow the session's
51
+ * active organization, which differs from a Factory pinned to another one.
52
+ */
53
+ async function platformMember(auth, c, orgId) {
54
+ const res = await platformFetch(auth, c, "/auth/me");
55
+ if (!res.ok) throw platformUnavailable(PLATFORM_UNREACHABLE);
56
+ const me = await readJson(res, PlatformMe, PLATFORM_UNREACHABLE);
57
+ if (me.organizationId !== orgId) throw new MastraGatewayError(409, "Your Mastra sign-in is on a different organization than this Factory. Sign in again with this Factory’s organization.");
58
+ return {
59
+ email: me.user?.email ?? void 0,
60
+ isAdmin: me.role === "admin" || me.role === "owner"
61
+ };
62
+ }
63
+ const CreatedGatewayKey = z.object({ apiKey: z.string().min(1) });
64
+ async function createGatewayKey(auth, c, orgId, scope) {
65
+ const { email } = await platformMember(auth, c, orgId);
66
+ const label = scope === "org" ? "Factory · Shared" : `Factory · ${email ?? "Personal"}`;
67
+ const res = await platformFetch(auth, c, GATEWAY_PROVISION_PATH, {
68
+ method: "POST",
69
+ headers: { "Content-Type": "application/json" },
70
+ body: JSON.stringify({
71
+ name: label,
72
+ keyLabel: label
73
+ })
74
+ });
75
+ if (res.status === 403) throw new MastraGatewayError(403, "Your Mastra role cannot create gateway keys for this organization. Ask an admin to connect it.");
76
+ const failure = "Could not create a Mastra Gateway key. Try again.";
77
+ if (!res.ok) throw platformUnavailable(failure);
78
+ const { apiKey } = await readJson(res, CreatedGatewayKey, failure);
79
+ return apiKey;
80
+ }
81
+ const CustomerBalance = z.object({
82
+ featureId: z.string().nullish(),
83
+ remaining: z.number().nullish(),
84
+ granted: z.number().nullish(),
85
+ usage: z.number().nullish(),
86
+ unlimited: z.boolean().nullish()
87
+ });
88
+ const BillingCustomer = z.object({ customer: z.object({
89
+ balances: z.record(z.string(), CustomerBalance.nullish()).nullish(),
90
+ creditPool: z.object({ featureId: z.string().nullish() }).nullish()
91
+ }).nullish() });
92
+ async function billingCustomer(auth, c, failure) {
93
+ const res = await platformFetch(auth, c, "/billing/customer");
94
+ if (!res.ok) throw platformUnavailable(failure);
95
+ return (await readJson(res, BillingCustomer, failure)).customer ?? void 0;
96
+ }
97
+ function addCreditsUrl(orgId) {
98
+ return `${MASTRA_PROJECTS_URL}/add-credits/${encodeURIComponent(orgId)}`;
99
+ }
100
+ function remainingCredits(balance) {
101
+ if (balance?.remaining != null) return Math.max(0, balance.remaining);
102
+ if (balance?.granted != null) return Math.max(0, balance.granted - (balance.usage ?? 0));
103
+ }
104
+ /** Read like the platform dashboard's `useCreditBalance`. */
105
+ async function getGatewayCredits(auth, c, orgId) {
106
+ const member = await platformMember(auth, c, orgId);
107
+ const customer = await billingCustomer(auth, c, "Could not read Mastra Gateway credits. Try again.");
108
+ const featureId = customer?.creditPool?.featureId ?? STARTER_CREDIT_POOL;
109
+ const balances = customer?.balances;
110
+ const balance = balances ? Object.values(balances).find((entry) => entry?.featureId === featureId) ?? balances[featureId] : void 0;
111
+ return {
112
+ remaining: remainingCredits(balance),
113
+ unlimited: balance?.unlimited === true,
114
+ canAddCredits: member.isAdmin,
115
+ addCreditsUrl: addCreditsUrl(orgId)
116
+ };
117
+ }
118
+ export { MASTRA_SIGN_IN_REQUIRED, MastraGatewayError, createGatewayKey, getGatewayCredits };
119
+
120
+ //# sourceMappingURL=mastra-gateway.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mastra-gateway.js","names":[],"sources":["../../src/routes/mastra-gateway.ts"],"sourcesContent":["import type { Context } from 'hono';\nimport { z } from 'zod';\n\nimport type { RouteAuth } from './route.js';\n\nconst MASTRA_PROJECTS_URL = process.env.MASTRA_PROJECTS_URL || 'https://projects.mastra.ai';\n\n/** The Starter plan's gateway credit pool, used when the customer names none. */\nconst STARTER_CREDIT_POOL = 'gateway_credits';\n\n/**\n * Provisions a Gateway project with a v1 key, which the live gateway accepts. Organization (v2) keys\n * aren't released yet, so Factory doesn't ask for one (the CLI does the same).\n */\nconst GATEWAY_PROVISION_PATH = '/gateway/projects/provision';\n\nconst PLATFORM_TIMEOUT_MS = 15_000;\n\nconst PLATFORM_UNREACHABLE = 'Could not reach Mastra. Try again.';\n\nexport const MASTRA_SIGN_IN_REQUIRED = 'The Mastra Gateway needs a Factory signed in with a Mastra account.';\n\nexport class MastraGatewayError extends Error {\n constructor(\n readonly status: 400 | 403 | 409 | 502,\n message: string,\n ) {\n super(message);\n }\n}\n\nfunction platformUnavailable(message: string): MastraGatewayError {\n return new MastraGatewayError(502, message);\n}\n\nasync function platformFetch(\n auth: RouteAuth,\n c: Context,\n path: string,\n init: RequestInit = {},\n unreachable = PLATFORM_UNREACHABLE,\n): Promise<Response> {\n if (!auth.fetchPlatformAsUser) throw new MastraGatewayError(400, MASTRA_SIGN_IN_REQUIRED);\n let res: Response | null;\n try {\n res = await auth.fetchPlatformAsUser(c, path, { ...init, signal: AbortSignal.timeout(PLATFORM_TIMEOUT_MS) });\n } catch {\n throw platformUnavailable(unreachable);\n }\n if (!res || res.status === 401) throw new MastraGatewayError(400, 'Your Mastra sign-in expired. Sign in again.');\n return res;\n}\n\nasync function readJson<T>(res: Response, schema: z.ZodType<T>, failure: string): Promise<T> {\n const parsed = schema.safeParse(await res.json().catch(() => undefined));\n if (!parsed.success) throw platformUnavailable(failure);\n return parsed.data;\n}\n\nconst PlatformMe = z.object({\n organizationId: z.string().nullish(),\n role: z.string().nullish(),\n user: z.object({ email: z.string().nullish() }).nullish(),\n});\n\n/**\n * The signed-in user on Mastra, once their session is confirmed to be on this\n * Factory's organization. Platform keys and billing follow the session's\n * active organization, which differs from a Factory pinned to another one.\n */\nasync function platformMember(auth: RouteAuth, c: Context, orgId: string) {\n const res = await platformFetch(auth, c, '/auth/me');\n if (!res.ok) throw platformUnavailable(PLATFORM_UNREACHABLE);\n const me = await readJson(res, PlatformMe, PLATFORM_UNREACHABLE);\n if (me.organizationId !== orgId) {\n throw new MastraGatewayError(\n 409,\n 'Your Mastra sign-in is on a different organization than this Factory. Sign in again with this Factory’s organization.',\n );\n }\n return { email: me.user?.email ?? undefined, isAdmin: me.role === 'admin' || me.role === 'owner' };\n}\n\nconst CreatedGatewayKey = z.object({ apiKey: z.string().min(1) });\n\nexport async function createGatewayKey(auth: RouteAuth, c: Context, orgId: string, scope: 'org' | 'user') {\n const { email } = await platformMember(auth, c, orgId);\n const label = scope === 'org' ? 'Factory · Shared' : `Factory · ${email ?? 'Personal'}`;\n const res = await platformFetch(auth, c, GATEWAY_PROVISION_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ name: label, keyLabel: label }),\n });\n if (res.status === 403) {\n throw new MastraGatewayError(\n 403,\n 'Your Mastra role cannot create gateway keys for this organization. Ask an admin to connect it.',\n );\n }\n const failure = 'Could not create a Mastra Gateway key. Try again.';\n if (!res.ok) throw platformUnavailable(failure);\n const { apiKey } = await readJson(res, CreatedGatewayKey, failure);\n return apiKey;\n}\n\nconst CustomerBalance = z.object({\n featureId: z.string().nullish(),\n remaining: z.number().nullish(),\n granted: z.number().nullish(),\n usage: z.number().nullish(),\n unlimited: z.boolean().nullish(),\n});\n\nconst BillingCustomer = z.object({\n customer: z\n .object({\n balances: z.record(z.string(), CustomerBalance.nullish()).nullish(),\n creditPool: z.object({ featureId: z.string().nullish() }).nullish(),\n })\n .nullish(),\n});\n\nasync function billingCustomer(auth: RouteAuth, c: Context, failure: string) {\n const res = await platformFetch(auth, c, '/billing/customer');\n if (!res.ok) throw platformUnavailable(failure);\n return (await readJson(res, BillingCustomer, failure)).customer ?? undefined;\n}\n\nfunction addCreditsUrl(orgId: string): string {\n return `${MASTRA_PROJECTS_URL}/add-credits/${encodeURIComponent(orgId)}`;\n}\n\nexport interface MastraGatewayCredits {\n /** Dollars (1 credit = $1); absent when the platform reports no balance for the pool. */\n remaining?: number;\n unlimited: boolean;\n /** Mastra lets only organization admins buy credits. */\n canAddCredits: boolean;\n addCreditsUrl: string;\n}\n\nfunction remainingCredits(balance: z.infer<typeof CustomerBalance> | null | undefined): number | undefined {\n if (balance?.remaining != null) return Math.max(0, balance.remaining);\n if (balance?.granted != null) return Math.max(0, balance.granted - (balance.usage ?? 0));\n return undefined;\n}\n\n/** Read like the platform dashboard's `useCreditBalance`. */\nexport async function getGatewayCredits(auth: RouteAuth, c: Context, orgId: string): Promise<MastraGatewayCredits> {\n const member = await platformMember(auth, c, orgId);\n const customer = await billingCustomer(auth, c, 'Could not read Mastra Gateway credits. Try again.');\n const featureId = customer?.creditPool?.featureId ?? STARTER_CREDIT_POOL;\n const balances = customer?.balances;\n const balance = balances\n ? (Object.values(balances).find(entry => entry?.featureId === featureId) ?? balances[featureId])\n : undefined;\n return {\n remaining: remainingCredits(balance),\n unlimited: balance?.unlimited === true,\n canAddCredits: member.isAdmin,\n addCreditsUrl: addCreditsUrl(orgId),\n };\n}\n"],"mappings":";;AAKA,MAAM,sBAAsB,QAAQ,IAAI,uBAAuB;;AAG/D,MAAM,sBAAsB;;;;;AAM5B,MAAM,yBAAyB;AAE/B,MAAM,sBAAsB;AAE5B,MAAM,uBAAuB;AAE7B,MAAa,0BAA0B;AAEvC,IAAa,qBAAb,cAAwC,MAAM;CAEjC;CADX,YACE,QACA,SACA;EACA,MAAM,OAAO;EAHJ,KAAA,SAAA;CAIX;AACF;AAEA,SAAS,oBAAoB,SAAqC;CAChE,OAAO,IAAI,mBAAmB,KAAK,OAAO;AAC5C;AAEA,eAAe,cACb,MACA,GACA,MACA,OAAoB,CAAC,GACrB,cAAc,sBACK;CACnB,IAAI,CAAC,KAAK,qBAAqB,MAAM,IAAI,mBAAmB,KAAK,uBAAuB;CACxF,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,KAAK,oBAAoB,GAAG,MAAM;GAAE,GAAG;GAAM,QAAQ,YAAY,QAAQ,mBAAmB;EAAE,CAAC;CAC7G,QAAQ;EACN,MAAM,oBAAoB,WAAW;CACvC;CACA,IAAI,CAAC,OAAO,IAAI,WAAW,KAAK,MAAM,IAAI,mBAAmB,KAAK,6CAA6C;CAC/G,OAAO;AACT;AAEA,eAAe,SAAY,KAAe,QAAsB,SAA6B;CAC3F,MAAM,SAAS,OAAO,UAAU,MAAM,IAAI,KAAK,CAAC,CAAC,YAAY,KAAA,CAAS,CAAC;CACvE,IAAI,CAAC,OAAO,SAAS,MAAM,oBAAoB,OAAO;CACtD,OAAO,OAAO;AAChB;AAEA,MAAM,aAAa,EAAE,OAAO;CAC1B,gBAAgB,EAAE,OAAO,CAAC,CAAC,QAAQ;CACnC,MAAM,EAAE,OAAO,CAAC,CAAC,QAAQ;CACzB,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,QAA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tB,eAAe,cAAc,KAAK;CACpC;AACF"}
@@ -22,7 +22,12 @@ import type { RouteAuth } from './route.js';
22
22
  * Tenant rows use the same keying so one lookup serves both OAuth tokens and
23
23
  * API keys, and match what model resolution reads.
24
24
  */
25
- export { getCredentialProviderId as getAuthProviderId } from '@mastra/code-sdk/providers/model-ids';
25
+ export declare function getAuthProviderId(provider: string): string;
26
+ /**
27
+ * Catalog provider id of Mastra Gateway models (`mastra/<provider>/<model>`).
28
+ * Their credential is the tenant's gateway key, stored as `mastra-gateway`.
29
+ */
30
+ export declare const MASTRA_GATEWAY_CATALOG_PROVIDER = "mastra";
26
31
  /**
27
32
  * Providers that support a browser-driven OAuth sign-in flow, keyed by
28
33
  * *catalog* provider id (what the routes and settings UI use). All flows need
@@ -1 +1 @@
1
- {"version":3,"file":"provider-credentials.d.ts","sourceRoot":"","sources":["../../src/routes/provider-credentials.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAKpC,OAAO,KAAK,EACV,gBAAgB,EAChB,gBAAgB,EAChB,uBAAuB,EACxB,MAAM,wCAAwC,CAAC;AAChD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE5C;;;;;GAKG;AACH,OAAO,EAAE,uBAAuB,IAAI,iBAAiB,EAAE,MAAM,sCAAsC,CAAC;AAEpG;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE;IAAE,IAAI,EAAE,gBAAgB,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,CAAC,CAK1G,CAAC;AAEF,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,cAAc,EAAE,gBAAgB,CAAC,YAAY,CAAC,CAAC,MAAM,CAAC,sBAIvG;AAED,MAAM,MAAM,iBAAiB,GACzB;IAAE,IAAI,EAAE,OAAO,CAAA;CA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GAAG,OAAO,CAAC,iBAAiB,GAAG;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,CA0BtD;AAED;;;;;;GAMG;AACH,wBAAsB,+BAA+B,CAAC,EACpD,CAAC,EACD,IAAI,EACJ,WAAW,EACX,MAAM,GACP,EAAE;IACD,CAAC,EAAE,OAAO,CAAC;IACX,IAAI,EAAE,SAAS,CAAC;IAChB,qEAAqE;IACrE,WAAW,CAAC,EAAE,uBAAuB,CAAC;IACtC;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GAAG,OAAO,CAAC,gBAAgB,EAAE,GAAG,SAAS,CAAC,CAO1C"}
@@ -1,9 +1,39 @@
1
1
  import { factoryUserOrgId } from "../auth.js";
2
2
  import { providerDisplayName } from "../provider-display-name.js";
3
3
  import { secretKeyMismatchHint } from "../secret-encryption.js";
4
- import { getCredentialProviderId as getAuthProviderId } from "@mastra/code-sdk/providers/model-ids";
4
+ import { MASTRA_GATEWAY_PROVIDER } from "@mastra/code-sdk/onboarding/settings";
5
+ import { getCredentialProviderId } from "@mastra/code-sdk/providers/model-ids";
5
6
  // src/routes/provider-credentials.ts
6
7
  /**
8
+ * Per-request model-provider credential context.
9
+ *
10
+ * The provider config/OAuth routes serve two deployment shapes:
11
+ *
12
+ * - **Local** (no web auth adapter): credentials live in the server-global
13
+ * file-backed `AuthStorage` (`auth.json`) — unchanged TUI behavior.
14
+ * - **Tenant** (auth adapter active): credentials live in the
15
+ * `model-credentials` factory storage domain, scoped per `(orgId, userId)`
16
+ * with optional org-wide rows (`userId` absent).
17
+ *
18
+ * `resolveCredentialContext` decides which shape a request is in: an
19
+ * authenticated user always gets the tenant path; an unauthenticated request
20
+ * is rejected when auth is enabled and falls back to local otherwise.
21
+ */
22
+ /**
23
+ * OAuth credentials are stored under the credential id, which differs from the
24
+ * catalog provider id for OpenAI (`openai-codex`) and Kimi (`kimi-for-coding`).
25
+ * Tenant rows use the same keying so one lookup serves both OAuth tokens and
26
+ * API keys, and match what model resolution reads.
27
+ */
28
+ function getAuthProviderId(provider) {
29
+ return provider === "mastra" ? MASTRA_GATEWAY_PROVIDER : getCredentialProviderId(provider);
30
+ }
31
+ /**
32
+ * Catalog provider id of Mastra Gateway models (`mastra/<provider>/<model>`).
33
+ * Their credential is the tenant's gateway key, stored as `mastra-gateway`.
34
+ */
35
+ const MASTRA_GATEWAY_CATALOG_PROVIDER = "mastra";
36
+ /**
7
37
  * Providers that support a browser-driven OAuth sign-in flow, keyed by
8
38
  * *catalog* provider id (what the routes and settings UI use). All flows need
9
39
  * no inbound connection to the server: Anthropic uses paste-code PKCE, the
@@ -107,6 +137,6 @@ async function listTenantCredentialsForRequest({ c, auth, credentials, userId })
107
137
  if (!storage) return [];
108
138
  return storage.listCredentials(tenantOrgId(tenant), userId ?? tenant.userId);
109
139
  }
110
- export { WEB_OAUTH_PROVIDERS, credentialLabel, getAuthProviderId, getTenantCredentialsStorage, listTenantCredentialsForRequest, resolveCredentialContext, tenantOrgId };
140
+ export { MASTRA_GATEWAY_CATALOG_PROVIDER, WEB_OAUTH_PROVIDERS, credentialLabel, getAuthProviderId, getTenantCredentialsStorage, listTenantCredentialsForRequest, resolveCredentialContext, tenantOrgId };
111
141
 
112
142
  //# sourceMappingURL=provider-credentials.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"provider-credentials.js","names":[],"sources":["../../src/routes/provider-credentials.ts"],"sourcesContent":["/**\n * Per-request model-provider credential context.\n *\n * The provider config/OAuth routes serve two deployment shapes:\n *\n * - **Local** (no web auth adapter): credentials live in the server-global\n * file-backed `AuthStorage` (`auth.json`) — unchanged TUI behavior.\n * - **Tenant** (auth adapter active): credentials live in the\n * `model-credentials` factory storage domain, scoped per `(orgId, userId)`\n * with optional org-wide rows (`userId` absent).\n *\n * `resolveCredentialContext` decides which shape a request is in: an\n * authenticated user always gets the tenant path; an unauthenticated request\n * is rejected when auth is enabled and falls back to local otherwise.\n */\n\nimport type { Context } from 'hono';\n\nimport { factoryUserOrgId } from '../auth.js';\nimport { providerDisplayName } from '../provider-display-name.js';\nimport { secretKeyMismatchHint } from '../secret-encryption.js';\nimport type {\n CredentialRecord,\n LoginSessionKind,\n ModelCredentialsStorage,\n} from '../storage/domains/credentials/base.js';\nimport type { RouteAuth } from './route.js';\n\n/**\n * OAuth credentials are stored under the credential id, which differs from the\n * catalog provider id for OpenAI (`openai-codex`) and Kimi (`kimi-for-coding`).\n * Tenant rows use the same keying so one lookup serves both OAuth tokens and\n * API keys, and match what model resolution reads.\n */\nexport { getCredentialProviderId as getAuthProviderId } from '@mastra/code-sdk/providers/model-ids';\n\n/**\n * Providers that support a browser-driven OAuth sign-in flow, keyed by\n * *catalog* provider id (what the routes and settings UI use). All flows need\n * no inbound connection to the server: Anthropic uses paste-code PKCE, the\n * rest use RFC 8628-style device codes. `subscription` names the plan the\n * sign-in bills, as shown under a reply and in the composer.\n */\nexport const WEB_OAUTH_PROVIDERS: Readonly<Record<string, { flow: LoginSessionKind; subscription: string }>> = {\n anthropic: { flow: 'paste-code', subscription: 'Claude Pro/Max' },\n openai: { flow: 'device-code', subscription: 'ChatGPT Plus/Pro' },\n 'github-copilot': { flow: 'device-code', subscription: 'GitHub Copilot' },\n xai: { flow: 'device-code', subscription: 'SuperGrok/X Premium+' },\n};\n\nexport function credentialLabel(provider: string, credentialType: CredentialRecord['credential']['type']) {\n return credentialType === 'api_key'\n ? `${providerDisplayName(provider)} API key`\n : WEB_OAUTH_PROVIDERS[provider]?.subscription;\n}\n\nexport type CredentialContext =\n | { mode: 'local' }\n | { mode: 'tenant'; storage: ModelCredentialsStorage; orgId: string; userId: string };\n\n/**\n * The tenant credentials domain, when registered and ready. `undefined` means\n * the factory never ran (no handle threaded in) or the domain's init failed\n * (fail-soft — callers report the feature unavailable instead of crashing).\n */\nexport async function getTenantCredentialsStorage(\n credentials: ModelCredentialsStorage | undefined,\n): Promise<ModelCredentialsStorage | undefined> {\n if (!credentials) return undefined;\n const failed = failedInit.get(credentials);\n if (failed && Date.now() - failed.at < INIT_RETRY_MS) return undefined;\n try {\n await credentials.ensureReady();\n } catch (error) {\n failedInit.set(credentials, { at: Date.now(), error });\n // Callers degrade to \"no credentials\", so this log is the only trace of why.\n if (error !== lastReportedInitError) {\n lastReportedInitError = error;\n console.error('[factory] model credential storage is unavailable; providers will show as not set:', error);\n }\n return undefined;\n }\n failedInit.delete(credentials);\n return credentials;\n}\n\nlet lastReportedInitError: unknown;\n/** Init is a full table scan and callers run per request and per model call, so a failure retries at most this often. */\nconst INIT_RETRY_MS = 15_000;\nconst failedInit = new WeakMap<ModelCredentialsStorage, { at: number; error: unknown }>();\n\n/**\n * Org key for tenant rows. Personal accounts get an org bootstrapped by the\n * auth adapter (`ensureOrg`); if one still isn't present, scope rows under a\n * per-user synthetic org so credentials never become server-global.\n */\nexport function tenantOrgId(tenant: { orgId?: string; userId: string }): string {\n return tenant.orgId ?? factoryUserOrgId({ id: tenant.userId }) ?? `user:${tenant.userId}`;\n}\n\n/**\n * Resolve the credential context for a request, or a ready-to-return error\n * response. Mutating credential routes call this and hard-fail (401/503)\n * when the tenant path is required but unavailable.\n */\nexport async function resolveCredentialContext({\n c,\n auth,\n credentials,\n}: {\n c: Context;\n auth: RouteAuth;\n /** Tenant credential domain handle; absent in local (no-DB) mode. */\n credentials?: ModelCredentialsStorage;\n}): Promise<CredentialContext | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) {\n // When an auth provider is active, credential operations always require a\n // signed-in caller — otherwise one anonymous request could write keys for\n // everyone. Without a provider this is a single-user local server.\n if (auth.enabled()) return { response: c.json({ error: 'unauthorized' }, 401) };\n return { mode: 'local' };\n }\n const storage = await getTenantCredentialsStorage(credentials);\n if (!storage) {\n return {\n response: c.json(\n {\n error: 'credentials_unavailable',\n message: `Provider credentials are unavailable. ${\n secretKeyMismatchHint(credentials && failedInit.get(credentials)?.error) ??\n 'The app database is not configured or failed to start. The server log line \"[factory] model credential storage is unavailable\" has the cause.'\n }`,\n },\n 503,\n ),\n };\n }\n return { mode: 'tenant', storage, orgId: tenantOrgId(tenant), userId: tenant.userId };\n}\n\n/**\n * List the caller's tenant credential records for provider listing, or\n * `undefined` in local mode (caller should fall back to `AuthStorage`).\n * Read-only and degradation-friendly: an authenticated caller with the domain\n * unavailable gets an empty list (sources show `env`/`none`) instead of a 503\n * so the settings page still renders.\n */\nexport async function listTenantCredentialsForRequest({\n c,\n auth,\n credentials,\n userId,\n}: {\n c: Context;\n auth: RouteAuth;\n /** Tenant credential domain handle; absent in local (no-DB) mode. */\n credentials?: ModelCredentialsStorage;\n /**\n * List another member's rows instead of the caller's — used when a preview\n * must mirror a run that authenticates as the addressed session's owner.\n */\n userId?: string;\n}): Promise<CredentialRecord[] | undefined> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return auth.enabled() ? [] : undefined;\n const storage = await getTenantCredentialsStorage(credentials);\n if (!storage) return [];\n return storage.listCredentials(tenantOrgId(tenant), userId ?? tenant.userId);\n}\n"],"mappings":";;;;;;;;;;;;AA2CA,MAAa,sBAAkG;CAC7G,WAAW;EAAE,MAAM;EAAc,cAAc;CAAiB;CAChE,QAAQ;EAAE,MAAM;EAAe,cAAc;CAAmB;CAChE,kBAAkB;EAAE,MAAM;EAAe,cAAc;CAAiB;CACxE,KAAK;EAAE,MAAM;EAAe,cAAc;CAAuB;AACnE;AAEA,SAAgB,gBAAgB,UAAkB,gBAAwD;CACxG,OAAO,mBAAmB,YACtB,GAAG,oBAAoB,QAAQ,EAAE,YACjC,oBAAoB,SAAS,EAAE;AACrC;;;;;;AAWA,eAAsB,4BACpB,aAC8C;CAC9C,IAAI,CAAC,aAAa,OAAO,KAAA;CACzB,MAAM,SAAS,WAAW,IAAI,WAAW;CACzC,IAAI,UAAU,KAAK,IAAI,IAAI,OAAO,KAAK,eAAe,OAAO,KAAA;CAC7D,IAAI;EACF,MAAM,YAAY,YAAY;CAChC,SAAS,OAAO;EACd,WAAW,IAAI,aAA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MAAM,GAAG,UAAU,OAAO,MAAM;AAC7E"}
1
+ {"version":3,"file":"provider-credentials.js","names":[],"sources":["../../src/routes/provider-credentials.ts"],"sourcesContent":["/**\n * Per-request model-provider credential context.\n *\n * The provider config/OAuth routes serve two deployment shapes:\n *\n * - **Local** (no web auth adapter): credentials live in the server-global\n * file-backed `AuthStorage` (`auth.json`) — unchanged TUI behavior.\n * - **Tenant** (auth adapter active): credentials live in the\n * `model-credentials` factory storage domain, scoped per `(orgId, userId)`\n * with optional org-wide rows (`userId` absent).\n *\n * `resolveCredentialContext` decides which shape a request is in: an\n * authenticated user always gets the tenant path; an unauthenticated request\n * is rejected when auth is enabled and falls back to local otherwise.\n */\n\nimport { MASTRA_GATEWAY_PROVIDER } from '@mastra/code-sdk/onboarding/settings';\nimport { getCredentialProviderId } from '@mastra/code-sdk/providers/model-ids';\nimport type { Context } from 'hono';\n\nimport { factoryUserOrgId } from '../auth.js';\nimport { providerDisplayName } from '../provider-display-name.js';\nimport { secretKeyMismatchHint } from '../secret-encryption.js';\nimport type {\n CredentialRecord,\n LoginSessionKind,\n ModelCredentialsStorage,\n} from '../storage/domains/credentials/base.js';\nimport type { RouteAuth } from './route.js';\n\n/**\n * OAuth credentials are stored under the credential id, which differs from the\n * catalog provider id for OpenAI (`openai-codex`) and Kimi (`kimi-for-coding`).\n * Tenant rows use the same keying so one lookup serves both OAuth tokens and\n * API keys, and match what model resolution reads.\n */\nexport function getAuthProviderId(provider: string): string {\n return provider === MASTRA_GATEWAY_CATALOG_PROVIDER ? MASTRA_GATEWAY_PROVIDER : getCredentialProviderId(provider);\n}\n\n/**\n * Catalog provider id of Mastra Gateway models (`mastra/<provider>/<model>`).\n * Their credential is the tenant's gateway key, stored as `mastra-gateway`.\n */\nexport const MASTRA_GATEWAY_CATALOG_PROVIDER = 'mastra';\n\n/**\n * Providers that support a browser-driven OAuth sign-in flow, keyed by\n * *catalog* provider id (what the routes and settings UI use). All flows need\n * no inbound connection to the server: Anthropic uses paste-code PKCE, the\n * rest use RFC 8628-style device codes. `subscription` names the plan the\n * sign-in bills, as shown under a reply and in the composer.\n */\nexport const WEB_OAUTH_PROVIDERS: Readonly<Record<string, { flow: LoginSessionKind; subscription: string }>> = {\n anthropic: { flow: 'paste-code', subscription: 'Claude Pro/Max' },\n openai: { flow: 'device-code', subscription: 'ChatGPT Plus/Pro' },\n 'github-copilot': { flow: 'device-code', subscription: 'GitHub Copilot' },\n xai: { flow: 'device-code', subscription: 'SuperGrok/X Premium+' },\n};\n\nexport function credentialLabel(provider: string, credentialType: CredentialRecord['credential']['type']) {\n return credentialType === 'api_key'\n ? `${providerDisplayName(provider)} API key`\n : WEB_OAUTH_PROVIDERS[provider]?.subscription;\n}\n\nexport type CredentialContext =\n | { mode: 'local' }\n | { mode: 'tenant'; storage: ModelCredentialsStorage; orgId: string; userId: string };\n\n/**\n * The tenant credentials domain, when registered and ready. `undefined` means\n * the factory never ran (no handle threaded in) or the domain's init failed\n * (fail-soft — callers report the feature unavailable instead of crashing).\n */\nexport async function getTenantCredentialsStorage(\n credentials: ModelCredentialsStorage | undefined,\n): Promise<ModelCredentialsStorage | undefined> {\n if (!credentials) return undefined;\n const failed = failedInit.get(credentials);\n if (failed && Date.now() - failed.at < INIT_RETRY_MS) return undefined;\n try {\n await credentials.ensureReady();\n } catch (error) {\n failedInit.set(credentials, { at: Date.now(), error });\n // Callers degrade to \"no credentials\", so this log is the only trace of why.\n if (error !== lastReportedInitError) {\n lastReportedInitError = error;\n console.error('[factory] model credential storage is unavailable; providers will show as not set:', error);\n }\n return undefined;\n }\n failedInit.delete(credentials);\n return credentials;\n}\n\nlet lastReportedInitError: unknown;\n/** Init is a full table scan and callers run per request and per model call, so a failure retries at most this often. */\nconst INIT_RETRY_MS = 15_000;\nconst failedInit = new WeakMap<ModelCredentialsStorage, { at: number; error: unknown }>();\n\n/**\n * Org key for tenant rows. Personal accounts get an org bootstrapped by the\n * auth adapter (`ensureOrg`); if one still isn't present, scope rows under a\n * per-user synthetic org so credentials never become server-global.\n */\nexport function tenantOrgId(tenant: { orgId?: string; userId: string }): string {\n return tenant.orgId ?? factoryUserOrgId({ id: tenant.userId }) ?? `user:${tenant.userId}`;\n}\n\n/**\n * Resolve the credential context for a request, or a ready-to-return error\n * response. Mutating credential routes call this and hard-fail (401/503)\n * when the tenant path is required but unavailable.\n */\nexport async function resolveCredentialContext({\n c,\n auth,\n credentials,\n}: {\n c: Context;\n auth: RouteAuth;\n /** Tenant credential domain handle; absent in local (no-DB) mode. */\n credentials?: ModelCredentialsStorage;\n}): Promise<CredentialContext | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) {\n // When an auth provider is active, credential operations always require a\n // signed-in caller — otherwise one anonymous request could write keys for\n // everyone. Without a provider this is a single-user local server.\n if (auth.enabled()) return { response: c.json({ error: 'unauthorized' }, 401) };\n return { mode: 'local' };\n }\n const storage = await getTenantCredentialsStorage(credentials);\n if (!storage) {\n return {\n response: c.json(\n {\n error: 'credentials_unavailable',\n message: `Provider credentials are unavailable. ${\n secretKeyMismatchHint(credentials && failedInit.get(credentials)?.error) ??\n 'The app database is not configured or failed to start. The server log line \"[factory] model credential storage is unavailable\" has the cause.'\n }`,\n },\n 503,\n ),\n };\n }\n return { mode: 'tenant', storage, orgId: tenantOrgId(tenant), userId: tenant.userId };\n}\n\n/**\n * List the caller's tenant credential records for provider listing, or\n * `undefined` in local mode (caller should fall back to `AuthStorage`).\n * Read-only and degradation-friendly: an authenticated caller with the domain\n * unavailable gets an empty list (sources show `env`/`none`) instead of a 503\n * so the settings page still renders.\n */\nexport async function listTenantCredentialsForRequest({\n c,\n auth,\n credentials,\n userId,\n}: {\n c: Context;\n auth: RouteAuth;\n /** Tenant credential domain handle; absent in local (no-DB) mode. */\n credentials?: ModelCredentialsStorage;\n /**\n * List another member's rows instead of the caller's — used when a preview\n * must mirror a run that authenticates as the addressed session's owner.\n */\n userId?: string;\n}): Promise<CredentialRecord[] | undefined> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return auth.enabled() ? [] : undefined;\n const storage = await getTenantCredentialsStorage(credentials);\n if (!storage) return [];\n return storage.listCredentials(tenantOrgId(tenant), userId ?? tenant.userId);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAgB,kBAAkB,UAA0B;CAC1D,OAAO,aAAA,WAA+C,0BAA0B,wBAAwB,QAAQ;AAClH;;;;;AAMA,MAAa,kCAAkC;;;;;;;;AAS/C,MAAa,sBAAkG;CAC7G,WAAW;EAAE,MAAM;EAAc,cAAc;CAAiB;CAChE,QAAQ;EAAE,MAAM;EAAe,cAAc;CAAmB;CAChE,kBAAkB;EAAE,MAAM;EAAe,cAAc;CAAiB;CACxE,KAAK;EAAE,MAAM;EAAe,cAAc;CAAuB;AACnE;AAEA,SAAgB,gBAAgB,UAAkB,gBAAwD;CACxG,OAAO,mBAAmB,YACtB,GAAG,oBAAoB,QAAQ,EAAE,YACjC,oBAAoB,SAAS,EAAE;AACrC;;;;;;AAWA,eAAsB,4BACpB,aAC8C;CAC9C,IAAI,CAAC,aAAa,OAAO,KAAA;CACzB,MAAM,SAAS,WAAW,IAAI,WAAW;CACzC,IAAI,UAAU,KAAK,IAAI,IAAI,OAAO,KAAK,eAAe,OAAO,KAAA;CAC7D,IAAI;EACF,MAAM,YAAY,YAAY;CAChC,SAAS,OAAO;EACd,WAAW,IAAI,aAAa;GAAE,IAAI,KAAK,IAAI;GAAG;EAAM,CAAC;EAErD,IAAI,UAAU,uBAAuB;GACnC,wBAAwB;GACxB,QAAQ,MAAM,sFAAsF,KAAK;EAC3G;EACA;CACF;CACA,WAAW,OAAO,WAAW;CAC7B,OAAO;AACT;AAEA,IAAI;;AAEJ,MAAM,gBAAgB;AACtB,MAAM,6BAAa,IAAI,QAAiE;;;;;;AAOxF,SAAgB,YAAY,QAAoD;CAC9E,OAAO,OAAO,SAAS,iBAAiB,EAAE,IAAI,OAAO,OAAO,CAAC,KAAK,QAAQ,OAAO;AACnF;;;;;;AAOA,eAAsB,yBAAyB,EAC7C,GACA,MACA,eAMsD;CACtD,MAAM,KAAK,WAAW,CAAC;CACvB,MAAM,SAAS,KAAK,OAAO,CAAC;CAC5B,IAAI,CAAC,QAAQ;EAIX,IAAI,KAAK,QAAQ,GAAG,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG,EAAE;EAC9E,OAAO,EAAE,MAAM,QAAQ;CACzB;CACA,MAAM,UAAU,MAAM,4BAA4B,WAAW;CAC7D,IAAI,CAAC,SACH,OAAO,EACL,UAAU,EAAE,KACV;EACE,OAAO;EACP,SAAS,yCACP,sBAAsB,eAAe,WAAW,IAAI,WAAW,CAAC,EAAE,KAAK,KACvE;CAEJ,GACA,GACF,EACF;CAEF,OAAO;EAAE,MAAM;EAAU;EAAS,OAAO,YAAY,MAAM;EAAG,QAAQ,OAAO;CAAO;AACtF;;;;;;;;AASA,eAAsB,gCAAgC,EACpD,GACA,MACA,aACA,UAW0C;CAC1C,MAAM,KAAK,WAAW,CAAC;CACvB,MAAM,SAAS,KAAK,OAAO,CAAC;CAC5B,IAAI,CAAC,QAAQ,OAAO,KAAK,QAAQ,IAAI,CAAC,IAAI,KAAA;CAC1C,MAAM,UAAU,MAAM,4BAA4B,WAAW;CAC7D,IAAI,CAAC,SAAS,OAAO,CAAC;CACtB,OAAO,QAAQ,gBAAgB,YAAY,MAAM,GAAG,UAAU,OAAO,MAAM;AAC7E"}
@@ -30,6 +30,12 @@ export interface RouteAuth {
30
30
  } | undefined;
31
31
  /** Fail-closed check that the caller administers the given organization. */
32
32
  isOrganizationAdmin(c: Context, organizationId: string): Promise<boolean>;
33
+ /**
34
+ * Call the Mastra platform API as the signed-in user (`path` like
35
+ * `/gateway/projects/provision`). Present only with Mastra platform auth
36
+ * (`MastraAuthStudio`); `null` when the request has no session.
37
+ */
38
+ fetchPlatformAsUser?(c: Context, path: string, init?: RequestInit): Promise<Response | null>;
33
39
  }
34
40
  /** Dependencies shared by every factory route module. */
35
41
  export interface RouteDependencies {
@@ -1 +1 @@
1
- {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../src/routes/route.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAEpC;;;;;;GAMG;AACH,MAAM,WAAW,SAAS;IACxB,wDAAwD;IACxD,OAAO,IAAI,OAAO,CAAC;IACnB;;;OAGG;IACH,UAAU,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACzC,uDAAuD;IACvD,MAAM,CAAC,CAAC,EAAE,OAAO,GAAG;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;IACnE,4EAA4E;IAC5E,mBAAmB,CAAC,CAAC,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC3E;AAED,yDAAyD;AACzD,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,SAAS,CAAC;CACjB;AAED,2HAA2H;AAC3H,wBAAgB,KAAK,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAEzC;AAED;;;GAGG;AACH,8BAAsB,KAAK,CAAC,KAAK,SAAS,iBAAiB,GAAG,iBAAiB;IAC7E,SAAS,CAAC,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC;IAE/B,YAAY,IAAI,EAAE,KAAK,EAEtB;IAED,0DAA0D;IAC1D,QAAQ,CAAC,MAAM,IAAI,QAAQ,EAAE,CAAC;CAC/B"}
1
+ {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../src/routes/route.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAEpC;;;;;;GAMG;AACH,MAAM,WAAW,SAAS;IACxB,wDAAwD;IACxD,OAAO,IAAI,OAAO,CAAC;IACnB;;;OAGG;IACH,UAAU,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACzC,uDAAuD;IACvD,MAAM,CAAC,CAAC,EAAE,OAAO,GAAG;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;IACnE,4EAA4E;IAC5E,mBAAmB,CAAC,CAAC,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC1E;;;;OAIG;IACH,mBAAmB,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAAC;CAC9F;AAED,yDAAyD;AACzD,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,SAAS,CAAC;CACjB;AAED,2HAA2H;AAC3H,wBAAgB,KAAK,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAEzC;AAED;;;GAGG;AACH,8BAAsB,KAAK,CAAC,KAAK,SAAS,iBAAiB,GAAG,iBAAiB;IAC7E,SAAS,CAAC,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC;IAE/B,YAAY,IAAI,EAAE,KAAK,EAEtB;IAED,0DAA0D;IAC1D,QAAQ,CAAC,MAAM,IAAI,QAAQ,EAAE,CAAC;CAC/B"}
@@ -1 +1 @@
1
- {"version":3,"file":"route.js","names":[],"sources":["../../src/routes/route.ts"],"sourcesContent":["/**\n * Base class for factory route modules.\n *\n * Route modules build Mastra `apiRoutes` from injected dependencies instead of\n * reaching into host globals. The host server (e.g. `mastracode/web`) supplies\n * the auth seam and storage domain handles at construction time, so the routes\n * stay portable and testable with fakes.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\n/**\n * The auth surface factory routes need, implemented by the host server.\n *\n * Local (no-auth) deployments implement this with a stub where `enabled()`\n * returns `false` and `tenant()` returns `undefined` — routes then take their\n * single-user local paths.\n */\nexport interface RouteAuth {\n /** Whether an auth provider is active (tenant mode). */\n enabled(): boolean;\n /**\n * Resolve (and cache) the signed-in user for the request, if any. Must be\n * called before `tenant()` so the request context is populated.\n */\n ensureUser(c: Context): Promise<unknown>;\n /** Tenant identity for the request, when signed in. */\n tenant(c: Context): { orgId?: string; userId: string } | undefined;\n /** Fail-closed check that the caller administers the given organization. */\n isOrganizationAdmin(c: Context, organizationId: string): Promise<boolean>;\n}\n\n/** Dependencies shared by every factory route module. */\nexport interface RouteDependencies {\n auth: RouteAuth;\n}\n\n/** A host's hono can differ from this package's, so a handler's `Context` only reaches route helpers through `unknown`. */\nexport function loose(c: unknown): Context {\n return c as Context;\n}\n\n/**\n * A route module: constructed once at boot with its dependencies, then asked\n * for the `ApiRoute[]` it serves.\n */\nexport abstract class Route<TDeps extends RouteDependencies = RouteDependencies> {\n protected readonly deps: TDeps;\n\n constructor(deps: TDeps) {\n this.deps = deps;\n }\n\n /** Build the Mastra `apiRoutes` served by this module. */\n abstract routes(): ApiRoute[];\n}\n"],"mappings":";;AAuCA,SAAgB,MAAM,GAAqB;CACzC,OAAO;AACT;;;;;AAMA,IAAsB,QAAtB,MAAiF;CAC/E;CAEA,YAAY,MAAa;EACvB,KAAK,OAAO;CACd;AAIF"}
1
+ {"version":3,"file":"route.js","names":[],"sources":["../../src/routes/route.ts"],"sourcesContent":["/**\n * Base class for factory route modules.\n *\n * Route modules build Mastra `apiRoutes` from injected dependencies instead of\n * reaching into host globals. The host server (e.g. `mastracode/web`) supplies\n * the auth seam and storage domain handles at construction time, so the routes\n * stay portable and testable with fakes.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\n/**\n * The auth surface factory routes need, implemented by the host server.\n *\n * Local (no-auth) deployments implement this with a stub where `enabled()`\n * returns `false` and `tenant()` returns `undefined` — routes then take their\n * single-user local paths.\n */\nexport interface RouteAuth {\n /** Whether an auth provider is active (tenant mode). */\n enabled(): boolean;\n /**\n * Resolve (and cache) the signed-in user for the request, if any. Must be\n * called before `tenant()` so the request context is populated.\n */\n ensureUser(c: Context): Promise<unknown>;\n /** Tenant identity for the request, when signed in. */\n tenant(c: Context): { orgId?: string; userId: string } | undefined;\n /** Fail-closed check that the caller administers the given organization. */\n isOrganizationAdmin(c: Context, organizationId: string): Promise<boolean>;\n /**\n * Call the Mastra platform API as the signed-in user (`path` like\n * `/gateway/projects/provision`). Present only with Mastra platform auth\n * (`MastraAuthStudio`); `null` when the request has no session.\n */\n fetchPlatformAsUser?(c: Context, path: string, init?: RequestInit): Promise<Response | null>;\n}\n\n/** Dependencies shared by every factory route module. */\nexport interface RouteDependencies {\n auth: RouteAuth;\n}\n\n/** A host's hono can differ from this package's, so a handler's `Context` only reaches route helpers through `unknown`. */\nexport function loose(c: unknown): Context {\n return c as Context;\n}\n\n/**\n * A route module: constructed once at boot with its dependencies, then asked\n * for the `ApiRoute[]` it serves.\n */\nexport abstract class Route<TDeps extends RouteDependencies = RouteDependencies> {\n protected readonly deps: TDeps;\n\n constructor(deps: TDeps) {\n this.deps = deps;\n }\n\n /** Build the Mastra `apiRoutes` served by this module. */\n abstract routes(): ApiRoute[];\n}\n"],"mappings":";;AA6CA,SAAgB,MAAM,GAAqB;CACzC,OAAO;AACT;;;;;AAMA,IAAsB,QAAtB,MAAiF;CAC/E;CAEA,YAAY,MAAa;EACvB,KAAK,OAAO;CACd;AAIF"}
@@ -1 +1 @@
1
- {"version":3,"file":"tenant-credentials.d.ts","sourceRoot":"","sources":["../../src/routes/tenant-credentials.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAE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ACH,wBAAgB,gCAAgC,CAC9C,WAAW,EAAE,uBAAuB,EACpC,mBAAmB,GAAE,WAAW,CAAC,MAAM,CAAa,EACpD,aAAa,CAAC,EAAE,wBAAwB,GACvC,IAAI,CAcN;AAED;;;;;GAKG;AACH,wBAAsB,uCAAuC,CAAC,cAAc,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAM3G;AAED,uFAAuF;AACvF,wBAAsB,+BAA+B,CAAC,MAAM,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC,CAYhG;AAED;;;;;GAKG;AACH,wBAAsB,iCAAiC,CACrD,MAAM,EAAE,mBAAmB,EAC3B,cAAc,EAAE,MAAM,GAAG,SAAS,GACjC,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAc7B;AAED,iEAAiE;AACjE,wBAAgB,qCAAqC,IAAI,IAAI,CAK5D;AAED;;;;;GAKG;AACH,wBAAgB,mCAAmC,CAAC,MAAM,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CASpG;AAED;;;;GAIG;AACH,wBAAsB,sBAAsB,CAAC,EAC3C,MAAM,EACN,WAAW,GACZ,EAAE;IACD,MAAM,EAAE,IAAI,CAAC,mBAAmB,EAAE,OAAO,GAAG,QAAQ,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,mBAAmB,EAAE,iBAAiB,CAAC,CAAC,CAAC;IAC9G,WAAW,EAAE,uBAAuB,CAAC;CACtC,GAAG,OAAO,CAAC,IAAI,CAAC,CAKhB;AAED,wBAAgB,4BAA4B,CAAC,EAC3C,IAAI,EACJ,WAAW,GACZ,EAAE;IACD,IAAI,EAAE,SAAS,CAAC;IAChB,WAAW,EAAE,uBAAuB,CAAC;CACtC,GAAG,iBAAiB,CAgBpB"}
@@ -2,6 +2,8 @@ import { isOAuthCredentialExpired } from "../storage/domains/credentials/base.js
2
2
  import { getAuthProviderId, getTenantCredentialsStorage, tenantOrgId } from "./provider-credentials.js";
3
3
  import { prepareCredentialTenant, resolveTenantFromRequestContext, setCredentialStoreProvider } from "@mastra/code-sdk/agents/credential-resolver";
4
4
  import { PROVIDER_DEFAULT_MODELS, getOAuthProvider } from "@mastra/code-sdk/auth/storage";
5
+ import { MASTRA_GATEWAY_PROVIDER } from "@mastra/code-sdk/onboarding/settings";
6
+ import { MASTRA_GATEWAY_PREFIX } from "@mastra/code-sdk/providers/model-ids";
5
7
  // src/routes/tenant-credentials.ts
6
8
  /** How long a hydrated snapshot is considered fresh. */
7
9
  const SNAPSHOT_TTL_MS = 15e3;
@@ -197,7 +199,9 @@ async function resolveTenantProviderDefaultModel(tenant, currentModelId) {
197
199
  return store.get(getAuthProviderId(provider)) !== void 0 || store.allowsDeploymentCredentials(provider);
198
200
  };
199
201
  if (currentModelId && usable(currentModelId)) return void 0;
200
- return Object.entries(PROVIDER_DEFAULT_MODELS).find(([provider]) => store.get(provider) !== void 0)?.[1];
202
+ const providerDefault = Object.entries(PROVIDER_DEFAULT_MODELS).find(([provider]) => store.get(provider) !== void 0)?.[1];
203
+ if (providerDefault) return providerDefault;
204
+ return store.get(MASTRA_GATEWAY_PROVIDER) ? `${MASTRA_GATEWAY_PREFIX}anthropic/claude-opus-5.5` : void 0;
201
205
  }
202
206
  /** Test hook: clear registration and cached tenant snapshots. */
203
207
  function resetTenantCredentialResolverForTests() {
@@ -1 +1 @@
1
- {"version":3,"file":"tenant-credentials.js","names":[],"sources":["../../src/routes/tenant-credentials.ts"],"sourcesContent":["/**\n * Per-tenant credential store for model resolution (deployed mode).\n *\n * The SDK's `resolveModel` asks the registered `CredentialStoreProvider` for a\n * store synchronously, so this module keeps a small per-tenant **snapshot** of\n * credentials from one exclusive scope hydrated from the `model-credentials`\n * domain. The snapshot serves the gateway's synchronous\n * path-selection reads (`get` / `getStoredApiKey`); the fetch-time\n * `getApiKey` is authoritative — it re-resolves against the domain and\n * refreshes expired OAuth tokens under the domain's row lock, so a slightly\n * stale snapshot can never send an expired token upstream.\n *\n * Snapshots are primed per request by `createTenantCredentialPrimer` (mounted\n * after the web auth gate) so the first model call of a request already sees\n * the caller's credentials. This store explicitly disables the SDK's\n * environment fallback so server-shell credentials never leak into tenants.\n */\n\nimport type {\n CredentialTenant as SdkCredentialTenant,\n CredentialTenantResolver,\n} from '@mastra/code-sdk/agents/credential-resolver';\nimport {\n prepareCredentialTenant,\n resolveTenantFromRequestContext,\n setCredentialStoreProvider,\n} from '@mastra/code-sdk/agents/credential-resolver';\nimport { getOAuthProvider, PROVIDER_DEFAULT_MODELS } from '@mastra/code-sdk/auth/storage';\nimport type { AuthCredential, CredentialStore, OAuthCredential } from '@mastra/code-sdk/auth/types';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MiddlewareHandler } from 'hono';\n\nimport { isOAuthCredentialExpired } from '../storage/domains/credentials/base.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport { getAuthProviderId, getTenantCredentialsStorage, tenantOrgId } from './provider-credentials.js';\nimport type { RouteAuth } from './route.js';\n\n/** How long a hydrated snapshot is considered fresh. */\nconst SNAPSHOT_TTL_MS = 15_000;\n\n/** Cap on cached tenant stores; oldest-inserted evicted beyond this. */\nconst MAX_CACHED_TENANTS = 1000;\n\nexport class TenantCredentialStore implements CredentialStore {\n readonly allowEnvironmentFallback = false;\n readonly #orgId: string;\n readonly #userId: string;\n readonly #scope: SdkCredentialTenant['credentialScope'];\n readonly #credentials: ModelCredentialsStorage | undefined;\n readonly #deploymentProviders: ReadonlySet<string>;\n #snapshot = new Map<string, AuthCredential>();\n #fetchedAt = 0;\n #hydrating: Promise<void> | undefined;\n\n constructor(\n orgId: string,\n userId: string,\n credentials: ModelCredentialsStorage | undefined,\n scope: SdkCredentialTenant['credentialScope'],\n deploymentProviders: ReadonlySet<string> = new Set(),\n ) {\n this.#orgId = orgId;\n this.#userId = userId;\n this.#credentials = credentials;\n this.#scope = scope;\n this.#deploymentProviders = deploymentProviders;\n }\n\n /** Providers the operator opted in to run on the server process's own credentials. */\n allowsDeploymentCredentials(provider: string): boolean {\n return this.#deploymentProviders.has(provider);\n }\n\n /** Hydrate the snapshot when stale; coalesces concurrent callers. */\n async ensureFresh(now = Date.now()): Promise<void> {\n if (now - this.#fetchedAt < SNAPSHOT_TTL_MS) return;\n this.#hydrating ??= this.#hydrate().finally(() => {\n this.#hydrating = undefined;\n });\n await this.#hydrating;\n }\n\n async #hydrate(): Promise<void> {\n const storage = await getTenantCredentialsStorage(this.#credentials);\n if (!storage) return; // Keep the last tenant-scoped snapshot.\n const records = await storage.listCredentials(this.#orgId, this.#userId);\n const next = new Map<string, AuthCredential>();\n const storageScope = this.#scope === 'factory' ? 'org' : 'user';\n for (const record of records.filter(r => r.scope === storageScope)) {\n next.set(record.provider, record.credential);\n }\n this.#snapshot = next;\n this.#fetchedAt = Date.now();\n }\n\n /** Sync by contract; kicks a background re-hydrate when the snapshot is stale. */\n reload(): void {\n if (Date.now() - this.#fetchedAt >= SNAPSHOT_TTL_MS) {\n void this.ensureFresh().catch(() => {});\n }\n }\n\n get(provider: string): AuthCredential | undefined {\n return this.#snapshot.get(provider);\n }\n\n getStoredApiKey(provider: string): string | undefined {\n const cred = this.#snapshot.get(provider);\n return cred?.type === 'api_key' ? cred.key : undefined;\n }\n\n /**\n * Authoritative fetch-time resolution: re-reads only the selected scope and\n * refreshes expired OAuth tokens under the domain's row lock. Mirrors\n * `AuthStorage.getApiKey` semantics: `undefined` on missing credential or\n * failed refresh (caller surfaces a re-login error).\n */\n async getApiKey(provider: string): Promise<string | undefined> {\n const storage = await getTenantCredentialsStorage(this.#credentials);\n if (!storage) {\n // Domain unavailable: best effort from the snapshot; expired OAuth\n // tokens cannot be refreshed without the domain's lock.\n const cred = this.#snapshot.get(provider);\n if (cred?.type === 'api_key') return cred.key;\n if (cred?.type === 'oauth' && !isOAuthCredentialExpired(cred)) {\n return getOAuthProvider(provider)?.getApiKey(cred);\n }\n return undefined;\n }\n\n const resolved = await storage.resolveCredential(\n this.#orgId,\n this.#userId,\n provider,\n this.#scope === 'factory' ? 'org' : 'user',\n );\n if (!resolved) {\n this.#snapshot.delete(provider);\n return undefined;\n }\n this.#snapshot.set(provider, resolved.credential);\n\n if (resolved.credential.type === 'api_key') {\n return resolved.credential.key;\n }\n\n const oauthProvider = getOAuthProvider(provider);\n if (!oauthProvider) return undefined;\n\n if (!isOAuthCredentialExpired(resolved.credential)) {\n return oauthProvider.getApiKey(resolved.credential);\n }\n\n return this.#refreshOAuth(storage, resolved.scope, provider, isOAuthCredentialExpired);\n }\n\n /**\n * Refresh the OAuth credential even though it hasn't expired. The\n * account-rotation processor calls this once when the provider rejects the\n * token (401/403): providers can revoke an access token before the expiry\n * recorded at sign-in. Only the token this store last served is replaced, so\n * when another session or replica already refreshed it the newer token is\n * reused instead of rotating the refresh token again.\n */\n async forceRefreshActiveAccount(provider: string): Promise<string | undefined> {\n const storage = await getTenantCredentialsStorage(this.#credentials);\n if (!storage) return undefined;\n const served = this.#snapshot.get(provider);\n const resolved = await storage.resolveCredential(\n this.#orgId,\n this.#userId,\n provider,\n this.#scope === 'factory' ? 'org' : 'user',\n );\n if (resolved?.credential.type !== 'oauth') return undefined;\n const rejectedAccess = served?.type === 'oauth' ? served.access : resolved.credential.access;\n return this.#refreshOAuth(\n storage,\n resolved.scope,\n provider,\n current => isOAuthCredentialExpired(current) || current.access === rejectedAccess,\n );\n }\n\n async #refreshOAuth(\n storage: ModelCredentialsStorage,\n scope: 'user' | 'org',\n provider: string,\n needsRefresh: (current: OAuthCredential) => boolean,\n ): Promise<string | undefined> {\n const oauthProvider = getOAuthProvider(provider);\n if (!oauthProvider) return undefined;\n // Refresh at the scope the credential actually lives at (OAuth rows are\n // user-scoped by policy, but resolve defensively from the record).\n const rowTenant = scope === 'user' ? { orgId: this.#orgId, userId: this.#userId } : { orgId: this.#orgId };\n try {\n const refreshed = await storage.refreshOAuth(\n rowTenant,\n provider,\n async current => ({\n type: 'oauth' as const,\n ...(await oauthProvider.refreshToken(current)),\n }),\n needsRefresh,\n );\n if (!refreshed) return undefined;\n this.#snapshot.set(provider, refreshed);\n return oauthProvider.getApiKey(refreshed);\n } catch {\n // Refresh failed — user needs to re-login (same posture as AuthStorage).\n return undefined;\n }\n }\n}\n\nconst tenantStores = new Map<string, TenantCredentialStore>();\nlet registeredCredentials: ModelCredentialsStorage | undefined;\nlet registeredDeploymentProviders: ReadonlySet<string> = new Set();\n\nfunction storeFor(tenant: SdkCredentialTenant, credentials: ModelCredentialsStorage): TenantCredentialStore {\n const orgId = tenantOrgId(tenant);\n const key = `${orgId}\\u0000${tenant.userId}\\u0000${tenant.credentialScope}`;\n let store = tenantStores.get(key);\n if (!store) {\n if (tenantStores.size >= MAX_CACHED_TENANTS) {\n const oldest = tenantStores.keys().next().value;\n if (oldest !== undefined) tenantStores.delete(oldest);\n }\n store = new TenantCredentialStore(\n orgId,\n tenant.userId,\n credentials,\n tenant.credentialScope,\n registeredDeploymentProviders,\n );\n tenantStores.set(key, store);\n }\n return store;\n}\n\n/**\n * Register the web tenant credential store provider with the SDK. Called by\n * the factory after storage init with the `model-credentials` domain handle;\n * from then on `resolveModel` uses per-tenant credentials and the SDK skips\n * the `loadStoredApiKeysIntoEnv` env side-channel. `deploymentProviders` are\n * the providers the operator opted in to authenticate with the server\n * process's own credentials (see `MastraFactoryConfig.deploymentModelProviders`).\n */\nexport function registerTenantCredentialResolver(\n credentials: ModelCredentialsStorage,\n deploymentProviders: ReadonlySet<string> = new Set(),\n resolveTenant?: CredentialTenantResolver,\n): void {\n registeredCredentials = credentials;\n registeredDeploymentProviders = deploymentProviders;\n tenantStores.clear();\n setCredentialStoreProvider(\n tenant => storeFor(tenant, credentials),\n resolveTenant\n ? async requestContext => {\n const tenant = await resolveTenant(requestContext);\n if (tenant) await storeFor(tenant, credentials).ensureFresh();\n return tenant;\n }\n : undefined,\n );\n}\n\n/**\n * Prime the tenant stores for a request context built outside the web layer,\n * such as a webhook-triggered session run. The auth middleware does this for\n * HTTP requests; a run that starts without one would otherwise resolve its\n * model against an empty snapshot and fail closed. No-op before registration.\n */\nexport async function primeTenantCredentialsForRequestContext(requestContext: RequestContext): Promise<void> {\n if (!registeredCredentials) return;\n await prepareCredentialTenant(requestContext);\n const tenant = resolveTenantFromRequestContext(requestContext);\n if (!tenant) return;\n await storeFor(tenant, registeredCredentials).ensureFresh();\n}\n\n/** Prime one already-resolved Factory session tenant before entering the agent run. */\nexport async function primeTenantCredentialsForTenant(tenant: SdkCredentialTenant): Promise<void> {\n if (!registeredCredentials) return;\n try {\n await storeFor(tenant, registeredCredentials).ensureFresh();\n } catch (error) {\n console.warn('[factory] Failed to prime scoped tenant model credentials', {\n orgId: tenant.orgId,\n userId: tenant.userId,\n credentialScope: tenant.credentialScope,\n error,\n });\n }\n}\n\n/**\n * The model a session should fall back to when its scope has no chosen default:\n * the provider default (`PROVIDER_DEFAULT_MODELS`) of the first provider the\n * tenant is connected to. Returns `undefined` when `currentModelId` is already\n * usable, when no connected provider has a default, or before registration.\n */\nexport async function resolveTenantProviderDefaultModel(\n tenant: SdkCredentialTenant,\n currentModelId: string | undefined,\n): Promise<string | undefined> {\n if (!registeredCredentials) return undefined;\n const store = storeFor(tenant, registeredCredentials);\n await store.ensureFresh();\n const usable = (modelId: string) => {\n const provider = modelId.split('/')[0] ?? '';\n return store.get(getAuthProviderId(provider)) !== undefined || store.allowsDeploymentCredentials(provider);\n };\n if (currentModelId && usable(currentModelId)) return undefined;\n return Object.entries(PROVIDER_DEFAULT_MODELS).find(([provider]) => store.get(provider) !== undefined)?.[1];\n}\n\n/** Test hook: clear registration and cached tenant snapshots. */\nexport function resetTenantCredentialResolverForTests(): void {\n setCredentialStoreProvider(undefined);\n registeredCredentials = undefined;\n registeredDeploymentProviders = new Set();\n tenantStores.clear();\n}\n\n/**\n * Drop cached snapshots after a credential write so the change is visible to\n * the next model call immediately instead of after the snapshot TTL. An org\n * write affects every member's resolved view, so all stores under the org are\n * invalidated; a user write only drops that user's store.\n */\nexport function invalidateTenantCredentialSnapshots(tenant: { orgId: string; userId?: string }): void {\n if (tenant.userId) {\n tenantStores.delete(`${tenant.orgId}\\u0000${tenant.userId}\\u0000user`);\n tenantStores.delete(`${tenant.orgId}\\u0000${tenant.userId}\\u0000factory`);\n return;\n }\n for (const key of tenantStores.keys()) {\n if (key.startsWith(`${tenant.orgId}\\u0000`)) tenantStores.delete(key);\n }\n}\n\n/**\n * Middleware mounted after the web auth gate: primes both exclusive credential\n * scopes because the HTTP principal is known before the controller session is.\n * Cheap when fresh because each store has a TTL.\n */\nexport async function primeTenantCredentials({\n tenant,\n credentials,\n}: {\n tenant: Pick<SdkCredentialTenant, 'orgId' | 'userId'> & Partial<Pick<SdkCredentialTenant, 'credentialScope'>>;\n credentials: ModelCredentialsStorage;\n}): Promise<void> {\n await Promise.all([\n storeFor({ ...tenant, credentialScope: 'user' }, credentials).ensureFresh(),\n storeFor({ ...tenant, credentialScope: 'factory' }, credentials).ensureFresh(),\n ]);\n}\n\nexport function createTenantCredentialPrimer({\n auth,\n credentials,\n}: {\n auth: RouteAuth;\n credentials: ModelCredentialsStorage;\n}): MiddlewareHandler {\n return async (c, next) => {\n const tenant = auth.tenant(c);\n if (tenant) {\n try {\n await primeTenantCredentials({ tenant, credentials });\n } catch (error) {\n console.warn('[factory] Failed to prime tenant model credentials', {\n orgId: tenant.orgId,\n userId: tenant.userId,\n error,\n });\n }\n }\n await next();\n };\n}\n"],"mappings":";;;;;;AAsCA,MAAM,kBAAkB;;AAGxB,MAAM,qBAAqB;AAE3B,IAAa,wBAAb,MAA8D;CAC5D,2BAAoC;CACpC;CACA;CACA;CACA;CACA;CACA,4BAAY,IAAI,IAA4B;CAC5C,aAAa;CACb;CAEA,YACE,OACA,QACA,aACA,OACA,sCAA2C,IAAI,IAAI,GACnD;EACA,KAAK,SAAS;EACd,KAAK,UAAU;EACf,KAAK,eAAe;EACpB,KAAK,SAAS;EACd,KAAK,uBAAuB;CAC9B;;CAG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EAC3C,QACA,eAIgB;CAChB,MAAM,QAAQ,IAAI,CAChB,SAAS;EAAE,GAAG;EAAQ,iBAAiB;CAAO,GAAG,WAAW,CAAC,CAAC,YAAY,GAC1E,SAAS;EAAE,GAAG;EAAQ,iBAAiB;CAAU,GAAG,WAAW,CAAC,CAAC,YAAY,CAC/E,CAAC;AACH;AAEA,SAAgB,6BAA6B,EAC3C,MACA,eAIoB;CACpB,OAAO,OAAO,GAAG,SAAS;EACxB,MAAM,SAAS,KAAK,OAAO,CAAC;EAC5B,IAAI,QACF,IAAI;GACF,MAAM,uBAAuB;IAAE;IAAQ;GAAY,CAAC;EACtD,SAAS,OAAO;GACd,QAAQ,KAAK,sDAAsD;IACjE,OAAO,OAAO;IACd,QAAQ,OAAO;IACf;GACF,CAAC;EACH;EAEF,MAAM,KAAK;CACb;AACF"}
1
+ {"version":3,"file":"tenant-credentials.js","names":[],"sources":["../../src/routes/tenant-credentials.ts"],"sourcesContent":["/**\n * Per-tenant credential store for model resolution (deployed mode).\n *\n * The SDK's `resolveModel` asks the registered `CredentialStoreProvider` for a\n * store synchronously, so this module keeps a small per-tenant **snapshot** of\n * credentials from one exclusive scope hydrated from the `model-credentials`\n * domain. The snapshot serves the gateway's synchronous\n * path-selection reads (`get` / `getStoredApiKey`); the fetch-time\n * `getApiKey` is authoritative — it re-resolves against the domain and\n * refreshes expired OAuth tokens under the domain's row lock, so a slightly\n * stale snapshot can never send an expired token upstream.\n *\n * Snapshots are primed per request by `createTenantCredentialPrimer` (mounted\n * after the web auth gate) so the first model call of a request already sees\n * the caller's credentials. This store explicitly disables the SDK's\n * environment fallback so server-shell credentials never leak into tenants.\n */\n\nimport type {\n CredentialTenant as SdkCredentialTenant,\n CredentialTenantResolver,\n} from '@mastra/code-sdk/agents/credential-resolver';\nimport {\n prepareCredentialTenant,\n resolveTenantFromRequestContext,\n setCredentialStoreProvider,\n} from '@mastra/code-sdk/agents/credential-resolver';\nimport { getOAuthProvider, PROVIDER_DEFAULT_MODELS } from '@mastra/code-sdk/auth/storage';\nimport type { AuthCredential, CredentialStore, OAuthCredential } from '@mastra/code-sdk/auth/types';\nimport { MASTRA_GATEWAY_PROVIDER } from '@mastra/code-sdk/onboarding/settings';\nimport { MASTRA_GATEWAY_PREFIX } from '@mastra/code-sdk/providers/model-ids';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MiddlewareHandler } from 'hono';\n\nimport { isOAuthCredentialExpired } from '../storage/domains/credentials/base.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport { getAuthProviderId, getTenantCredentialsStorage, tenantOrgId } from './provider-credentials.js';\nimport type { RouteAuth } from './route.js';\n\n/** How long a hydrated snapshot is considered fresh. */\nconst SNAPSHOT_TTL_MS = 15_000;\n\n/** Cap on cached tenant stores; oldest-inserted evicted beyond this. */\nconst MAX_CACHED_TENANTS = 1000;\n\nexport class TenantCredentialStore implements CredentialStore {\n readonly allowEnvironmentFallback = false;\n readonly #orgId: string;\n readonly #userId: string;\n readonly #scope: SdkCredentialTenant['credentialScope'];\n readonly #credentials: ModelCredentialsStorage | undefined;\n readonly #deploymentProviders: ReadonlySet<string>;\n #snapshot = new Map<string, AuthCredential>();\n #fetchedAt = 0;\n #hydrating: Promise<void> | undefined;\n\n constructor(\n orgId: string,\n userId: string,\n credentials: ModelCredentialsStorage | undefined,\n scope: SdkCredentialTenant['credentialScope'],\n deploymentProviders: ReadonlySet<string> = new Set(),\n ) {\n this.#orgId = orgId;\n this.#userId = userId;\n this.#credentials = credentials;\n this.#scope = scope;\n this.#deploymentProviders = deploymentProviders;\n }\n\n /** Providers the operator opted in to run on the server process's own credentials. */\n allowsDeploymentCredentials(provider: string): boolean {\n return this.#deploymentProviders.has(provider);\n }\n\n /** Hydrate the snapshot when stale; coalesces concurrent callers. */\n async ensureFresh(now = Date.now()): Promise<void> {\n if (now - this.#fetchedAt < SNAPSHOT_TTL_MS) return;\n this.#hydrating ??= this.#hydrate().finally(() => {\n this.#hydrating = undefined;\n });\n await this.#hydrating;\n }\n\n async #hydrate(): Promise<void> {\n const storage = await getTenantCredentialsStorage(this.#credentials);\n if (!storage) return; // Keep the last tenant-scoped snapshot.\n const records = await storage.listCredentials(this.#orgId, this.#userId);\n const next = new Map<string, AuthCredential>();\n const storageScope = this.#scope === 'factory' ? 'org' : 'user';\n for (const record of records.filter(r => r.scope === storageScope)) {\n next.set(record.provider, record.credential);\n }\n this.#snapshot = next;\n this.#fetchedAt = Date.now();\n }\n\n /** Sync by contract; kicks a background re-hydrate when the snapshot is stale. */\n reload(): void {\n if (Date.now() - this.#fetchedAt >= SNAPSHOT_TTL_MS) {\n void this.ensureFresh().catch(() => {});\n }\n }\n\n get(provider: string): AuthCredential | undefined {\n return this.#snapshot.get(provider);\n }\n\n getStoredApiKey(provider: string): string | undefined {\n const cred = this.#snapshot.get(provider);\n return cred?.type === 'api_key' ? cred.key : undefined;\n }\n\n /**\n * Authoritative fetch-time resolution: re-reads only the selected scope and\n * refreshes expired OAuth tokens under the domain's row lock. Mirrors\n * `AuthStorage.getApiKey` semantics: `undefined` on missing credential or\n * failed refresh (caller surfaces a re-login error).\n */\n async getApiKey(provider: string): Promise<string | undefined> {\n const storage = await getTenantCredentialsStorage(this.#credentials);\n if (!storage) {\n // Domain unavailable: best effort from the snapshot; expired OAuth\n // tokens cannot be refreshed without the domain's lock.\n const cred = this.#snapshot.get(provider);\n if (cred?.type === 'api_key') return cred.key;\n if (cred?.type === 'oauth' && !isOAuthCredentialExpired(cred)) {\n return getOAuthProvider(provider)?.getApiKey(cred);\n }\n return undefined;\n }\n\n const resolved = await storage.resolveCredential(\n this.#orgId,\n this.#userId,\n provider,\n this.#scope === 'factory' ? 'org' : 'user',\n );\n if (!resolved) {\n this.#snapshot.delete(provider);\n return undefined;\n }\n this.#snapshot.set(provider, resolved.credential);\n\n if (resolved.credential.type === 'api_key') {\n return resolved.credential.key;\n }\n\n const oauthProvider = getOAuthProvider(provider);\n if (!oauthProvider) return undefined;\n\n if (!isOAuthCredentialExpired(resolved.credential)) {\n return oauthProvider.getApiKey(resolved.credential);\n }\n\n return this.#refreshOAuth(storage, resolved.scope, provider, isOAuthCredentialExpired);\n }\n\n /**\n * Refresh the OAuth credential even though it hasn't expired. The\n * account-rotation processor calls this once when the provider rejects the\n * token (401/403): providers can revoke an access token before the expiry\n * recorded at sign-in. Only the token this store last served is replaced, so\n * when another session or replica already refreshed it the newer token is\n * reused instead of rotating the refresh token again.\n */\n async forceRefreshActiveAccount(provider: string): Promise<string | undefined> {\n const storage = await getTenantCredentialsStorage(this.#credentials);\n if (!storage) return undefined;\n const served = this.#snapshot.get(provider);\n const resolved = await storage.resolveCredential(\n this.#orgId,\n this.#userId,\n provider,\n this.#scope === 'factory' ? 'org' : 'user',\n );\n if (resolved?.credential.type !== 'oauth') return undefined;\n const rejectedAccess = served?.type === 'oauth' ? served.access : resolved.credential.access;\n return this.#refreshOAuth(\n storage,\n resolved.scope,\n provider,\n current => isOAuthCredentialExpired(current) || current.access === rejectedAccess,\n );\n }\n\n async #refreshOAuth(\n storage: ModelCredentialsStorage,\n scope: 'user' | 'org',\n provider: string,\n needsRefresh: (current: OAuthCredential) => boolean,\n ): Promise<string | undefined> {\n const oauthProvider = getOAuthProvider(provider);\n if (!oauthProvider) return undefined;\n // Refresh at the scope the credential actually lives at (OAuth rows are\n // user-scoped by policy, but resolve defensively from the record).\n const rowTenant = scope === 'user' ? { orgId: this.#orgId, userId: this.#userId } : { orgId: this.#orgId };\n try {\n const refreshed = await storage.refreshOAuth(\n rowTenant,\n provider,\n async current => ({\n type: 'oauth' as const,\n ...(await oauthProvider.refreshToken(current)),\n }),\n needsRefresh,\n );\n if (!refreshed) return undefined;\n this.#snapshot.set(provider, refreshed);\n return oauthProvider.getApiKey(refreshed);\n } catch {\n // Refresh failed — user needs to re-login (same posture as AuthStorage).\n return undefined;\n }\n }\n}\n\nconst tenantStores = new Map<string, TenantCredentialStore>();\nlet registeredCredentials: ModelCredentialsStorage | undefined;\nlet registeredDeploymentProviders: ReadonlySet<string> = new Set();\n\nfunction storeFor(tenant: SdkCredentialTenant, credentials: ModelCredentialsStorage): TenantCredentialStore {\n const orgId = tenantOrgId(tenant);\n const key = `${orgId}\\u0000${tenant.userId}\\u0000${tenant.credentialScope}`;\n let store = tenantStores.get(key);\n if (!store) {\n if (tenantStores.size >= MAX_CACHED_TENANTS) {\n const oldest = tenantStores.keys().next().value;\n if (oldest !== undefined) tenantStores.delete(oldest);\n }\n store = new TenantCredentialStore(\n orgId,\n tenant.userId,\n credentials,\n tenant.credentialScope,\n registeredDeploymentProviders,\n );\n tenantStores.set(key, store);\n }\n return store;\n}\n\n/**\n * Register the web tenant credential store provider with the SDK. Called by\n * the factory after storage init with the `model-credentials` domain handle;\n * from then on `resolveModel` uses per-tenant credentials and the SDK skips\n * the `loadStoredApiKeysIntoEnv` env side-channel. `deploymentProviders` are\n * the providers the operator opted in to authenticate with the server\n * process's own credentials (see `MastraFactoryConfig.deploymentModelProviders`).\n */\nexport function registerTenantCredentialResolver(\n credentials: ModelCredentialsStorage,\n deploymentProviders: ReadonlySet<string> = new Set(),\n resolveTenant?: CredentialTenantResolver,\n): void {\n registeredCredentials = credentials;\n registeredDeploymentProviders = deploymentProviders;\n tenantStores.clear();\n setCredentialStoreProvider(\n tenant => storeFor(tenant, credentials),\n resolveTenant\n ? async requestContext => {\n const tenant = await resolveTenant(requestContext);\n if (tenant) await storeFor(tenant, credentials).ensureFresh();\n return tenant;\n }\n : undefined,\n );\n}\n\n/**\n * Prime the tenant stores for a request context built outside the web layer,\n * such as a webhook-triggered session run. The auth middleware does this for\n * HTTP requests; a run that starts without one would otherwise resolve its\n * model against an empty snapshot and fail closed. No-op before registration.\n */\nexport async function primeTenantCredentialsForRequestContext(requestContext: RequestContext): Promise<void> {\n if (!registeredCredentials) return;\n await prepareCredentialTenant(requestContext);\n const tenant = resolveTenantFromRequestContext(requestContext);\n if (!tenant) return;\n await storeFor(tenant, registeredCredentials).ensureFresh();\n}\n\n/** Prime one already-resolved Factory session tenant before entering the agent run. */\nexport async function primeTenantCredentialsForTenant(tenant: SdkCredentialTenant): Promise<void> {\n if (!registeredCredentials) return;\n try {\n await storeFor(tenant, registeredCredentials).ensureFresh();\n } catch (error) {\n console.warn('[factory] Failed to prime scoped tenant model credentials', {\n orgId: tenant.orgId,\n userId: tenant.userId,\n credentialScope: tenant.credentialScope,\n error,\n });\n }\n}\n\n/**\n * The model a session should fall back to when its scope has no chosen default:\n * the provider default (`PROVIDER_DEFAULT_MODELS`) of the first provider the\n * tenant is connected to. Returns `undefined` when `currentModelId` is already\n * usable, when no connected provider has a default, or before registration.\n */\nexport async function resolveTenantProviderDefaultModel(\n tenant: SdkCredentialTenant,\n currentModelId: string | undefined,\n): Promise<string | undefined> {\n if (!registeredCredentials) return undefined;\n const store = storeFor(tenant, registeredCredentials);\n await store.ensureFresh();\n const usable = (modelId: string) => {\n const provider = modelId.split('/')[0] ?? '';\n return store.get(getAuthProviderId(provider)) !== undefined || store.allowsDeploymentCredentials(provider);\n };\n if (currentModelId && usable(currentModelId)) return undefined;\n const providerDefault = Object.entries(PROVIDER_DEFAULT_MODELS).find(\n ([provider]) => store.get(provider) !== undefined,\n )?.[1];\n if (providerDefault) return providerDefault;\n return store.get(MASTRA_GATEWAY_PROVIDER) ? `${MASTRA_GATEWAY_PREFIX}anthropic/claude-opus-5.5` : undefined;\n}\n\n/** Test hook: clear registration and cached tenant snapshots. */\nexport function resetTenantCredentialResolverForTests(): void {\n setCredentialStoreProvider(undefined);\n registeredCredentials = undefined;\n registeredDeploymentProviders = new Set();\n tenantStores.clear();\n}\n\n/**\n * Drop cached snapshots after a credential write so the change is visible to\n * the next model call immediately instead of after the snapshot TTL. An org\n * write affects every member's resolved view, so all stores under the org are\n * invalidated; a user write only drops that user's store.\n */\nexport function invalidateTenantCredentialSnapshots(tenant: { orgId: string; userId?: string }): void {\n if (tenant.userId) {\n tenantStores.delete(`${tenant.orgId}\\u0000${tenant.userId}\\u0000user`);\n tenantStores.delete(`${tenant.orgId}\\u0000${tenant.userId}\\u0000factory`);\n return;\n }\n for (const key of tenantStores.keys()) {\n if (key.startsWith(`${tenant.orgId}\\u0000`)) tenantStores.delete(key);\n }\n}\n\n/**\n * Middleware mounted after the web auth gate: primes both exclusive credential\n * scopes because the HTTP principal is known before the controller session is.\n * Cheap when fresh because each store has a TTL.\n */\nexport async function primeTenantCredentials({\n tenant,\n credentials,\n}: {\n tenant: Pick<SdkCredentialTenant, 'orgId' | 'userId'> & Partial<Pick<SdkCredentialTenant, 'credentialScope'>>;\n credentials: ModelCredentialsStorage;\n}): Promise<void> {\n await Promise.all([\n storeFor({ ...tenant, credentialScope: 'user' }, credentials).ensureFresh(),\n storeFor({ ...tenant, credentialScope: 'factory' }, credentials).ensureFresh(),\n ]);\n}\n\nexport function createTenantCredentialPrimer({\n auth,\n credentials,\n}: {\n auth: RouteAuth;\n credentials: ModelCredentialsStorage;\n}): MiddlewareHandler {\n return async (c, next) => {\n const tenant = auth.tenant(c);\n if (tenant) {\n try {\n await primeTenantCredentials({ tenant, credentials });\n } catch (error) {\n console.warn('[factory] Failed to prime tenant model credentials', {\n orgId: tenant.orgId,\n userId: tenant.userId,\n error,\n });\n }\n }\n await next();\n };\n}\n"],"mappings":";;;;;;;;AAwCA,MAAM,kBAAkB;;AAGxB,MAAM,qBAAqB;AAE3B,IAAa,wBAAb,MAA8D;CAC5D,2BAAoC;CACpC;CACA;CACA;CACA;CACA;CACA,4BAAY,IAAI,IAA4B;CAC5C,aAAa;CACb;CAEA,YACE,OACA,QACA,aACA,OACA,sCAA2C,IAAI,IAAI,GACnD;EACA,KAAK,SAAS;EACd,KAAK,UAAU;EACf,KAAK,eAAe;EACpB,KAAK,SAAS;EACd,KAAK,uBAAuB;CAC9B;;CAGA,4BAA4B,UAA2B;EACrD,OAAO,KAAK,qBAAqB,IAAI,QAAQ;CAC/C;;CAGA,MAAM,YAAY,MAAM,KAAK,IAAI,GAAkB;EACjD,IAAI,MAAM,KAA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AAM,QAAQ,IAAI,CAChB,SAAS;EAAE,GAAG;EAAQ,iBAAiB;CAAO,GAAG,WAAW,CAAC,CAAC,YAAY,GAC1E,SAAS;EAAE,GAAG;EAAQ,iBAAiB;CAAU,GAAG,WAAW,CAAC,CAAC,YAAY,CAC/E,CAAC;AACH;AAEA,SAAgB,6BAA6B,EAC3C,MACA,eAIoB;CACpB,OAAO,OAAO,GAAG,SAAS;EACxB,MAAM,SAAS,KAAK,OAAO,CAAC;EAC5B,IAAI,QACF,IAAI;GACF,MAAM,uBAAuB;IAAE;IAAQ;GAAY,CAAC;EACtD,SAAS,OAAO;GACd,QAAQ,KAAK,sDAAsD;IACjE,OAAO,OAAO;IACd,QAAQ,OAAO;IACf;GACF,CAAC;EACH;EAEF,MAAM,KAAK;CACb;AACF"}
@@ -1,4 +1,4 @@
1
- export type RunErrorRecovery = 'continue' | 'credentials' | 'model' | 'new_session';
1
+ export type RunErrorRecovery = 'continue' | 'credentials' | 'credits' | 'model' | 'new_session';
2
2
  export interface RunErrorDescription {
3
3
  title: string;
4
4
  message: string;
@@ -1 +1 @@
1
- {"version":3,"file":"run-error.d.ts","sourceRoot":"","sources":["../src/run-error.ts"],"names":[],"mappings":"AAQA,MAAM,MAAM,gBAAgB,GAAG,UAAU,GAAG,aAAa,GAAG,OAAO,GAAG,aAAa,CAAC;AAEpF,MAAM,WAAW,mBAAmB;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,gBAAgB,EAAE,CAAC;IAC/B,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAMD,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,gBAAgB,GAAG,mBAAmB,CAE7E"}
1
+ {"version":3,"file":"run-error.d.ts","sourceRoot":"","sources":["../src/run-error.ts"],"names":[],"mappings":"AASA,MAAM,MAAM,gBAAgB,GAAG,UAAU,GAAG,aAAa,GAAG,SAAS,GAAG,OAAO,GAAG,aAAa,CAAC;AAEhG,MAAM,WAAW,mBAAmB;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,gBAAgB,EAAE,CAAC;IAC/B,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAMD,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,gBAAgB,GAAG,mBAAmB,CAE7E"}
package/dist/run-error.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { MASTRA_GATEWAY_PREFIX } from "@mastra/code-sdk/providers/model-ids";
1
2
  import { PROVIDER_CALL_ERROR_NAME, classifyProviderError, providerErrorReason, providerModelId } from "@mastra/core/error";
2
3
  import { PROVIDER_AUTH_REQUIRED_ERROR } from "@mastra/code-sdk/auth/provider-auth-error";
3
4
  // src/run-error.ts
@@ -16,11 +17,21 @@ function explainRunError(error) {
16
17
  recoveries: ["credentials", "model"]
17
18
  };
18
19
  switch (classifyProviderError(error)) {
19
- case "quota": return {
20
- title: "Provider quota exhausted",
21
- message: afterProviderReason(error, "Check the provider account’s billing or usage allowance, or use another credential or model."),
22
- recoveries: ["credentials", "model"]
23
- };
20
+ case "quota":
21
+ if (isMastraGatewayError(error)) return {
22
+ title: "Out of Mastra Gateway credits",
23
+ message: "Your organization has no gateway credits left. Add credits, then continue the run, or choose another model.",
24
+ recoveries: [
25
+ "credits",
26
+ "continue",
27
+ "model"
28
+ ]
29
+ };
30
+ return {
31
+ title: "Provider quota exhausted",
32
+ message: afterProviderReason(error, "Check the provider account’s billing or usage allowance, or use another credential or model."),
33
+ recoveries: ["credentials", "model"]
34
+ };
24
35
  case "auth": return {
25
36
  title: "Provider access failed",
26
37
  message: afterProviderReason(error, "Review the credentials and model access configured for this session."),
@@ -68,6 +79,28 @@ function explainRunError(error) {
68
79
  case "unknown": return describeUnclassifiedError(error);
69
80
  }
70
81
  }
82
+ const MASTRA_GATEWAY_HOST = /(?:^|\.)gateway(?:-api)?\.mastra\.ai$/;
83
+ /**
84
+ * The Mastra Gateway answered: a `mastra/…` model, a request sent to its host, or its billing reply
85
+ * (which links to `gateway.mastra.ai`). The request reaches the gateway without the `mastra/` prefix.
86
+ */
87
+ function isMastraGatewayError(error) {
88
+ return providerModelId(error)?.startsWith(MASTRA_GATEWAY_PREFIX) === true || calledMastraGateway(error) || /gateway\.mastra\.ai/.test(providerErrorReason(error) ?? error.message);
89
+ }
90
+ /** Whether the request, or a provider error it wraps, went to the gateway's host. */
91
+ function calledMastraGateway(error, depth = 0) {
92
+ if (depth > 4 || typeof error !== "object" || error === null) return false;
93
+ const url = "url" in error ? error.url : void 0;
94
+ const cause = "cause" in error ? error.cause : void 0;
95
+ return typeof url === "string" && MASTRA_GATEWAY_HOST.test(hostOf(url)) || calledMastraGateway(cause, depth + 1);
96
+ }
97
+ function hostOf(url) {
98
+ try {
99
+ return new URL(url).hostname;
100
+ } catch {
101
+ return "";
102
+ }
103
+ }
71
104
  function afterProviderReason(error, next, fallback) {
72
105
  const reason = providerErrorReason(error) ?? fallback;
73
106
  return reason ? `${reason.replace(/\.?$/, ".")} ${next}` : next;
@@ -1 +1 @@
1
- {"version":3,"file":"run-error.js","names":[],"sources":["../src/run-error.ts"],"sourcesContent":["import { PROVIDER_AUTH_REQUIRED_ERROR } from '@mastra/code-sdk/auth/provider-auth-error';\nimport {\n classifyProviderError,\n PROVIDER_CALL_ERROR_NAME,\n providerErrorReason,\n providerModelId,\n} from '@mastra/core/error';\n\nexport type RunErrorRecovery = 'continue' | 'credentials' | 'model' | 'new_session';\n\nexport interface RunErrorDescription {\n title: string;\n message: string;\n recoveries: RunErrorRecovery[];\n model?: string;\n}\n\nexport interface RunErrorIdentity {\n name: string;\n message: string;\n}\n\nconst UNEXPECTED_ERROR = 'An unexpected error stopped the run. Copy the error details to investigate.';\nconst NO_REASON_AVAILABLE =\n 'The provider rejected the request. A specific reason isn’t available here. Copy the error details and check the server logs.';\n\nexport function describeRunError(error: RunErrorIdentity): RunErrorDescription {\n return { ...explainRunError(error), model: providerModelId(error) };\n}\n\nfunction explainRunError(error: RunErrorIdentity): Omit<RunErrorDescription, 'model'> {\n if (error.name === PROVIDER_AUTH_REQUIRED_ERROR) {\n return { title: 'Provider sign-in required', message: error.message, recoveries: ['credentials', 'model'] };\n }\n switch (classifyProviderError(error)) {\n case 'quota':\n return {\n title: 'Provider quota exhausted',\n message: afterProviderReason(\n error,\n 'Check the provider account’s billing or usage allowance, or use another credential or model.',\n ),\n recoveries: ['credentials', 'model'],\n };\n case 'auth':\n return {\n title: 'Provider access failed',\n message: afterProviderReason(error, 'Review the credentials and model access configured for this session.'),\n recoveries: ['credentials', 'model'],\n };\n case 'context_overflow':\n return {\n title: 'Conversation exceeds the model’s limit',\n message: 'Choose a model with a larger context window or start a new session with a shorter prompt.',\n recoveries: ['model', 'new_session'],\n };\n case 'model_rejected':\n return {\n title: 'Model not available',\n message: afterProviderReason(\n error,\n 'Choose another model for this session.',\n 'The provider rejected this model.',\n ),\n recoveries: ['model'],\n };\n case 'tool_history_rejected':\n return {\n title: 'Conversation history rejected',\n message:\n 'The provider could not match a tool call with its result. Start a new session to keep working, and copy the error details so this session can be investigated.',\n recoveries: ['new_session'],\n };\n case 'invalid_request':\n return {\n title: 'Model request rejected',\n message: providerErrorReason(error) ?? NO_REASON_AVAILABLE,\n recoveries: ['model'],\n };\n case 'timeout':\n return {\n title: 'Request timed out',\n message: 'The request took too long to complete. Send a message to continue the run.',\n recoveries: ['continue'],\n };\n case 'rate_limited':\n return {\n title: 'Provider rate limit reached',\n message:\n 'The provider account behind this session’s credential hit a rate or usage limit. Continue once it resets, or use another credential or model.',\n recoveries: ['continue', 'credentials', 'model'],\n };\n case 'unavailable':\n return {\n title: 'Model provider temporarily unavailable',\n message:\n 'The provider could not complete the request. Send a message to continue the run, or choose another model.',\n recoveries: ['continue', 'model'],\n };\n case 'unknown':\n return describeUnclassifiedError(error);\n }\n}\n\nfunction afterProviderReason(error: RunErrorIdentity, next: string, fallback?: string): string {\n const reason = providerErrorReason(error) ?? fallback;\n return reason ? `${reason.replace(/\\.?$/, '.')} ${next}` : next;\n}\n\nfunction describeUnclassifiedError(error: RunErrorIdentity): Omit<RunErrorDescription, 'model'> {\n const message = providerErrorReason(error) ?? (error.message || UNEXPECTED_ERROR);\n const providerCall = PROVIDER_CALL_ERROR_NAME.test(error.name);\n return {\n title: providerCall ? 'Model request failed' : 'Run stopped',\n message,\n recoveries: providerCall ? ['model'] : [],\n };\n}\n"],"mappings":";;;AAsBA,MAAM,mBAAmB;AACzB,MAAM,sBACJ;AAEF,SAAgB,iBAAiB,OAA8C;CAC7E,OAAO;EAAE,GAAG,gBAAgB,KAAK;EAAG,OAAO,gBAAgB,KAAK;CAAE;AACpE;AAEA,SAAS,gBAAgB,OAA6D;CACpF,IAAI,MAAM,SAAS,8BACjB,OAAO;EAAE,OAAO;EAA6B,SAAS,MAAM;EAAS,YAAY,CAAC,eAAe,OAAO;CAAE;CAE5G,QAAQ,sBAAsB,KAAK,GAAnC;EACE,KAAK,SACH,OAAO;GACL,OAAO;GACP,SAAS,oBACP,OACA,8FACF;GACA,YAAY,CAAC,eAAe,OAAO;EACrC;EACF,KAAK,QACH,OAAO;GACL,OAAO;GACP,SAAS,oBAAoB,OAAO,sEAAsE;GAC1G,YAAY,CAAC,eAAe,OAAO;EACrC;EACF,KAAK,oBACH,OAAO;GACL,OAAO;GACP,SAAS;GACT,YAAY,CAAC,SAAS,aAAa;EACrC;EACF,KAAK,kBACH,OAAO;GACL,OAAO;GACP,SAAS,oBACP,OACA,0CACA,mCACF;GACA,YAAY,CAAC,OAAO;EACtB;EACF,KAAK,yBACH,OAAO;GACL,OAAO;GACP,SACE;GACF,YAAY,CAAC,aAAa;EAC5B;EACF,KAAK,mBACH,OAAO;GACL,OAAO;GACP,SAAS,oBAAoB,KAAK,KAAK;GACvC,YAAY,CAAC,OAAO;EACtB;EACF,KAAK,WACH,OAAO;GACL,OAAO;GACP,SAAS;GACT,YAAY,CAAC,UAAU;EACzB;EACF,KAAK,gBACH,OAAO;GACL,OAAO;GACP,SACE;GACF,YAAY;IAAC;IAAY;IAAe;GAAO;EACjD;EACF,KAAK,eACH,OAAO;GACL,OAAO;GACP,SACE;GACF,YAAY,CAAC,YAAY,OAAO;EAClC;EACF,KAAK,WACH,OAAO,0BAA0B,KAAK;CAC1C;AACF;AAEA,SAAS,oBAAoB,OAAyB,MAAc,UAA2B;CAC7F,MAAM,SAAS,oBAAoB,KAAK,KAAK;CAC7C,OAAO,SAAS,GAAG,OAAO,QAAQ,QAAQ,GAAG,EAAE,GAAG,SAAS;AAC7D;AAEA,SAAS,0BAA0B,OAA6D;CAC9F,MAAM,UAAU,oBAAoB,KAAK,MAAM,MAAM,WAAW;CAChE,MAAM,eAAe,yBAAyB,KAAK,MAAM,IAAI;CAC7D,OAAO;EACL,OAAO,eAAe,yBAAyB;EAC/C;EACA,YAAY,eAAe,CAAC,OAAO,IAAI,CAAC;CAC1C;AACF"}
1
+ {"version":3,"file":"run-error.js","names":[],"sources":["../src/run-error.ts"],"sourcesContent":["import { PROVIDER_AUTH_REQUIRED_ERROR } from '@mastra/code-sdk/auth/provider-auth-error';\nimport { MASTRA_GATEWAY_PREFIX } from '@mastra/code-sdk/providers/model-ids';\nimport {\n classifyProviderError,\n PROVIDER_CALL_ERROR_NAME,\n providerErrorReason,\n providerModelId,\n} from '@mastra/core/error';\n\nexport type RunErrorRecovery = 'continue' | 'credentials' | 'credits' | 'model' | 'new_session';\n\nexport interface RunErrorDescription {\n title: string;\n message: string;\n recoveries: RunErrorRecovery[];\n model?: string;\n}\n\nexport interface RunErrorIdentity {\n name: string;\n message: string;\n}\n\nconst UNEXPECTED_ERROR = 'An unexpected error stopped the run. Copy the error details to investigate.';\nconst NO_REASON_AVAILABLE =\n 'The provider rejected the request. A specific reason isn’t available here. Copy the error details and check the server logs.';\n\nexport function describeRunError(error: RunErrorIdentity): RunErrorDescription {\n return { ...explainRunError(error), model: providerModelId(error) };\n}\n\nfunction explainRunError(error: RunErrorIdentity): Omit<RunErrorDescription, 'model'> {\n if (error.name === PROVIDER_AUTH_REQUIRED_ERROR) {\n return { title: 'Provider sign-in required', message: error.message, recoveries: ['credentials', 'model'] };\n }\n switch (classifyProviderError(error)) {\n case 'quota':\n if (isMastraGatewayError(error)) {\n return {\n title: 'Out of Mastra Gateway credits',\n message:\n 'Your organization has no gateway credits left. Add credits, then continue the run, or choose another model.',\n recoveries: ['credits', 'continue', 'model'],\n };\n }\n return {\n title: 'Provider quota exhausted',\n message: afterProviderReason(\n error,\n 'Check the provider account’s billing or usage allowance, or use another credential or model.',\n ),\n recoveries: ['credentials', 'model'],\n };\n case 'auth':\n return {\n title: 'Provider access failed',\n message: afterProviderReason(error, 'Review the credentials and model access configured for this session.'),\n recoveries: ['credentials', 'model'],\n };\n case 'context_overflow':\n return {\n title: 'Conversation exceeds the model’s limit',\n message: 'Choose a model with a larger context window or start a new session with a shorter prompt.',\n recoveries: ['model', 'new_session'],\n };\n case 'model_rejected':\n return {\n title: 'Model not available',\n message: afterProviderReason(\n error,\n 'Choose another model for this session.',\n 'The provider rejected this model.',\n ),\n recoveries: ['model'],\n };\n case 'tool_history_rejected':\n return {\n title: 'Conversation history rejected',\n message:\n 'The provider could not match a tool call with its result. Start a new session to keep working, and copy the error details so this session can be investigated.',\n recoveries: ['new_session'],\n };\n case 'invalid_request':\n return {\n title: 'Model request rejected',\n message: providerErrorReason(error) ?? NO_REASON_AVAILABLE,\n recoveries: ['model'],\n };\n case 'timeout':\n return {\n title: 'Request timed out',\n message: 'The request took too long to complete. Send a message to continue the run.',\n recoveries: ['continue'],\n };\n case 'rate_limited':\n return {\n title: 'Provider rate limit reached',\n message:\n 'The provider account behind this session’s credential hit a rate or usage limit. Continue once it resets, or use another credential or model.',\n recoveries: ['continue', 'credentials', 'model'],\n };\n case 'unavailable':\n return {\n title: 'Model provider temporarily unavailable',\n message:\n 'The provider could not complete the request. Send a message to continue the run, or choose another model.',\n recoveries: ['continue', 'model'],\n };\n case 'unknown':\n return describeUnclassifiedError(error);\n }\n}\n\nconst MASTRA_GATEWAY_HOST = /(?:^|\\.)gateway(?:-api)?\\.mastra\\.ai$/;\n\n/**\n * The Mastra Gateway answered: a `mastra/…` model, a request sent to its host, or its billing reply\n * (which links to `gateway.mastra.ai`). The request reaches the gateway without the `mastra/` prefix.\n */\nfunction isMastraGatewayError(error: RunErrorIdentity): boolean {\n return (\n providerModelId(error)?.startsWith(MASTRA_GATEWAY_PREFIX) === true ||\n calledMastraGateway(error) ||\n /gateway\\.mastra\\.ai/.test(providerErrorReason(error) ?? error.message)\n );\n}\n\n/** Whether the request, or a provider error it wraps, went to the gateway's host. */\nfunction calledMastraGateway(error: unknown, depth = 0): boolean {\n if (depth > 4 || typeof error !== 'object' || error === null) return false;\n const url = 'url' in error ? error.url : undefined;\n const cause = 'cause' in error ? error.cause : undefined;\n return (typeof url === 'string' && MASTRA_GATEWAY_HOST.test(hostOf(url))) || calledMastraGateway(cause, depth + 1);\n}\n\nfunction hostOf(url: string): string {\n try {\n return new URL(url).hostname;\n } catch {\n return '';\n }\n}\n\nfunction afterProviderReason(error: RunErrorIdentity, next: string, fallback?: string): string {\n const reason = providerErrorReason(error) ?? fallback;\n return reason ? `${reason.replace(/\\.?$/, '.')} ${next}` : next;\n}\n\nfunction describeUnclassifiedError(error: RunErrorIdentity): Omit<RunErrorDescription, 'model'> {\n const message = providerErrorReason(error) ?? (error.message || UNEXPECTED_ERROR);\n const providerCall = PROVIDER_CALL_ERROR_NAME.test(error.name);\n return {\n title: providerCall ? 'Model request failed' : 'Run stopped',\n message,\n recoveries: providerCall ? ['model'] : [],\n };\n}\n"],"mappings":";;;;AAuBA,MAAM,mBAAmB;AACzB,MAAM,sBACJ;A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,SAAS,qBAAqB,OAAkC;CAC9D,OACE,gBAAgB,KAAK,CAAC,EAAE,WAAW,qBAAqB,MAAM,QAC9D,oBAAoB,KAAK,KACzB,sBAAsB,KAAK,oBAAoB,KAAK,KAAK,MAAM,OAAO;AAE1E;;AAGA,SAAS,oBAAoB,OAAgB,QAAQ,GAAY;CAC/D,IAAI,QAAQ,KAAK,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACrE,MAAM,MAAM,SAAS,QAAQ,MAAM,MAAM,KAAA;CACzC,MAAM,QAAQ,WAAW,QAAQ,MAAM,QAAQ,KAAA;CAC/C,OAAQ,OAAO,QAAQ,YAAY,oBAAoB,KAAK,OAAO,GAAG,CAAC,KAAM,oBAAoB,OAAO,QAAQ,CAAC;AACnH;AAEA,SAAS,OAAO,KAAqB;CACnC,IAAI;EACF,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC;CACtB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,oBAAoB,OAAyB,MAAc,UAA2B;CAC7F,MAAM,SAAS,oBAAoB,KAAK,KAAK;CAC7C,OAAO,SAAS,GAAG,OAAO,QAAQ,QAAQ,GAAG,EAAE,GAAG,SAAS;AAC7D;AAEA,SAAS,0BAA0B,OAA6D;CAC9F,MAAM,UAAU,oBAAoB,KAAK,MAAM,MAAM,WAAW;CAChE,MAAM,eAAe,yBAAyB,KAAK,MAAM,IAAI;CAC7D,OAAO;EACL,OAAO,eAAe,yBAAyB;EAC/C;EACA,YAAY,eAAe,CAAC,OAAO,IAAI,CAAC;CAC1C;AACF"}
@@ -1,4 +1,6 @@
1
1
  import type { AgentControllerEvent } from '@mastra/core/agent-controller';
2
+ import type { PubSub } from '@mastra/core/events';
3
+ import type { SourceControlSession } from '../storage/domains/source-control/base.js';
2
4
  /** The slice of a live session this registry needs: its id, its run, its parked tools, and who it works for. */
3
5
  export interface LiveSession {
4
6
  readonly identity: {
@@ -22,10 +24,14 @@ export interface LiveSession {
22
24
  };
23
25
  subscribe(listener: (event: AgentControllerEvent) => void): () => void;
24
26
  }
25
- interface SessionNotifier {
27
+ export interface SessionNotifier {
26
28
  onSessionCreated(listener: (session: LiveSession) => void): () => void;
27
29
  onSessionDeleted(listener: (session: LiveSession) => void): () => void;
28
30
  }
31
+ /** Where a session's Factory is written down for good: its live state can lose it, its row cannot. */
32
+ export interface SessionRows {
33
+ getBySessionId(sessionId: string): Promise<Pick<SourceControlSession, 'orgId' | 'factoryProjectId'> | null>;
34
+ }
29
35
  /** The tool a session has waited on longest, and since when (epoch ms). */
30
36
  export interface ParkedRun {
31
37
  toolName: string;
@@ -56,8 +62,9 @@ export declare class LiveSessions {
56
62
  sessionId: string;
57
63
  run: ParkedRun;
58
64
  }>;
59
- /** Fires when a session parks, is answered, or finishes a turn: whoever shows parked runs re-reads. */
60
- onParkedChanged(listener: (session: LiveSession) => void): () => void;
65
+ /** Fires when a session starts a run, parks, is answered, or finishes a turn: whoever shows runs re-reads. */
66
+ onRunChanged(listener: (session: LiveSession) => void): () => void;
61
67
  }
62
- export {};
68
+ /** A run starting, parking, being answered or ending changes what boards show, so the registry bumps the project's feed. */
69
+ export declare function liveSessionsTouchingTheFeed(controller: SessionNotifier, eventBus: PubSub, rows: SessionRows): LiveSessions;
63
70
  //# sourceMappingURL=live-sessions.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"live-sessions.d.ts","sourceRoot":"","sources":["../../src/session/live-sessions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAE1E,gHAAgH;AAChH,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,QAAQ,EAAE;QAAE,KAAK,IAAI,MAAM,CAAA;KAAE,CAAC;IACvC,QAAQ,CAAC,GAAG,EAAE;QAAE,SAAS,IAAI,OAAO,CAAA;KAAE,CAAC;IACvC,QAAQ,CAAC,KAAK,EAAE;QAAE,GAAG,IAAI,QAAQ,CAAC;YAAE,YAAY,CAAC,EAAE,M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