@mastra/factory 0.24.0-alpha.1 → 0.24.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/README.md +80 -4
  2. package/dist/auth.d.ts +8 -0
  3. package/dist/auth.d.ts.map +1 -1
  4. package/dist/auth.js +15 -1
  5. package/dist/auth.js.map +1 -1
  6. package/dist/boards/work-transition-policy.d.ts.map +1 -1
  7. package/dist/boards/work-transition-policy.js +10 -0
  8. package/dist/boards/work-transition-policy.js.map +1 -1
  9. package/dist/boards/work.d.ts +14 -0
  10. package/dist/boards/work.d.ts.map +1 -1
  11. package/dist/boards/work.js +70 -7
  12. package/dist/boards/work.js.map +1 -1
  13. package/dist/capabilities/version-control.d.ts +26 -0
  14. package/dist/capabilities/version-control.d.ts.map +1 -1
  15. package/dist/factory.d.ts.map +1 -1
  16. package/dist/factory.js +173 -11
  17. package/dist/factory.js.map +1 -1
  18. package/dist/integrations/github/integration.d.ts.map +1 -1
  19. package/dist/integrations/github/integration.js +37 -1
  20. package/dist/integrations/github/integration.js.map +1 -1
  21. package/dist/integrations/gitlab/api.d.ts +15 -0
  22. package/dist/integrations/gitlab/api.d.ts.map +1 -1
  23. package/dist/integrations/gitlab/api.js +9 -0
  24. package/dist/integrations/gitlab/api.js.map +1 -1
  25. package/dist/integrations/gitlab/version-control.d.ts.map +1 -1
  26. package/dist/integrations/gitlab/version-control.js +37 -3
  27. package/dist/integrations/gitlab/version-control.js.map +1 -1
  28. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  29. package/dist/integrations/platform/github/integration.js +27 -1
  30. package/dist/integrations/platform/github/integration.js.map +1 -1
  31. package/dist/integrations/subscription-session.d.ts +15 -0
  32. package/dist/integrations/subscription-session.d.ts.map +1 -1
  33. package/dist/integrations/subscription-session.js +30 -13
  34. package/dist/integrations/subscription-session.js.map +1 -1
  35. package/dist/provider-display-name.d.ts +2 -0
  36. package/dist/provider-display-name.d.ts.map +1 -0
  37. package/dist/provider-display-name.js +16 -0
  38. package/dist/provider-display-name.js.map +1 -0
  39. package/dist/routes/config.js +2 -2
  40. package/dist/routes/config.js.map +1 -1
  41. package/dist/routes/contracts.d.ts +4 -0
  42. package/dist/routes/contracts.d.ts.map +1 -1
  43. package/dist/routes/contracts.js +3 -1
  44. package/dist/routes/contracts.js.map +1 -1
  45. package/dist/routes/oauth.js +1 -1
  46. package/dist/routes/oauth.js.map +1 -1
  47. package/dist/routes/provider-credentials.d.ts +6 -2
  48. package/dist/routes/provider-credentials.d.ts.map +1 -1
  49. package/dist/routes/provider-credentials.js +20 -7
  50. package/dist/routes/provider-credentials.js.map +1 -1
  51. package/dist/routes/source-control-sessions.d.ts +1 -0
  52. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  53. package/dist/routes/source-control-sessions.js +1 -1
  54. package/dist/routes/source-control-sessions.js.map +1 -1
  55. package/dist/routes/surface.d.ts +1 -0
  56. package/dist/routes/surface.d.ts.map +1 -1
  57. package/dist/routes/surface.js +1 -0
  58. package/dist/routes/surface.js.map +1 -1
  59. package/dist/routes/work-items.d.ts.map +1 -1
  60. package/dist/routes/work-items.js +57 -117
  61. package/dist/routes/work-items.js.map +1 -1
  62. package/dist/rules/dispatcher.d.ts +7 -0
  63. package/dist/rules/dispatcher.d.ts.map +1 -1
  64. package/dist/rules/dispatcher.js +60 -3
  65. package/dist/rules/dispatcher.js.map +1 -1
  66. package/dist/rules/processor.d.ts.map +1 -1
  67. package/dist/rules/processor.js +2 -1
  68. package/dist/rules/processor.js.map +1 -1
  69. package/dist/rules/tools.d.ts.map +1 -1
  70. package/dist/rules/tools.js +82 -3
  71. package/dist/rules/tools.js.map +1 -1
  72. package/dist/rules/transition-service.d.ts +17 -0
  73. package/dist/rules/transition-service.d.ts.map +1 -1
  74. package/dist/rules/transition-service.js +25 -0
  75. package/dist/rules/transition-service.js.map +1 -1
  76. package/dist/rules/types.d.ts +2 -0
  77. package/dist/rules/types.d.ts.map +1 -1
  78. package/dist/rules/types.js.map +1 -1
  79. package/dist/sandbox/local-factory-sandbox.d.ts.map +1 -1
  80. package/dist/sandbox/local-factory-sandbox.js +1 -0
  81. package/dist/sandbox/local-factory-sandbox.js.map +1 -1
  82. package/dist/session/factory-session.d.ts +15 -1
  83. package/dist/session/factory-session.d.ts.map +1 -1
  84. package/dist/session/factory-session.js +4 -2
  85. package/dist/session/factory-session.js.map +1 -1
  86. package/dist/session/reply-credential-processor.d.ts +15 -0
  87. package/dist/session/reply-credential-processor.d.ts.map +1 -0
  88. package/dist/session/reply-credential-processor.js +40 -0
  89. package/dist/session/reply-credential-processor.js.map +1 -0
  90. package/dist/session/source-control-tools.d.ts +19 -1
  91. package/dist/session/source-control-tools.d.ts.map +1 -1
  92. package/dist/session/source-control-tools.js +70 -3
  93. package/dist/session/source-control-tools.js.map +1 -1
  94. package/dist/storage/domains/projects/base.d.ts +6 -0
  95. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  96. package/dist/storage/domains/projects/base.js +12 -0
  97. package/dist/storage/domains/projects/base.js.map +1 -1
  98. package/dist/storage/domains/source-control/base.d.ts +17 -0
  99. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  100. package/dist/storage/domains/source-control/base.js +23 -0
  101. package/dist/storage/domains/source-control/base.js.map +1 -1
  102. package/dist/storage/domains/source-control/inmemory.d.ts +4 -0
  103. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  104. package/dist/storage/domains/source-control/inmemory.js +5 -1
  105. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  106. package/dist/storage/domains/work-items/base.d.ts +56 -0
  107. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  108. package/dist/storage/domains/work-items/base.js +139 -25
  109. package/dist/storage/domains/work-items/base.js.map +1 -1
  110. package/dist/tools/approval-tools.d.ts +15 -0
  111. package/dist/tools/approval-tools.d.ts.map +1 -0
  112. package/dist/tools/approval-tools.js +77 -0
  113. package/dist/tools/approval-tools.js.map +1 -0
  114. package/dist/tools/deliver.d.ts +54 -0
  115. package/dist/tools/deliver.d.ts.map +1 -0
  116. package/dist/tools/deliver.js +105 -0
  117. package/dist/tools/deliver.js.map +1 -0
  118. package/dist/tools/index.d.ts +29 -0
  119. package/dist/tools/index.d.ts.map +1 -0
  120. package/dist/tools/index.js +39 -0
  121. package/dist/tools/index.js.map +1 -0
  122. package/dist/tools/messaging-tools.d.ts +28 -0
  123. package/dist/tools/messaging-tools.d.ts.map +1 -0
  124. package/dist/tools/messaging-tools.js +312 -0
  125. package/dist/tools/messaging-tools.js.map +1 -0
  126. package/dist/tools/permissions.d.ts +31 -0
  127. package/dist/tools/permissions.d.ts.map +1 -0
  128. package/dist/tools/permissions.js +44 -0
  129. package/dist/tools/permissions.js.map +1 -0
  130. package/dist/tools/read-tools.d.ts +27 -0
  131. package/dist/tools/read-tools.d.ts.map +1 -0
  132. package/dist/tools/read-tools.js +285 -0
  133. package/dist/tools/read-tools.js.map +1 -0
  134. package/dist/tools/reports.d.ts +163 -0
  135. package/dist/tools/reports.d.ts.map +1 -0
  136. package/dist/tools/reports.js +352 -0
  137. package/dist/tools/reports.js.map +1 -0
  138. package/dist/tools/run-watch.d.ts +46 -0
  139. package/dist/tools/run-watch.d.ts.map +1 -0
  140. package/dist/tools/run-watch.js +102 -0
  141. package/dist/tools/run-watch.js.map +1 -0
  142. package/dist/tools/scope.d.ts +45 -0
  143. package/dist/tools/scope.d.ts.map +1 -0
  144. package/dist/tools/scope.js +73 -0
  145. package/dist/tools/scope.js.map +1 -0
  146. package/dist/tools/session-tools.d.ts +31 -0
  147. package/dist/tools/session-tools.d.ts.map +1 -0
  148. package/dist/tools/session-tools.js +312 -0
  149. package/dist/tools/session-tools.js.map +1 -0
  150. package/dist/tools/sessions-state-processor.d.ts +37 -0
  151. package/dist/tools/sessions-state-processor.d.ts.map +1 -0
  152. package/dist/tools/sessions-state-processor.js +206 -0
  153. package/dist/tools/sessions-state-processor.js.map +1 -0
  154. package/dist/tools/work-item-tools.d.ts +28 -0
  155. package/dist/tools/work-item-tools.d.ts.map +1 -0
  156. package/dist/tools/work-item-tools.js +322 -0
  157. package/dist/tools/work-item-tools.js.map +1 -0
  158. package/dist/work-items/create-work-item.d.ts +55 -0
  159. package/dist/work-items/create-work-item.d.ts.map +1 -0
  160. package/dist/work-items/create-work-item.js +101 -0
  161. package/dist/work-items/create-work-item.js.map +1 -0
  162. package/dist/work-items/decision-actions.d.ts +42 -0
  163. package/dist/work-items/decision-actions.d.ts.map +1 -0
  164. package/dist/work-items/decision-actions.js +70 -0
  165. package/dist/work-items/decision-actions.js.map +1 -0
  166. package/dist/workspace.d.ts.map +1 -1
  167. package/dist/workspace.js +3 -1
  168. package/dist/workspace.js.map +1 -1
  169. package/factory-skills/factory-gitlab-rereview/SKILL.md +1 -1
  170. package/factory-skills/factory-gitlab-review/SKILL.md +1 -1
  171. package/factory-skills/factory-plan/SKILL.md +4 -4
  172. package/factory-skills/factory-rereview/SKILL.md +3 -1
  173. package/factory-skills/factory-review/SKILL.md +3 -1
  174. package/factory-skills/factory-self-review/SKILL.md +46 -0
  175. package/package.json +9 -9
@@ -39,7 +39,9 @@ const updateProjectBodySchema = z.object({
39
39
  modelScope: z.enum(FACTORY_MODEL_SCOPES).optional(),
40
40
  defaultThinkingLevel: z.enum(THINKING_LEVELS).optional(),
41
41
  autoRunEnabled: z.boolean().optional(),
42
- autoApprovePlans: z.boolean().optional()
42
+ autoApprovePlans: z.boolean().optional(),
43
+ reviewTestChecksEnabled: z.boolean().optional(),
44
+ selfReviewEnabled: z.boolean().optional()
43
45
  }).refine((input) => Object.keys(input).length > 0, { message: "At least one project field is required" });
44
46
  const environmentRepositorySchema = z.object({
45
47
  projectRepositoryId: z.string(),
@@ -1 +1 @@
1
- {"version":3,"file":"contracts.js","names":[],"sources":["../../src/routes/contracts.ts"],"sourcesContent":["import { THINKING_LEVEL_VALUES } from '@mastra/code-sdk/thinking';\nimport type { ThinkingLevelSetting } from '@mastra/code-sdk/thinking';\nimport { z } from 'zod';\n\nimport { FACTORY_ROLE_STAGES } from '../rules/types.js';\nimport { BOARD_IDENTIFIER_RE, MAX_BOARD_IDENTIFIER_LENGTH } from '../rules/validation.js';\nimport { FACTORY_MODEL_SCOPES } from '../storage/domains/projects/base.js';\n\nconst FACTORY_ROLE_VALUES = Object.keys(FACTORY_ROLE_STAGES) as [string, ...string[]];\nconst THINKING_LEVELS = THINKING_LEVEL_VALUES as [ThinkingLevelSetting, ...ThinkingLevelSetting[]];\n\nexport type FactoryRouteContract = {\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n path: string;\n description: string;\n pathSchema?: z.ZodType;\n querySchema?: z.ZodType;\n bodySchema?: z.ZodType;\n responseSchema: z.ZodType;\n};\n\nexport const UUID_PATTERN = '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$';\nconst uuidSchema = z.string().regex(new RegExp(UUID_PATTERN));\nconst entitySchema = z.record(z.string(), z.unknown());\nconst nonEmptyTrimmed = (max: number) => z.string().trim().min(1).max(max);\nconst rawBoundedTrimmed = (max: number) =>\n z\n .string()\n .max(max)\n .transform(value => value.trim())\n .pipe(z.string().min(1));\nconst trimmedUuidSchema = z.string().trim().regex(new RegExp(UUID_PATTERN));\nconst nullableTrimmed = (max: number) =>\n z.union([\n z\n .string()\n .trim()\n .max(max)\n .transform(value => value || null),\n z.null(),\n ]);\nconst projectPathSchema = z.object({ id: uuidSchema });\nconst projectDecisionPathSchema = z.object({ id: uuidSchema, decisionId: uuidSchema });\nconst workItemPathSchema = z.object({ id: uuidSchema });\nconst transitionPathSchema = z.object({ id: uuidSchema, workItemId: uuidSchema });\n\nconst projectSchema = entitySchema;\nconst projectResponseSchema = z.object({ project: projectSchema });\nconst workItemResponseSchema = z.object({ workItem: entitySchema });\nconst decisionResponseSchema = z.object({ decision: entitySchema });\n\nexport const createProjectBodySchema = z.object({\n name: nonEmptyTrimmed(200),\n description: nullableTrimmed(2_000).optional().default(null),\n modelScope: z.enum(FACTORY_MODEL_SCOPES).optional(),\n});\n\nexport const updateProjectBodySchema = z\n .object({\n name: nonEmptyTrimmed(200).optional(),\n description: nullableTrimmed(2_000).optional(),\n defaultModelId: nullableTrimmed(200).optional(),\n modelScope: z.enum(FACTORY_MODEL_SCOPES).optional(),\n defaultThinkingLevel: z.enum(THINKING_LEVELS).optional(),\n autoRunEnabled: z.boolean().optional(),\n autoApprovePlans: z.boolean().optional(),\n })\n .refine(input => Object.keys(input).length > 0, { message: 'At least one project field is required' });\n\nconst environmentRepositorySchema = z.object({\n projectRepositoryId: z.string(),\n connectionId: z.string(),\n repositoryId: z.string(),\n // Null when the repository row behind the link is missing.\n slug: z.string().nullable(),\n defaultBranch: z.string().nullable(),\n position: z.number().int(),\n inEnvironment: z.boolean(),\n setupCommand: z.string().nullable(),\n teardownCommand: z.string().nullable(),\n lastBuildStatus: z.enum(['unbuilt', 'configured', 'failed']),\n lastBuildError: z.string().nullable(),\n lastBuiltAt: z.string().nullable(),\n});\n\n/** The configured FactorySandbox as factory describes it: provider id, JSON Schema of its settings, capabilities. */\nexport const environmentSandboxSchema = z.object({\n provider: z.string(),\n settingsSchema: z.record(z.string(), z.unknown()),\n capabilities: z.object({\n template: z.boolean(),\n builds: z.object({ available: z.boolean(), history: z.boolean() }),\n }),\n});\n\n/** When the environment builds on its own; present only when the sandbox can build. */\nexport const environmentBuildTriggersSchema = z.object({\n schedule: z.object({\n enabled: z.boolean(),\n cron: z.string().nullable(),\n timezone: z.string().nullable(),\n /** False when the host's storage has no schedules domain; the cron trigger cannot be enabled then. */\n scheduleAvailable: z.boolean(),\n }),\n push: z.object({ enabled: z.boolean(), debounceMinutes: z.number().int() }),\n});\n\n/** The last build factory asked the provider for, from the project row only; status is read live. */\nexport const environmentLastBuildSchema = z.object({ buildId: z.string(), attemptedAt: z.string().nullable() });\n\nexport const projectEnvironmentResponseSchema = z.object({\n environment: z.object({\n sandbox: environmentSandboxSchema,\n /** The stored settings document; only keys the user set. */\n settings: z.record(z.string(), z.unknown()),\n sandboxWorkingDirectory: z.string().nullable(),\n workspaceSetupCommand: z.string().nullable(),\n activeTemplateId: z.string().nullable(),\n activeTemplateHeads: z.record(z.string(), z.string()).nullable(),\n repositories: z.array(environmentRepositorySchema),\n buildTriggers: environmentBuildTriggersSchema.optional(),\n build: environmentLastBuildSchema.nullable().optional(),\n }),\n});\n\nconst environmentBuildStatusSchema = z.enum(['pending', 'building', 'ready', 'failed', 'unknown']);\n\nexport const environmentBuildStartResponseSchema = z.object({\n outcome: z.enum(['started', 'skipped', 'unavailable', 'failed']),\n buildId: z.string().optional(),\n templateId: z.string().optional(),\n reason: z.string().optional(),\n});\n\nexport const environmentBuildSchema = z.object({\n buildId: z.string(),\n status: environmentBuildStatusSchema,\n templateId: z.string().optional(),\n startedAt: z.string().optional(),\n finishedAt: z.string().optional(),\n error: z.string().optional(),\n logs: z.array(z.string()).optional(),\n});\n\nexport const environmentBuildsResponseSchema = z.object({ builds: z.array(environmentBuildSchema) });\nexport const environmentBuildResponseSchema = z.object({ build: environmentBuildSchema });\n\nconst buildPathSchema = projectPathSchema.extend({ buildId: z.string().min(1) });\n\nconst environmentRepositoryPatchSchema = z.object({\n projectRepositoryId: uuidSchema,\n position: z.number().int().min(1).optional(),\n inEnvironment: z.boolean().optional(),\n setupCommand: nullableTrimmed(2_000).optional(),\n teardownCommand: nullableTrimmed(2_000).optional(),\n});\n\nexport const updateProjectEnvironmentBodySchema = z\n .object({\n sandboxWorkingDirectory: nullableTrimmed(1_000)\n .refine(value => value === null || value.startsWith('/'), {\n message: 'sandboxWorkingDirectory must be absolute',\n })\n .optional(),\n /** Partial settings merged onto the stored document; null removes a key. Validated by the FactorySandbox. */\n settings: z.record(z.string(), z.unknown().nullable()).optional(),\n workspaceSetupCommand: nullableTrimmed(2_000).optional(),\n /** Build triggers; only accepted when the sandbox can build. */\n buildTriggers: z\n .object({\n schedule: z\n .object({\n enabled: z.boolean(),\n cron: z.string().trim().min(1).max(100).optional(),\n timezone: z.string().trim().min(1).max(100).optional(),\n })\n .optional(),\n push: z\n .object({\n enabled: z.boolean().optional(),\n debounceMinutes: z.number().int().min(0).max(1_440).optional(),\n })\n .optional(),\n })\n .optional(),\n repositories: z\n .array(environmentRepositoryPatchSchema)\n .max(100)\n .superRefine((entries, ctx) => {\n const ids = new Set(entries.map(entry => entry.projectRepositoryId));\n if (ids.size !== entries.length) {\n ctx.addIssue({ code: 'custom', message: 'Each repository may be listed once' });\n }\n const positions = entries.flatMap(entry => (entry.position === undefined ? [] : [entry.position]));\n if (positions.length === 0) return;\n const expected = Array.from({ length: entries.length }, (_, index) => index + 1);\n if (\n positions.length !== entries.length ||\n [...positions].sort((a, b) => a - b).some((p, i) => p !== expected[i])\n ) {\n ctx.addIssue({\n code: 'custom',\n message: 'Positions must be a permutation of 1..n over the listed repositories',\n });\n }\n })\n .optional(),\n })\n .refine(input => Object.keys(input).length > 0, { message: 'At least one environment field is required' });\n\nconst stagesSchema = z\n .array(\n z\n .string()\n .max(64)\n .regex(/^[a-z0-9][a-z0-9_-]*$/i),\n )\n .min(1)\n .max(16)\n .refine(stages => new Set(stages).size === stages.length, { message: 'Stages must be unique' });\n\nconst externalSourceSchema = z\n .object({\n integrationId: z.string().min(1).max(128),\n type: z.string().min(1).max(128),\n externalId: z.string().min(1).max(512),\n url: z.string().max(2_048).optional(),\n })\n .nullable();\n\nconst sessionSchema = z.object({\n sessionId: z.string().min(1).max(512),\n branch: z.string().min(1).max(512),\n threadId: z.string().min(1).max(512),\n});\n\nconst sessionsSchema = z.record(z.string().min(1).max(64), sessionSchema);\nconst metadataSchema = z\n .union([z.record(z.string(), z.unknown()), z.null()])\n .refine(value => {\n try {\n return JSON.stringify(value).length <= 16 * 1024;\n } catch {\n return false;\n }\n }, 'Metadata exceeds 16 KiB')\n .transform(value => {\n if (value === null) return null;\n const {\n factoryRuleMaterializationKey: _materialization,\n factoryPullRequestReconciliation: _reconciliation,\n externalSourceMissingAt: _externalSourceMissingAt,\n ...metadata\n } = value;\n return metadata;\n });\n\nexport const createWorkItemBodySchema = z.object({\n title: rawBoundedTrimmed(500),\n board: z.string().min(1).max(128).optional(),\n externalSource: externalSourceSchema.optional(),\n parentWorkItemId: uuidSchema.nullable().optional(),\n stages: stagesSchema.optional(),\n sessions: sessionsSchema.optional(),\n metadata: metadataSchema.optional(),\n});\n\nexport const updateWorkItemBodySchema = z\n .object({\n title: rawBoundedTrimmed(500).optional(),\n board: z.string().min(1).max(128).optional(),\n parentWorkItemId: uuidSchema.nullable().optional(),\n stages: stagesSchema.optional(),\n sessions: sessionsSchema.optional(),\n metadata: metadataSchema.optional(),\n plansPreapproved: z.literal(true).optional(),\n })\n .refine(input => Object.keys(input).length > 0, { message: 'At least one work-item field is required' });\n\nexport const transitionBodySchema = z\n .object({\n board: z.string().max(MAX_BOARD_IDENTIFIER_LENGTH).regex(BOARD_IDENTIFIER_RE),\n stage: z.string().max(MAX_BOARD_IDENTIFIER_LENGTH).regex(BOARD_IDENTIFIER_RE),\n expectedRevision: z.number().int().min(1),\n requestId: trimmedUuidSchema,\n cause: nonEmptyTrimmed(256),\n reenter: z.unknown().optional(),\n })\n .transform(input => ({\n board: input.board,\n stage: input.stage,\n expectedRevision: input.expectedRevision,\n ingress: { type: 'human' as const, identity: input.requestId },\n cause: input.cause,\n ...(input.reenter === true ? { reenter: true } : {}),\n }));\n\nexport const startWorkItemBodySchema = z.object({\n sessionId: trimmedUuidSchema,\n threadTitle: nonEmptyTrimmed(512),\n kickoffKey: trimmedUuidSchema,\n workItem: z.object({\n id: trimmedUuidSchema,\n role: nonEmptyTrimmed(32),\n input: createWorkItemBodySchema,\n }),\n});\n\nexport const automationRunStartBodySchema = z\n .object({\n requestId: trimmedUuidSchema,\n expectedRevision: z.number().int().min(1),\n role: z.enum(FACTORY_ROLE_VALUES),\n skillName: nonEmptyTrimmed(128),\n arguments: nonEmptyTrimmed(4_096).optional(),\n })\n .strict();\n\nexport const metricsQuerySchema = z.object({\n from: z.string().optional(),\n to: z.string().optional(),\n});\n\nconst decisionStatusSchema = z.enum([\n 'pending',\n 'proposed',\n 'dismissed',\n 'superseded',\n 'leased',\n 'retry',\n 'succeeded',\n 'failed',\n]);\nconst boundedLimitSchema = (defaultValue: number, max: number) =>\n z\n .string()\n .optional()\n .transform(value => {\n const parsed = value ? Number.parseInt(value, 10) : defaultValue;\n return Number.isFinite(parsed) ? Math.max(1, Math.min(max, parsed)) : defaultValue;\n });\nconst decisionCursorSchema = z\n .string()\n .optional()\n .transform((value, context) => {\n if (!value) return undefined;\n try {\n const decoded = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) as unknown;\n if (\n !Array.isArray(decoded) ||\n decoded.length !== 2 ||\n typeof decoded[0] !== 'string' ||\n typeof decoded[1] !== 'string'\n ) {\n throw new Error('invalid cursor');\n }\n const createdAt = new Date(decoded[0]);\n if (Number.isNaN(createdAt.getTime()) || !new RegExp(UUID_PATTERN).test(decoded[1])) {\n throw new Error('invalid cursor');\n }\n return { createdAt, id: decoded[1] };\n } catch {\n context.addIssue({ code: 'custom', message: 'Invalid cursor' });\n return z.NEVER;\n }\n });\n\nexport const decisionQuerySchema = z.object({\n statuses: z\n .string()\n .optional()\n .transform(value => {\n if (!value) return undefined;\n const statuses = [...new Set(value.split(',').map(status => status.trim()))].filter(\n status => decisionStatusSchema.safeParse(status).success,\n ) as Array<z.infer<typeof decisionStatusSchema>>;\n return statuses.length > 0 ? statuses : undefined;\n }),\n before: decisionCursorSchema,\n limit: boundedLimitSchema(25, 50),\n});\n\nconst attentionKindSchema = z.enum([\n 'automation-failed',\n 'automation-proposed',\n 'mention',\n 'activity',\n 'agent-waiting',\n]);\ntype AttentionKind = z.infer<typeof attentionKindSchema>;\ntype AttentionStreamPosition = { occurredAt: Date; id: string };\ntype AttentionCursorMap = Map<AttentionKind, AttentionStreamPosition | undefined>;\n\nfunction parseAttentionStreamPosition(value: unknown): AttentionStreamPosition | undefined {\n if (!Array.isArray(value) || value.length !== 2 || typeof value[0] !== 'string' || typeof value[1] !== 'string') {\n return undefined;\n }\n const occurredAt = new Date(value[0]);\n if (Number.isNaN(occurredAt.getTime()) || !new RegExp(UUID_PATTERN).test(value[1])) return undefined;\n return { occurredAt, id: value[1] };\n}\n\nconst attentionCursorSchema = z\n .string()\n .optional()\n .transform((value, context) => {\n if (!value) return undefined;\n try {\n const decoded: unknown = JSON.parse(Buffer.from(value, 'base64url').toString('utf8'));\n if (Array.isArray(decoded)) {\n const legacy = parseAttentionStreamPosition(decoded);\n if (!legacy) throw new Error('invalid cursor');\n return new Map<AttentionKind, AttentionStreamPosition | undefined>([['automation-failed', legacy]]);\n }\n if (!decoded || typeof decoded !== 'object') throw new Error('invalid cursor');\n const cursors: AttentionCursorMap = new Map();\n for (const [kind, positionValue] of Object.entries(decoded)) {\n const parsedKind = attentionKindSchema.safeParse(kind);\n if (!parsedKind.success) throw new Error('invalid cursor');\n if (positionValue === null) {\n cursors.set(parsedKind.data, undefined);\n continue;\n }\n const position = parseAttentionStreamPosition(positionValue);\n if (!position) throw new Error('invalid cursor');\n cursors.set(parsedKind.data, position);\n }\n if (cursors.size === 0) throw new Error('invalid cursor');\n return cursors;\n } catch {\n context.addIssue({ code: 'custom', message: 'Invalid cursor' });\n return z.NEVER;\n }\n });\n\nexport const attentionQuerySchema = z.object({\n view: z.enum(['open', 'unread', 'archived']).optional().default('open'),\n kind: z.array(attentionKindSchema).optional(),\n before: attentionCursorSchema,\n limit: boundedLimitSchema(25, 50),\n search: z\n .string()\n .optional()\n .transform(value => value?.trim().toLowerCase().slice(0, 200) || undefined),\n});\n\nconst attentionActionPathSchema = z\n .object({\n id: uuidSchema,\n kind: attentionKindSchema,\n sourceId: z.string().min(1).max(256),\n occurrence: z\n .string()\n .regex(/^(0|[1-9]\\d*)$/)\n .transform((value, context) => {\n const occurrence = Number(value);\n if (Number.isSafeInteger(occurrence)) return occurrence;\n context.addIssue({ code: 'custom', message: 'Invalid occurrence' });\n return z.NEVER;\n }),\n })\n .refine(input => new RegExp(UUID_PATTERN).test(input.sourceId), {\n message: 'Invalid attention source id',\n path: ['sourceId'],\n });\n\nexport const FACTORY_ROUTE_CONTRACTS = {\n projectList: {\n method: 'GET',\n path: '/web/factory/projects',\n description: 'List Factory projects for the current organization',\n responseSchema: z.object({ projects: z.array(projectSchema) }),\n },\n projectCreate: {\n method: 'POST',\n path: '/web/factory/projects',\n description: 'Create a Factory project',\n bodySchema: createProjectBodySchema,\n responseSchema: projectResponseSchema,\n },\n projectGet: {\n method: 'GET',\n path: '/web/factory/projects/:id',\n description: 'Get a Factory project',\n pathSchema: projectPathSchema,\n responseSchema: projectResponseSchema,\n },\n projectUpdate: {\n method: 'PATCH',\n path: '/web/factory/projects/:id',\n description: 'Update a Factory project',\n pathSchema: projectPathSchema,\n bodySchema: updateProjectBodySchema,\n responseSchema: projectResponseSchema,\n },\n projectEnvironmentGet: {\n method: 'GET',\n path: '/web/factory/projects/:id/environment',\n description: 'Get the sandbox environment of a Factory project: provider settings and its repositories in order',\n pathSchema: projectPathSchema,\n responseSchema: projectEnvironmentResponseSchema,\n },\n projectEnvironmentUpdate: {\n method: 'PATCH',\n path: '/web/factory/projects/:id/environment',\n description: 'Update the sandbox environment of a Factory project: provider settings, repository order and setup',\n pathSchema: projectPathSchema,\n bodySchema: updateProjectEnvironmentBodySchema,\n responseSchema: projectEnvironmentResponseSchema,\n },\n projectEnvironmentBuild: {\n method: 'POST',\n path: '/web/factory/projects/:id/environment/build',\n description: 'Build the sandbox environment template of a Factory project now',\n pathSchema: projectPathSchema,\n responseSchema: environmentBuildStartResponseSchema,\n },\n projectEnvironmentBuilds: {\n method: 'GET',\n path: '/web/factory/projects/:id/environment/builds',\n description:\n 'List the environment template builds of a Factory project, newest first, when the provider keeps history',\n pathSchema: projectPathSchema,\n responseSchema: environmentBuildsResponseSchema,\n },\n projectEnvironmentBuildGet: {\n method: 'GET',\n path: '/web/factory/projects/:id/environment/builds/:buildId',\n description: 'Get the live status of one environment template build of a Factory project',\n pathSchema: buildPathSchema,\n responseSchema: environmentBuildResponseSchema,\n },\n projectApplyDefaultModel: {\n method: 'POST',\n path: '/web/factory/projects/:id/apply-default-model',\n description: 'Apply the Factory default model to running work and review threads',\n pathSchema: projectPathSchema,\n responseSchema: z.object({\n modelId: z.string(),\n applied: z.array(z.string()),\n skipped: z.array(\n z.object({\n threadId: z.string(),\n reason: z.enum([\n 'not-running',\n 'work-item-missing',\n 'stage-inactive',\n 'thread-missing',\n 'mode-unknown',\n 'apply-failed',\n ]),\n }),\n ),\n }),\n },\n projectDelete: {\n method: 'DELETE',\n path: '/web/factory/projects/:id',\n description: 'Delete a Factory project',\n pathSchema: projectPathSchema,\n responseSchema: z.null(),\n },\n metricsGet: {\n method: 'GET',\n path: '/web/factory/projects/:id/metrics',\n description: 'Get Factory project metrics',\n pathSchema: projectPathSchema,\n querySchema: metricsQuerySchema,\n responseSchema: z.object({ metrics: entitySchema }),\n },\n healthThresholdsGet: {\n method: 'GET',\n path: '/web/factory/projects/:id/health/thresholds',\n description: 'Get queue-health thresholds',\n pathSchema: projectPathSchema,\n responseSchema: z.object({ thresholds: z.array(z.number().finite()) }),\n },\n boardCatalog: {\n method: 'GET',\n path: '/web/factory/projects/:id/boards',\n description: 'List installed Factory boards',\n pathSchema: projectPathSchema,\n responseSchema: z.object({\n boards: z.array(\n z.object({\n id: z.string(),\n title: z.string(),\n initialPhase: z.string(),\n phases: z.array(\n z.object({\n id: z.string(),\n title: z.string(),\n kind: z.enum(['resting', 'working', 'terminal']),\n role: z.string().optional(),\n transitions: z.array(z.object({ outcome: z.string().nullable(), to: z.string() })),\n }),\n ),\n }),\n ),\n }),\n },\n workItemList: {\n method: 'GET',\n path: '/web/factory/projects/:id/work-items',\n description: 'List Factory work items and running sessions',\n pathSchema: projectPathSchema,\n responseSchema: z.object({\n workItems: z.array(entitySchema),\n runningSessionIds: z.array(z.string()),\n parkedSessionIds: z.array(z.string()),\n }),\n },\n workItemCreate: {\n method: 'POST',\n path: '/web/factory/projects/:id/work-items',\n description: 'Create a work item in Intake',\n pathSchema: projectPathSchema,\n bodySchema: createWorkItemBodySchema,\n responseSchema: workItemResponseSchema,\n },\n workItemUpdate: {\n method: 'PATCH',\n path: '/web/factory/work-items/:id',\n description: 'Update non-stage work-item fields',\n pathSchema: workItemPathSchema,\n bodySchema: updateWorkItemBodySchema,\n responseSchema: workItemResponseSchema,\n },\n workItemDelete: {\n method: 'DELETE',\n path: '/web/factory/work-items/:id',\n description: 'Delete a Factory work item',\n pathSchema: workItemPathSchema,\n responseSchema: z.object({ ok: z.literal(true) }),\n },\n workItemTransition: {\n method: 'POST',\n path: '/web/factory/projects/:id/work-items/:workItemId/transition',\n description: 'Transition a work item with its expected revision',\n pathSchema: transitionPathSchema,\n bodySchema: transitionBodySchema,\n responseSchema: entitySchema,\n },\n workItemStart: {\n method: 'POST',\n path: '/web/factory/projects/:id/runs/start',\n description: 'Explicitly start a Factory work-item run',\n pathSchema: projectPathSchema,\n bodySchema: startWorkItemBodySchema,\n responseSchema: entitySchema,\n },\n workItemAutomationRun: {\n method: 'POST',\n path: '/web/factory/projects/:id/work-items/:workItemId/automation-runs',\n description: 'Enqueue an idempotent deferred skill dispatch for a trusted external orchestrator',\n pathSchema: transitionPathSchema,\n bodySchema: automationRunStartBodySchema,\n responseSchema: entitySchema,\n },\n decisionList: {\n method: 'GET',\n path: '/web/factory/projects/:id/decisions',\n description: 'List Factory decisions',\n pathSchema: projectPathSchema,\n querySchema: decisionQuerySchema,\n responseSchema: z.object({ decisions: z.array(entitySchema), nextCursor: z.string().optional() }),\n },\n decisionApprove: {\n method: 'POST',\n path: '/web/factory/projects/:id/decisions/:decisionId/approve',\n description: 'Approve a proposed Factory decision',\n pathSchema: projectDecisionPathSchema,\n responseSchema: decisionResponseSchema,\n },\n decisionDismiss: {\n method: 'POST',\n path: '/web/factory/projects/:id/decisions/:decisionId/dismiss',\n description: 'Dismiss a proposed Factory decision',\n pathSchema: projectDecisionPathSchema,\n responseSchema: decisionResponseSchema,\n },\n decisionRetry: {\n method: 'POST',\n path: '/web/factory/projects/:id/decisions/:decisionId/retry',\n description: 'Retry a failed retryable Factory decision',\n pathSchema: projectDecisionPathSchema,\n responseSchema: decisionResponseSchema,\n },\n attentionList: {\n method: 'GET',\n path: '/web/factory/projects/:id/attention',\n description: 'List the Factory attention inbox',\n pathSchema: projectPathSchema,\n querySchema: attentionQuerySchema,\n responseSchema: z.object({\n items: z.array(entitySchema),\n kinds: z.record(\n attentionKindSchema,\n z.object({\n open: z.number(),\n unread: z.number(),\n latest: z.object({ key: z.string(), at: z.string(), unread: z.boolean() }).nullable(),\n }),\n ),\n hasMore: z.boolean(),\n nextCursor: z.string().optional(),\n }),\n },\n attentionReadAll: {\n method: 'POST',\n path: '/web/factory/projects/:id/attention/read-all',\n description: 'Mark all Factory attention as read',\n pathSchema: projectPathSchema,\n querySchema: z.object({ before: attentionCursorSchema }),\n responseSchema: z.object({ ok: z.literal(true), hasMore: z.boolean(), nextCursor: z.string().optional() }),\n },\n attentionRead: {\n method: 'POST',\n path: '/web/factory/projects/:id/attention/:kind/:sourceId/:occurrence/read',\n description: 'Mark a Factory attention receipt as read',\n pathSchema: attentionActionPathSchema,\n responseSchema: z.object({ receipt: entitySchema }),\n },\n attentionArchive: {\n method: 'POST',\n path: '/web/factory/projects/:id/attention/:kind/:sourceId/:occurrence/archive',\n description: 'Archive a Factory attention receipt',\n pathSchema: attentionActionPathSchema,\n responseSchema: z.object({ receipt: entitySchema }),\n },\n attentionRestore: {\n method: 'POST',\n path: '/web/factory/projects/:id/attention/:kind/:sourceId/:occurrence/restore',\n description: 'Restore an archived Factory attention receipt',\n pathSchema: attentionActionPathSchema,\n responseSchema: z.object({ receipt: entitySchema }),\n },\n} as const satisfies Record<string, FactoryRouteContract>;\n\nexport type FactoryRouteContractKey = keyof typeof FACTORY_ROUTE_CONTRACTS;\n"],"mappings":";;;;;;AAQA,MAAM,sBAA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AAE,CAAC;CAC3G;CACA,eAAe;EACb,QAAQ;EACR,MAAM;EACN,aAAa;EACb,YAAY;EACZ,gBAAgB,EAAE,OAAO,EAAE,SAAS,aAAa,CAAC;CACpD;CACA,kBAAkB;EAChB,QAAQ;EACR,MAAM;EACN,aAAa;EACb,YAAY;EACZ,gBAAgB,EAAE,OAAO,EAAE,SAAS,aAAa,CAAC;CACpD;CACA,kBAAkB;EAChB,QAAQ;EACR,MAAM;EACN,aAAa;EACb,YAAY;EACZ,gBAAgB,EAAE,OAAO,EAAE,SAAS,aAAa,CAAC;CACpD;AACF"}
1
+ {"version":3,"file":"contracts.js","names":[],"sources":["../../src/routes/contracts.ts"],"sourcesContent":["import { THINKING_LEVEL_VALUES } from '@mastra/code-sdk/thinking';\nimport type { ThinkingLevelSetting } from '@mastra/code-sdk/thinking';\nimport { z } from 'zod';\n\nimport { FACTORY_ROLE_STAGES } from '../rules/types.js';\nimport { BOARD_IDENTIFIER_RE, MAX_BOARD_IDENTIFIER_LENGTH } from '../rules/validation.js';\nimport { FACTORY_MODEL_SCOPES } from '../storage/domains/projects/base.js';\n\nconst FACTORY_ROLE_VALUES = Object.keys(FACTORY_ROLE_STAGES) as [string, ...string[]];\nconst THINKING_LEVELS = THINKING_LEVEL_VALUES as [ThinkingLevelSetting, ...ThinkingLevelSetting[]];\n\nexport type FactoryRouteContract = {\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n path: string;\n description: string;\n pathSchema?: z.ZodType;\n querySchema?: z.ZodType;\n bodySchema?: z.ZodType;\n responseSchema: z.ZodType;\n};\n\nexport const UUID_PATTERN = '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$';\nconst uuidSchema = z.string().regex(new RegExp(UUID_PATTERN));\nconst entitySchema = z.record(z.string(), z.unknown());\nconst nonEmptyTrimmed = (max: number) => z.string().trim().min(1).max(max);\nconst rawBoundedTrimmed = (max: number) =>\n z\n .string()\n .max(max)\n .transform(value => value.trim())\n .pipe(z.string().min(1));\nconst trimmedUuidSchema = z.string().trim().regex(new RegExp(UUID_PATTERN));\nconst nullableTrimmed = (max: number) =>\n z.union([\n z\n .string()\n .trim()\n .max(max)\n .transform(value => value || null),\n z.null(),\n ]);\nconst projectPathSchema = z.object({ id: uuidSchema });\nconst projectDecisionPathSchema = z.object({ id: uuidSchema, decisionId: uuidSchema });\nconst workItemPathSchema = z.object({ id: uuidSchema });\nconst transitionPathSchema = z.object({ id: uuidSchema, workItemId: uuidSchema });\n\nconst projectSchema = entitySchema;\nconst projectResponseSchema = z.object({ project: projectSchema });\nconst workItemResponseSchema = z.object({ workItem: entitySchema });\nconst decisionResponseSchema = z.object({ decision: entitySchema });\n\nexport const createProjectBodySchema = z.object({\n name: nonEmptyTrimmed(200),\n description: nullableTrimmed(2_000).optional().default(null),\n modelScope: z.enum(FACTORY_MODEL_SCOPES).optional(),\n});\n\nexport const updateProjectBodySchema = z\n .object({\n name: nonEmptyTrimmed(200).optional(),\n description: nullableTrimmed(2_000).optional(),\n defaultModelId: nullableTrimmed(200).optional(),\n modelScope: z.enum(FACTORY_MODEL_SCOPES).optional(),\n defaultThinkingLevel: z.enum(THINKING_LEVELS).optional(),\n autoRunEnabled: z.boolean().optional(),\n autoApprovePlans: z.boolean().optional(),\n reviewTestChecksEnabled: z.boolean().optional(),\n selfReviewEnabled: z.boolean().optional(),\n })\n .refine(input => Object.keys(input).length > 0, { message: 'At least one project field is required' });\n\nconst environmentRepositorySchema = z.object({\n projectRepositoryId: z.string(),\n connectionId: z.string(),\n repositoryId: z.string(),\n // Null when the repository row behind the link is missing.\n slug: z.string().nullable(),\n defaultBranch: z.string().nullable(),\n position: z.number().int(),\n inEnvironment: z.boolean(),\n setupCommand: z.string().nullable(),\n teardownCommand: z.string().nullable(),\n lastBuildStatus: z.enum(['unbuilt', 'configured', 'failed']),\n lastBuildError: z.string().nullable(),\n lastBuiltAt: z.string().nullable(),\n});\n\n/** The configured FactorySandbox as factory describes it: provider id, JSON Schema of its settings, capabilities. */\nexport const environmentSandboxSchema = z.object({\n provider: z.string(),\n settingsSchema: z.record(z.string(), z.unknown()),\n capabilities: z.object({\n template: z.boolean(),\n builds: z.object({ available: z.boolean(), history: z.boolean() }),\n }),\n});\n\n/** When the environment builds on its own; present only when the sandbox can build. */\nexport const environmentBuildTriggersSchema = z.object({\n schedule: z.object({\n enabled: z.boolean(),\n cron: z.string().nullable(),\n timezone: z.string().nullable(),\n /** False when the host's storage has no schedules domain; the cron trigger cannot be enabled then. */\n scheduleAvailable: z.boolean(),\n }),\n push: z.object({ enabled: z.boolean(), debounceMinutes: z.number().int() }),\n});\n\n/** The last build factory asked the provider for, from the project row only; status is read live. */\nexport const environmentLastBuildSchema = z.object({ buildId: z.string(), attemptedAt: z.string().nullable() });\n\nexport const projectEnvironmentResponseSchema = z.object({\n environment: z.object({\n sandbox: environmentSandboxSchema,\n /** The stored settings document; only keys the user set. */\n settings: z.record(z.string(), z.unknown()),\n sandboxWorkingDirectory: z.string().nullable(),\n workspaceSetupCommand: z.string().nullable(),\n activeTemplateId: z.string().nullable(),\n activeTemplateHeads: z.record(z.string(), z.string()).nullable(),\n repositories: z.array(environmentRepositorySchema),\n buildTriggers: environmentBuildTriggersSchema.optional(),\n build: environmentLastBuildSchema.nullable().optional(),\n }),\n});\n\nconst environmentBuildStatusSchema = z.enum(['pending', 'building', 'ready', 'failed', 'unknown']);\n\nexport const environmentBuildStartResponseSchema = z.object({\n outcome: z.enum(['started', 'skipped', 'unavailable', 'failed']),\n buildId: z.string().optional(),\n templateId: z.string().optional(),\n reason: z.string().optional(),\n});\n\nexport const environmentBuildSchema = z.object({\n buildId: z.string(),\n status: environmentBuildStatusSchema,\n templateId: z.string().optional(),\n startedAt: z.string().optional(),\n finishedAt: z.string().optional(),\n error: z.string().optional(),\n logs: z.array(z.string()).optional(),\n});\n\nexport const environmentBuildsResponseSchema = z.object({ builds: z.array(environmentBuildSchema) });\nexport const environmentBuildResponseSchema = z.object({ build: environmentBuildSchema });\n\nconst buildPathSchema = projectPathSchema.extend({ buildId: z.string().min(1) });\n\nconst environmentRepositoryPatchSchema = z.object({\n projectRepositoryId: uuidSchema,\n position: z.number().int().min(1).optional(),\n inEnvironment: z.boolean().optional(),\n setupCommand: nullableTrimmed(2_000).optional(),\n teardownCommand: nullableTrimmed(2_000).optional(),\n});\n\nexport const updateProjectEnvironmentBodySchema = z\n .object({\n sandboxWorkingDirectory: nullableTrimmed(1_000)\n .refine(value => value === null || value.startsWith('/'), {\n message: 'sandboxWorkingDirectory must be absolute',\n })\n .optional(),\n /** Partial settings merged onto the stored document; null removes a key. Validated by the FactorySandbox. */\n settings: z.record(z.string(), z.unknown().nullable()).optional(),\n workspaceSetupCommand: nullableTrimmed(2_000).optional(),\n /** Build triggers; only accepted when the sandbox can build. */\n buildTriggers: z\n .object({\n schedule: z\n .object({\n enabled: z.boolean(),\n cron: z.string().trim().min(1).max(100).optional(),\n timezone: z.string().trim().min(1).max(100).optional(),\n })\n .optional(),\n push: z\n .object({\n enabled: z.boolean().optional(),\n debounceMinutes: z.number().int().min(0).max(1_440).optional(),\n })\n .optional(),\n })\n .optional(),\n repositories: z\n .array(environmentRepositoryPatchSchema)\n .max(100)\n .superRefine((entries, ctx) => {\n const ids = new Set(entries.map(entry => entry.projectRepositoryId));\n if (ids.size !== entries.length) {\n ctx.addIssue({ code: 'custom', message: 'Each repository may be listed once' });\n }\n const positions = entries.flatMap(entry => (entry.position === undefined ? [] : [entry.position]));\n if (positions.length === 0) return;\n const expected = Array.from({ length: entries.length }, (_, index) => index + 1);\n if (\n positions.length !== entries.length ||\n [...positions].sort((a, b) => a - b).some((p, i) => p !== expected[i])\n ) {\n ctx.addIssue({\n code: 'custom',\n message: 'Positions must be a permutation of 1..n over the listed repositories',\n });\n }\n })\n .optional(),\n })\n .refine(input => Object.keys(input).length > 0, { message: 'At least one environment field is required' });\n\nconst stagesSchema = z\n .array(\n z\n .string()\n .max(64)\n .regex(/^[a-z0-9][a-z0-9_-]*$/i),\n )\n .min(1)\n .max(16)\n .refine(stages => new Set(stages).size === stages.length, { message: 'Stages must be unique' });\n\nconst externalSourceSchema = z\n .object({\n integrationId: z.string().min(1).max(128),\n type: z.string().min(1).max(128),\n externalId: z.string().min(1).max(512),\n url: z.string().max(2_048).optional(),\n })\n .nullable();\n\nconst sessionSchema = z.object({\n sessionId: z.string().min(1).max(512),\n branch: z.string().min(1).max(512),\n threadId: z.string().min(1).max(512),\n});\n\nconst sessionsSchema = z.record(z.string().min(1).max(64), sessionSchema);\nconst metadataSchema = z\n .union([z.record(z.string(), z.unknown()), z.null()])\n .refine(value => {\n try {\n return JSON.stringify(value).length <= 16 * 1024;\n } catch {\n return false;\n }\n }, 'Metadata exceeds 16 KiB')\n .transform(value => {\n if (value === null) return null;\n const {\n factoryRuleMaterializationKey: _materialization,\n factoryPullRequestReconciliation: _reconciliation,\n externalSourceMissingAt: _externalSourceMissingAt,\n ...metadata\n } = value;\n return metadata;\n });\n\nexport const createWorkItemBodySchema = z.object({\n title: rawBoundedTrimmed(500),\n board: z.string().min(1).max(128).optional(),\n externalSource: externalSourceSchema.optional(),\n parentWorkItemId: uuidSchema.nullable().optional(),\n stages: stagesSchema.optional(),\n sessions: sessionsSchema.optional(),\n metadata: metadataSchema.optional(),\n});\n\nexport const updateWorkItemBodySchema = z\n .object({\n title: rawBoundedTrimmed(500).optional(),\n board: z.string().min(1).max(128).optional(),\n parentWorkItemId: uuidSchema.nullable().optional(),\n stages: stagesSchema.optional(),\n sessions: sessionsSchema.optional(),\n metadata: metadataSchema.optional(),\n plansPreapproved: z.literal(true).optional(),\n })\n .refine(input => Object.keys(input).length > 0, { message: 'At least one work-item field is required' });\n\nexport const transitionBodySchema = z\n .object({\n board: z.string().max(MAX_BOARD_IDENTIFIER_LENGTH).regex(BOARD_IDENTIFIER_RE),\n stage: z.string().max(MAX_BOARD_IDENTIFIER_LENGTH).regex(BOARD_IDENTIFIER_RE),\n expectedRevision: z.number().int().min(1),\n requestId: trimmedUuidSchema,\n cause: nonEmptyTrimmed(256),\n reenter: z.unknown().optional(),\n })\n .transform(input => ({\n board: input.board,\n stage: input.stage,\n expectedRevision: input.expectedRevision,\n ingress: { type: 'human' as const, identity: input.requestId },\n cause: input.cause,\n ...(input.reenter === true ? { reenter: true } : {}),\n }));\n\nexport const startWorkItemBodySchema = z.object({\n sessionId: trimmedUuidSchema,\n threadTitle: nonEmptyTrimmed(512),\n kickoffKey: trimmedUuidSchema,\n workItem: z.object({\n id: trimmedUuidSchema,\n role: nonEmptyTrimmed(32),\n input: createWorkItemBodySchema,\n }),\n});\n\nexport const automationRunStartBodySchema = z\n .object({\n requestId: trimmedUuidSchema,\n expectedRevision: z.number().int().min(1),\n role: z.enum(FACTORY_ROLE_VALUES),\n skillName: nonEmptyTrimmed(128),\n arguments: nonEmptyTrimmed(4_096).optional(),\n })\n .strict();\n\nexport const metricsQuerySchema = z.object({\n from: z.string().optional(),\n to: z.string().optional(),\n});\n\nconst decisionStatusSchema = z.enum([\n 'pending',\n 'proposed',\n 'dismissed',\n 'superseded',\n 'leased',\n 'retry',\n 'succeeded',\n 'failed',\n]);\nconst boundedLimitSchema = (defaultValue: number, max: number) =>\n z\n .string()\n .optional()\n .transform(value => {\n const parsed = value ? Number.parseInt(value, 10) : defaultValue;\n return Number.isFinite(parsed) ? Math.max(1, Math.min(max, parsed)) : defaultValue;\n });\nconst decisionCursorSchema = z\n .string()\n .optional()\n .transform((value, context) => {\n if (!value) return undefined;\n try {\n const decoded = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) as unknown;\n if (\n !Array.isArray(decoded) ||\n decoded.length !== 2 ||\n typeof decoded[0] !== 'string' ||\n typeof decoded[1] !== 'string'\n ) {\n throw new Error('invalid cursor');\n }\n const createdAt = new Date(decoded[0]);\n if (Number.isNaN(createdAt.getTime()) || !new RegExp(UUID_PATTERN).test(decoded[1])) {\n throw new Error('invalid cursor');\n }\n return { createdAt, id: decoded[1] };\n } catch {\n context.addIssue({ code: 'custom', message: 'Invalid cursor' });\n return z.NEVER;\n }\n });\n\nexport const decisionQuerySchema = z.object({\n statuses: z\n .string()\n .optional()\n .transform(value => {\n if (!value) return undefined;\n const statuses = [...new Set(value.split(',').map(status => status.trim()))].filter(\n status => decisionStatusSchema.safeParse(status).success,\n ) as Array<z.infer<typeof decisionStatusSchema>>;\n return statuses.length > 0 ? statuses : undefined;\n }),\n before: decisionCursorSchema,\n limit: boundedLimitSchema(25, 50),\n});\n\nconst attentionKindSchema = z.enum([\n 'automation-failed',\n 'automation-proposed',\n 'mention',\n 'activity',\n 'agent-waiting',\n]);\ntype AttentionKind = z.infer<typeof attentionKindSchema>;\ntype AttentionStreamPosition = { occurredAt: Date; id: string };\ntype AttentionCursorMap = Map<AttentionKind, AttentionStreamPosition | undefined>;\n\nfunction parseAttentionStreamPosition(value: unknown): AttentionStreamPosition | undefined {\n if (!Array.isArray(value) || value.length !== 2 || typeof value[0] !== 'string' || typeof value[1] !== 'string') {\n return undefined;\n }\n const occurredAt = new Date(value[0]);\n if (Number.isNaN(occurredAt.getTime()) || !new RegExp(UUID_PATTERN).test(value[1])) return undefined;\n return { occurredAt, id: value[1] };\n}\n\nconst attentionCursorSchema = z\n .string()\n .optional()\n .transform((value, context) => {\n if (!value) return undefined;\n try {\n const decoded: unknown = JSON.parse(Buffer.from(value, 'base64url').toString('utf8'));\n if (Array.isArray(decoded)) {\n const legacy = parseAttentionStreamPosition(decoded);\n if (!legacy) throw new Error('invalid cursor');\n return new Map<AttentionKind, AttentionStreamPosition | undefined>([['automation-failed', legacy]]);\n }\n if (!decoded || typeof decoded !== 'object') throw new Error('invalid cursor');\n const cursors: AttentionCursorMap = new Map();\n for (const [kind, positionValue] of Object.entries(decoded)) {\n const parsedKind = attentionKindSchema.safeParse(kind);\n if (!parsedKind.success) throw new Error('invalid cursor');\n if (positionValue === null) {\n cursors.set(parsedKind.data, undefined);\n continue;\n }\n const position = parseAttentionStreamPosition(positionValue);\n if (!position) throw new Error('invalid cursor');\n cursors.set(parsedKind.data, position);\n }\n if (cursors.size === 0) throw new Error('invalid cursor');\n return cursors;\n } catch {\n context.addIssue({ code: 'custom', message: 'Invalid cursor' });\n return z.NEVER;\n }\n });\n\nexport const attentionQuerySchema = z.object({\n view: z.enum(['open', 'unread', 'archived']).optional().default('open'),\n kind: z.array(attentionKindSchema).optional(),\n before: attentionCursorSchema,\n limit: boundedLimitSchema(25, 50),\n search: z\n .string()\n .optional()\n .transform(value => value?.trim().toLowerCase().slice(0, 200) || undefined),\n});\n\nconst attentionActionPathSchema = z\n .object({\n id: uuidSchema,\n kind: attentionKindSchema,\n sourceId: z.string().min(1).max(256),\n occurrence: z\n .string()\n .regex(/^(0|[1-9]\\d*)$/)\n .transform((value, context) => {\n const occurrence = Number(value);\n if (Number.isSafeInteger(occurrence)) return occurrence;\n context.addIssue({ code: 'custom', message: 'Invalid occurrence' });\n return z.NEVER;\n }),\n })\n .refine(input => new RegExp(UUID_PATTERN).test(input.sourceId), {\n message: 'Invalid attention source id',\n path: ['sourceId'],\n });\n\nexport const FACTORY_ROUTE_CONTRACTS = {\n projectList: {\n method: 'GET',\n path: '/web/factory/projects',\n description: 'List Factory projects for the current organization',\n responseSchema: z.object({ projects: z.array(projectSchema) }),\n },\n projectCreate: {\n method: 'POST',\n path: '/web/factory/projects',\n description: 'Create a Factory project',\n bodySchema: createProjectBodySchema,\n responseSchema: projectResponseSchema,\n },\n projectGet: {\n method: 'GET',\n path: '/web/factory/projects/:id',\n description: 'Get a Factory project',\n pathSchema: projectPathSchema,\n responseSchema: projectResponseSchema,\n },\n projectUpdate: {\n method: 'PATCH',\n path: '/web/factory/projects/:id',\n description: 'Update a Factory project',\n pathSchema: projectPathSchema,\n bodySchema: updateProjectBodySchema,\n responseSchema: projectResponseSchema,\n },\n projectEnvironmentGet: {\n method: 'GET',\n path: '/web/factory/projects/:id/environment',\n description: 'Get the sandbox environment of a Factory project: provider settings and its repositories in order',\n pathSchema: projectPathSchema,\n responseSchema: projectEnvironmentResponseSchema,\n },\n projectEnvironmentUpdate: {\n method: 'PATCH',\n path: '/web/factory/projects/:id/environment',\n description: 'Update the sandbox environment of a Factory project: provider settings, repository order and setup',\n pathSchema: projectPathSchema,\n bodySchema: updateProjectEnvironmentBodySchema,\n responseSchema: projectEnvironmentResponseSchema,\n },\n projectEnvironmentBuild: {\n method: 'POST',\n path: '/web/factory/projects/:id/environment/build',\n description: 'Build the sandbox environment template of a Factory project now',\n pathSchema: projectPathSchema,\n responseSchema: environmentBuildStartResponseSchema,\n },\n projectEnvironmentBuilds: {\n method: 'GET',\n path: '/web/factory/projects/:id/environment/builds',\n description:\n 'List the environment template builds of a Factory project, newest first, when the provider keeps history',\n pathSchema: projectPathSchema,\n responseSchema: environmentBuildsResponseSchema,\n },\n projectEnvironmentBuildGet: {\n method: 'GET',\n path: '/web/factory/projects/:id/environment/builds/:buildId',\n description: 'Get the live status of one environment template build of a Factory project',\n pathSchema: buildPathSchema,\n responseSchema: environmentBuildResponseSchema,\n },\n projectApplyDefaultModel: {\n method: 'POST',\n path: '/web/factory/projects/:id/apply-default-model',\n description: 'Apply the Factory default model to running work and review threads',\n pathSchema: projectPathSchema,\n responseSchema: z.object({\n modelId: z.string(),\n applied: z.array(z.string()),\n skipped: z.array(\n z.object({\n threadId: z.string(),\n reason: z.enum([\n 'not-running',\n 'work-item-missing',\n 'stage-inactive',\n 'thread-missing',\n 'mode-unknown',\n 'apply-failed',\n ]),\n }),\n ),\n }),\n },\n projectDelete: {\n method: 'DELETE',\n path: '/web/factory/projects/:id',\n description: 'Delete a Factory project',\n pathSchema: projectPathSchema,\n responseSchema: z.null(),\n },\n metricsGet: {\n method: 'GET',\n path: '/web/factory/projects/:id/metrics',\n description: 'Get Factory project metrics',\n pathSchema: projectPathSchema,\n querySchema: metricsQuerySchema,\n responseSchema: z.object({ metrics: entitySchema }),\n },\n healthThresholdsGet: {\n method: 'GET',\n path: '/web/factory/projects/:id/health/thresholds',\n description: 'Get queue-health thresholds',\n pathSchema: projectPathSchema,\n responseSchema: z.object({ thresholds: z.array(z.number().finite()) }),\n },\n boardCatalog: {\n method: 'GET',\n path: '/web/factory/projects/:id/boards',\n description: 'List installed Factory boards',\n pathSchema: projectPathSchema,\n responseSchema: z.object({\n boards: z.array(\n z.object({\n id: z.string(),\n title: z.string(),\n initialPhase: z.string(),\n phases: z.array(\n z.object({\n id: z.string(),\n title: z.string(),\n kind: z.enum(['resting', 'working', 'terminal']),\n role: z.string().optional(),\n transitions: z.array(z.object({ outcome: z.string().nullable(), to: z.string() })),\n }),\n ),\n }),\n ),\n }),\n },\n workItemList: {\n method: 'GET',\n path: '/web/factory/projects/:id/work-items',\n description: 'List Factory work items and running sessions',\n pathSchema: projectPathSchema,\n responseSchema: z.object({\n workItems: z.array(entitySchema),\n runningSessionIds: z.array(z.string()),\n parkedSessionIds: z.array(z.string()),\n }),\n },\n workItemCreate: {\n method: 'POST',\n path: '/web/factory/projects/:id/work-items',\n description: 'Create a work item in Intake',\n pathSchema: projectPathSchema,\n bodySchema: createWorkItemBodySchema,\n responseSchema: workItemResponseSchema,\n },\n workItemUpdate: {\n method: 'PATCH',\n path: '/web/factory/work-items/:id',\n description: 'Update non-stage work-item fields',\n pathSchema: workItemPathSchema,\n bodySchema: updateWorkItemBodySchema,\n responseSchema: workItemResponseSchema,\n },\n workItemDelete: {\n method: 'DELETE',\n path: '/web/factory/work-items/:id',\n description: 'Delete a Factory work item',\n pathSchema: workItemPathSchema,\n responseSchema: z.object({ ok: z.literal(true) }),\n },\n workItemTransition: {\n method: 'POST',\n path: '/web/factory/projects/:id/work-items/:workItemId/transition',\n description: 'Transition a work item with its expected revision',\n pathSchema: transitionPathSchema,\n bodySchema: transitionBodySchema,\n responseSchema: entitySchema,\n },\n workItemStart: {\n method: 'POST',\n path: '/web/factory/projects/:id/runs/start',\n description: 'Explicitly start a Factory work-item run',\n pathSchema: projectPathSchema,\n bodySchema: startWorkItemBodySchema,\n responseSchema: entitySchema,\n },\n workItemAutomationRun: {\n method: 'POST',\n path: '/web/factory/projects/:id/work-items/:workItemId/automation-runs',\n description: 'Enqueue an idempotent deferred skill dispatch for a trusted external orchestrator',\n pathSchema: transitionPathSchema,\n bodySchema: automationRunStartBodySchema,\n responseSchema: entitySchema,\n },\n decisionList: {\n method: 'GET',\n path: '/web/factory/projects/:id/decisions',\n description: 'List Factory decisions',\n pathSchema: projectPathSchema,\n querySchema: decisionQuerySchema,\n responseSchema: z.object({ decisions: z.array(entitySchema), nextCursor: z.string().optional() }),\n },\n decisionApprove: {\n method: 'POST',\n path: '/web/factory/projects/:id/decisions/:decisionId/approve',\n description: 'Approve a proposed Factory decision',\n pathSchema: projectDecisionPathSchema,\n responseSchema: decisionResponseSchema,\n },\n decisionDismiss: {\n method: 'POST',\n path: '/web/factory/projects/:id/decisions/:decisionId/dismiss',\n description: 'Dismiss a proposed Factory decision',\n pathSchema: projectDecisionPathSchema,\n responseSchema: decisionResponseSchema,\n },\n decisionRetry: {\n method: 'POST',\n path: '/web/factory/projects/:id/decisions/:decisionId/retry',\n description: 'Retry a failed retryable Factory decision',\n pathSchema: projectDecisionPathSchema,\n responseSchema: decisionResponseSchema,\n },\n attentionList: {\n method: 'GET',\n path: '/web/factory/projects/:id/attention',\n description: 'List the Factory attention inbox',\n pathSchema: projectPathSchema,\n querySchema: attentionQuerySchema,\n responseSchema: z.object({\n items: z.array(entitySchema),\n kinds: z.record(\n attentionKindSchema,\n z.object({\n open: z.number(),\n unread: z.number(),\n latest: z.object({ key: z.string(), at: z.string(), unread: z.boolean() }).nullable(),\n }),\n ),\n hasMore: z.boolean(),\n nextCursor: z.string().optional(),\n }),\n },\n attentionReadAll: {\n method: 'POST',\n path: '/web/factory/projects/:id/attention/read-all',\n description: 'Mark all Factory attention as read',\n pathSchema: projectPathSchema,\n querySchema: z.object({ before: attentionCursorSchema }),\n responseSchema: z.object({ ok: z.literal(true), hasMore: z.boolean(), nextCursor: z.string().optional() }),\n },\n attentionRead: {\n method: 'POST',\n path: '/web/factory/projects/:id/attention/:kind/:sourceId/:occurrence/read',\n description: 'Mark a Factory attention receipt as read',\n pathSchema: attentionActionPathSchema,\n responseSchema: z.object({ receipt: entitySchema }),\n },\n attentionArchive: {\n method: 'POST',\n path: '/web/factory/projects/:id/attention/:kind/:sourceId/:occurrence/archive',\n description: 'Archive a Factory attention receipt',\n pathSchema: attentionActionPathSchema,\n responseSchema: z.object({ receipt: entitySchema }),\n },\n attentionRestore: {\n method: 'POST',\n path: '/web/factory/projects/:id/attention/:kind/:sourceId/:occurrence/restore',\n description: 'Restore an archived Factory attention receipt',\n pathSchema: attentionActionPathSchema,\n responseSchema: z.object({ receipt: entitySchema }),\n },\n} as const satisfies Record<string, FactoryRouteContract>;\n\nexport type FactoryRouteContractKey = keyof typeof FACTORY_ROUTE_CONTRACTS;\n"],"mappings":";;;;;;AAQA,MAAM,sBAAsB,OAAO,KAAK,mBAAmB;AAC3D,MAAM,kBAAkB;AAYxB,MAAa,eAAe;AAC5B,MAAM,aAAa,EAAE,OAAO,CAAC,CAAC,MAAM,IAAI,OAAO,YAAY,CAAC;AAC5D,MAAM,eAAe,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC;AACrD,MAAM,mBAAmB,QAAgB,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG;AACzE,MAAM,qBAAqB,QACzB,EACG,OAAO,CAAC,CACR,IAAI,GAAG,CAAC,CACR,WAAU,UAAS,MAAM,KAAK,CAAC,CAAC,CAChC,KAAK,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC;AAC3B,MAAM,oBAAoB,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,MAAM,IAAI,OAAO,YAAY,CAAC;AAC1E,MAAM,mBAAmB,QACvB,EAAE,MAAM,CACN,EACG,OAAO,CAAC,CACR,KAAK,CAAC,CACN,IAAI,GAAG,CA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AQ;EACR,MAAM;EACN,aAAa;EACb,YAAY;EACZ,aAAa;EACb,gBAAgB,EAAE,OAAO;GACvB,OAAO,EAAE,MAAM,YAAY;GAC3B,OAAO,EAAE,OACP,qBACA,EAAE,OAAO;IACP,MAAM,EAAE,OAAO;IACf,QAAQ,EAAE,OAAO;IACjB,QAAQ,EAAE,OAAO;KAAE,KAAK,EAAE,OAAO;KAAG,IAAI,EAAE,OAAO;KAAG,QAAQ,EAAE,QAAQ;IAAE,CAAC,CAAC,CAAC,SAAS;GACtF,CAAC,CACH;GACA,SAAS,EAAE,QAAQ;GACnB,YAAY,EAAE,OAAO,CAAC,CAAC,SAAS;EAClC,CAAC;CACH;CACA,kBAAkB;EAChB,QAAQ;EACR,MAAM;EACN,aAAa;EACb,YAAY;EACZ,aAAa,EAAE,OAAO,EAAE,QAAQ,sBAAsB,CAAC;EACvD,gBAAgB,EAAE,OAAO;GAAE,IAAI,EAAE,QAAQ,IAAI;GAAG,SAAS,EAAE,QAAQ;GAAG,YAAY,EAAE,OAAO,CAAC,CAAC,SAAS;EAAE,CAAC;CAC3G;CACA,eAAe;EACb,QAAQ;EACR,MAAM;EACN,aAAa;EACb,YAAY;EACZ,gBAAgB,EAAE,OAAO,EAAE,SAAS,aAAa,CAAC;CACpD;CACA,kBAAkB;EAChB,QAAQ;EACR,MAAM;EACN,aAAa;EACb,YAAY;EACZ,gBAAgB,EAAE,OAAO,EAAE,SAAS,aAAa,CAAC;CACpD;CACA,kBAAkB;EAChB,QAAQ;EACR,MAAM;EACN,aAAa;EACb,YAAY;EACZ,gBAAgB,EAAE,OAAO,EAAE,SAAS,aAAa,CAAC;CACpD;AACF"}
@@ -25,7 +25,7 @@ import { pollXAIDeviceLogin, startXAIDeviceLogin } from "@mastra/code-sdk/auth/p
25
25
  */
26
26
  /** Lifetime of a paste-code session (Anthropic gives no explicit expiry). */
27
27
  const PASTE_CODE_TTL_MS = 600 * 1e3;
28
- /** Web OAuth flows keyed by *catalog* provider id (mirrors {@link WEB_OAUTH_FLOW_KINDS}). */
28
+ /** Web OAuth flows keyed by *catalog* provider id (mirrors {@link WEB_OAUTH_PROVIDERS}). */
29
29
  const OAUTH_FLOWS = {
30
30
  anthropic: {
31
31
  kind: "paste-code",
@@ -1 +1 @@
1
- {"version":3,"file":"oauth.js","names":[],"sources":["../../src/routes/oauth.ts"],"sourcesContent":["/**\n * Web OAuth sign-in routes for model providers (Settings › Providers).\n *\n * Wraps the SDK's step-based OAuth primitives (start/complete for Anthropic's\n * paste-code PKCE flow, start/poll for the Codex/Copilot/xAI device flows) in\n * HTTP routes. Flow state lives in login sessions — the `model-credentials`\n * domain's `oauth_login_sessions` table in tenant mode (any replica can\n * complete/poll), an in-memory store in local mode — so a flow can span\n * requests. Completed credentials are **user-scoped by default**; org admins\n * can start a flow with `{ scope: 'org' }` to share the credential with the\n * whole org. Local mode writes to the file-backed `AuthStorage`.\n *\n * Tokens never leave the server; responses only carry flow metadata (URLs,\n * user codes, poll delays).\n */\n\nimport { nextPollDelayMs } from '@mastra/code-sdk/auth/device-code';\nimport { completeAnthropicLogin, startAnthropicLogin } from '@mastra/code-sdk/auth/providers/anthropic';\nimport {\n copilotNextPollDelayMs,\n pollGitHubCopilotDeviceLogin,\n startGitHubCopilotDeviceLogin,\n} from '@mastra/code-sdk/auth/providers/github-copilot';\nimport type { CopilotDeviceLoginPending } from '@mastra/code-sdk/auth/providers/github-copilot';\nimport { pollCodexDeviceLogin, startCodexDeviceLogin } from '@mastra/code-sdk/auth/providers/openai-codex';\nimport type { CodexDeviceLoginPending } from '@mastra/code-sdk/auth/providers/openai-codex';\nimport { pollXAIDeviceLogin, startXAIDeviceLogin } from '@mastra/code-sdk/auth/providers/xai';\nimport type { XAIDeviceLoginPending } from '@mastra/code-sdk/auth/providers/xai';\nimport type { AuthStorage } from '@mastra/code-sdk/auth/storage';\nimport type { OAuthCredentials } from '@mastra/code-sdk/auth/types';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport type { LoginCredentialScope, LoginSessionKind, LoginSessionRow } from '../storage/domains/credentials/base.js';\nimport { getAuthProviderId, resolveCredentialContext } from './provider-credentials.js';\nimport type { CredentialContext } from './provider-credentials.js';\nimport { Route } from './route.js';\nimport type { RouteDependencies } from './route.js';\n\n/** Lifetime of a paste-code session (Anthropic gives no explicit expiry). */\nconst PASTE_CODE_TTL_MS = 10 * 60 * 1000;\n\ninterface OAuthFlowStart {\n url: string;\n userCode?: string;\n instructions: string;\n /** ms epoch after which the flow expires. */\n expiresAt: number;\n /** Delay before the first upstream poll (device-code flows only). */\n nextPollMs?: number;\n /** Serializable flow state persisted in the login session. */\n pending: Record<string, unknown>;\n}\n\ntype OAuthFlowPoll =\n | { status: 'complete'; credentials: OAuthCredentials }\n | { status: 'pending'; nextPollMs: number; pending?: Record<string, unknown> }\n | { status: 'failed'; error: string };\n\ninterface OAuthFlow {\n kind: LoginSessionKind;\n start(): Promise<OAuthFlowStart>;\n /** Paste-code flows: exchange the pasted code for credentials. Throws on bad input. */\n complete?(pending: Record<string, unknown>, code: string): Promise<OAuthCredentials>;\n /** Device-code flows: perform exactly one upstream poll. */\n poll?(pending: Record<string, unknown>): Promise<OAuthFlowPoll>;\n}\n\n/** Web OAuth flows keyed by *catalog* provider id (mirrors {@link WEB_OAUTH_FLOW_KINDS}). */\nconst OAUTH_FLOWS: Record<string, OAuthFlow> = {\n anthropic: {\n kind: 'paste-code',\n start: async () => {\n const { url, verifier } = await startAnthropicLogin();\n return {\n url,\n instructions: 'Open the link, authorize, then paste the code shown on the final page.',\n expiresAt: Date.now() + PASTE_CODE_TTL_MS,\n pending: { verifier },\n };\n },\n complete: (pending, code) => completeAnthropicLogin(code, String(pending.verifier ?? '')),\n },\n openai: {\n kind: 'device-code',\n start: async () => {\n const p = await startCodexDeviceLogin();\n return {\n url: p.url,\n userCode: p.userCode,\n instructions: p.instructions,\n expiresAt: p.deadlineAt,\n nextPollMs: p.intervalMs,\n pending: { ...p },\n };\n },\n poll: async pending => {\n const r = await pollCodexDeviceLogin(pending as unknown as CodexDeviceLoginPending);\n if (r.status === 'complete') return { status: 'complete', credentials: r.credentials };\n if (r.status === 'pending') return { status: 'pending', nextPollMs: r.nextPollMs };\n return { status: 'failed', error: r.error };\n },\n },\n 'github-copilot': {\n kind: 'device-code',\n start: async () => {\n const p = await startGitHubCopilotDeviceLogin();\n return {\n url: p.url,\n userCode: p.userCode,\n instructions: p.instructions,\n expiresAt: p.deadlineAt,\n nextPollMs: copilotNextPollDelayMs(p),\n pending: { ...p },\n };\n },\n poll: async pending => {\n const p = pending as unknown as CopilotDeviceLoginPending;\n // Web flows are always started against github.com (no Enterprise input).\n // Never let deserialized session state redirect server-side polling to\n // an arbitrary hostname.\n if (p.domain !== 'github.com' || p.enterpriseDomain !== undefined) {\n return { status: 'failed', error: 'Unsupported GitHub host' };\n }\n const r = await pollGitHubCopilotDeviceLogin(p);\n if (r.status === 'complete') return { status: 'complete', credentials: r.credentials };\n if (r.status === 'pending') return { status: 'pending', nextPollMs: r.nextPollMs, pending: { ...r.pending } };\n return { status: 'failed', error: r.error };\n },\n },\n xai: {\n kind: 'device-code',\n start: async () => {\n const p = await startXAIDeviceLogin();\n return {\n url: p.url,\n userCode: p.userCode,\n instructions: p.instructions,\n expiresAt: p.state.deadlineAt,\n nextPollMs: nextPollDelayMs(p.state),\n pending: { ...p },\n };\n },\n poll: async pending => {\n const r = await pollXAIDeviceLogin(pending as unknown as XAIDeviceLoginPending);\n if (r.status === 'complete') return { status: 'complete', credentials: r.credentials };\n if (r.status === 'pending') return { status: 'pending', nextPollMs: r.nextPollMs, pending: { ...r.pending } };\n return { status: 'failed', error: r.error };\n },\n },\n};\n\nfunction loose(c: unknown): Context {\n return c as Context;\n}\n\n/**\n * Local-mode login sessions. Flows in local mode are single-process, so a\n * process-local libsql `:memory:` database (which already handles TTL\n * cleanup) is sufficient.\n */\nlet localSessionsPromise: Promise<ModelCredentialsStorage> | undefined;\nfunction localSessions(): Promise<ModelCredentialsStorage> {\n localSessionsPromise ??= (async () => {\n const { LibSQLFactoryStorage } = await import('@mastra/libsql');\n const storage = new LibSQLFactoryStorage({ id: 'local-oauth-sessions', url: ':memory:' });\n const store = storage.registerDomain(new ModelCredentialsStorage());\n await storage.init();\n return store;\n })();\n return localSessionsPromise;\n}\nconst LOCAL_TENANT = { orgId: 'local', userId: 'local' } as const;\n\nasync function sessionStore(ctx: CredentialContext): Promise<ModelCredentialsStorage> {\n return ctx.mode === 'tenant' ? ctx.storage : localSessions();\n}\n\nfunction sessionTenant(ctx: CredentialContext): { orgId: string; userId: string } {\n return ctx.mode === 'tenant' ? { orgId: ctx.orgId, userId: ctx.userId } : LOCAL_TENANT;\n}\n\n/** Load a session and verify it belongs to the caller + provider (else undefined). */\nasync function loadOwnedSession({\n ctx,\n provider,\n sessionId,\n}: {\n ctx: CredentialContext;\n provider: string;\n sessionId: string;\n}): Promise<LoginSessionRow | undefined> {\n const session = await (await sessionStore(ctx)).getLoginSession(sessionId);\n if (!session) return undefined;\n const tenant = sessionTenant(ctx);\n if (session.orgId !== tenant.orgId || session.userId !== tenant.userId) return undefined;\n if (session.provider !== provider) return undefined;\n return session;\n}\n\n/** Persist completed OAuth credentials — user-scoped unless the flow was started org-wide. */\nasync function persistOAuthCredential({\n ctx,\n provider,\n scope,\n credentials,\n authStorage,\n onCredentialsChanged,\n}: {\n ctx: CredentialContext;\n provider: string;\n scope: LoginCredentialScope | undefined;\n credentials: OAuthCredentials;\n authStorage: AuthStorage | undefined;\n onCredentialsChanged: (tenant: { orgId: string; userId?: string }) => void;\n}): Promise<void> {\n const authProviderId = getAuthProviderId(provider);\n if (ctx.mode === 'tenant') {\n const tenant = { orgId: ctx.orgId, ...(scope === 'org' ? {} : { userId: ctx.userId }) };\n await ctx.storage.setCredential(tenant, authProviderId, {\n type: 'oauth',\n ...credentials,\n });\n onCredentialsChanged(tenant);\n return;\n }\n if (!authStorage) throw new Error('Credential storage is not available');\n await authStorage.addAccount(authProviderId, credentials);\n}\n\nasync function readJsonBody(c: Context): Promise<Record<string, unknown>> {\n try {\n const body = (await c.req.json()) as unknown;\n return body && typeof body === 'object' ? (body as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n\nexport interface OAuthRoutesDeps extends RouteDependencies {\n /** File-backed credential store; used in local (no-auth) mode. */\n authStorage?: AuthStorage;\n /** Tenant credential domain handle; absent in local (no-DB) mode. */\n modelCredentials?: ModelCredentialsStorage;\n /** Notifies the host after tenant credentials change so caches can be dropped. */\n onCredentialsChanged?: (tenant: { orgId: string; userId?: string }) => void;\n}\n\n/**\n * Provider OAuth sign-in routes as Mastra `apiRoutes`:\n * - `POST /web/config/providers/:provider/oauth/start` — begin a sign-in flow\n * - `POST /web/config/providers/:provider/oauth/complete` — paste-code exchange\n * - `POST /web/config/providers/:provider/oauth/poll` — one device-code poll\n * - `DELETE /web/config/providers/:provider/oauth/session/:sessionId` — cancel a flow\n * - `DELETE /web/config/providers/:provider/oauth` — sign out (caller only)\n */\nexport class OAuthRoutes extends Route<OAuthRoutesDeps> {\n routes(): ApiRoute[] {\n const { auth, authStorage, modelCredentials } = this.deps;\n const onCredentialsChanged = this.deps.onCredentialsChanged ?? (() => {});\n\n return [\n registerApiRoute('/web/config/providers/:provider/oauth/start', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const ctx = await resolveCredentialContext({ c: loose(c), auth, credentials: modelCredentials });\n if ('response' in ctx) return ctx.response;\n\n const provider = c.req.param('provider');\n const flow = OAUTH_FLOWS[provider];\n if (!flow) {\n return c.json({ error: 'oauth_not_supported', message: `Provider does not support web sign-in` }, 404);\n }\n // Body may carry `{ mode }` for future multi-mode providers; each web\n // flow currently has exactly one mode, so an unknown mode is rejected.\n const body = await readJsonBody(loose(c));\n if (typeof body.mode === 'string' && body.mode !== flow.kind) {\n return c.json({ error: 'invalid_mode', message: `Unsupported mode for ${provider}: ${body.mode}` }, 400);\n }\n\n // Optional `{ scope: 'org' }` shares the completed credential with\n // the whole org (admin-only, tenant mode). Anything else is personal.\n const scope: LoginCredentialScope = body.scope === 'org' ? 'org' : 'user';\n if (scope === 'org' && ctx.mode === 'tenant' && !(await auth.isOrganizationAdmin(loose(c), ctx.orgId))) {\n return c.json({ error: 'forbidden', message: 'Only org admins can sign in for the whole org' }, 403);\n }\n\n let started: OAuthFlowStart;\n try {\n started = await flow.start();\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 502);\n }\n\n const sessionId = globalThis.crypto.randomUUID();\n const tenant = sessionTenant(ctx);\n await (\n await sessionStore(ctx)\n ).createLoginSession({\n sessionId,\n orgId: tenant.orgId,\n userId: tenant.userId,\n provider,\n kind: flow.kind,\n ...(scope === 'org' && ctx.mode === 'tenant' ? { credentialScope: scope } : {}),\n pending: started.pending,\n expiresAt: new Date(started.expiresAt),\n nextPollAt: started.nextPollMs != null ? new Date(Date.now() + started.nextPollMs) : null,\n });\n\n return c.json({\n sessionId,\n kind: flow.kind,\n url: started.url,\n ...(started.userCode ? { userCode: started.userCode } : {}),\n instructions: started.instructions,\n expiresAt: started.expiresAt,\n ...(started.nextPollMs != null ? { nextPollMs: started.nextPollMs } : {}),\n });\n },\n }),\n\n registerApiRoute('/web/config/providers/:provider/oauth/complete', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const ctx = await resolveCredentialContext({ c: loose(c), auth, credentials: modelCredentials });\n if ('response' in ctx) return ctx.response;\n\n const provider = c.req.param('provider');\n const flow = OAUTH_FLOWS[provider];\n if (!flow?.complete) return c.json({ error: 'oauth_not_supported' }, 404);\n\n const body = await readJsonBody(loose(c));\n const sessionId = typeof body.sessionId === 'string' ? body.sessionId : '';\n const code = typeof body.code === 'string' ? body.code.trim() : '';\n if (!sessionId || !code) return c.json({ error: 'Missing required fields: sessionId, code' }, 400);\n\n const session = await loadOwnedSession({ ctx, provider, sessionId });\n if (!session) return c.json({ error: 'session_not_found' }, 404);\n if (session.kind !== 'paste-code') return c.json({ error: 'wrong_session_kind' }, 400);\n // Org-scoped flows recheck admin access at completion time — the\n // caller may have lost admin since the flow was started.\n if (\n session.credentialScope === 'org' &&\n ctx.mode === 'tenant' &&\n !(await auth.isOrganizationAdmin(loose(c), ctx.orgId))\n ) {\n return c.json({ error: 'forbidden', message: 'Only org admins can sign in for the whole org' }, 403);\n }\n\n const claimed = await (\n await sessionStore(ctx)\n ).claimLoginSession(sessionId, {\n orgId: session.orgId,\n userId: session.userId,\n provider,\n kind: 'paste-code',\n });\n if (!claimed) return c.json({ error: 'oauth_in_progress' }, 409);\n\n let credentials: OAuthCredentials;\n try {\n credentials = await flow.complete(claimed.pending, code);\n } catch (error) {\n await (await sessionStore(ctx)).touchLoginSession(sessionId, { nextPollAt: null });\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n }\n\n await persistOAuthCredential({\n ctx,\n provider,\n scope: session.credentialScope,\n credentials,\n authStorage,\n onCredentialsChanged,\n });\n await (await sessionStore(ctx)).deleteLoginSession(sessionId);\n return c.json({ status: 'complete', ok: true });\n },\n }),\n\n registerApiRoute('/web/config/providers/:provider/oauth/poll', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const ctx = await resolveCredentialContext({ c: loose(c), auth, credentials: modelCredentials });\n if ('response' in ctx) return ctx.response;\n\n const provider = c.req.param('provider');\n const flow = OAUTH_FLOWS[provider];\n if (!flow?.poll) return c.json({ error: 'oauth_not_supported' }, 404);\n\n const body = await readJsonBody(loose(c));\n const sessionId = typeof body.sessionId === 'string' ? body.sessionId : '';\n if (!sessionId) return c.json({ error: 'Missing required field: sessionId' }, 400);\n\n const session = await loadOwnedSession({ ctx, provider, sessionId });\n if (!session) return c.json({ error: 'session_not_found' }, 404);\n if (session.kind !== 'device-code') return c.json({ error: 'wrong_session_kind' }, 400);\n // Org-scoped flows recheck admin access before the credential write —\n // the caller may have lost admin since the flow was started.\n if (\n session.credentialScope === 'org' &&\n ctx.mode === 'tenant' &&\n !(await auth.isOrganizationAdmin(loose(c), ctx.orgId))\n ) {\n return c.json({ error: 'forbidden', message: 'Only org admins can sign in for the whole org' }, 403);\n }\n\n // Server-side rate limit: at most one upstream poll per interval,\n // regardless of how eagerly the client calls this route.\n const now = Date.now();\n const nextPollAt = session.nextPollAt?.getTime();\n // claimLoginSession parks next_poll_at at expires_at while another\n // request owns the flow. That is a lock, not a schedule, so fall\n // through to the claim and take its short retry instead.\n const parkedByClaim = nextPollAt != null && nextPollAt >= session.expiresAt.getTime();\n if (nextPollAt != null && now < nextPollAt && !parkedByClaim) {\n return c.json({ status: 'pending', nextPollMs: nextPollAt - now });\n }\n\n const claimed = await (\n await sessionStore(ctx)\n ).claimLoginSession(sessionId, {\n orgId: session.orgId,\n userId: session.userId,\n provider,\n kind: 'device-code',\n });\n if (!claimed) return c.json({ status: 'pending', nextPollMs: 250 });\n\n let result: OAuthFlowPoll;\n try {\n result = await flow.poll(claimed.pending);\n } catch (error) {\n await (await sessionStore(ctx)).touchLoginSession(sessionId, { nextPollAt: null });\n throw error;\n }\n\n if (result.status === 'complete') {\n await persistOAuthCredential({\n ctx,\n provider,\n scope: session.credentialScope,\n credentials: result.credentials,\n authStorage,\n onCredentialsChanged,\n });\n await (await sessionStore(ctx)).deleteLoginSession(sessionId);\n return c.json({ status: 'complete', ok: true });\n }\n\n if (result.status === 'failed') {\n await (await sessionStore(ctx)).deleteLoginSession(sessionId);\n return c.json({ status: 'failed', error: result.error });\n }\n\n await (\n await sessionStore(ctx)\n ).touchLoginSession(sessionId, {\n ...(result.pending ? { pending: result.pending } : {}),\n nextPollAt: new Date(now + result.nextPollMs),\n });\n return c.json({ status: 'pending', nextPollMs: result.nextPollMs });\n },\n }),\n\n registerApiRoute('/web/config/providers/:provider/oauth/session/:sessionId', {\n method: 'DELETE',\n requiresAuth: false,\n handler: async c => {\n const ctx = await resolveCredentialContext({ c: loose(c), auth, credentials: modelCredentials });\n if ('response' in ctx) return ctx.response;\n\n const provider = c.req.param('provider');\n const sessionId = c.req.param('sessionId');\n const session = await loadOwnedSession({ ctx, provider, sessionId });\n if (session) await (await sessionStore(ctx)).deleteLoginSession(sessionId);\n return c.json({ ok: true });\n },\n }),\n\n registerApiRoute('/web/config/providers/:provider/oauth', {\n method: 'DELETE',\n requiresAuth: false,\n handler: async c => {\n const ctx = await resolveCredentialContext({ c: loose(c), auth, credentials: modelCredentials });\n if ('response' in ctx) return ctx.response;\n\n const provider = c.req.param('provider');\n const authProviderId = getAuthProviderId(provider);\n // `?scope=org` removes the shared org credential (admin-only);\n // default removes the caller's personal credential only.\n const scope = c.req.query('scope') === 'org' ? 'org' : 'user';\n try {\n if (ctx.mode === 'tenant') {\n if (scope === 'org' && !(await auth.isOrganizationAdmin(loose(c), ctx.orgId))) {\n return c.json({ error: 'forbidden', message: 'Only org admins can remove an org-wide sign-in' }, 403);\n }\n const tenant = { orgId: ctx.orgId, ...(scope === 'org' ? {} : { userId: ctx.userId }) };\n await ctx.storage.removeCredential(tenant, authProviderId);\n onCredentialsChanged(tenant);\n } else {\n if (!authStorage) return c.json({ error: 'Credential storage is not available' }, 503);\n authStorage.logout(authProviderId);\n }\n return c.json({ ok: true });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n ];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,MAAM,oBAAoB,MAAU;;AA6BpC,MAAM,cAAyC;CAC7C,WAAW;EACT,MAAM;EACN,OAAO,YAAY;GACjB,MAAM,EAAE,KAAK,aAAa,MAAM,oBAAoB;GACpD,OAAO;IACL;IACA,cAAc;IACd,WAAW,KAAK,IAAI,IAAI;IACxB,SAAS,EAAE,SAAS;GACtB;EACF;EACA,WAAW,SAAS,SAAS,uBAAuB,MAAM,OAAO,QAAQ,YAAY,EAAE,CAAC;CAC1F;CACA,QAAQ;EACN,MAAM;EACN,OAAO,YAAY;GACjB,MAAM,IAAI,MAAM,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,IAAI,QAAQ,iBAAiB,QAAQ,cAAc;OACzD,qBAAqB,MAAM;MAC7B,OAAO;OACL,IAAI,CAAC,aAAa,OAAO,EAAE,KAAK,EAAE,OAAO,sCAAsC,GAAG,GAAG;OACrF,YAAY,OAAO,cAAc;MACnC;MACA,OAAO,EAAE,KAAK,EAAE,IAAI,KAAK,CAAC;KAC5B,SAAS,OAAO;MACd,OAAO,EAAE,KAAK,EAAE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,GAAG,GAAG;KACtF;IACF;GACF,CAAC;EACH;CACF;AACF"}
1
+ {"version":3,"file":"oauth.js","names":[],"sources":["../../src/routes/oauth.ts"],"sourcesContent":["/**\n * Web OAuth sign-in routes for model providers (Settings › Providers).\n *\n * Wraps the SDK's step-based OAuth primitives (start/complete for Anthropic's\n * paste-code PKCE flow, start/poll for the Codex/Copilot/xAI device flows) in\n * HTTP routes. Flow state lives in login sessions — the `model-credentials`\n * domain's `oauth_login_sessions` table in tenant mode (any replica can\n * complete/poll), an in-memory store in local mode — so a flow can span\n * requests. Completed credentials are **user-scoped by default**; org admins\n * can start a flow with `{ scope: 'org' }` to share the credential with the\n * whole org. Local mode writes to the file-backed `AuthStorage`.\n *\n * Tokens never leave the server; responses only carry flow metadata (URLs,\n * user codes, poll delays).\n */\n\nimport { nextPollDelayMs } from '@mastra/code-sdk/auth/device-code';\nimport { completeAnthropicLogin, startAnthropicLogin } from '@mastra/code-sdk/auth/providers/anthropic';\nimport {\n copilotNextPollDelayMs,\n pollGitHubCopilotDeviceLogin,\n startGitHubCopilotDeviceLogin,\n} from '@mastra/code-sdk/auth/providers/github-copilot';\nimport type { CopilotDeviceLoginPending } from '@mastra/code-sdk/auth/providers/github-copilot';\nimport { pollCodexDeviceLogin, startCodexDeviceLogin } from '@mastra/code-sdk/auth/providers/openai-codex';\nimport type { CodexDeviceLoginPending } from '@mastra/code-sdk/auth/providers/openai-codex';\nimport { pollXAIDeviceLogin, startXAIDeviceLogin } from '@mastra/code-sdk/auth/providers/xai';\nimport type { XAIDeviceLoginPending } from '@mastra/code-sdk/auth/providers/xai';\nimport type { AuthStorage } from '@mastra/code-sdk/auth/storage';\nimport type { OAuthCredentials } from '@mastra/code-sdk/auth/types';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport type { LoginCredentialScope, LoginSessionKind, LoginSessionRow } from '../storage/domains/credentials/base.js';\nimport { getAuthProviderId, resolveCredentialContext } from './provider-credentials.js';\nimport type { CredentialContext } from './provider-credentials.js';\nimport { Route } from './route.js';\nimport type { RouteDependencies } from './route.js';\n\n/** Lifetime of a paste-code session (Anthropic gives no explicit expiry). */\nconst PASTE_CODE_TTL_MS = 10 * 60 * 1000;\n\ninterface OAuthFlowStart {\n url: string;\n userCode?: string;\n instructions: string;\n /** ms epoch after which the flow expires. */\n expiresAt: number;\n /** Delay before the first upstream poll (device-code flows only). */\n nextPollMs?: number;\n /** Serializable flow state persisted in the login session. */\n pending: Record<string, unknown>;\n}\n\ntype OAuthFlowPoll =\n | { status: 'complete'; credentials: OAuthCredentials }\n | { status: 'pending'; nextPollMs: number; pending?: Record<string, unknown> }\n | { status: 'failed'; error: string };\n\ninterface OAuthFlow {\n kind: LoginSessionKind;\n start(): Promise<OAuthFlowStart>;\n /** Paste-code flows: exchange the pasted code for credentials. Throws on bad input. */\n complete?(pending: Record<string, unknown>, code: string): Promise<OAuthCredentials>;\n /** Device-code flows: perform exactly one upstream poll. */\n poll?(pending: Record<string, unknown>): Promise<OAuthFlowPoll>;\n}\n\n/** Web OAuth flows keyed by *catalog* provider id (mirrors {@link WEB_OAUTH_PROVIDERS}). */\nconst OAUTH_FLOWS: Record<string, OAuthFlow> = {\n anthropic: {\n kind: 'paste-code',\n start: async () => {\n const { url, verifier } = await startAnthropicLogin();\n return {\n url,\n instructions: 'Open the link, authorize, then paste the code shown on the final page.',\n expiresAt: Date.now() + PASTE_CODE_TTL_MS,\n pending: { verifier },\n };\n },\n complete: (pending, code) => completeAnthropicLogin(code, String(pending.verifier ?? '')),\n },\n openai: {\n kind: 'device-code',\n start: async () => {\n const p = await startCodexDeviceLogin();\n return {\n url: p.url,\n userCode: p.userCode,\n instructions: p.instructions,\n expiresAt: p.deadlineAt,\n nextPollMs: p.intervalMs,\n pending: { ...p },\n };\n },\n poll: async pending => {\n const r = await pollCodexDeviceLogin(pending as unknown as CodexDeviceLoginPending);\n if (r.status === 'complete') return { status: 'complete', credentials: r.credentials };\n if (r.status === 'pending') return { status: 'pending', nextPollMs: r.nextPollMs };\n return { status: 'failed', error: r.error };\n },\n },\n 'github-copilot': {\n kind: 'device-code',\n start: async () => {\n const p = await startGitHubCopilotDeviceLogin();\n return {\n url: p.url,\n userCode: p.userCode,\n instructions: p.instructions,\n expiresAt: p.deadlineAt,\n nextPollMs: copilotNextPollDelayMs(p),\n pending: { ...p },\n };\n },\n poll: async pending => {\n const p = pending as unknown as CopilotDeviceLoginPending;\n // Web flows are always started against github.com (no Enterprise input).\n // Never let deserialized session state redirect server-side polling to\n // an arbitrary hostname.\n if (p.domain !== 'github.com' || p.enterpriseDomain !== undefined) {\n return { status: 'failed', error: 'Unsupported GitHub host' };\n }\n const r = await pollGitHubCopilotDeviceLogin(p);\n if (r.status === 'complete') return { status: 'complete', credentials: r.credentials };\n if (r.status === 'pending') return { status: 'pending', nextPollMs: r.nextPollMs, pending: { ...r.pending } };\n return { status: 'failed', error: r.error };\n },\n },\n xai: {\n kind: 'device-code',\n start: async () => {\n const p = await startXAIDeviceLogin();\n return {\n url: p.url,\n userCode: p.userCode,\n instructions: p.instructions,\n expiresAt: p.state.deadlineAt,\n nextPollMs: nextPollDelayMs(p.state),\n pending: { ...p },\n };\n },\n poll: async pending => {\n const r = await pollXAIDeviceLogin(pending as unknown as XAIDeviceLoginPending);\n if (r.status === 'complete') return { status: 'complete', credentials: r.credentials };\n if (r.status === 'pending') return { status: 'pending', nextPollMs: r.nextPollMs, pending: { ...r.pending } };\n return { status: 'failed', error: r.error };\n },\n },\n};\n\nfunction loose(c: unknown): Context {\n return c as Context;\n}\n\n/**\n * Local-mode login sessions. Flows in local mode are single-process, so a\n * process-local libsql `:memory:` database (which already handles TTL\n * cleanup) is sufficient.\n */\nlet localSessionsPromise: Promise<ModelCredentialsStorage> | undefined;\nfunction localSessions(): Promise<ModelCredentialsStorage> {\n localSessionsPromise ??= (async () => {\n const { LibSQLFactoryStorage } = await import('@mastra/libsql');\n const storage = new LibSQLFactoryStorage({ id: 'local-oauth-sessions', url: ':memory:' });\n const store = storage.registerDomain(new ModelCredentialsStorage());\n await storage.init();\n return store;\n })();\n return localSessionsPromise;\n}\nconst LOCAL_TENANT = { orgId: 'local', userId: 'local' } as const;\n\nasync function sessionStore(ctx: CredentialContext): Promise<ModelCredentialsStorage> {\n return ctx.mode === 'tenant' ? ctx.storage : localSessions();\n}\n\nfunction sessionTenant(ctx: CredentialContext): { orgId: string; userId: string } {\n return ctx.mode === 'tenant' ? { orgId: ctx.orgId, userId: ctx.userId } : LOCAL_TENANT;\n}\n\n/** Load a session and verify it belongs to the caller + provider (else undefined). */\nasync function loadOwnedSession({\n ctx,\n provider,\n sessionId,\n}: {\n ctx: CredentialContext;\n provider: string;\n sessionId: string;\n}): Promise<LoginSessionRow | undefined> {\n const session = await (await sessionStore(ctx)).getLoginSession(sessionId);\n if (!session) return undefined;\n const tenant = sessionTenant(ctx);\n if (session.orgId !== tenant.orgId || session.userId !== tenant.userId) return undefined;\n if (session.provider !== provider) return undefined;\n return session;\n}\n\n/** Persist completed OAuth credentials — user-scoped unless the flow was started org-wide. */\nasync function persistOAuthCredential({\n ctx,\n provider,\n scope,\n credentials,\n authStorage,\n onCredentialsChanged,\n}: {\n ctx: CredentialContext;\n provider: string;\n scope: LoginCredentialScope | undefined;\n credentials: OAuthCredentials;\n authStorage: AuthStorage | undefined;\n onCredentialsChanged: (tenant: { orgId: string; userId?: string }) => void;\n}): Promise<void> {\n const authProviderId = getAuthProviderId(provider);\n if (ctx.mode === 'tenant') {\n const tenant = { orgId: ctx.orgId, ...(scope === 'org' ? {} : { userId: ctx.userId }) };\n await ctx.storage.setCredential(tenant, authProviderId, {\n type: 'oauth',\n ...credentials,\n });\n onCredentialsChanged(tenant);\n return;\n }\n if (!authStorage) throw new Error('Credential storage is not available');\n await authStorage.addAccount(authProviderId, credentials);\n}\n\nasync function readJsonBody(c: Context): Promise<Record<string, unknown>> {\n try {\n const body = (await c.req.json()) as unknown;\n return body && typeof body === 'object' ? (body as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n\nexport interface OAuthRoutesDeps extends RouteDependencies {\n /** File-backed credential store; used in local (no-auth) mode. */\n authStorage?: AuthStorage;\n /** Tenant credential domain handle; absent in local (no-DB) mode. */\n modelCredentials?: ModelCredentialsStorage;\n /** Notifies the host after tenant credentials change so caches can be dropped. */\n onCredentialsChanged?: (tenant: { orgId: string; userId?: string }) => void;\n}\n\n/**\n * Provider OAuth sign-in routes as Mastra `apiRoutes`:\n * - `POST /web/config/providers/:provider/oauth/start` — begin a sign-in flow\n * - `POST /web/config/providers/:provider/oauth/complete` — paste-code exchange\n * - `POST /web/config/providers/:provider/oauth/poll` — one device-code poll\n * - `DELETE /web/config/providers/:provider/oauth/session/:sessionId` — cancel a flow\n * - `DELETE /web/config/providers/:provider/oauth` — sign out (caller only)\n */\nexport class OAuthRoutes extends Route<OAuthRoutesDeps> {\n routes(): ApiRoute[] {\n const { auth, authStorage, modelCredentials } = this.deps;\n const onCredentialsChanged = this.deps.onCredentialsChanged ?? (() => {});\n\n return [\n registerApiRoute('/web/config/providers/:provider/oauth/start', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const ctx = await resolveCredentialContext({ c: loose(c), auth, credentials: modelCredentials });\n if ('response' in ctx) return ctx.response;\n\n const provider = c.req.param('provider');\n const flow = OAUTH_FLOWS[provider];\n if (!flow) {\n return c.json({ error: 'oauth_not_supported', message: `Provider does not support web sign-in` }, 404);\n }\n // Body may carry `{ mode }` for future multi-mode providers; each web\n // flow currently has exactly one mode, so an unknown mode is rejected.\n const body = await readJsonBody(loose(c));\n if (typeof body.mode === 'string' && body.mode !== flow.kind) {\n return c.json({ error: 'invalid_mode', message: `Unsupported mode for ${provider}: ${body.mode}` }, 400);\n }\n\n // Optional `{ scope: 'org' }` shares the completed credential with\n // the whole org (admin-only, tenant mode). Anything else is personal.\n const scope: LoginCredentialScope = body.scope === 'org' ? 'org' : 'user';\n if (scope === 'org' && ctx.mode === 'tenant' && !(await auth.isOrganizationAdmin(loose(c), ctx.orgId))) {\n return c.json({ error: 'forbidden', message: 'Only org admins can sign in for the whole org' }, 403);\n }\n\n let started: OAuthFlowStart;\n try {\n started = await flow.start();\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 502);\n }\n\n const sessionId = globalThis.crypto.randomUUID();\n const tenant = sessionTenant(ctx);\n await (\n await sessionStore(ctx)\n ).createLoginSession({\n sessionId,\n orgId: tenant.orgId,\n userId: tenant.userId,\n provider,\n kind: flow.kind,\n ...(scope === 'org' && ctx.mode === 'tenant' ? { credentialScope: scope } : {}),\n pending: started.pending,\n expiresAt: new Date(started.expiresAt),\n nextPollAt: started.nextPollMs != null ? new Date(Date.now() + started.nextPollMs) : null,\n });\n\n return c.json({\n sessionId,\n kind: flow.kind,\n url: started.url,\n ...(started.userCode ? { userCode: started.userCode } : {}),\n instructions: started.instructions,\n expiresAt: started.expiresAt,\n ...(started.nextPollMs != null ? { nextPollMs: started.nextPollMs } : {}),\n });\n },\n }),\n\n registerApiRoute('/web/config/providers/:provider/oauth/complete', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const ctx = await resolveCredentialContext({ c: loose(c), auth, credentials: modelCredentials });\n if ('response' in ctx) return ctx.response;\n\n const provider = c.req.param('provider');\n const flow = OAUTH_FLOWS[provider];\n if (!flow?.complete) return c.json({ error: 'oauth_not_supported' }, 404);\n\n const body = await readJsonBody(loose(c));\n const sessionId = typeof body.sessionId === 'string' ? body.sessionId : '';\n const code = typeof body.code === 'string' ? body.code.trim() : '';\n if (!sessionId || !code) return c.json({ error: 'Missing required fields: sessionId, code' }, 400);\n\n const session = await loadOwnedSession({ ctx, provider, sessionId });\n if (!session) return c.json({ error: 'session_not_found' }, 404);\n if (session.kind !== 'paste-code') return c.json({ error: 'wrong_session_kind' }, 400);\n // Org-scoped flows recheck admin access at completion time — the\n // caller may have lost admin since the flow was started.\n if (\n session.credentialScope === 'org' &&\n ctx.mode === 'tenant' &&\n !(await auth.isOrganizationAdmin(loose(c), ctx.orgId))\n ) {\n return c.json({ error: 'forbidden', message: 'Only org admins can sign in for the whole org' }, 403);\n }\n\n const claimed = await (\n await sessionStore(ctx)\n ).claimLoginSession(sessionId, {\n orgId: session.orgId,\n userId: session.userId,\n provider,\n kind: 'paste-code',\n });\n if (!claimed) return c.json({ error: 'oauth_in_progress' }, 409);\n\n let credentials: OAuthCredentials;\n try {\n credentials = await flow.complete(claimed.pending, code);\n } catch (error) {\n await (await sessionStore(ctx)).touchLoginSession(sessionId, { nextPollAt: null });\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n }\n\n await persistOAuthCredential({\n ctx,\n provider,\n scope: session.credentialScope,\n credentials,\n authStorage,\n onCredentialsChanged,\n });\n await (await sessionStore(ctx)).deleteLoginSession(sessionId);\n return c.json({ status: 'complete', ok: true });\n },\n }),\n\n registerApiRoute('/web/config/providers/:provider/oauth/poll', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const ctx = await resolveCredentialContext({ c: loose(c), auth, credentials: modelCredentials });\n if ('response' in ctx) return ctx.response;\n\n const provider = c.req.param('provider');\n const flow = OAUTH_FLOWS[provider];\n if (!flow?.poll) return c.json({ error: 'oauth_not_supported' }, 404);\n\n const body = await readJsonBody(loose(c));\n const sessionId = typeof body.sessionId === 'string' ? body.sessionId : '';\n if (!sessionId) return c.json({ error: 'Missing required field: sessionId' }, 400);\n\n const session = await loadOwnedSession({ ctx, provider, sessionId });\n if (!session) return c.json({ error: 'session_not_found' }, 404);\n if (session.kind !== 'device-code') return c.json({ error: 'wrong_session_kind' }, 400);\n // Org-scoped flows recheck admin access before the credential write —\n // the caller may have lost admin since the flow was started.\n if (\n session.credentialScope === 'org' &&\n ctx.mode === 'tenant' &&\n !(await auth.isOrganizationAdmin(loose(c), ctx.orgId))\n ) {\n return c.json({ error: 'forbidden', message: 'Only org admins can sign in for the whole org' }, 403);\n }\n\n // Server-side rate limit: at most one upstream poll per interval,\n // regardless of how eagerly the client calls this route.\n const now = Date.now();\n const nextPollAt = session.nextPollAt?.getTime();\n // claimLoginSession parks next_poll_at at expires_at while another\n // request owns the flow. That is a lock, not a schedule, so fall\n // through to the claim and take its short retry instead.\n const parkedByClaim = nextPollAt != null && nextPollAt >= session.expiresAt.getTime();\n if (nextPollAt != null && now < nextPollAt && !parkedByClaim) {\n return c.json({ status: 'pending', nextPollMs: nextPollAt - now });\n }\n\n const claimed = await (\n await sessionStore(ctx)\n ).claimLoginSession(sessionId, {\n orgId: session.orgId,\n userId: session.userId,\n provider,\n kind: 'device-code',\n });\n if (!claimed) return c.json({ status: 'pending', nextPollMs: 250 });\n\n let result: OAuthFlowPoll;\n try {\n result = await flow.poll(claimed.pending);\n } catch (error) {\n await (await sessionStore(ctx)).touchLoginSession(sessionId, { nextPollAt: null });\n throw error;\n }\n\n if (result.status === 'complete') {\n await persistOAuthCredential({\n ctx,\n provider,\n scope: session.credentialScope,\n credentials: result.credentials,\n authStorage,\n onCredentialsChanged,\n });\n await (await sessionStore(ctx)).deleteLoginSession(sessionId);\n return c.json({ status: 'complete', ok: true });\n }\n\n if (result.status === 'failed') {\n await (await sessionStore(ctx)).deleteLoginSession(sessionId);\n return c.json({ status: 'failed', error: result.error });\n }\n\n await (\n await sessionStore(ctx)\n ).touchLoginSession(sessionId, {\n ...(result.pending ? { pending: result.pending } : {}),\n nextPollAt: new Date(now + result.nextPollMs),\n });\n return c.json({ status: 'pending', nextPollMs: result.nextPollMs });\n },\n }),\n\n registerApiRoute('/web/config/providers/:provider/oauth/session/:sessionId', {\n method: 'DELETE',\n requiresAuth: false,\n handler: async c => {\n const ctx = await resolveCredentialContext({ c: loose(c), auth, credentials: modelCredentials });\n if ('response' in ctx) return ctx.response;\n\n const provider = c.req.param('provider');\n const sessionId = c.req.param('sessionId');\n const session = await loadOwnedSession({ ctx, provider, sessionId });\n if (session) await (await sessionStore(ctx)).deleteLoginSession(sessionId);\n return c.json({ ok: true });\n },\n }),\n\n registerApiRoute('/web/config/providers/:provider/oauth', {\n method: 'DELETE',\n requiresAuth: false,\n handler: async c => {\n const ctx = await resolveCredentialContext({ c: loose(c), auth, credentials: modelCredentials });\n if ('response' in ctx) return ctx.response;\n\n const provider = c.req.param('provider');\n const authProviderId = getAuthProviderId(provider);\n // `?scope=org` removes the shared org credential (admin-only);\n // default removes the caller's personal credential only.\n const scope = c.req.query('scope') === 'org' ? 'org' : 'user';\n try {\n if (ctx.mode === 'tenant') {\n if (scope === 'org' && !(await auth.isOrganizationAdmin(loose(c), ctx.orgId))) {\n return c.json({ error: 'forbidden', message: 'Only org admins can remove an org-wide sign-in' }, 403);\n }\n const tenant = { orgId: ctx.orgId, ...(scope === 'org' ? {} : { userId: ctx.userId }) };\n await ctx.storage.removeCredential(tenant, authProviderId);\n onCredentialsChanged(tenant);\n } else {\n if (!authStorage) return c.json({ error: 'Credential storage is not available' }, 503);\n authStorage.logout(authProviderId);\n }\n return c.json({ ok: true });\n } catch (error) {\n return c.json({ error: error instanceof Error ? error.message : String(error) }, 500);\n }\n },\n }),\n ];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,MAAM,oBAAoB,MAAU;;AA6BpC,MAAM,cAAyC;CAC7C,WAAW;EACT,MAAM;EACN,OAAO,YAAY;GACjB,MAAM,EAAE,KAAK,aAAa,MAAM,oBAAoB;GACpD,OAAO;IACL;IACA,cAAc;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,GAAG,IAAI,KAAK,GACzE,OAAO,EAAE,KAAK;QAAE,OAAO;QAAa,SAAS;OAAiD,GAAG,GAAG;OAEtG,MAAM,SAAS;QAAE,OAAO,IAAI;QAAO,GAAI,UAAU,QAAQ,CAAC,IAAI,EAAE,QAAQ,IAAI,OAAO;OAAG;OACtF,MAAM,IAAI,QAAQ,iBAAiB,QAAQ,cAAc;OACzD,qBAAqB,MAAM;MAC7B,OAAO;OACL,IAAI,CAAC,aAAa,OAAO,EAAE,KAAK,EAAE,OAAO,sCAAsC,GAAG,GAAG;OACrF,YAAY,OAAO,cAAc;MACnC;MACA,OAAO,EAAE,KAAK,EAAE,IAAI,KAAK,CAAC;KAC5B,SAAS,OAAO;MACd,OAAO,EAAE,KAAK,EAAE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,GAAG,GAAG;KACtF;IACF;GACF,CAAC;EACH;CACF;AACF"}
@@ -27,9 +27,13 @@ export { getCredentialProviderId as getAuthProviderId } from '@mastra/code-sdk/p
27
27
  * Providers that support a browser-driven OAuth sign-in flow, keyed by
28
28
  * *catalog* provider id (what the routes and settings UI use). All flows need
29
29
  * no inbound connection to the server: Anthropic uses paste-code PKCE, the
30
- * rest use RFC 8628-style device codes.
30
+ * rest use RFC 8628-style device codes. `subscription` names the plan the
31
+ * sign-in bills, as shown under a reply.
31
32
  */
32
- export declare const WEB_OAUTH_FLOW_KINDS: Readonly<Record<string, LoginSessionKind>>;
33
+ export declare const WEB_OAUTH_PROVIDERS: Readonly<Record<string, {
34
+ flow: LoginSessionKind;
35
+ subscription: string;
36
+ }>>;
33
37
  export type CredentialContext = {
34
38
  mode: 'local';
35
39
  } | {
@@ -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;AAGpC,OAA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AC,EAC7C,CAAC,EACD,IAAI,EACJ,WAAW,GACZ,EAAE;IACD,CAAC,EAAE,OAAO,CAAC;IACX,IAAI,EAAE,SAAS,CAAC;IAChB,qEAAqE;IACrE,WAAW,CAAC,EAAE,uBAAuB,CAAC;CACvC,GAAG,OAAO,CAAC,iBAAiB,GAAG;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,CAuBtD;AAED;;;;;;GAMG;AACH,wBAAsB,+BAA+B,CAAC,EACpD,CAAC,EACD,IAAI,EACJ,WAAW,GACZ,EAAE;IACD,CAAC,EAAE,OAAO,CAAC;IACX,IAAI,EAAE,SAAS,CAAC;IAChB,qEAAqE;IACrE,WAAW,CAAC,EAAE,uBAAuB,CAAC;CACvC,GAAG,OAAO,CAAC,gBAAgB,EAAE,GAAG,SAAS,CAAC,CAO1C"}
@@ -5,13 +5,26 @@ import { getCredentialProviderId as getAuthProviderId } from "@mastra/code-sdk/p
5
5
  * Providers that support a browser-driven OAuth sign-in flow, keyed by
6
6
  * *catalog* provider id (what the routes and settings UI use). All flows need
7
7
  * no inbound connection to the server: Anthropic uses paste-code PKCE, the
8
- * rest use RFC 8628-style device codes.
8
+ * rest use RFC 8628-style device codes. `subscription` names the plan the
9
+ * sign-in bills, as shown under a reply.
9
10
  */
10
- const WEB_OAUTH_FLOW_KINDS = {
11
- anthropic: "paste-code",
12
- openai: "device-code",
13
- "github-copilot": "device-code",
14
- xai: "device-code"
11
+ const WEB_OAUTH_PROVIDERS = {
12
+ anthropic: {
13
+ flow: "paste-code",
14
+ subscription: "Claude Pro/Max"
15
+ },
16
+ openai: {
17
+ flow: "device-code",
18
+ subscription: "ChatGPT Plus/Pro"
19
+ },
20
+ "github-copilot": {
21
+ flow: "device-code",
22
+ subscription: "GitHub Copilot"
23
+ },
24
+ xai: {
25
+ flow: "device-code",
26
+ subscription: "SuperGrok/X Premium+"
27
+ }
15
28
  };
16
29
  /**
17
30
  * The tenant credentials domain, when registered and ready. `undefined` means
@@ -75,6 +88,6 @@ async function listTenantCredentialsForRequest({ c, auth, credentials }) {
75
88
  return storage.listCredentials(tenantOrgId(tenant), tenant.userId);
76
89
  }
77
90
  //#endregion
78
- export { WEB_OAUTH_FLOW_KINDS, getAuthProviderId, getTenantCredentialsStorage, listTenantCredentialsForRequest, resolveCredentialContext, tenantOrgId };
91
+ export { WEB_OAUTH_PROVIDERS, getAuthProviderId, getTenantCredentialsStorage, listTenantCredentialsForRequest, resolveCredentialContext, tenantOrgId };
79
92
 
80
93
  //# 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 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.\n */\nexport const WEB_OAUTH_FLOW_KINDS: Readonly<Record<string, LoginSessionKind>> = {\n anthropic: 'paste-code',\n openai: 'device-code',\n 'github-copilot': 'device-code',\n xai: 'device-code',\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 try {\n await credentials.ensureReady();\n } catch {\n return undefined;\n }\n return credentials;\n}\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: 'Tenant credential storage is unavailable — the app database is not configured or failed to start.',\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}: {\n c: Context;\n auth: RouteAuth;\n /** Tenant credential domain handle; absent in local (no-DB) mode. */\n credentials?: ModelCredentialsStorage;\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), tenant.userId);\n}\n"],"mappings":";;;;;;;;;AAwCA,MAAa,uBAAmE;CAC9E,WAAW;CACX,QAAQ;CACR,kBAAkB;CAClB,KAAK;AACP;;;;;;AAWA,eAAsB,4BACpB,aAC8C;CAC9C,IAAI,CAAC,aAAa,OAAO,KAAA;CACzB,IAAI;EACF,MAAM,YAAY,YAAY;CAChC,QAAQ;EACN;CACF;CACA,OAAO;AACT;;;;;;AAOA,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;CACX,GACA,GACF,EACF;CAEF,OAAO;EAAE,MAAM;EAAU;EAAS,OAAO,YAAY,MAAM;EAAG,QAAQ,OAAO;CAAO;AACtF;;;;;;;;AASA,eAAsB,gCAAgC,EACpD,GACA,MACA,eAM0C;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,OAAO,MAAM;AACnE"}
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 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.\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 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 try {\n await credentials.ensureReady();\n } catch {\n return undefined;\n }\n return credentials;\n}\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: 'Tenant credential storage is unavailable — the app database is not configured or failed to start.',\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}: {\n c: Context;\n auth: RouteAuth;\n /** Tenant credential domain handle; absent in local (no-DB) mode. */\n credentials?: ModelCredentialsStorage;\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), tenant.userId);\n}\n"],"mappings":";;;;;;;;;;AAyCA,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;;;;;;AAWA,eAAsB,4BACpB,aAC8C;CAC9C,IAAI,CAAC,aAAa,OAAO,KAAA;CACzB,IAAI;EACF,MAAM,YAAY,YAAY;CAChC,QAAQ;EACN;CACF;CACA,OAAO;AACT;;;;;;AAOA,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;CACX,GACA,GACF,EACF;CAEF,OAAO;EAAE,MAAM;EAAU;EAAS,OAAO,YAAY,MAAM;EAAG,QAAQ,OAAO;CAAO;AACtF;;;;;;;;AASA,eAAsB,gCAAgC,EACpD,GACA,MACA,eAM0C;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,OAAO,MAAM;AACnE"}
@@ -6,6 +6,7 @@ import type { FactoryProjectsStorage } from '../storage/domains/projects/base.js
6
6
  import type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';
7
7
  import type { WorkItemsStorage } from '../storage/domains/work-items/base.js';
8
8
  import type { RouteAuth } from './route.js';
9
+ export declare const USER_SESSION_BRANCH_PREFIX = "user/session-";
9
10
  type SessionOwnerUserProvider = Pick<IUserProvider, 'getUser'> & Partial<Pick<IUserProvider, 'getUsers'>>;
10
11
  export interface SourceControlSessionRoutesOptions {
11
12
  auth: RouteAuth;
@@ -1 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iC,GAAG,QAAQ,EAAE,CA6ItG"}
@@ -351,6 +351,6 @@ function buildSourceControlSessionRoutes(options) {
351
351
  ];
352
352
  }
353
353
  //#endregion
354
- export { buildSourceControlSessionRoutes };
354
+ export { USER_SESSION_BRANCH_PREFIX, buildSourceControlSessionRoutes };
355
355
 
356
356
  //# sourceMappingURL=source-control-sessions.js.map