@mastra/factory 0.13.0-alpha.15 → 0.13.0-alpha.17

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 (67) hide show
  1. package/README.md +123 -1
  2. package/dist/auth.d.ts.map +1 -1
  3. package/dist/auth.js +2 -0
  4. package/dist/auth.js.map +1 -1
  5. package/dist/boards/define-board.d.ts.map +1 -1
  6. package/dist/boards/define-board.js +9 -2
  7. package/dist/boards/define-board.js.map +1 -1
  8. package/dist/boards/index.d.ts +1 -1
  9. package/dist/boards/review.d.ts +1 -1
  10. package/dist/boards/work.d.ts +1 -1
  11. package/dist/boards/work.js +1 -1
  12. package/dist/factory.d.ts.map +1 -1
  13. package/dist/factory.js +7 -0
  14. package/dist/factory.js.map +1 -1
  15. package/dist/integrations/github/rules.d.ts.map +1 -1
  16. package/dist/integrations/github/rules.js +7 -4
  17. package/dist/integrations/github/rules.js.map +1 -1
  18. package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -1
  19. package/dist/integrations/linear/issue-reconciler.js +1 -0
  20. package/dist/integrations/linear/issue-reconciler.js.map +1 -1
  21. package/dist/integrations/linear/rules.d.ts +2 -0
  22. package/dist/integrations/linear/rules.d.ts.map +1 -1
  23. package/dist/integrations/linear/rules.js +9 -3
  24. package/dist/integrations/linear/rules.js.map +1 -1
  25. package/dist/routes/contracts.d.ts +21 -43
  26. package/dist/routes/contracts.d.ts.map +1 -1
  27. package/dist/routes/contracts.js +3 -10
  28. package/dist/routes/contracts.js.map +1 -1
  29. package/dist/routes/telemetry.d.ts +13 -0
  30. package/dist/routes/telemetry.d.ts.map +1 -0
  31. package/dist/routes/telemetry.js +60 -0
  32. package/dist/routes/telemetry.js.map +1 -0
  33. package/dist/rules/dispatcher.d.ts.map +1 -1
  34. package/dist/rules/dispatcher.js +23 -6
  35. package/dist/rules/dispatcher.js.map +1 -1
  36. package/dist/rules/index.js +1 -1
  37. package/dist/rules/processor.d.ts.map +1 -1
  38. package/dist/rules/processor.js +17 -22
  39. package/dist/rules/processor.js.map +1 -1
  40. package/dist/rules/tools.d.ts.map +1 -1
  41. package/dist/rules/tools.js +18 -7
  42. package/dist/rules/tools.js.map +1 -1
  43. package/dist/rules/transition-service.d.ts.map +1 -1
  44. package/dist/rules/transition-service.js +2 -1
  45. package/dist/rules/transition-service.js.map +1 -1
  46. package/dist/rules/validation.d.ts +5 -0
  47. package/dist/rules/validation.d.ts.map +1 -1
  48. package/dist/rules/validation.js +21 -6
  49. package/dist/rules/validation.js.map +1 -1
  50. package/dist/storage/domains/work-items/base.d.ts +5 -0
  51. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  52. package/dist/storage/domains/work-items/base.js +8 -0
  53. package/dist/storage/domains/work-items/base.js.map +1 -1
  54. package/dist/supervisor/health.js +1 -1
  55. package/dist/supervisor/write-tools.d.ts.map +1 -1
  56. package/dist/supervisor/write-tools.js +6 -4
  57. package/dist/supervisor/write-tools.js.map +1 -1
  58. package/dist/telemetry-types.d.ts +7 -0
  59. package/dist/telemetry-types.d.ts.map +1 -0
  60. package/dist/telemetry-types.js +24 -0
  61. package/dist/telemetry-types.js.map +1 -0
  62. package/dist/telemetry.d.ts +9 -0
  63. package/dist/telemetry.d.ts.map +1 -0
  64. package/dist/telemetry.js +47 -0
  65. package/dist/telemetry.js.map +1 -0
  66. package/factory-skills/configure-factory-rules/SKILL.md +13 -1
  67. package/package.json +8 -7
package/README.md CHANGED
@@ -29,6 +29,32 @@ A host application calls `MastraFactory.prepare()`, constructs its `Mastra` inst
29
29
 
30
30
  `prepare()` initializes the Factory-owned resources needed before Mastra is constructed. `finalize()` connects those resources to the completed host, including Factory routes, integrations, storage-backed behavior, and agent-controller features. Consumers should keep frontend concerns in `factory-ui` and host-specific environment or deployment wiring in `web` rather than adding them to this package.
31
31
 
32
+ ### Product telemetry
33
+
34
+ Factory records `factory_web_activity` in Mastra's existing PostHog project for users signed in through the default `mastra-studio` auth provider. The browser sends only a known page category and an activity type to the authenticated `/web/telemetry/activity` endpoint. The server adds the verified account and deployment context.
35
+
36
+ | Property | Meaning |
37
+ | ------------------------------------- | -------------------------------------------------------------------------------- |
38
+ | `activity` | `page_view` for a visible screen, or `interaction` for pointer/keyboard activity |
39
+ | `page` | A bounded category such as `work`, `review`, or `settings`; never a URL |
40
+ | `platform_user_id`, `platform_org_id` | Opaque IDs from the authenticated platform account |
41
+ | `platform_project_id` | `MASTRA_PROJECT_ID`, when configured |
42
+ | `platform_hosted` | Whether a nonempty `MASTRA_DEPLOYMENT_ID` is present |
43
+ | `deployment_id`, `platform_region` | `MASTRA_DEPLOYMENT_ID` and `MASTRA_PLATFORM_REGION`, when configured |
44
+ | `schema_version` | `1` |
45
+
46
+ The person ID is `factory:platform:<user ID>`, consistent across local and hosted servers. This does not merge existing CLI or platform analytics profiles. A local server can have a platform project ID and use platform services while `platform_hosted` remains `false`. Non-platform hosting includes both local and other self-hosted servers; this event does not distinguish them.
47
+
48
+ Count unique people per day for visitors, and filter to `activity = interaction` for engaged users. Group by `platform_project_id` for project adoption. Interaction events are limited to once per minute per mounted browser app, and the server caps captures at 60 per minute per account/organization per process. Hidden tabs do not capture activity, and there is no background heartbeat. These are best-effort usage signals, not a record of successful product actions.
49
+
50
+ To disable collection, set this on the Factory Server:
51
+
52
+ ```bash
53
+ MASTRA_TELEMETRY_DISABLED=true
54
+ ```
55
+
56
+ `1`, `true`, and `yes` are accepted, ignoring case and surrounding whitespace. Older servers without the explicit capability do not receive browser telemetry requests. Custom auth providers are outside this initial measurement scope until they have a stable identity namespace. No names, emails, tokens, prompts, input values, raw URLs, session replay, or anonymous browser identity are collected by this event. Account IDs are identifiable account data, not anonymous data.
57
+
32
58
  ### Board lifecycle rules
33
59
 
34
60
  Installed board definitions exclusively own phase entry and exit handlers. Work and Review are installed automatically with Mastra's preferred defaults; no rule configuration is needed. Custom boards declare source-specific `onEnter` and `onExit` handlers through `defineBoard()`:
@@ -193,7 +219,103 @@ phases: {
193
219
  }
194
220
  ```
195
221
 
196
- **Remaining limitations:** Rule-decision and tool-input validation still accept only the built-in board IDs and phase names, so custom-board lifecycle handlers cannot emit `transition` or `upsertLinkedWorkItem` decisions into custom phases, and the `held-waiting` supervisor finding stays Work-specific. Throughput and lead-time metrics still count completions by Work's `done` phase. `factory-ui` still renders the built-in stage and role pipeline.
222
+ **Remaining limitations:** The `held-waiting` supervisor finding stays Work-specific. Throughput and lead-time metrics still count completions by Work's `done` phase. `factory-ui` still renders the built-in stage and role pipeline. Built-in board replacement and customization remain unsupported.
223
+
224
+ ### Execute a custom board
225
+
226
+ Installed custom boards can create linked items, start working roles, transition through bound tools, and react to completed tool results. Board and phase identifiers contain 1–128 letters, digits, underscores, or hyphens and start with a letter or digit. Identifiers are case-sensitive and cannot contain surrounding whitespace.
227
+
228
+ This configuration runs a release rehearsal through `queued → preparing → shipping → shipped`. Add it to an existing Factory host with configured storage, a GitHub integration, a connected project repository, a sandbox, and organization-scoped model credentials. Enable automatic runs for the project. The repository must contain a `release:check` package script; it should validate the release without publishing it.
229
+
230
+ ```typescript
231
+ import { MastraFactory } from '@mastra/factory';
232
+ import type { MastraFactoryConfig } from '@mastra/factory';
233
+ import { defineBoard } from '@mastra/factory/boards';
234
+ import type { BoardPhaseDefinition } from '@mastra/factory/boards';
235
+
236
+ type ReleasePhase = 'queued' | 'preparing' | 'shipping' | 'shipped';
237
+
238
+ const releaseBoard = defineBoard<'release', Record<ReleasePhase, BoardPhaseDefinition<ReleasePhase>>>({
239
+ id: 'release',
240
+ title: 'Release',
241
+ initialPhase: 'queued',
242
+ transitionPolicy: context => {
243
+ if (context.fromStage === 'queued' && context.toStage === 'preparing' && !context.isHumanTransition) {
244
+ return {
245
+ type: 'reject',
246
+ code: 'approval_required',
247
+ reason: 'A person must start the release rehearsal.',
248
+ };
249
+ }
250
+ },
251
+ phases: {
252
+ queued: { title: 'Queued', kind: 'resting', next: 'preparing' },
253
+ preparing: {
254
+ title: 'Preparing',
255
+ kind: 'working',
256
+ role: 'release-preparer',
257
+ next: 'shipping',
258
+ onEnter: {
259
+ issue: context => ({
260
+ type: 'invokeSkill',
261
+ idempotencyKey: `${context.ingress.id}:prepare`,
262
+ role: 'release-preparer',
263
+ prompt:
264
+ 'Inspect the release changes. When ready, call factory_transition_work_item with stage shipping and the current expectedRevision from the Factory phase signal.',
265
+ }),
266
+ },
267
+ },
268
+ shipping: {
269
+ title: 'Shipping',
270
+ kind: 'working',
271
+ role: 'release-publisher',
272
+ next: 'shipped',
273
+ onEnter: {
274
+ issue: context => ({
275
+ type: 'invokeSkill',
276
+ idempotencyKey: `${context.ingress.id}:check`,
277
+ role: 'release-publisher',
278
+ prompt:
279
+ 'Run npm run release:check && printf "RELEASE_CHECK_PASSED\\n" with execute_command. This is a rehearsal; do not publish anything.',
280
+ }),
281
+ },
282
+ },
283
+ shipped: { title: 'Shipped', kind: 'terminal' },
284
+ },
285
+ tools: {
286
+ execute_command: {
287
+ onResult: context => {
288
+ if (
289
+ context.item.stages[0] !== 'shipping' ||
290
+ context.result.status !== 'success' ||
291
+ typeof context.result.value !== 'string' ||
292
+ !context.result.value.trimEnd().endsWith('RELEASE_CHECK_PASSED')
293
+ ) {
294
+ return;
295
+ }
296
+ return {
297
+ type: 'transition',
298
+ idempotencyKey: `${context.ingress.id}:checked`,
299
+ board: 'release',
300
+ stage: 'shipped',
301
+ };
302
+ },
303
+ },
304
+ },
305
+ });
306
+
307
+ export function createFactory(config: Omit<MastraFactoryConfig, 'boards' | 'includeDefaultBoards'>) {
308
+ return new MastraFactory({ ...config, boards: [releaseBoard], includeDefaultBoards: true });
309
+ }
310
+ ```
311
+
312
+ Use the host's normal `prepare()`, `new Mastra(...)`, and `finalize()` sequence. Change the hardcoded `includeDefaultBoards: true` in `createFactory` to `false` to run without Work or Review. Working roles name bindings on the shared Code Agent; they do not register separate agents. Factory has no per-role agent configuration option. The board's kickoff prompts supply the role-specific instructions.
313
+
314
+ Create a card with `POST /web/factory/projects/:id/work-items`, passing `board: 'release'`, a title, and the GitHub issue's `externalSource`. The card starts in `queued`. Then use `POST /web/factory/projects/:id/work-items/:workItemId/transition` with `board: 'release'`, `stage: 'preparing'`, the returned `expectedRevision`, a unique `requestId`, and a `cause`. Send these requests as an authorized user using the host's authentication. The human transition satisfies this board's policy and starts the preparer. Its bound tool advances to `shipping`; the publisher's completed check produces a deferred transition to `shipped`. Terminal entry revokes the binding and releases the sandbox. Check the persisted card's board, phase, and deferred decision status rather than relying on the built-in UI pipeline.
315
+
316
+ Lifecycle, tool-result, and integration handlers may return `upsertLinkedWorkItem` targeting a different installed board. Linked cards enter that board's declared initial phase before moving to the requested phase. Existing cards cannot be reassigned to another board through either decision type. Targets are validated against their own installed board before acceptance and again before uncommitted deferred effects execute; a phase declared only on another board is not valid. Committed replay retains its recorded result and original `configVersion`.
317
+
318
+ Custom phase signals and persisted tool-result ingestion use the item's installed board. Bound tools re-resolve the live binding, retain revision and topology checks, and reject session reassignment. A custom role named `triage` does not inherit Work's classification requirements. Existing authorization, external-author safeguards, and board-owned policies still apply.
197
319
 
198
320
  ### GitHub event rules
199
321
 
@@ -1 +1 @@
1
- {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAWvD,OAAO,KAAK,EAAE,QAAQ,EAAE,mBAAmB,EAAoB,MAAM,qBAAqB,CAAC;AAC3F,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAG1C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAMnD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,2EAA2E;AAC3E,MAAM,WAAW,eAAe;IAC9B,gFAAgF;IAChF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,yFAAyF;IACzF,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,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AAQ,EAAE,mBAAmB,GAAG,SAAS,EACzC,CAAC,EAAE,OAAO,GACT,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,CAoBtC;AAED,MAAM,WAAW,uBAAuB;IACtC;;;;OAIG;IACH,QAAQ,CAAC,EAAE,mBAAmB,CAAC;IAC/B;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iEAAiE;IACjE,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AA2RD;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EACd,QAAQ,EAAE,mBAAmB,EAC7B,OAAO,GAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAO,GACnC,IAAI,CAMN;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,mBAAmB,EAAE,OAAO,GAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,QAAQ,EAAE,CAmB/G;AAkBD;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,mBAAmB,IACnD,GAAG,OAAO,EAAE,MAAM,MAAM,OAAO,CAAC,IAAI,CAAC,KAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAmF/E;AAED;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,OAAO,GAAE,uBAA4B,GAAG,OAAO,CAO/F"}
package/dist/auth.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { actorFromAuthUser } from "./storage/domains/comments/actor.js";
2
+ import { isFactoryTelemetryEnabled } from "./telemetry.js";
2
3
  import { timedAboveThreshold } from "./timing.js";
3
4
  import { MastraAuthWorkos } from "@mastra/auth-workos";
4
5
  import { MASTRA_MESSAGE_AUTHOR_KEY } from "@mastra/core/request-context";
@@ -300,6 +301,7 @@ async function handleAuthMe(provider, c) {
300
301
  await ensureUserOrg(provider, user);
301
302
  return c.json({
302
303
  authenticated: true,
304
+ telemetryEnabled: isFactoryTelemetryEnabled(provider.name),
303
305
  user: {
304
306
  userId: getFactoryAuthUserId(user),
305
307
  email: user.email,
package/dist/auth.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"auth.js","names":[],"sources":["../src/auth.ts"],"sourcesContent":["import { MastraAuthWorkos } from '@mastra/auth-workos';\nimport type { MessageAuthor } from '@mastra/core/agent-controller';\nimport { MASTRA_MESSAGE_AUTHOR_KEY } from '@mastra/core/request-context';\nimport {\n registerApiRoute,\n isAuthHttpHandler,\n isCredentialsProvider,\n isOrganizationsProvider,\n isSessionProvider,\n isSSOProvider,\n} from '@mastra/core/server';\nimport type { ApiRoute, IMastraAuthProvider, ISessionProvider } from '@mastra/core/server';\nimport type { Context, Hono } from 'hono';\nimport { HTTPException } from 'hono/http-exception';\n\nimport type { RouteAuth } from './routes/route.js';\nimport { actorFromAuthUser } from './storage/domains/comments/actor.js';\nimport { timedAboveThreshold } from './timing.js';\n\nconst ORGANIZATION_ID_HEADER = 'X-Mastra-Organization-Id';\n\n/**\n * Provider-neutral factory auth gating for the MastraCode web server.\n *\n * When an auth provider is active (a `MastraAuthProvider` instance passed to\n * `MastraFactory`'s `auth` slot, or — back-compat for suites/paths that never\n * boot the factory — implied by the WorkOS env vars), every route on the web\n * server is placed behind it: unauthenticated browser navigations are\n * redirected to the SPA's `/signin` page, API/XHR calls receive a 401, and a\n * small set of public routes stay reachable while signed out — the provider's\n * `/auth/*` routes plus `/auth/me`, the `/signin` page, its `/assets/*` bundle,\n * and the SPA manifest metadata. When no provider is active, `mountFactoryAuth` is a no-op and the server\n * behaves exactly as it does without auth.\n *\n * Provider specifics stay in the providers (`@mastra/auth-workos`,\n * `@mastra/auth-better-auth`, or any custom `IMastraAuthProvider`); this\n * module composes them capability-first via the core type guards:\n * - `authenticateToken` — session/bearer validation (all providers)\n * - `ISSOProvider` — hosted-login `/auth/login`, `/auth/callback`, `/auth/logout`\n * - `IAuthHttpHandler` — provider-owned `/auth/api/*` endpoints (better-auth)\n * - `IOrganizationsProvider` — personal-org bootstrap + admin checks\n * - `ICredentialsProvider.isSignUpEnabled` — SPA sign-up affordance\n * - `getClearSessionHeaders` — session cookie clearing on logout\n */\n\n/** Minimal shape of the signed-in user surfaced to the SPA (no tokens). */\nexport interface FactoryAuthUser {\n /** Stable WorkOS user id used to scope per-user data (GitHub installs etc.). */\n workosId?: string;\n /** Provider user id; WorkOS shapes may use `workosId` instead (see {@link workosId}). */\n id?: string;\n email?: string;\n name?: string;\n /** Provider-supplied profile picture URL, when the auth provider exposes one. */\n avatarUrl?: string;\n /**\n * Organization id. The org is the top-level tenant: it owns the GitHub\n * App installation and connected projects, while each user inside the org gets\n * isolated building instances. Absent for personal (no-org) accounts.\n */\n organizationId?: string;\n /** Organization ids proven by the provider's authenticated membership response. */\n organizationMembershipIds?: string[];\n}\n\n/**\n * Tenant identity: the org is the top-level tenant, and each user inside it is\n * an isolated builder. Agent state, worktrees and sandboxes are scoped per\n * `(orgId, userId)`. Personal (no-org) users have `orgId === undefined`.\n */\nexport interface FactoryAuthTenant {\n /** Organization id, or `undefined` for personal (no-org) accounts. */\n orgId?: string;\n /** Stable provider user id. */\n userId: string;\n}\n\n/**\n * Validate that a `returnTo` value is a safe same-site path, to prevent\n * open-redirect attacks. Only absolute local paths (`/foo`) are allowed;\n * protocol-relative (`//evil.com`) and absolute URLs are rejected.\n */\nexport function sanitizeReturnTo(raw: string | undefined): string {\n if (!raw) return '/';\n if (!raw.startsWith('/')) return '/';\n // Reject protocol-relative URLs like \"//evil.com\" and \"/\\evil.com\".\n if (raw.startsWith('//') || raw.startsWith('/\\\\')) return '/';\n return raw;\n}\n\n/** Extract a bearer token from the Authorization header, if present. */\nexport function getBearerToken(authorization: string | undefined): string {\n if (!authorization) return '';\n const match = /^Bearer\\s+(.+)$/i.exec(authorization);\n return match?.[1] ?? '';\n}\n\n/**\n * Whether the SPA is served cross-origin from this API (platform deploy). When\n * `MASTRACODE_ALLOWED_ORIGINS` is set the browser talks to us cross-site, so\n * session cookies must be `SameSite=None; Secure` for the browser to send them.\n * Same-origin local dev leaves this unset and keeps the stricter `SameSite=Lax`.\n */\nexport function isCrossSiteAuth(): boolean {\n return Boolean(process.env.MASTRACODE_ALLOWED_ORIGINS?.trim());\n}\n\n/** Hono context variables set by the auth gate. */\nexport interface FactoryAuthVariables {\n factoryAuthUser: FactoryAuthUser;\n}\n\n/** Context key under which the gate stashes the authenticated user. */\nconst FACTORY_AUTH_USER_KEY = 'factoryAuthUser';\n\n/**\n * Read the authenticated user the gate stashed on the context, or\n * `undefined` when unauthenticated / auth disabled. Used by downstream routes\n * (e.g. GitHub) to scope rows per user.\n */\nexport function getFactoryAuthUser(c: Context): FactoryAuthUser | undefined {\n return c.get(FACTORY_AUTH_USER_KEY) as FactoryAuthUser | undefined;\n}\n\n/**\n * Read the authenticated user off a request context, normalizing whatever the\n * active auth provider put there.\n *\n * The server's auth layer writes the provider's `authenticateToken` result into\n * the request context's `user` slot verbatim, so the value's shape follows the\n * provider: WorkOS writes a flat user, better-auth writes a `{ session, user }`\n * wrapper whose org lives on the session. Reading that slot as a\n * {@link FactoryAuthUser} therefore yields `undefined` for both the id and the\n * org under better-auth, which reads as \"this session belongs to somebody else\"\n * at every ownership check. Normalize on the way in instead.\n */\nexport function getFactoryAuthUserFromContext(\n requestContext: { get: (key: string) => unknown } | undefined,\n): FactoryAuthUser | undefined {\n if (!requestContext || typeof requestContext.get !== 'function') return undefined;\n return toFactoryAuthUser(requestContext.get('user')) ?? undefined;\n}\n\n/** Resolve the stable user id from an authenticated user shape. */\nexport function getFactoryAuthUserId(user: FactoryAuthUser | undefined): string | undefined {\n return user?.workosId ?? user?.id;\n}\n\n/** Resolve the organization id from a user shape, if present. */\nexport function getFactoryAuthOrgId(user: FactoryAuthUser | undefined): string | undefined {\n return user?.organizationId;\n}\n\n/**\n * Resolve the tenant identity `(orgId, userId)` from the authenticated user on\n * the context. Returns `undefined` when there is no signed-in user (auth\n * disabled or unauthenticated). `orgId` is `undefined` for personal accounts;\n * callers gate org-scoped GitHub features on its presence while agent state\n * falls back to a user-only tenant.\n */\nexport function factoryAuthTenant(c: Context): FactoryAuthTenant | undefined {\n const user = getFactoryAuthUser(c);\n const userId = getFactoryAuthUserId(user);\n if (!userId) return undefined;\n return { orgId: getFactoryAuthOrgId(user), userId };\n}\n\nfunction messageAuthor(user: FactoryAuthUser): MessageAuthor | undefined {\n const userId = getFactoryAuthUserId(user);\n if (!userId) return undefined;\n const actor = actorFromAuthUser(userId, user);\n return {\n id: actor.id,\n ...(actor.displayName ? { name: actor.displayName } : {}),\n ...(actor.avatarUrl ? { avatarUrl: actor.avatarUrl } : {}),\n };\n}\n\n/** True when both WorkOS credential env vars are present (legacy env gate). */\nfunction envWorkosConfigured(): boolean {\n return Boolean(process.env.WORKOS_API_KEY && process.env.WORKOS_CLIENT_ID);\n}\n\n/**\n * WorkOS provider implied by the `WORKOS_*` env vars — back-compat for test\n * suites exercised without booting the factory (route suites set `WORKOS_*`\n * directly and call {@link mountFactoryAuth} without an explicit provider).\n * `fetchMemberships: true` lets `authenticateToken` resolve `organizationId`\n * from a single membership when the JWT has no org claim — required so a\n * bootstrapped personal org resolves without re-auth.\n */\nfunction envFallbackAuthProvider(redirectUri: string | undefined): MastraAuthWorkos | undefined {\n if (!envWorkosConfigured()) return undefined;\n return new MastraAuthWorkos({\n redirectUri: redirectUri ?? process.env.WORKOS_REDIRECT_URI,\n fetchMemberships: true,\n });\n}\n\n/**\n * Map a provider `authenticateToken` result onto the neutral SPA user shape.\n *\n * Two result families exist today:\n * - flat provider users (WorkOS `WorkOSUser` et al.): `id`/`workosId`/`email`/\n * `name`/`organizationId` directly on the object;\n * - session-shaped results (better-auth `BetterAuthUser`): `{ session, user }`\n * with the active org on the session.\n */\nfunction toFactoryAuthUser(result: unknown): FactoryAuthUser | null {\n if (!result || typeof result !== 'object') return null;\n const record = result as Record<string, unknown>;\n\n // Session-shaped results: { session, user }. A result carrying both halves and\n // top-level identity fields is read as session-shaped: the session half is the\n // authenticated one, and preferring it keeps the org and the id from coming\n // from two different places.\n if (record.user && typeof record.user === 'object' && record.session && typeof record.session === 'object') {\n const user = record.user as { id?: unknown; email?: unknown; name?: unknown; avatarUrl?: unknown };\n const session = record.session as { activeOrganizationId?: unknown };\n if (typeof user.id !== 'string') return null;\n return {\n id: user.id,\n email: typeof user.email === 'string' ? user.email : undefined,\n name: typeof user.name === 'string' ? user.name : undefined,\n avatarUrl: typeof user.avatarUrl === 'string' ? user.avatarUrl : undefined,\n organizationId: typeof session.activeOrganizationId === 'string' ? session.activeOrganizationId : undefined,\n };\n }\n\n // Flat provider users.\n const flat = record as {\n id?: unknown;\n workosId?: unknown;\n email?: unknown;\n name?: unknown;\n avatarUrl?: unknown;\n organizationId?: unknown;\n memberships?: unknown;\n memberOrgIds?: unknown;\n };\n const id = typeof flat.id === 'string' ? flat.id : undefined;\n const workosId = typeof flat.workosId === 'string' ? flat.workosId : undefined;\n if (!id && !workosId) return null;\n const membershipOrganizationIds = Array.isArray(flat.memberships)\n ? flat.memberships.flatMap(membership => {\n if (!membership || typeof membership !== 'object') return [];\n const organizationId = (membership as { organizationId?: unknown }).organizationId;\n return typeof organizationId === 'string' ? [organizationId] : [];\n })\n : [];\n const memberOrgIds = Array.isArray(flat.memberOrgIds)\n ? flat.memberOrgIds.filter((organizationId): organizationId is string => typeof organizationId === 'string')\n : [];\n const organizationMembershipIds = [...new Set([...membershipOrganizationIds, ...memberOrgIds])];\n return {\n id,\n workosId,\n email: typeof flat.email === 'string' ? flat.email : undefined,\n name: typeof flat.name === 'string' ? flat.name : undefined,\n avatarUrl: typeof flat.avatarUrl === 'string' ? flat.avatarUrl : undefined,\n organizationId: typeof flat.organizationId === 'string' ? flat.organizationId : undefined,\n organizationMembershipIds,\n };\n}\n\n/**\n * Resolve the authenticated user for a request via the provider. Never throws:\n * ordinary invalid/expired sessions resolve to `null`.\n */\nasync function authenticateRequest(\n provider: IMastraAuthProvider,\n token: string,\n raw: Request,\n): Promise<FactoryAuthUser | null> {\n try {\n const result = await provider.authenticateToken(token, raw);\n return toFactoryAuthUser(result);\n } catch {\n return null;\n }\n}\n\n/**\n * Bootstrap a personal org for no-org accounts so org-scoped features (GitHub\n * connect) work without leaving the app. Mutates the resolved user so the\n * current request sees the org immediately; subsequent requests resolve it via\n * the provider's own session/membership lookup (providers cache internally).\n * Best-effort: providers swallow their own bootstrap failures, and any\n * unexpected throw leaves the user no-org.\n */\nasync function ensureUserOrg(provider: IMastraAuthProvider, user: FactoryAuthUser): Promise<void> {\n if (getFactoryAuthOrgId(user)) return;\n if (!isOrganizationsProvider(provider)) return;\n const userId = getFactoryAuthUserId(user);\n if (!userId) return;\n try {\n const orgId = await provider.ensureOrganization(userId);\n if (orgId) user.organizationId = orgId;\n } catch {\n // Best-effort: the user stays no-org until a later request succeeds.\n }\n}\n\nfunction selectRequestedOrganization(user: FactoryAuthUser, requestedOrganizationId: string): boolean {\n if (user.organizationId === requestedOrganizationId) return true;\n if (!user.organizationMembershipIds?.includes(requestedOrganizationId)) return false;\n user.organizationId = requestedOrganizationId;\n return true;\n}\n\n/**\n * `Set-Cookie` values that clear the provider's session cookie(s), from the\n * provider's (possibly partial) `ISessionProvider.getClearSessionHeaders`.\n */\nfunction providerClearCookies(provider: IMastraAuthProvider): string[] {\n const getClearSessionHeaders = (provider as Partial<ISessionProvider>).getClearSessionHeaders;\n if (typeof getClearSessionHeaders !== 'function') return [];\n const headers = getClearSessionHeaders.call(provider) ?? {};\n const setCookie = headers['Set-Cookie'];\n if (!setCookie) return [];\n // A provider may join several clearing cookies into one header value.\n return setCookie.split(/,(?=\\s*[^;=,\\s]+=)/).map(cookie => cookie.trim());\n}\n\n/**\n * Fail-closed authorization for organization-level administrative mutations.\n * The caller must belong to the same active organization and the provider must\n * explicitly confirm an admin/owner role.\n */\nexport async function isOrganizationAdmin(\n provider: IMastraAuthProvider | undefined,\n c: Context,\n organizationId: string,\n): Promise<boolean> {\n const user = await ensureFactoryAuthUser(provider, c);\n if (!user || user.organizationId !== organizationId || !provider || !isOrganizationsProvider(provider)) {\n return false;\n }\n const userId = getFactoryAuthUserId(user);\n if (!userId) return false;\n try {\n return await provider.isOrganizationAdmin(organizationId, userId);\n } catch {\n return false;\n }\n}\n\n/**\n * Build the factory's implementation of the `RouteAuth` seam over the\n * resolved provider (`undefined` = auth disabled). Constructed once per boot\n * by `MastraFactory.prepare()` and handed to factory route modules at\n * construction — they never import the factory auth module directly.\n */\nexport function createFactoryRouteAuth(provider: IMastraAuthProvider | undefined): RouteAuth {\n return {\n enabled: () => provider !== undefined,\n ensureUser: (c: Context) => ensureFactoryAuthUser(provider, c),\n tenant: (c: Context) => factoryAuthTenant(c),\n isOrganizationAdmin: (c: Context, organizationId: string) => isOrganizationAdmin(provider, c, organizationId),\n };\n}\n\n/** True when the given provider is WorkOS. Gates WorkOS-only capabilities. */\nexport function isWorkOSAuth(provider: IMastraAuthProvider | undefined): boolean {\n return provider instanceof MastraAuthWorkos;\n}\n\n/**\n * The raw WorkOS provider, for features that need the WorkOS client directly\n * (audit-log export, Admin Portal links). Callers must gate on\n * {@link isWorkOSAuth} first — throws when the provider is not WorkOS.\n */\nexport function getWorkOSProvider(provider: IMastraAuthProvider | undefined): MastraAuthWorkos {\n if (provider instanceof MastraAuthWorkos) return provider;\n throw new Error('WorkOS provider requested but the active factory auth provider is not WorkOS');\n}\n\n/**\n * Resolve the authenticated user for a request, stashing it on the context.\n *\n * The gate only authenticates non-`/auth/*` requests via the `Authorization`\n * header, so cookie-based browser navigations to public `/auth/*` routes (the\n * GitHub connect/callback flow) arrive without a gate-stashed user. This reads\n * the session cookie from the raw request the same way `/auth/me` does,\n * caches the result on the context, and returns it so downstream helpers like\n * {@link factoryAuthTenant} work uniformly on both gated and public routes.\n *\n * Returns `undefined` when there is no valid session (or auth is disabled).\n */\nexport async function ensureFactoryAuthUser(\n provider: IMastraAuthProvider | undefined,\n c: Context,\n): Promise<FactoryAuthUser | undefined> {\n const existing = getFactoryAuthUser(c);\n if (existing) return existing;\n if (!provider) return undefined;\n\n const token = getBearerToken(c.req.header('Authorization'));\n const user = await authenticateRequest(provider, token, c.req.raw);\n if (!user) return undefined;\n\n const requestedOrganizationId = token ? c.req.header(ORGANIZATION_ID_HEADER)?.trim() : undefined;\n if (requestedOrganizationId) {\n if (!selectRequestedOrganization(user, requestedOrganizationId)) {\n throw new HTTPException(403, { message: 'organization_forbidden' });\n }\n } else {\n await ensureUserOrg(provider, user);\n }\n\n c.set(FACTORY_AUTH_USER_KEY, user);\n return user;\n}\n\nexport interface MountFactoryAuthOptions {\n /**\n * Explicit auth provider to mount. When omitted, falls back to a WorkOS\n * provider implied by the `WORKOS_*` env vars (back-compat for suites that\n * never boot the factory).\n */\n provider?: IMastraAuthProvider;\n /**\n * Absolute URL the identity provider redirects back to after login (WorkOS\n * env-fallback path only). Defaults to the `WORKOS_REDIRECT_URI` env var.\n */\n redirectUri?: string;\n /** Browser-facing origin used to derive the SSO callback URL. */\n publicUrl?: string;\n}\n\n/**\n * Decide whether a request is a top-level browser navigation (which should be\n * redirected to `/signin`) versus an API/XHR call (which should get a 401 JSON\n * response the SPA can react to).\n */\nfunction isNavigationRequest(path: string, accept: string | undefined): boolean {\n if (path.startsWith('/api/')) return false;\n return (accept ?? '').includes('text/html');\n}\n\n/**\n * Handle the provider-neutral `/auth/me` route: validate the session with the\n * active provider and report the signed-in user (no tokens) to the SPA.\n * `/auth/me` is public (the gate skips `/auth/*`), so it validates the session\n * itself rather than reading a value the gate would have stashed.\n */\nasync function handleAuthMe(provider: IMastraAuthProvider, c: Context): Promise<Response> {\n const token = getBearerToken(c.req.header('Authorization'));\n const user = await authenticateRequest(provider, token, c.req.raw);\n // Provider identity for the SPA: `/signin` renders the hosted-login button\n // for WorkOS and an email/password form for better-auth (with sign-up hidden\n // when the provider disables it).\n const signUpDisabled = isCredentialsProvider(provider) && provider.isSignUpEnabled?.() === false;\n const meta = { provider: provider.name, ...(signUpDisabled ? { signUpDisabled: true } : {}) };\n if (!user) {\n return c.json({ authenticated: false, user: null, ...meta });\n }\n // Resolve the org the same way gated requests do (providers cache, so this\n // is a lookup — not a create — after first bootstrap).\n await ensureUserOrg(provider, user);\n return c.json({\n authenticated: true,\n user: {\n userId: getFactoryAuthUserId(user),\n email: user.email,\n name: user.name,\n avatarUrl: user.avatarUrl,\n organizationId: user.organizationId,\n },\n ...meta,\n });\n}\n\n/**\n * Encode a validated returnTo path into the OAuth `state` parameter.\n *\n * Pipe format (`uuid|encodedPath`) is the contract `MastraAuthStudio` parses\n * to forward the path as the platform's `post_login_redirect`; a JSON blob\n * here silently degrades every post-login redirect to `/`.\n */\nfunction encodeState(returnTo: string): string {\n return `${crypto.randomUUID()}|${encodeURIComponent(returnTo)}`;\n}\n\n/** Decode the OAuth `state` parameter back into a sanitized returnTo path. */\nfunction decodeState(state: string | undefined): string {\n if (!state) return '/';\n const pipeIndex = state.indexOf('|');\n if (pipeIndex !== -1) {\n try {\n return sanitizeReturnTo(decodeURIComponent(state.slice(pipeIndex + 1)));\n } catch {\n return '/';\n }\n }\n return '/';\n}\n\n/**\n * Short-lived cookie stashing the post-login destination across the hosted\n * OAuth round-trip. Providers/platforms differ in whether they echo `state`\n * back to the callback, so the cookie is the reliable channel; `state` (when\n * echoed) takes precedence only if the cookie is missing.\n */\nconst RETURN_TO_COOKIE = 'mastra_factory_return_to';\n\nfunction returnToCookieHeader(returnTo: string): string {\n const crossSite = isCrossSiteAuth() ? '; SameSite=None; Secure' : '; SameSite=Lax';\n return `${RETURN_TO_COOKIE}=${encodeURIComponent(returnTo)}; Path=/; Max-Age=600; HttpOnly${crossSite}`;\n}\n\nfunction clearReturnToCookieHeader(): string {\n const crossSite = isCrossSiteAuth() ? '; SameSite=None; Secure' : '; SameSite=Lax';\n return `${RETURN_TO_COOKIE}=; Path=/; Max-Age=0; HttpOnly${crossSite}`;\n}\n\nfunction readReturnToCookie(c: Context): string | undefined {\n const header = c.req.header('Cookie');\n if (!header) return undefined;\n for (const part of header.split(';')) {\n const [name, ...rest] = part.trim().split('=');\n if (name === RETURN_TO_COOKIE) {\n try {\n return decodeURIComponent(rest.join('='));\n } catch {\n return undefined;\n }\n }\n }\n return undefined;\n}\n\n/** HTTP methods supported for public auth routes. */\ntype AuthRouteMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL';\n\n/** A public `/auth/*` route derived from the provider's capabilities. */\ninterface AuthRouteSpec {\n path: string;\n method: AuthRouteMethod;\n handler: (c: Context) => Response | Promise<Response>;\n}\n\n/**\n * Derive the public `/auth/*` routes from the provider's capabilities:\n *\n * - `IAuthHttpHandler` → `ALL /auth/api/*` proxy to the provider's own HTTP\n * surface (better-auth sign-in/up/out/session — what the SPA's\n * email/password form posts to).\n * - `ISSOProvider` → hosted-login `GET /auth/login` / `GET /auth/callback` /\n * `GET /auth/logout` (returnTo preserved through the OAuth `state` param).\n * - handler-shaped, non-SSO providers → `GET /auth/login` redirects to the\n * SPA's `/signin` form, `GET /auth/logout` revokes via the provider's\n * sign-out endpoint and clears the session cookie.\n */\nfunction providerAuthRoutes(provider: IMastraAuthProvider, publicUrl?: string): AuthRouteSpec[] {\n const routes: AuthRouteSpec[] = [];\n\n if (isAuthHttpHandler(provider)) {\n routes.push({\n path: '/auth/api/*',\n method: 'ALL',\n handler: c => provider.handleAuthRequest(c.req.raw),\n });\n }\n\n if (isSSOProvider(provider)) {\n routes.push(\n {\n path: '/auth/login',\n method: 'GET',\n handler: async c => {\n const returnTo = sanitizeReturnTo(c.req.query('returnTo'));\n const state = encodeState(returnTo);\n // Build the callback URL from the browser-facing public origin so\n // the OAuth round-trip lands back on the SPA's origin (in dev the\n // SPA is on :5173 and Vite proxies /auth/* to the API on :4111 —\n // deriving from c.req.url would use :4111 and the post-callback\n // redirect to `/` would miss the SPA). Providers that ignore the\n // caller's URI in favor of their own config (e.g. MastraAuthWorkos\n // with an explicit `redirectUri` option) still take precedence.\n const redirectUri = publicUrl ? new URL('/auth/callback', publicUrl).toString() : '';\n const loginUrl = await provider.getLoginUrl(redirectUri, state);\n for (const cookie of (await provider.getLoginCookies?.(redirectUri, state)) ?? []) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n // Stash the destination in a cookie too: not every provider/platform\n // echoes `state` back to the callback.\n if (returnTo !== '/') {\n c.header('Set-Cookie', returnToCookieHeader(returnTo), { append: true });\n }\n return c.redirect(loginUrl);\n },\n },\n {\n path: '/auth/callback',\n method: 'GET',\n handler: async c => {\n const code = c.req.query('code');\n const stateReturnTo = decodeState(c.req.query('state'));\n const cookieReturnTo = sanitizeReturnTo(readReturnToCookie(c));\n const returnTo = cookieReturnTo !== '/' ? cookieReturnTo : stateReturnTo;\n c.header('Set-Cookie', clearReturnToCookieHeader(), { append: true });\n const idpError = c.req.query('error');\n if (idpError) {\n // IdP denial (e.g. access_denied for a non-org-member): bouncing to\n // /auth/login would re-enter the IdP in a redirect loop.\n const query = new URLSearchParams({ error: idpError.slice(0, 64) });\n const description = c.req.query('error_description');\n if (description) query.set('error_description', description.slice(0, 256));\n if (returnTo !== '/') query.set('returnTo', returnTo);\n return c.redirect(`/signin?${query.toString()}`);\n }\n if (!code) {\n return c.redirect('/auth/login');\n }\n try {\n const result = await provider.handleCallback(code, c.req.query('state') ?? '');\n if (result.cookies?.length) {\n // Provider populated cookies directly (e.g. WorkOS AuthKit builds\n // its own sealed session cookie inside handleCallback).\n for (const cookie of result.cookies) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n } else if (isSessionProvider(provider) && result.tokens) {\n // Fallback for providers that expose ISessionProvider but leave\n // cookie construction to the server (e.g. MastraAuthStudio, which\n // returns just the sealed session as accessToken so\n // getSessionHeaders can scope the cookie to this deployment's\n // domain via MASTRA_COOKIE_DOMAIN / sharedApiUrl auto-detection).\n // Mirrors packages/server/src/server/handlers/auth.ts:492-503.\n const resultUser = result.user as { id: string; organizationId?: string };\n const session = await provider.createSession(resultUser.id, {\n accessToken: result.tokens.accessToken,\n refreshToken: result.tokens.refreshToken,\n expiresAt: result.tokens.expiresAt,\n organizationId: resultUser.organizationId,\n });\n for (const [key, value] of Object.entries(provider.getSessionHeaders(session))) {\n c.header(key, value, { append: true });\n }\n }\n return c.redirect(returnTo);\n } catch {\n // Code exchange failed (expired/replayed code, misconfig). Send the\n // user back to login rather than surfacing a raw error.\n return c.redirect('/auth/login');\n }\n },\n },\n {\n path: '/auth/logout',\n method: 'GET',\n handler: async c => {\n let logoutUrl: string | null = null;\n try {\n logoutUrl = (await provider.getLogoutUrl?.('/', c.req.raw)) ?? null;\n } catch {\n logoutUrl = null;\n }\n // Clear the session cookie regardless of whether the provider\n // returned a logout URL.\n for (const cookie of providerClearCookies(provider)) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n return c.redirect(logoutUrl ?? '/');\n },\n },\n );\n } else if (isAuthHttpHandler(provider)) {\n routes.push(\n {\n // Hosted-login equivalent: no hosted page, so send the browser to the\n // SPA's /signin form, preserving returnTo.\n path: '/auth/login',\n method: 'GET',\n handler: c => {\n const returnTo = sanitizeReturnTo(c.req.query('returnTo'));\n return c.redirect(`/signin?returnTo=${encodeURIComponent(returnTo)}`);\n },\n },\n {\n path: '/auth/logout',\n method: 'GET',\n handler: async c => {\n // Revoke the session server-side through the provider's own sign-out\n // endpoint and forward its clearing cookies; fall back to our clear\n // cookies regardless.\n try {\n const origin = new URL(c.req.url).origin;\n const response = await provider.handleAuthRequest(\n new Request(`${origin}/auth/api/sign-out`, { method: 'POST', headers: c.req.raw.headers }),\n );\n for (const cookie of response.headers.getSetCookie()) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n } catch {\n // No/invalid session: nothing to revoke.\n }\n for (const cookie of providerClearCookies(provider)) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n return c.redirect('/');\n },\n },\n );\n }\n\n return routes;\n}\n\n/**\n * Register the public `/auth/*` routes on a Hono app: the capability-derived\n * provider routes (login/callback/logout/provider APIs) plus the\n * provider-neutral `/auth/me`. Split out from `mountFactoryAuth` so both the local\n * Hono server and the platform Mastra entry can reuse the exact same handlers.\n */\nexport function registerAuthRoutes(\n app: Hono<any>,\n provider: IMastraAuthProvider,\n options: { publicUrl?: string } = {},\n): void {\n for (const route of providerAuthRoutes(provider, options.publicUrl)) {\n const methods = route.method === 'ALL' ? ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] : [route.method];\n app.on(methods, route.path, c => route.handler(c));\n }\n app.get('/auth/me', c => handleAuthMe(provider, c));\n}\n\n/**\n * Build the public `/auth/*` routes (provider routes + `/auth/me`) as Mastra\n * `server.apiRoutes`. Used by the platform Mastra entry (`src/mastra/index.ts`),\n * which can't register plain Hono routes on the deployer-generated app the way\n * the local server does via {@link registerAuthRoutes}.\n *\n * Handlers are identical to {@link registerAuthRoutes}. All are `requiresAuth: false`\n * (they must be reachable while unauthenticated), and the gate middleware skips\n * `/auth/*` so it never blocks them. `/auth/*` is not under `/api`, so it is a\n * valid custom-route path.\n */\nexport function buildAuthRoutes(provider: IMastraAuthProvider, options: { publicUrl?: string } = {}): ApiRoute[] {\n return [\n // `registerApiRoute` handlers see @mastra/core's bundled hono Context type,\n // which is structurally identical to (but nominally distinct from) the\n // local hono version the route handlers are typed against — cast across\n // the seam.\n ...providerAuthRoutes(provider, options.publicUrl).map(route =>\n registerApiRoute(route.path, {\n method: route.method,\n requiresAuth: false,\n handler: c => route.handler(c as unknown as Context),\n }),\n ),\n registerApiRoute('/auth/me', {\n method: 'GET',\n requiresAuth: false,\n handler: c => handleAuthMe(provider, c as unknown as Context),\n }),\n ];\n}\n\n/**\n * Channel webhook paths whose adapter verifies the platform's request signature,\n * making the delivery self-authenticating. Add a platform here only once its\n * adapter rejects unsigned or mis-signed requests.\n */\nconst SIGNATURE_VERIFYING_CHANNEL_WEBHOOK = /^\\/api\\/agent-controllers\\/[^/]+\\/channels\\/slack\\/webhook$/;\n\n// Fetched by tabs that may already be signed out. Enumerated, not prefix-matched,\n// so a future route under the same prefix does not inherit the pass.\nconst SESSION_FAVICON_PATHS = new Set([\n '/favicon-session-initializing.svg',\n '/favicon-session-working.svg',\n '/favicon-session-awaiting.svg',\n '/favicon-session-error.svg',\n]);\n\n/**\n * Build the auth gate as a plain Hono middleware handler `(c, next)`. Protects\n * everything that is not a public `/auth/*` route: authenticated requests stash\n * the user on the context and continue; unauthenticated navigations redirect to\n * login and XHR/API calls get a 401 JSON. Shared by the local Hono server\n * (`mountFactoryAuth`) and the platform Mastra entry (`server.middleware`).\n */\nexport function createFactoryAuthGate(provider: IMastraAuthProvider) {\n return async (c: Context, next: () => Promise<void>): Promise<Response | void> => {\n const path = c.req.path;\n if (path.startsWith('/auth/')) {\n return next();\n }\n if (c.req.method === 'POST' && path === '/web/github/webhook') {\n return next();\n }\n // Inbound chat-channel webhooks (Slack events) carry no user session: they\n // authenticate by platform signature, the adapter verifying the request\n // against its signing secret. The routes declare `requiresAuth: false`, but\n // this gate is `use()` middleware — it runs before route matching, so that\n // metadata is not readable here and the path needs an explicit pass.\n //\n // The platform is allowlisted rather than matched as a wildcard: a pass\n // keyed on path shape alone would silently extend to any future adapter,\n // including one that does not verify signatures. Controller id stays a\n // wildcard because it is whatever the host registered.\n if (c.req.method === 'POST' && SIGNATURE_VERIFYING_CHANNEL_WEBHOOK.test(path)) {\n return next();\n }\n // The Slack account-linking deep link and the Sign-in-with-Slack OIDC\n // start/callback do their own auth (friendly login-redirect for signed-out\n // visitors; the OIDC callback authenticates via its signed `state`) — see\n // connect-route.ts.\n if (c.req.method === 'GET' && (path === '/connect/slack' || path.startsWith('/connect/slack/'))) {\n return next();\n }\n // The platform's deploy-auth flow lands IdP denials on `/login`\n // (`error=access_denied&error_description=...`); the SPA serves sign-in at\n // `/signin`, so forward the query there instead of burying it in returnTo.\n if (c.req.method === 'GET' && path === '/login') {\n return c.redirect(`/signin${new URL(c.req.url).search}`);\n }\n // The SPA sign-in page, its static bundle, and browser-fetched metadata\n // must be reachable while signed out; no user is stashed, so `/api/*`\n // stays protected.\n if (\n path === '/signin' ||\n path.startsWith('/assets/') ||\n path === '/manifest.webmanifest' ||\n path === '/mastra.svg' ||\n path === '/pwa-192.png' ||\n path === '/pwa-512.png' ||\n path === '/apple-touch-icon.png' ||\n (c.req.method === 'GET' && SESSION_FAVICON_PATHS.has(path))\n ) {\n return next();\n }\n\n const token = getBearerToken(c.req.header('Authorization'));\n // A slow verification here delays EVERY protected request — surface\n // outliers so auth-backend latency is attributable from server logs.\n const user = await timedAboveThreshold('auth.gate.authenticate', 1_000, () =>\n authenticateRequest(provider, token, c.req.raw),\n );\n\n if (user) {\n const requestedOrganizationId = token ? c.req.header(ORGANIZATION_ID_HEADER)?.trim() : undefined;\n if (requestedOrganizationId) {\n if (!selectRequestedOrganization(user, requestedOrganizationId)) {\n return c.json({ error: 'organization_forbidden' }, 403);\n }\n } else {\n // Bootstrap a personal org for no-org accounts so the org id resolves on\n // this request (see ensureFactoryAuthUser for the rationale).\n await ensureUserOrg(provider, user);\n }\n c.set(FACTORY_AUTH_USER_KEY, user);\n const requestContext = c.get('requestContext');\n requestContext?.set('user', user);\n requestContext?.set(MASTRA_MESSAGE_AUTHOR_KEY, messageAuthor(user));\n return next();\n }\n\n if (isNavigationRequest(path, c.req.header('Accept'))) {\n const url = new URL(c.req.url);\n const returnTo = sanitizeReturnTo(url.pathname + url.search);\n return c.redirect(`/signin?returnTo=${encodeURIComponent(returnTo)}`);\n }\n\n return c.json({ error: 'unauthorized' }, 401);\n };\n}\n\n/**\n * Mount factory auth gating onto the host app. No-op when auth is disabled\n * (no provider active).\n *\n * Must be called before the Mastra adapter routes, the `/web/*` routes, and\n * the static UI handlers so the gate covers every request. Composes the shared\n * `registerAuthRoutes` + `createFactoryAuthGate` factories so the local Hono server\n * and the platform Mastra entry stay behavior-identical.\n */\nexport function mountFactoryAuth(app: Hono<any>, options: MountFactoryAuthOptions = {}): boolean {\n const provider = options.provider ?? envFallbackAuthProvider(options.redirectUri);\n if (!provider) return false;\n\n registerAuthRoutes(app, provider, { publicUrl: options.publicUrl });\n app.use('*', createFactoryAuthGate(provider));\n return true;\n}\n"],"mappings":";;;;;;;AAmBA,MAAM,yBAAyB;;;;;;AA+D/B,SAAgB,iBAAiB,KAAiC;CAChE,IAAI,CAAC,KAAK,OAAO;CACjB,IAAI,CAAC,IAAI,WAAW,GAAG,GAAG,OAAO;CAEjC,IAAI,IAAI,WAAW,IAAI,KAAK,IAAI,WAAW,KAAK,GAAG,OAAO;CAC1D,OAAO;AACT;;AAGA,SAAgB,eAAe,eAA2C;CACxE,IAAI,CAAC,eAAe,OAAO;CAE3B,OADc,mBAAmB,KAAK,aAC3B,CAAC,GAAG,MAAM;AACvB;;;;;;;AAQA,SAAgB,kBAA2B;CACzC,OAAO,QAAQ,QAAQ,IAAI,4BAA4B,KAAK,CAAC;AAC/D;;AAQA,MAAM,wBAAwB;;;;;;AAO9B,SAAgB,mBAAmB,GAAyC;CAC1E,OAAO,EAAE,IAAI,qBAAqB;AACpC;;;;;;;;;;;;;AAcA,SAAgB,8BACd,gBAC6B;CAC7B,IAAI,CAAC,kBAAkB,OAAO,eAAe,QAAQ,YAAY,OAAO,KAAA;CACxE,OAAO,kBAAkB,eAAe,IAAI,MAAM,CAAC,KAAK,KAAA;AAC1D;;AAGA,SAAgB,qBAAqB,MAAuD;CAC1F,OAAO,MAAM,YAAY,MAAM;AACjC;;AAGA,SAAgB,oBAAoB,MAAuD;CACzF,OAAO,MAAM;AACf;;;;;;;;AASA,SAAgB,kBAAkB,GAA2C;CAC3E,MAAM,OAAO,mBAAmB,CAAC;CACjC,MAAM,SAAS,qBAAqB,IAAI;CACxC,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,OAAO;EAAE,OAAO,oBAAoB,IAAI;EAAG;CAAO;AACpD;AAEA,SAAS,cAAc,MAAkD;CACvE,MAAM,SAAS,qBAAqB,IAAI;CACxC,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,MAAM,QAAQ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IAAI,GAAG;GAC7B,MAAM,WAAW,iBAAiB,IAAI,WAAW,IAAI,MAAM;GAC3D,OAAO,EAAE,SAAS,oBAAoB,mBAAmB,QAAQ,GAAG;EACtE;EAEA,OAAO,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG;CAC9C;AACF;;;;;;;;;;AAWA,SAAgB,iBAAiB,KAAgB,UAAmC,CAAC,GAAY;CAC/F,MAAM,WAAW,QAAQ,YAAY,wBAAwB,QAAQ,WAAW;CAChF,IAAI,CAAC,UAAU,OAAO;CAEtB,mBAAmB,KAAK,UAAU,EAAE,WAAW,QAAQ,UAAU,CAAC;CAClE,IAAI,IAAI,KAAK,sBAAsB,QAAQ,CAAC;CAC5C,OAAO;AACT"}
1
+ {"version":3,"file":"auth.js","names":[],"sources":["../src/auth.ts"],"sourcesContent":["import { MastraAuthWorkos } from '@mastra/auth-workos';\nimport type { MessageAuthor } from '@mastra/core/agent-controller';\nimport { MASTRA_MESSAGE_AUTHOR_KEY } from '@mastra/core/request-context';\nimport {\n registerApiRoute,\n isAuthHttpHandler,\n isCredentialsProvider,\n isOrganizationsProvider,\n isSessionProvider,\n isSSOProvider,\n} from '@mastra/core/server';\nimport type { ApiRoute, IMastraAuthProvider, ISessionProvider } from '@mastra/core/server';\nimport type { Context, Hono } from 'hono';\nimport { HTTPException } from 'hono/http-exception';\n\nimport type { RouteAuth } from './routes/route.js';\nimport { actorFromAuthUser } from './storage/domains/comments/actor.js';\nimport { isFactoryTelemetryEnabled } from './telemetry.js';\nimport { timedAboveThreshold } from './timing.js';\n\nconst ORGANIZATION_ID_HEADER = 'X-Mastra-Organization-Id';\n\n/**\n * Provider-neutral factory auth gating for the MastraCode web server.\n *\n * When an auth provider is active (a `MastraAuthProvider` instance passed to\n * `MastraFactory`'s `auth` slot, or — back-compat for suites/paths that never\n * boot the factory — implied by the WorkOS env vars), every route on the web\n * server is placed behind it: unauthenticated browser navigations are\n * redirected to the SPA's `/signin` page, API/XHR calls receive a 401, and a\n * small set of public routes stay reachable while signed out — the provider's\n * `/auth/*` routes plus `/auth/me`, the `/signin` page, its `/assets/*` bundle,\n * and the SPA manifest metadata. When no provider is active, `mountFactoryAuth` is a no-op and the server\n * behaves exactly as it does without auth.\n *\n * Provider specifics stay in the providers (`@mastra/auth-workos`,\n * `@mastra/auth-better-auth`, or any custom `IMastraAuthProvider`); this\n * module composes them capability-first via the core type guards:\n * - `authenticateToken` — session/bearer validation (all providers)\n * - `ISSOProvider` — hosted-login `/auth/login`, `/auth/callback`, `/auth/logout`\n * - `IAuthHttpHandler` — provider-owned `/auth/api/*` endpoints (better-auth)\n * - `IOrganizationsProvider` — personal-org bootstrap + admin checks\n * - `ICredentialsProvider.isSignUpEnabled` — SPA sign-up affordance\n * - `getClearSessionHeaders` — session cookie clearing on logout\n */\n\n/** Minimal shape of the signed-in user surfaced to the SPA (no tokens). */\nexport interface FactoryAuthUser {\n /** Stable WorkOS user id used to scope per-user data (GitHub installs etc.). */\n workosId?: string;\n /** Provider user id; WorkOS shapes may use `workosId` instead (see {@link workosId}). */\n id?: string;\n email?: string;\n name?: string;\n /** Provider-supplied profile picture URL, when the auth provider exposes one. */\n avatarUrl?: string;\n /**\n * Organization id. The org is the top-level tenant: it owns the GitHub\n * App installation and connected projects, while each user inside the org gets\n * isolated building instances. Absent for personal (no-org) accounts.\n */\n organizationId?: string;\n /** Organization ids proven by the provider's authenticated membership response. */\n organizationMembershipIds?: string[];\n}\n\n/**\n * Tenant identity: the org is the top-level tenant, and each user inside it is\n * an isolated builder. Agent state, worktrees and sandboxes are scoped per\n * `(orgId, userId)`. Personal (no-org) users have `orgId === undefined`.\n */\nexport interface FactoryAuthTenant {\n /** Organization id, or `undefined` for personal (no-org) accounts. */\n orgId?: string;\n /** Stable provider user id. */\n userId: string;\n}\n\n/**\n * Validate that a `returnTo` value is a safe same-site path, to prevent\n * open-redirect attacks. Only absolute local paths (`/foo`) are allowed;\n * protocol-relative (`//evil.com`) and absolute URLs are rejected.\n */\nexport function sanitizeReturnTo(raw: string | undefined): string {\n if (!raw) return '/';\n if (!raw.startsWith('/')) return '/';\n // Reject protocol-relative URLs like \"//evil.com\" and \"/\\evil.com\".\n if (raw.startsWith('//') || raw.startsWith('/\\\\')) return '/';\n return raw;\n}\n\n/** Extract a bearer token from the Authorization header, if present. */\nexport function getBearerToken(authorization: string | undefined): string {\n if (!authorization) return '';\n const match = /^Bearer\\s+(.+)$/i.exec(authorization);\n return match?.[1] ?? '';\n}\n\n/**\n * Whether the SPA is served cross-origin from this API (platform deploy). When\n * `MASTRACODE_ALLOWED_ORIGINS` is set the browser talks to us cross-site, so\n * session cookies must be `SameSite=None; Secure` for the browser to send them.\n * Same-origin local dev leaves this unset and keeps the stricter `SameSite=Lax`.\n */\nexport function isCrossSiteAuth(): boolean {\n return Boolean(process.env.MASTRACODE_ALLOWED_ORIGINS?.trim());\n}\n\n/** Hono context variables set by the auth gate. */\nexport interface FactoryAuthVariables {\n factoryAuthUser: FactoryAuthUser;\n}\n\n/** Context key under which the gate stashes the authenticated user. */\nconst FACTORY_AUTH_USER_KEY = 'factoryAuthUser';\n\n/**\n * Read the authenticated user the gate stashed on the context, or\n * `undefined` when unauthenticated / auth disabled. Used by downstream routes\n * (e.g. GitHub) to scope rows per user.\n */\nexport function getFactoryAuthUser(c: Context): FactoryAuthUser | undefined {\n return c.get(FACTORY_AUTH_USER_KEY) as FactoryAuthUser | undefined;\n}\n\n/**\n * Read the authenticated user off a request context, normalizing whatever the\n * active auth provider put there.\n *\n * The server's auth layer writes the provider's `authenticateToken` result into\n * the request context's `user` slot verbatim, so the value's shape follows the\n * provider: WorkOS writes a flat user, better-auth writes a `{ session, user }`\n * wrapper whose org lives on the session. Reading that slot as a\n * {@link FactoryAuthUser} therefore yields `undefined` for both the id and the\n * org under better-auth, which reads as \"this session belongs to somebody else\"\n * at every ownership check. Normalize on the way in instead.\n */\nexport function getFactoryAuthUserFromContext(\n requestContext: { get: (key: string) => unknown } | undefined,\n): FactoryAuthUser | undefined {\n if (!requestContext || typeof requestContext.get !== 'function') return undefined;\n return toFactoryAuthUser(requestContext.get('user')) ?? undefined;\n}\n\n/** Resolve the stable user id from an authenticated user shape. */\nexport function getFactoryAuthUserId(user: FactoryAuthUser | undefined): string | undefined {\n return user?.workosId ?? user?.id;\n}\n\n/** Resolve the organization id from a user shape, if present. */\nexport function getFactoryAuthOrgId(user: FactoryAuthUser | undefined): string | undefined {\n return user?.organizationId;\n}\n\n/**\n * Resolve the tenant identity `(orgId, userId)` from the authenticated user on\n * the context. Returns `undefined` when there is no signed-in user (auth\n * disabled or unauthenticated). `orgId` is `undefined` for personal accounts;\n * callers gate org-scoped GitHub features on its presence while agent state\n * falls back to a user-only tenant.\n */\nexport function factoryAuthTenant(c: Context): FactoryAuthTenant | undefined {\n const user = getFactoryAuthUser(c);\n const userId = getFactoryAuthUserId(user);\n if (!userId) return undefined;\n return { orgId: getFactoryAuthOrgId(user), userId };\n}\n\nfunction messageAuthor(user: FactoryAuthUser): MessageAuthor | undefined {\n const userId = getFactoryAuthUserId(user);\n if (!userId) return undefined;\n const actor = actorFromAuthUser(userId, user);\n return {\n id: actor.id,\n ...(actor.displayName ? { name: actor.displayName } : {}),\n ...(actor.avatarUrl ? { avatarUrl: actor.avatarUrl } : {}),\n };\n}\n\n/** True when both WorkOS credential env vars are present (legacy env gate). */\nfunction envWorkosConfigured(): boolean {\n return Boolean(process.env.WORKOS_API_KEY && process.env.WORKOS_CLIENT_ID);\n}\n\n/**\n * WorkOS provider implied by the `WORKOS_*` env vars — back-compat for test\n * suites exercised without booting the factory (route suites set `WORKOS_*`\n * directly and call {@link mountFactoryAuth} without an explicit provider).\n * `fetchMemberships: true` lets `authenticateToken` resolve `organizationId`\n * from a single membership when the JWT has no org claim — required so a\n * bootstrapped personal org resolves without re-auth.\n */\nfunction envFallbackAuthProvider(redirectUri: string | undefined): MastraAuthWorkos | undefined {\n if (!envWorkosConfigured()) return undefined;\n return new MastraAuthWorkos({\n redirectUri: redirectUri ?? process.env.WORKOS_REDIRECT_URI,\n fetchMemberships: true,\n });\n}\n\n/**\n * Map a provider `authenticateToken` result onto the neutral SPA user shape.\n *\n * Two result families exist today:\n * - flat provider users (WorkOS `WorkOSUser` et al.): `id`/`workosId`/`email`/\n * `name`/`organizationId` directly on the object;\n * - session-shaped results (better-auth `BetterAuthUser`): `{ session, user }`\n * with the active org on the session.\n */\nfunction toFactoryAuthUser(result: unknown): FactoryAuthUser | null {\n if (!result || typeof result !== 'object') return null;\n const record = result as Record<string, unknown>;\n\n // Session-shaped results: { session, user }. A result carrying both halves and\n // top-level identity fields is read as session-shaped: the session half is the\n // authenticated one, and preferring it keeps the org and the id from coming\n // from two different places.\n if (record.user && typeof record.user === 'object' && record.session && typeof record.session === 'object') {\n const user = record.user as { id?: unknown; email?: unknown; name?: unknown; avatarUrl?: unknown };\n const session = record.session as { activeOrganizationId?: unknown };\n if (typeof user.id !== 'string') return null;\n return {\n id: user.id,\n email: typeof user.email === 'string' ? user.email : undefined,\n name: typeof user.name === 'string' ? user.name : undefined,\n avatarUrl: typeof user.avatarUrl === 'string' ? user.avatarUrl : undefined,\n organizationId: typeof session.activeOrganizationId === 'string' ? session.activeOrganizationId : undefined,\n };\n }\n\n // Flat provider users.\n const flat = record as {\n id?: unknown;\n workosId?: unknown;\n email?: unknown;\n name?: unknown;\n avatarUrl?: unknown;\n organizationId?: unknown;\n memberships?: unknown;\n memberOrgIds?: unknown;\n };\n const id = typeof flat.id === 'string' ? flat.id : undefined;\n const workosId = typeof flat.workosId === 'string' ? flat.workosId : undefined;\n if (!id && !workosId) return null;\n const membershipOrganizationIds = Array.isArray(flat.memberships)\n ? flat.memberships.flatMap(membership => {\n if (!membership || typeof membership !== 'object') return [];\n const organizationId = (membership as { organizationId?: unknown }).organizationId;\n return typeof organizationId === 'string' ? [organizationId] : [];\n })\n : [];\n const memberOrgIds = Array.isArray(flat.memberOrgIds)\n ? flat.memberOrgIds.filter((organizationId): organizationId is string => typeof organizationId === 'string')\n : [];\n const organizationMembershipIds = [...new Set([...membershipOrganizationIds, ...memberOrgIds])];\n return {\n id,\n workosId,\n email: typeof flat.email === 'string' ? flat.email : undefined,\n name: typeof flat.name === 'string' ? flat.name : undefined,\n avatarUrl: typeof flat.avatarUrl === 'string' ? flat.avatarUrl : undefined,\n organizationId: typeof flat.organizationId === 'string' ? flat.organizationId : undefined,\n organizationMembershipIds,\n };\n}\n\n/**\n * Resolve the authenticated user for a request via the provider. Never throws:\n * ordinary invalid/expired sessions resolve to `null`.\n */\nasync function authenticateRequest(\n provider: IMastraAuthProvider,\n token: string,\n raw: Request,\n): Promise<FactoryAuthUser | null> {\n try {\n const result = await provider.authenticateToken(token, raw);\n return toFactoryAuthUser(result);\n } catch {\n return null;\n }\n}\n\n/**\n * Bootstrap a personal org for no-org accounts so org-scoped features (GitHub\n * connect) work without leaving the app. Mutates the resolved user so the\n * current request sees the org immediately; subsequent requests resolve it via\n * the provider's own session/membership lookup (providers cache internally).\n * Best-effort: providers swallow their own bootstrap failures, and any\n * unexpected throw leaves the user no-org.\n */\nasync function ensureUserOrg(provider: IMastraAuthProvider, user: FactoryAuthUser): Promise<void> {\n if (getFactoryAuthOrgId(user)) return;\n if (!isOrganizationsProvider(provider)) return;\n const userId = getFactoryAuthUserId(user);\n if (!userId) return;\n try {\n const orgId = await provider.ensureOrganization(userId);\n if (orgId) user.organizationId = orgId;\n } catch {\n // Best-effort: the user stays no-org until a later request succeeds.\n }\n}\n\nfunction selectRequestedOrganization(user: FactoryAuthUser, requestedOrganizationId: string): boolean {\n if (user.organizationId === requestedOrganizationId) return true;\n if (!user.organizationMembershipIds?.includes(requestedOrganizationId)) return false;\n user.organizationId = requestedOrganizationId;\n return true;\n}\n\n/**\n * `Set-Cookie` values that clear the provider's session cookie(s), from the\n * provider's (possibly partial) `ISessionProvider.getClearSessionHeaders`.\n */\nfunction providerClearCookies(provider: IMastraAuthProvider): string[] {\n const getClearSessionHeaders = (provider as Partial<ISessionProvider>).getClearSessionHeaders;\n if (typeof getClearSessionHeaders !== 'function') return [];\n const headers = getClearSessionHeaders.call(provider) ?? {};\n const setCookie = headers['Set-Cookie'];\n if (!setCookie) return [];\n // A provider may join several clearing cookies into one header value.\n return setCookie.split(/,(?=\\s*[^;=,\\s]+=)/).map(cookie => cookie.trim());\n}\n\n/**\n * Fail-closed authorization for organization-level administrative mutations.\n * The caller must belong to the same active organization and the provider must\n * explicitly confirm an admin/owner role.\n */\nexport async function isOrganizationAdmin(\n provider: IMastraAuthProvider | undefined,\n c: Context,\n organizationId: string,\n): Promise<boolean> {\n const user = await ensureFactoryAuthUser(provider, c);\n if (!user || user.organizationId !== organizationId || !provider || !isOrganizationsProvider(provider)) {\n return false;\n }\n const userId = getFactoryAuthUserId(user);\n if (!userId) return false;\n try {\n return await provider.isOrganizationAdmin(organizationId, userId);\n } catch {\n return false;\n }\n}\n\n/**\n * Build the factory's implementation of the `RouteAuth` seam over the\n * resolved provider (`undefined` = auth disabled). Constructed once per boot\n * by `MastraFactory.prepare()` and handed to factory route modules at\n * construction — they never import the factory auth module directly.\n */\nexport function createFactoryRouteAuth(provider: IMastraAuthProvider | undefined): RouteAuth {\n return {\n enabled: () => provider !== undefined,\n ensureUser: (c: Context) => ensureFactoryAuthUser(provider, c),\n tenant: (c: Context) => factoryAuthTenant(c),\n isOrganizationAdmin: (c: Context, organizationId: string) => isOrganizationAdmin(provider, c, organizationId),\n };\n}\n\n/** True when the given provider is WorkOS. Gates WorkOS-only capabilities. */\nexport function isWorkOSAuth(provider: IMastraAuthProvider | undefined): boolean {\n return provider instanceof MastraAuthWorkos;\n}\n\n/**\n * The raw WorkOS provider, for features that need the WorkOS client directly\n * (audit-log export, Admin Portal links). Callers must gate on\n * {@link isWorkOSAuth} first — throws when the provider is not WorkOS.\n */\nexport function getWorkOSProvider(provider: IMastraAuthProvider | undefined): MastraAuthWorkos {\n if (provider instanceof MastraAuthWorkos) return provider;\n throw new Error('WorkOS provider requested but the active factory auth provider is not WorkOS');\n}\n\n/**\n * Resolve the authenticated user for a request, stashing it on the context.\n *\n * The gate only authenticates non-`/auth/*` requests via the `Authorization`\n * header, so cookie-based browser navigations to public `/auth/*` routes (the\n * GitHub connect/callback flow) arrive without a gate-stashed user. This reads\n * the session cookie from the raw request the same way `/auth/me` does,\n * caches the result on the context, and returns it so downstream helpers like\n * {@link factoryAuthTenant} work uniformly on both gated and public routes.\n *\n * Returns `undefined` when there is no valid session (or auth is disabled).\n */\nexport async function ensureFactoryAuthUser(\n provider: IMastraAuthProvider | undefined,\n c: Context,\n): Promise<FactoryAuthUser | undefined> {\n const existing = getFactoryAuthUser(c);\n if (existing) return existing;\n if (!provider) return undefined;\n\n const token = getBearerToken(c.req.header('Authorization'));\n const user = await authenticateRequest(provider, token, c.req.raw);\n if (!user) return undefined;\n\n const requestedOrganizationId = token ? c.req.header(ORGANIZATION_ID_HEADER)?.trim() : undefined;\n if (requestedOrganizationId) {\n if (!selectRequestedOrganization(user, requestedOrganizationId)) {\n throw new HTTPException(403, { message: 'organization_forbidden' });\n }\n } else {\n await ensureUserOrg(provider, user);\n }\n\n c.set(FACTORY_AUTH_USER_KEY, user);\n return user;\n}\n\nexport interface MountFactoryAuthOptions {\n /**\n * Explicit auth provider to mount. When omitted, falls back to a WorkOS\n * provider implied by the `WORKOS_*` env vars (back-compat for suites that\n * never boot the factory).\n */\n provider?: IMastraAuthProvider;\n /**\n * Absolute URL the identity provider redirects back to after login (WorkOS\n * env-fallback path only). Defaults to the `WORKOS_REDIRECT_URI` env var.\n */\n redirectUri?: string;\n /** Browser-facing origin used to derive the SSO callback URL. */\n publicUrl?: string;\n}\n\n/**\n * Decide whether a request is a top-level browser navigation (which should be\n * redirected to `/signin`) versus an API/XHR call (which should get a 401 JSON\n * response the SPA can react to).\n */\nfunction isNavigationRequest(path: string, accept: string | undefined): boolean {\n if (path.startsWith('/api/')) return false;\n return (accept ?? '').includes('text/html');\n}\n\n/**\n * Handle the provider-neutral `/auth/me` route: validate the session with the\n * active provider and report the signed-in user (no tokens) to the SPA.\n * `/auth/me` is public (the gate skips `/auth/*`), so it validates the session\n * itself rather than reading a value the gate would have stashed.\n */\nasync function handleAuthMe(provider: IMastraAuthProvider, c: Context): Promise<Response> {\n const token = getBearerToken(c.req.header('Authorization'));\n const user = await authenticateRequest(provider, token, c.req.raw);\n // Provider identity for the SPA: `/signin` renders the hosted-login button\n // for WorkOS and an email/password form for better-auth (with sign-up hidden\n // when the provider disables it).\n const signUpDisabled = isCredentialsProvider(provider) && provider.isSignUpEnabled?.() === false;\n const meta = { provider: provider.name, ...(signUpDisabled ? { signUpDisabled: true } : {}) };\n if (!user) {\n return c.json({ authenticated: false, user: null, ...meta });\n }\n // Resolve the org the same way gated requests do (providers cache, so this\n // is a lookup — not a create — after first bootstrap).\n await ensureUserOrg(provider, user);\n return c.json({\n authenticated: true,\n telemetryEnabled: isFactoryTelemetryEnabled(provider.name),\n user: {\n userId: getFactoryAuthUserId(user),\n email: user.email,\n name: user.name,\n avatarUrl: user.avatarUrl,\n organizationId: user.organizationId,\n },\n ...meta,\n });\n}\n\n/**\n * Encode a validated returnTo path into the OAuth `state` parameter.\n *\n * Pipe format (`uuid|encodedPath`) is the contract `MastraAuthStudio` parses\n * to forward the path as the platform's `post_login_redirect`; a JSON blob\n * here silently degrades every post-login redirect to `/`.\n */\nfunction encodeState(returnTo: string): string {\n return `${crypto.randomUUID()}|${encodeURIComponent(returnTo)}`;\n}\n\n/** Decode the OAuth `state` parameter back into a sanitized returnTo path. */\nfunction decodeState(state: string | undefined): string {\n if (!state) return '/';\n const pipeIndex = state.indexOf('|');\n if (pipeIndex !== -1) {\n try {\n return sanitizeReturnTo(decodeURIComponent(state.slice(pipeIndex + 1)));\n } catch {\n return '/';\n }\n }\n return '/';\n}\n\n/**\n * Short-lived cookie stashing the post-login destination across the hosted\n * OAuth round-trip. Providers/platforms differ in whether they echo `state`\n * back to the callback, so the cookie is the reliable channel; `state` (when\n * echoed) takes precedence only if the cookie is missing.\n */\nconst RETURN_TO_COOKIE = 'mastra_factory_return_to';\n\nfunction returnToCookieHeader(returnTo: string): string {\n const crossSite = isCrossSiteAuth() ? '; SameSite=None; Secure' : '; SameSite=Lax';\n return `${RETURN_TO_COOKIE}=${encodeURIComponent(returnTo)}; Path=/; Max-Age=600; HttpOnly${crossSite}`;\n}\n\nfunction clearReturnToCookieHeader(): string {\n const crossSite = isCrossSiteAuth() ? '; SameSite=None; Secure' : '; SameSite=Lax';\n return `${RETURN_TO_COOKIE}=; Path=/; Max-Age=0; HttpOnly${crossSite}`;\n}\n\nfunction readReturnToCookie(c: Context): string | undefined {\n const header = c.req.header('Cookie');\n if (!header) return undefined;\n for (const part of header.split(';')) {\n const [name, ...rest] = part.trim().split('=');\n if (name === RETURN_TO_COOKIE) {\n try {\n return decodeURIComponent(rest.join('='));\n } catch {\n return undefined;\n }\n }\n }\n return undefined;\n}\n\n/** HTTP methods supported for public auth routes. */\ntype AuthRouteMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL';\n\n/** A public `/auth/*` route derived from the provider's capabilities. */\ninterface AuthRouteSpec {\n path: string;\n method: AuthRouteMethod;\n handler: (c: Context) => Response | Promise<Response>;\n}\n\n/**\n * Derive the public `/auth/*` routes from the provider's capabilities:\n *\n * - `IAuthHttpHandler` → `ALL /auth/api/*` proxy to the provider's own HTTP\n * surface (better-auth sign-in/up/out/session — what the SPA's\n * email/password form posts to).\n * - `ISSOProvider` → hosted-login `GET /auth/login` / `GET /auth/callback` /\n * `GET /auth/logout` (returnTo preserved through the OAuth `state` param).\n * - handler-shaped, non-SSO providers → `GET /auth/login` redirects to the\n * SPA's `/signin` form, `GET /auth/logout` revokes via the provider's\n * sign-out endpoint and clears the session cookie.\n */\nfunction providerAuthRoutes(provider: IMastraAuthProvider, publicUrl?: string): AuthRouteSpec[] {\n const routes: AuthRouteSpec[] = [];\n\n if (isAuthHttpHandler(provider)) {\n routes.push({\n path: '/auth/api/*',\n method: 'ALL',\n handler: c => provider.handleAuthRequest(c.req.raw),\n });\n }\n\n if (isSSOProvider(provider)) {\n routes.push(\n {\n path: '/auth/login',\n method: 'GET',\n handler: async c => {\n const returnTo = sanitizeReturnTo(c.req.query('returnTo'));\n const state = encodeState(returnTo);\n // Build the callback URL from the browser-facing public origin so\n // the OAuth round-trip lands back on the SPA's origin (in dev the\n // SPA is on :5173 and Vite proxies /auth/* to the API on :4111 —\n // deriving from c.req.url would use :4111 and the post-callback\n // redirect to `/` would miss the SPA). Providers that ignore the\n // caller's URI in favor of their own config (e.g. MastraAuthWorkos\n // with an explicit `redirectUri` option) still take precedence.\n const redirectUri = publicUrl ? new URL('/auth/callback', publicUrl).toString() : '';\n const loginUrl = await provider.getLoginUrl(redirectUri, state);\n for (const cookie of (await provider.getLoginCookies?.(redirectUri, state)) ?? []) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n // Stash the destination in a cookie too: not every provider/platform\n // echoes `state` back to the callback.\n if (returnTo !== '/') {\n c.header('Set-Cookie', returnToCookieHeader(returnTo), { append: true });\n }\n return c.redirect(loginUrl);\n },\n },\n {\n path: '/auth/callback',\n method: 'GET',\n handler: async c => {\n const code = c.req.query('code');\n const stateReturnTo = decodeState(c.req.query('state'));\n const cookieReturnTo = sanitizeReturnTo(readReturnToCookie(c));\n const returnTo = cookieReturnTo !== '/' ? cookieReturnTo : stateReturnTo;\n c.header('Set-Cookie', clearReturnToCookieHeader(), { append: true });\n const idpError = c.req.query('error');\n if (idpError) {\n // IdP denial (e.g. access_denied for a non-org-member): bouncing to\n // /auth/login would re-enter the IdP in a redirect loop.\n const query = new URLSearchParams({ error: idpError.slice(0, 64) });\n const description = c.req.query('error_description');\n if (description) query.set('error_description', description.slice(0, 256));\n if (returnTo !== '/') query.set('returnTo', returnTo);\n return c.redirect(`/signin?${query.toString()}`);\n }\n if (!code) {\n return c.redirect('/auth/login');\n }\n try {\n const result = await provider.handleCallback(code, c.req.query('state') ?? '');\n if (result.cookies?.length) {\n // Provider populated cookies directly (e.g. WorkOS AuthKit builds\n // its own sealed session cookie inside handleCallback).\n for (const cookie of result.cookies) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n } else if (isSessionProvider(provider) && result.tokens) {\n // Fallback for providers that expose ISessionProvider but leave\n // cookie construction to the server (e.g. MastraAuthStudio, which\n // returns just the sealed session as accessToken so\n // getSessionHeaders can scope the cookie to this deployment's\n // domain via MASTRA_COOKIE_DOMAIN / sharedApiUrl auto-detection).\n // Mirrors packages/server/src/server/handlers/auth.ts:492-503.\n const resultUser = result.user as { id: string; organizationId?: string };\n const session = await provider.createSession(resultUser.id, {\n accessToken: result.tokens.accessToken,\n refreshToken: result.tokens.refreshToken,\n expiresAt: result.tokens.expiresAt,\n organizationId: resultUser.organizationId,\n });\n for (const [key, value] of Object.entries(provider.getSessionHeaders(session))) {\n c.header(key, value, { append: true });\n }\n }\n return c.redirect(returnTo);\n } catch {\n // Code exchange failed (expired/replayed code, misconfig). Send the\n // user back to login rather than surfacing a raw error.\n return c.redirect('/auth/login');\n }\n },\n },\n {\n path: '/auth/logout',\n method: 'GET',\n handler: async c => {\n let logoutUrl: string | null = null;\n try {\n logoutUrl = (await provider.getLogoutUrl?.('/', c.req.raw)) ?? null;\n } catch {\n logoutUrl = null;\n }\n // Clear the session cookie regardless of whether the provider\n // returned a logout URL.\n for (const cookie of providerClearCookies(provider)) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n return c.redirect(logoutUrl ?? '/');\n },\n },\n );\n } else if (isAuthHttpHandler(provider)) {\n routes.push(\n {\n // Hosted-login equivalent: no hosted page, so send the browser to the\n // SPA's /signin form, preserving returnTo.\n path: '/auth/login',\n method: 'GET',\n handler: c => {\n const returnTo = sanitizeReturnTo(c.req.query('returnTo'));\n return c.redirect(`/signin?returnTo=${encodeURIComponent(returnTo)}`);\n },\n },\n {\n path: '/auth/logout',\n method: 'GET',\n handler: async c => {\n // Revoke the session server-side through the provider's own sign-out\n // endpoint and forward its clearing cookies; fall back to our clear\n // cookies regardless.\n try {\n const origin = new URL(c.req.url).origin;\n const response = await provider.handleAuthRequest(\n new Request(`${origin}/auth/api/sign-out`, { method: 'POST', headers: c.req.raw.headers }),\n );\n for (const cookie of response.headers.getSetCookie()) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n } catch {\n // No/invalid session: nothing to revoke.\n }\n for (const cookie of providerClearCookies(provider)) {\n c.header('Set-Cookie', cookie, { append: true });\n }\n return c.redirect('/');\n },\n },\n );\n }\n\n return routes;\n}\n\n/**\n * Register the public `/auth/*` routes on a Hono app: the capability-derived\n * provider routes (login/callback/logout/provider APIs) plus the\n * provider-neutral `/auth/me`. Split out from `mountFactoryAuth` so both the local\n * Hono server and the platform Mastra entry can reuse the exact same handlers.\n */\nexport function registerAuthRoutes(\n app: Hono<any>,\n provider: IMastraAuthProvider,\n options: { publicUrl?: string } = {},\n): void {\n for (const route of providerAuthRoutes(provider, options.publicUrl)) {\n const methods = route.method === 'ALL' ? ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] : [route.method];\n app.on(methods, route.path, c => route.handler(c));\n }\n app.get('/auth/me', c => handleAuthMe(provider, c));\n}\n\n/**\n * Build the public `/auth/*` routes (provider routes + `/auth/me`) as Mastra\n * `server.apiRoutes`. Used by the platform Mastra entry (`src/mastra/index.ts`),\n * which can't register plain Hono routes on the deployer-generated app the way\n * the local server does via {@link registerAuthRoutes}.\n *\n * Handlers are identical to {@link registerAuthRoutes}. All are `requiresAuth: false`\n * (they must be reachable while unauthenticated), and the gate middleware skips\n * `/auth/*` so it never blocks them. `/auth/*` is not under `/api`, so it is a\n * valid custom-route path.\n */\nexport function buildAuthRoutes(provider: IMastraAuthProvider, options: { publicUrl?: string } = {}): ApiRoute[] {\n return [\n // `registerApiRoute` handlers see @mastra/core's bundled hono Context type,\n // which is structurally identical to (but nominally distinct from) the\n // local hono version the route handlers are typed against — cast across\n // the seam.\n ...providerAuthRoutes(provider, options.publicUrl).map(route =>\n registerApiRoute(route.path, {\n method: route.method,\n requiresAuth: false,\n handler: c => route.handler(c as unknown as Context),\n }),\n ),\n registerApiRoute('/auth/me', {\n method: 'GET',\n requiresAuth: false,\n handler: c => handleAuthMe(provider, c as unknown as Context),\n }),\n ];\n}\n\n/**\n * Channel webhook paths whose adapter verifies the platform's request signature,\n * making the delivery self-authenticating. Add a platform here only once its\n * adapter rejects unsigned or mis-signed requests.\n */\nconst SIGNATURE_VERIFYING_CHANNEL_WEBHOOK = /^\\/api\\/agent-controllers\\/[^/]+\\/channels\\/slack\\/webhook$/;\n\n// Fetched by tabs that may already be signed out. Enumerated, not prefix-matched,\n// so a future route under the same prefix does not inherit the pass.\nconst SESSION_FAVICON_PATHS = new Set([\n '/favicon-session-initializing.svg',\n '/favicon-session-working.svg',\n '/favicon-session-awaiting.svg',\n '/favicon-session-error.svg',\n]);\n\n/**\n * Build the auth gate as a plain Hono middleware handler `(c, next)`. Protects\n * everything that is not a public `/auth/*` route: authenticated requests stash\n * the user on the context and continue; unauthenticated navigations redirect to\n * login and XHR/API calls get a 401 JSON. Shared by the local Hono server\n * (`mountFactoryAuth`) and the platform Mastra entry (`server.middleware`).\n */\nexport function createFactoryAuthGate(provider: IMastraAuthProvider) {\n return async (c: Context, next: () => Promise<void>): Promise<Response | void> => {\n const path = c.req.path;\n if (path.startsWith('/auth/')) {\n return next();\n }\n if (c.req.method === 'POST' && path === '/web/github/webhook') {\n return next();\n }\n // Inbound chat-channel webhooks (Slack events) carry no user session: they\n // authenticate by platform signature, the adapter verifying the request\n // against its signing secret. The routes declare `requiresAuth: false`, but\n // this gate is `use()` middleware — it runs before route matching, so that\n // metadata is not readable here and the path needs an explicit pass.\n //\n // The platform is allowlisted rather than matched as a wildcard: a pass\n // keyed on path shape alone would silently extend to any future adapter,\n // including one that does not verify signatures. Controller id stays a\n // wildcard because it is whatever the host registered.\n if (c.req.method === 'POST' && SIGNATURE_VERIFYING_CHANNEL_WEBHOOK.test(path)) {\n return next();\n }\n // The Slack account-linking deep link and the Sign-in-with-Slack OIDC\n // start/callback do their own auth (friendly login-redirect for signed-out\n // visitors; the OIDC callback authenticates via its signed `state`) — see\n // connect-route.ts.\n if (c.req.method === 'GET' && (path === '/connect/slack' || path.startsWith('/connect/slack/'))) {\n return next();\n }\n // The platform's deploy-auth flow lands IdP denials on `/login`\n // (`error=access_denied&error_description=...`); the SPA serves sign-in at\n // `/signin`, so forward the query there instead of burying it in returnTo.\n if (c.req.method === 'GET' && path === '/login') {\n return c.redirect(`/signin${new URL(c.req.url).search}`);\n }\n // The SPA sign-in page, its static bundle, and browser-fetched metadata\n // must be reachable while signed out; no user is stashed, so `/api/*`\n // stays protected.\n if (\n path === '/signin' ||\n path.startsWith('/assets/') ||\n path === '/manifest.webmanifest' ||\n path === '/mastra.svg' ||\n path === '/pwa-192.png' ||\n path === '/pwa-512.png' ||\n path === '/apple-touch-icon.png' ||\n (c.req.method === 'GET' && SESSION_FAVICON_PATHS.has(path))\n ) {\n return next();\n }\n\n const token = getBearerToken(c.req.header('Authorization'));\n // A slow verification here delays EVERY protected request — surface\n // outliers so auth-backend latency is attributable from server logs.\n const user = await timedAboveThreshold('auth.gate.authenticate', 1_000, () =>\n authenticateRequest(provider, token, c.req.raw),\n );\n\n if (user) {\n const requestedOrganizationId = token ? c.req.header(ORGANIZATION_ID_HEADER)?.trim() : undefined;\n if (requestedOrganizationId) {\n if (!selectRequestedOrganization(user, requestedOrganizationId)) {\n return c.json({ error: 'organization_forbidden' }, 403);\n }\n } else {\n // Bootstrap a personal org for no-org accounts so the org id resolves on\n // this request (see ensureFactoryAuthUser for the rationale).\n await ensureUserOrg(provider, user);\n }\n c.set(FACTORY_AUTH_USER_KEY, user);\n const requestContext = c.get('requestContext');\n requestContext?.set('user', user);\n requestContext?.set(MASTRA_MESSAGE_AUTHOR_KEY, messageAuthor(user));\n return next();\n }\n\n if (isNavigationRequest(path, c.req.header('Accept'))) {\n const url = new URL(c.req.url);\n const returnTo = sanitizeReturnTo(url.pathname + url.search);\n return c.redirect(`/signin?returnTo=${encodeURIComponent(returnTo)}`);\n }\n\n return c.json({ error: 'unauthorized' }, 401);\n };\n}\n\n/**\n * Mount factory auth gating onto the host app. No-op when auth is disabled\n * (no provider active).\n *\n * Must be called before the Mastra adapter routes, the `/web/*` routes, and\n * the static UI handlers so the gate covers every request. Composes the shared\n * `registerAuthRoutes` + `createFactoryAuthGate` factories so the local Hono server\n * and the platform Mastra entry stay behavior-identical.\n */\nexport function mountFactoryAuth(app: Hono<any>, options: MountFactoryAuthOptions = {}): boolean {\n const provider = options.provider ?? envFallbackAuthProvider(options.redirectUri);\n if (!provider) return false;\n\n registerAuthRoutes(app, provider, { publicUrl: options.publicUrl });\n app.use('*', createFactoryAuthGate(provider));\n return true;\n}\n"],"mappings":";;;;;;;;AAoBA,MAAM,yBAAyB;;;;;;AA+D/B,SAAgB,iBAAiB,KAAiC;CAChE,IAAI,CAAC,KAAK,OAAO;CACjB,IAAI,CAAC,IAAI,WAAW,GAAG,GAAG,OAAO;CAEjC,IAAI,IAAI,WAAW,IAAI,KAAK,IAAI,WAAW,KAAK,GAAG,OAAO;CAC1D,OAAO;AACT;;AAGA,SAAgB,eAAe,eAA2C;CACxE,IAAI,CAAC,eAAe,OAAO;CAE3B,OADc,mBAAmB,KAAK,aAC3B,CAAC,GAAG,MAAM;AACvB;;;;;;;AAQA,SAAgB,kBAA2B;CACzC,OAAO,QAAQ,QAAQ,IAAI,4BAA4B,KAAK,CAAC;AAC/D;;AAQA,MAAM,wBAAwB;;;;;;AAO9B,SAAgB,mBAAmB,GAAyC;CAC1E,OAAO,EAAE,IAAI,qBAAqB;AACpC;;;;;;;;;;;;;AAcA,SAAgB,8BACd,gBAC6B;CAC7B,IAAI,CAAC,kBAAkB,OAAO,eAAe,QAAQ,YAAY,OAAO,KAAA;CACxE,OAAO,kBAAkB,eAAe,IAAI,MAAM,CAAC,KAAK,KAAA;AAC1D;;AAGA,SAAgB,qBAAqB,MAAuD;CAC1F,OAAO,MAAM,YAAY,MAAM;AACjC;;AAGA,S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ation.js";
2
2
  //#region src/boards/define-board.ts
3
3
  var BoardDefinitionError = class extends Error {
4
4
  name = "BoardDefinitionError";
@@ -8,6 +8,9 @@ const PHASE_KINDS = /* @__PURE__ */ new Set([
8
8
  "working",
9
9
  "terminal"
10
10
  ]);
11
+ function validateBoardIdentifier(value, label) {
12
+ if (!isBoardIdentifier(value)) throw new BoardDefinitionError(`${label} must be a valid board identifier.`);
13
+ }
11
14
  function validatePhaseSemantics(phaseId, phase) {
12
15
  if (!PHASE_KINDS.has(phase.kind)) throw new BoardDefinitionError(`Phase "${phaseId}" must declare kind 'resting', 'working', or 'terminal'.`);
13
16
  if (phase.kind === "working") {
@@ -33,12 +36,16 @@ function validateToolRules(tools) {
33
36
  return Object.freeze(frozen);
34
37
  }
35
38
  function defineBoard(config) {
39
+ validateBoardIdentifier(config.id, "Board id");
36
40
  if (config.transitionPolicy !== void 0 && typeof config.transitionPolicy !== "function") throw new BoardDefinitionError("Board transitionPolicy must be a function.");
37
41
  const tools = validateToolRules(config.tools);
38
42
  const phaseIds = new Set(Object.keys(config.phases));
39
43
  if (phaseIds.size === 0) throw new BoardDefinitionError("A board must define at least one phase.");
40
44
  if (!phaseIds.has(config.initialPhase)) throw new BoardDefinitionError(`Initial phase "${config.initialPhase}" is not defined.`);
41
- for (const [phaseId, phase] of Object.entries(config.phases)) validatePhaseSemantics(phaseId, phase);
45
+ for (const [phaseId, phase] of Object.entries(config.phases)) {
46
+ validateBoardIdentifier(phaseId, "Phase id");
47
+ validatePhaseSemantics(phaseId, phase);
48
+ }
42
49
  if (config.phases[config.initialPhase].kind !== "resting") throw new BoardDefinitionError(`Initial phase "${config.initialPhase}" must be a resting phase.`);
43
50
  const transitions = Object.fromEntries(Object.entries(config.phases).map(([phaseId, phase]) => {
44
51
  if (phase.next !== void 0 && phase.outcomes) throw new BoardDefinitionError(`Phase "${phaseId}" cannot define both next and outcomes.`);
@@ -1 +1 @@
1
- {"version":3,"file":"define-board.js","names":[],"sources":["../../src/boards/define-board.ts"],"sourcesContent":["import type {\n FactoryRuleHandler,\n FactoryRuleSource,\n FactoryStageRuleContext,\n FactoryToolResultRuleContext,\n} from '../rules/types.js';\nimport { IDENTIFIER_RE, MAX_ROLE_LENGTH, MAX_TOOL_NAME_LENGTH } from '../rules/validation.js';\nimport type { BoardTransitionPolicy } from './transition-policy.js';\n\ntype BoardPhaseHandlers = Partial<Record<FactoryRuleSource, FactoryRuleHandler<FactoryStageRuleContext>>>;\ntype ReadonlyBoardPhaseHandlers = Readonly<BoardPhaseHandlers>;\n\n/** Runs when an agent seated on this board completes the named tool. */\nexport type BoardToolResultRuleHandler = FactoryRuleHandler<FactoryToolResultRuleContext>;\nexport type BoardToolRule = { readonly onResult: BoardToolResultRuleHandler };\nexport type BoardToolRules = Readonly<Record<string, BoardToolRule>>;\n\ntype ReadonlyFactoryBoardRules = Readonly<\n Record<\n string,\n Readonly<\n Partial<\n Record<\n FactoryRuleSource,\n Readonly<{\n onEnter?: FactoryRuleHandler<FactoryStageRuleContext>;\n onExit?: FactoryRuleHandler<FactoryStageRuleContext>;\n }>\n >\n >\n >\n >\n>;\n\n/**\n * What a phase means to the runtime.\n * - `resting`: nobody is seated; a card waits for a person or an event.\n * - `working`: an agent in `role` carries the card; a person's move in arms autonomy.\n * - `terminal`: the card is finished; sessions stop and held resources are released.\n */\nexport type BoardPhaseKind = 'resting' | 'working' | 'terminal';\n\ntype BoardPhaseBase<PhaseId extends string> = {\n readonly title: string;\n readonly next?: PhaseId;\n readonly outcomes?: Readonly<Record<string, PhaseId>>;\n readonly onEnter?: ReadonlyBoardPhaseHandlers;\n readonly onExit?: ReadonlyBoardPhaseHandlers;\n};\n\nexport type BoardPhaseDefinition<PhaseId extends string> =\n | (BoardPhaseBase<PhaseId> & { readonly kind: 'resting'; readonly role?: never })\n | (BoardPhaseBase<PhaseId> & { readonly kind: 'working'; readonly role: string })\n | (BoardPhaseBase<PhaseId> & { readonly kind: 'terminal'; readonly role?: never });\n\nexport interface BoardTransition<PhaseId extends string> {\n readonly outcome: string | null;\n readonly to: PhaseId;\n}\n\nexport interface BoardDefinition<BoardId extends string, PhaseId extends string> {\n readonly id: BoardId;\n readonly title: string;\n readonly initialPhase: PhaseId;\n readonly phases: Readonly<Record<PhaseId, BoardPhaseDefinition<PhaseId>>>;\n readonly transitions: Readonly<Record<PhaseId, readonly BoardTransition<PhaseId>[]>>;\n readonly rules: ReadonlyFactoryBoardRules;\n /** Tool-result rules keyed by tool name; empty when the board declares none. */\n readonly tools: BoardToolRules;\n readonly transitionPolicy?: BoardTransitionPolicy;\n allowsTransition(from: PhaseId, to: PhaseId): boolean;\n /** Declared kind of a phase, or undefined when the board has no such phase. */\n phaseKind(phase: string): BoardPhaseKind | undefined;\n isWorking(phase: string): boolean;\n isTerminal(phase: string): boolean;\n /** Role seated in a working phase; undefined for resting/terminal/unknown phases. */\n roleForPhase(phase: string): string | undefined;\n /** First working phase, in declaration order, carried by `role`. */\n phaseForRole(role: string): PhaseId | undefined;\n}\n\ntype BoardConfig<BoardId extends string, Phases extends Record<string, BoardPhaseDefinition<keyof Phases & string>>> = {\n id: BoardId;\n title: string;\n initialPhase: keyof Phases & string;\n phases: Phases;\n tools?: Record<string, BoardToolRule>;\n transitionPolicy?: BoardTransitionPolicy;\n};\n\nexport class BoardDefinitionError extends Error {\n override name = 'BoardDefinitionError';\n}\n\nconst PHASE_KINDS: ReadonlySet<string> = new Set<BoardPhaseKind>(['resting', 'working', 'terminal']);\n\nfunction validatePhaseSemantics(phaseId: string, phase: BoardPhaseDefinition<string>): void {\n if (!PHASE_KINDS.has(phase.kind as string)) {\n throw new BoardDefinitionError(`Phase \"${phaseId}\" must declare kind 'resting', 'working', or 'terminal'.`);\n }\n if (phase.kind === 'working') {\n const role: unknown = phase.role;\n if (typeof role !== 'string' || role.length === 0 || role.length > MAX_ROLE_LENGTH || !IDENTIFIER_RE.test(role)) {\n throw new BoardDefinitionError(`Working phase \"${phaseId}\" must declare a valid role.`);\n }\n } else if ((phase as { role?: unknown }).role !== undefined) {\n throw new BoardDefinitionError(`Phase \"${phaseId}\" is ${phase.kind} and cannot declare a role.`);\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction validateToolRules(tools: unknown): BoardToolRules {\n if (tools === undefined) return Object.freeze({});\n if (!isPlainObject(tools)) throw new BoardDefinitionError('Board tools must be a plain object.');\n const frozen: Record<string, BoardToolRule> = {};\n for (const [toolName, leaf] of Object.entries(tools)) {\n if (toolName.length === 0 || toolName.length > MAX_TOOL_NAME_LENGTH || !IDENTIFIER_RE.test(toolName)) {\n throw new BoardDefinitionError(`Tool rule \"${toolName}\" has an invalid tool name.`);\n }\n if (!isPlainObject(leaf) || Object.keys(leaf).some(key => key !== 'onResult')) {\n throw new BoardDefinitionError(`Tool rule \"${toolName}\" must be an object with only onResult.`);\n }\n if (typeof leaf.onResult !== 'function') {\n throw new BoardDefinitionError(`Tool rule \"${toolName}\" must declare an onResult function.`);\n }\n frozen[toolName] = Object.freeze({ onResult: leaf.onResult as BoardToolResultRuleHandler });\n }\n return Object.freeze(frozen);\n}\n\nexport function defineBoard<\n const BoardId extends string,\n const Phases extends Record<string, BoardPhaseDefinition<keyof Phases & string>>,\n>(config: BoardConfig<BoardId, Phases>): BoardDefinition<BoardId, keyof Phases & string> {\n type PhaseId = keyof Phases & string;\n if (config.transitionPolicy !== undefined && typeof config.transitionPolicy !== 'function') {\n throw new BoardDefinitionError('Board transitionPolicy must be a function.');\n }\n const tools = validateToolRules(config.tools);\n const phaseIds = new Set(Object.keys(config.phases));\n if (phaseIds.size === 0) throw new BoardDefinitionError('A board must define at least one phase.');\n if (!phaseIds.has(config.initialPhase)) {\n throw new BoardDefinitionError(`Initial phase \"${config.initialPhase}\" is not defined.`);\n }\n for (const [phaseId, phase] of Object.entries(config.phases)) validatePhaseSemantics(phaseId, phase);\n if (config.phases[config.initialPhase]!.kind !== 'resting') {\n throw new BoardDefinitionError(`Initial phase \"${config.initialPhase}\" must be a resting phase.`);\n }\n\n const transitions = Object.fromEntries(\n Object.entries(config.phases).map(([phaseId, phase]) => {\n if (phase.next !== undefined && phase.outcomes) {\n throw new BoardDefinitionError(`Phase \"${phaseId}\" cannot define both next and outcomes.`);\n }\n const targets: BoardTransition<string>[] =\n phase.next !== undefined\n ? [Object.freeze({ outcome: null, to: phase.next })]\n : Object.entries(phase.outcomes ?? {}).map(([outcome, to]) => Object.freeze({ outcome, to }));\n for (const { to } of targets) {\n if (!phaseIds.has(to)) {\n throw new BoardDefinitionError(`Phase \"${phaseId}\" targets undefined phase \"${to}\".`);\n }\n }\n return [phaseId, Object.freeze(targets)];\n }),\n ) as Record<PhaseId, readonly BoardTransition<PhaseId>[]>;\n\n const phases = Object.freeze(\n Object.fromEntries(\n Object.entries(config.phases).map(([phaseId, phase]) => [\n phaseId,\n Object.freeze({\n title: phase.title,\n kind: phase.kind,\n ...(phase.kind === 'working' ? { role: phase.role } : {}),\n ...(phase.next !== undefined ? { next: phase.next } : {}),\n ...(phase.outcomes ? { outcomes: Object.freeze({ ...phase.outcomes }) } : {}),\n ...(phase.onEnter ? { onEnter: Object.freeze({ ...phase.onEnter }) } : {}),\n ...(phase.onExit ? { onExit: Object.freeze({ ...phase.onExit }) } : {}),\n }),\n ]),\n ),\n ) as Readonly<Record<PhaseId, BoardPhaseDefinition<PhaseId>>>;\n const rules = Object.freeze(\n Object.fromEntries(\n Object.entries(config.phases).flatMap(([phaseId, phase]) => {\n const sources = new Set([...Object.keys(phase.onEnter ?? {}), ...Object.keys(phase.onExit ?? {})]);\n if (sources.size === 0) return [];\n return [\n [\n phaseId,\n Object.freeze(\n Object.fromEntries(\n [...sources].map(source => [\n source,\n Object.freeze({\n ...(phase.onEnter?.[source as FactoryRuleSource]\n ? { onEnter: phase.onEnter[source as FactoryRuleSource] }\n : {}),\n ...(phase.onExit?.[source as FactoryRuleSource]\n ? { onExit: phase.onExit[source as FactoryRuleSource] }\n : {}),\n }),\n ]),\n ),\n ),\n ],\n ];\n }),\n ),\n ) as ReadonlyFactoryBoardRules;\n\n const kinds = new Map<string, BoardPhaseKind>();\n const roles = new Map<string, string>();\n const phaseByRole = new Map<string, PhaseId>();\n for (const [phaseId, phase] of Object.entries(phases) as [PhaseId, BoardPhaseDefinition<PhaseId>][]) {\n kinds.set(phaseId, phase.kind);\n if (phase.kind !== 'working') continue;\n roles.set(phaseId, phase.role);\n if (!phaseByRole.has(phase.role)) phaseByRole.set(phase.role, phaseId);\n }\n\n return Object.freeze({\n id: config.id,\n title: config.title,\n initialPhase: config.initialPhase,\n phases,\n transitions: Object.freeze(transitions),\n rules: Object.freeze(rules),\n tools,\n ...(config.transitionPolicy ? { transitionPolicy: config.transitionPolicy } : {}),\n allowsTransition(from: PhaseId, to: PhaseId) {\n return from === to || transitions[from]?.some(transition => transition.to === to) === true;\n },\n phaseKind: (phase: string) => kinds.get(phase),\n isWorking: (phase: string) => kinds.get(phase) === 'working',\n isTerminal: (phase: string) => kinds.get(phase) === 'terminal',\n roleForPhase: (phase: string) => roles.get(phase),\n phaseForRole: (role: string) => phaseByRole.get(role),\n });\n}\n"],"mappings":";;AA0FA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,OAAgB;AAClB;AAEA,MAAM,8BAAmC,IAAI,IAAoB;CAAC;CAAW;CAAW;AAAU,CAAC;AAEnG,SAAS,uBAAuB,SAAiB,OAA2C;CAC1F,IAAI,CAAC,YAAY,IAAI,MAAM,IAAc,GACvC,MAAM,IAAI,qBAAqB,UAAU,QAAQ,yDAAyD;CAE5G,IAAI,MAAM,SAAS,WAAW;EAC5B,MAAM,OAAgB,MAAM;EAC5B,IAAI,OAAO,SAAS,YAAY,KAAK,WAAW,KAAK,KAAK,SAAA,MAA4B,CAAC,cAAc,KAAK,IAAI,GAC5G,MAAM,IAAI,qBAAqB,kBAAkB,QAAQ,6BAA6B;CAE1F,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AI,GAAG,YAAY,IAAI,MAAM,MAAM,OAAO;CACvE;CAEA,OAAO,OAAO,OAAO;EACnB,IAAI,OAAO;EACX,OAAO,OAAO;EACd,cAAc,OAAO;EACrB;EACA,aAAa,OAAO,OAAO,WAAW;EACtC,OAAO,OAAO,OAAO,KAAK;EAC1B;EACA,GAAI,OAAO,mBAAmB,EAAE,kBAAkB,OAAO,iBAAiB,IAAI,CAAC;EAC/E,iBAAiB,MAAe,IAAa;GAC3C,OAAO,SAAS,MAAM,YAAY,KAAK,EAAE,MAAK,eAAc,WAAW,OAAO,EAAE,MAAM;EACxF;EACA,YAAY,UAAkB,MAAM,IAAI,KAAK;EAC7C,YAAY,UAAkB,MAAM,IAAI,KAAK,MAAM;EACnD,aAAa,UAAkB,MAAM,IAAI,KAAK,MAAM;EACpD,eAAe,UAAkB,MAAM,IAAI,KAAK;EAChD,eAAe,SAAiB,YAAY,IAAI,IAAI;CACtD,CAAC;AACH"}
1
+ {"version":3,"file":"define-board.js","names":[],"sources":["../../src/boards/define-board.ts"],"sourcesContent":["import type {\n FactoryRuleHandler,\n FactoryRuleSource,\n FactoryStageRuleContext,\n FactoryToolResultRuleContext,\n} from '../rules/types.js';\nimport { IDENTIFIER_RE, isBoardIdentifier, MAX_ROLE_LENGTH, MAX_TOOL_NAME_LENGTH } from '../rules/validation.js';\nimport type { BoardTransitionPolicy } from './transition-policy.js';\n\ntype BoardPhaseHandlers = Partial<Record<FactoryRuleSource, FactoryRuleHandler<FactoryStageRuleContext>>>;\ntype ReadonlyBoardPhaseHandlers = Readonly<BoardPhaseHandlers>;\n\n/** Runs when an agent seated on this board completes the named tool. */\nexport type BoardToolResultRuleHandler = FactoryRuleHandler<FactoryToolResultRuleContext>;\nexport type BoardToolRule = { readonly onResult: BoardToolResultRuleHandler };\nexport type BoardToolRules = Readonly<Record<string, BoardToolRule>>;\n\ntype ReadonlyFactoryBoardRules = Readonly<\n Record<\n string,\n Readonly<\n Partial<\n Record<\n FactoryRuleSource,\n Readonly<{\n onEnter?: FactoryRuleHandler<FactoryStageRuleContext>;\n onExit?: FactoryRuleHandler<FactoryStageRuleContext>;\n }>\n >\n >\n >\n >\n>;\n\n/**\n * What a phase means to the runtime.\n * - `resting`: nobody is seated; a card waits for a person or an event.\n * - `working`: an agent in `role` carries the card; a person's move in arms autonomy.\n * - `terminal`: the card is finished; sessions stop and held resources are released.\n */\nexport type BoardPhaseKind = 'resting' | 'working' | 'terminal';\n\ntype BoardPhaseBase<PhaseId extends string> = {\n readonly title: string;\n readonly next?: PhaseId;\n readonly outcomes?: Readonly<Record<string, PhaseId>>;\n readonly onEnter?: ReadonlyBoardPhaseHandlers;\n readonly onExit?: ReadonlyBoardPhaseHandlers;\n};\n\nexport type BoardPhaseDefinition<PhaseId extends string> =\n | (BoardPhaseBase<PhaseId> & { readonly kind: 'resting'; readonly role?: never })\n | (BoardPhaseBase<PhaseId> & { readonly kind: 'working'; readonly role: string })\n | (BoardPhaseBase<PhaseId> & { readonly kind: 'terminal'; readonly role?: never });\n\nexport interface BoardTransition<PhaseId extends string> {\n readonly outcome: string | null;\n readonly to: PhaseId;\n}\n\nexport interface BoardDefinition<BoardId extends string, PhaseId extends string> {\n readonly id: BoardId;\n readonly title: string;\n readonly initialPhase: PhaseId;\n readonly phases: Readonly<Record<PhaseId, BoardPhaseDefinition<PhaseId>>>;\n readonly transitions: Readonly<Record<PhaseId, readonly BoardTransition<PhaseId>[]>>;\n readonly rules: ReadonlyFactoryBoardRules;\n /** Tool-result rules keyed by tool name; empty when the board declares none. */\n readonly tools: BoardToolRules;\n readonly transitionPolicy?: BoardTransitionPolicy;\n allowsTransition(from: PhaseId, to: PhaseId): boolean;\n /** Declared kind of a phase, or undefined when the board has no such phase. */\n phaseKind(phase: string): BoardPhaseKind | undefined;\n isWorking(phase: string): boolean;\n isTerminal(phase: string): boolean;\n /** Role seated in a working phase; undefined for resting/terminal/unknown phases. */\n roleForPhase(phase: string): string | undefined;\n /** First working phase, in declaration order, carried by `role`. */\n phaseForRole(role: string): PhaseId | undefined;\n}\n\ntype BoardConfig<BoardId extends string, Phases extends Record<string, BoardPhaseDefinition<keyof Phases & string>>> = {\n id: BoardId;\n title: string;\n initialPhase: keyof Phases & string;\n phases: Phases;\n tools?: Record<string, BoardToolRule>;\n transitionPolicy?: BoardTransitionPolicy;\n};\n\nexport class BoardDefinitionError extends Error {\n override name = 'BoardDefinitionError';\n}\n\nconst PHASE_KINDS: ReadonlySet<string> = new Set<BoardPhaseKind>(['resting', 'working', 'terminal']);\n\nfunction validateBoardIdentifier(value: unknown, label: string): void {\n if (!isBoardIdentifier(value)) {\n throw new BoardDefinitionError(`${label} must be a valid board identifier.`);\n }\n}\n\nfunction validatePhaseSemantics(phaseId: string, phase: BoardPhaseDefinition<string>): void {\n if (!PHASE_KINDS.has(phase.kind as string)) {\n throw new BoardDefinitionError(`Phase \"${phaseId}\" must declare kind 'resting', 'working', or 'terminal'.`);\n }\n if (phase.kind === 'working') {\n const role: unknown = phase.role;\n if (typeof role !== 'string' || role.length === 0 || role.length > MAX_ROLE_LENGTH || !IDENTIFIER_RE.test(role)) {\n throw new BoardDefinitionError(`Working phase \"${phaseId}\" must declare a valid role.`);\n }\n } else if ((phase as { role?: unknown }).role !== undefined) {\n throw new BoardDefinitionError(`Phase \"${phaseId}\" is ${phase.kind} and cannot declare a role.`);\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction validateToolRules(tools: unknown): BoardToolRules {\n if (tools === undefined) return Object.freeze({});\n if (!isPlainObject(tools)) throw new BoardDefinitionError('Board tools must be a plain object.');\n const frozen: Record<string, BoardToolRule> = {};\n for (const [toolName, leaf] of Object.entries(tools)) {\n if (toolName.length === 0 || toolName.length > MAX_TOOL_NAME_LENGTH || !IDENTIFIER_RE.test(toolName)) {\n throw new BoardDefinitionError(`Tool rule \"${toolName}\" has an invalid tool name.`);\n }\n if (!isPlainObject(leaf) || Object.keys(leaf).some(key => key !== 'onResult')) {\n throw new BoardDefinitionError(`Tool rule \"${toolName}\" must be an object with only onResult.`);\n }\n if (typeof leaf.onResult !== 'function') {\n throw new BoardDefinitionError(`Tool rule \"${toolName}\" must declare an onResult function.`);\n }\n frozen[toolName] = Object.freeze({ onResult: leaf.onResult as BoardToolResultRuleHandler });\n }\n return Object.freeze(frozen);\n}\n\nexport function defineBoard<\n const BoardId extends string,\n const Phases extends Record<string, BoardPhaseDefinition<keyof Phases & string>>,\n>(config: BoardConfig<BoardId, Phases>): BoardDefinition<BoardId, keyof Phases & string> {\n type PhaseId = keyof Phases & string;\n validateBoardIdentifier(config.id, 'Board id');\n if (config.transitionPolicy !== undefined && typeof config.transitionPolicy !== 'function') {\n throw new BoardDefinitionError('Board transitionPolicy must be a function.');\n }\n const tools = validateToolRules(config.tools);\n const phaseIds = new Set(Object.keys(config.phases));\n if (phaseIds.size === 0) throw new BoardDefinitionError('A board must define at least one phase.');\n if (!phaseIds.has(config.initialPhase)) {\n throw new BoardDefinitionError(`Initial phase \"${config.initialPhase}\" is not defined.`);\n }\n for (const [phaseId, phase] of Object.entries(config.phases)) {\n validateBoardIdentifier(phaseId, 'Phase id');\n validatePhaseSemantics(phaseId, phase);\n }\n if (config.phases[config.initialPhase]!.kind !== 'resting') {\n throw new BoardDefinitionError(`Initial phase \"${config.initialPhase}\" must be a resting phase.`);\n }\n\n const transitions = Object.fromEntries(\n Object.entries(config.phases).map(([phaseId, phase]) => {\n if (phase.next !== undefined && phase.outcomes) {\n throw new BoardDefinitionError(`Phase \"${phaseId}\" cannot define both next and outcomes.`);\n }\n const targets: BoardTransition<string>[] =\n phase.next !== undefined\n ? [Object.freeze({ outcome: null, to: phase.next })]\n : Object.entries(phase.outcomes ?? {}).map(([outcome, to]) => Object.freeze({ outcome, to }));\n for (const { to } of targets) {\n if (!phaseIds.has(to)) {\n throw new BoardDefinitionError(`Phase \"${phaseId}\" targets undefined phase \"${to}\".`);\n }\n }\n return [phaseId, Object.freeze(targets)];\n }),\n ) as Record<PhaseId, readonly BoardTransition<PhaseId>[]>;\n\n const phases = Object.freeze(\n Object.fromEntries(\n Object.entries(config.phases).map(([phaseId, phase]) => [\n phaseId,\n Object.freeze({\n title: phase.title,\n kind: phase.kind,\n ...(phase.kind === 'working' ? { role: phase.role } : {}),\n ...(phase.next !== undefined ? { next: phase.next } : {}),\n ...(phase.outcomes ? { outcomes: Object.freeze({ ...phase.outcomes }) } : {}),\n ...(phase.onEnter ? { onEnter: Object.freeze({ ...phase.onEnter }) } : {}),\n ...(phase.onExit ? { onExit: Object.freeze({ ...phase.onExit }) } : {}),\n }),\n ]),\n ),\n ) as Readonly<Record<PhaseId, BoardPhaseDefinition<PhaseId>>>;\n const rules = Object.freeze(\n Object.fromEntries(\n Object.entries(config.phases).flatMap(([phaseId, phase]) => {\n const sources = new Set([...Object.keys(phase.onEnter ?? {}), ...Object.keys(phase.onExit ?? {})]);\n if (sources.size === 0) return [];\n return [\n [\n phaseId,\n Object.freeze(\n Object.fromEntries(\n [...sources].map(source => [\n source,\n Object.freeze({\n ...(phase.onEnter?.[source as FactoryRuleSource]\n ? { onEnter: phase.onEnter[source as FactoryRuleSource] }\n : {}),\n ...(phase.onExit?.[source as FactoryRuleSource]\n ? { onExit: phase.onExit[source as FactoryRuleSource] }\n : {}),\n }),\n ]),\n ),\n ),\n ],\n ];\n }),\n ),\n ) as ReadonlyFactoryBoardRules;\n\n const kinds = new Map<string, BoardPhaseKind>();\n const roles = new Map<string, string>();\n const phaseByRole = new Map<string, PhaseId>();\n for (const [phaseId, phase] of Object.entries(phases) as [PhaseId, BoardPhaseDefinition<PhaseId>][]) {\n kinds.set(phaseId, phase.kind);\n if (phase.kind !== 'working') continue;\n roles.set(phaseId, phase.role);\n if (!phaseByRole.has(phase.role)) phaseByRole.set(phase.role, phaseId);\n }\n\n return Object.freeze({\n id: config.id,\n title: config.title,\n initialPhase: config.initialPhase,\n phases,\n transitions: Object.freeze(transitions),\n rules: Object.freeze(rules),\n tools,\n ...(config.transitionPolicy ? { transitionPolicy: config.transitionPolicy } : {}),\n allowsTransition(from: PhaseId, to: PhaseId) {\n return from === to || transitions[from]?.some(transition => transition.to === to) === true;\n },\n phaseKind: (phase: string) => kinds.get(phase),\n isWorking: (phase: string) => kinds.get(phase) === 'working',\n isTerminal: (phase: string) => kinds.get(phase) === 'terminal',\n roleForPhase: (phase: string) => roles.get(phase),\n phaseForRole: (role: string) => phaseByRole.get(role),\n });\n}\n"],"mappings":";;AA0FA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,OAAgB;AAClB;AAEA,MAAM,8BAAmC,IAAI,IAAoB;CAAC;CAAW;CAAW;AAAU,CAAC;AAEnG,SAAS,wBAAwB,OAAgB,OAAqB;CACpE,IAAI,CAAC,kBAAkB,KAAK,GAC1B,MAAM,IAAI,qBAAqB,GAAG,MAAM,mCAAmC;AAE/E;AAEA,SAAS,uBAAuB,SAAiB,OAA2C;CAC1F,IAAI,CAAC,YAAY,IAAI,MAAM,IAAc,GACvC,MAAM,IAAI,qBAAqB,UAAU,QAAQ,yDAAyD;CAE5G,IAAI,MAAM,SAAS,WAAW;EAC5B,MAAM,OAAgB,MAAM;EAC5B,IAAI,OAAO,SAAS,YAAY,KAAK,WAAW,KAAK,KAAK,SAAA,MAA4B,CAAC,cAAc,KAAK,IAAI,GAC5G,MAAM,IAAI,qBAAqB,kBAAkB,QAAQ,6BAA6B;CAE1F,OAAO,IAAK,MAA6B,SAAS,KAAA,GAChD,MAAM,IAAI,qBAAqB,UAAU,QAAQ,OAAO,MAAM,KAAK,4BAA4B;AAEnG;AAEA,SAAS,cAAc,OAAkD;CACvE,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG,OAAO;CAChF,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;AAEA,SA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EAAE,kBAAkB,OAAO,iBAAiB,IAAI,CAAC;EAC/E,iBAAiB,MAAe,IAAa;GAC3C,OAAO,SAAS,MAAM,YAAY,KAAK,EAAE,MAAK,eAAc,WAAW,OAAO,EAAE,MAAM;EACxF;EACA,YAAY,UAAkB,MAAM,IAAI,KAAK;EAC7C,YAAY,UAAkB,MAAM,IAAI,KAAK,MAAM;EACnD,aAAa,UAAkB,MAAM,IAAI,KAAK,MAAM;EACpD,eAAe,UAAkB,MAAM,IAAI,KAAK;EAChD,eAAe,SAAiB,YAAY,IAAI,IAAI;CACtD,CAAC;AACH"}
@@ -9,6 +9,6 @@ export { reviewBoard } from './review.js';
9
9
  export type { ReviewBoardPhase } from './review.js';
10
10
  export { workBoard } from './work.js';
11
11
  export type { WorkBoardPhase } from './work.js';
12
- export declare function builtInBoard(board: 'work' | 'review'): import("./define-board.js").BoardDefinition<"review", "intake" | "review" | "done" | "canceled"> | import("./define-board.js").BoardDefinition<"work", "intake" | "triage" | "planning" | "execute" | "review" | "done" | "canceled">;
12
+ export declare function builtInBoard(board: 'work' | 'review'): import("./define-board.js").BoardDefinition<"review", "review" | "intake" | "done" | "canceled"> | import("./define-board.js").BoardDefinition<"work", "review" | "intake" | "triage" | "planning" | "execute" | "done" | "canceled">;
13
13
  export declare function allowsBuiltInBoardTransition(board: 'work' | 'review', from: string, to: string): boolean;
14
14
  //# sourceMappingURL=index.d.ts.map
@@ -1,4 +1,4 @@
1
- export declare const reviewBoard: import("./define-board.js").BoardDefinition<"review", "intake" | "review" | "done" | "canceled">;
1
+ export declare const reviewBoard: import("./define-board.js").BoardDefinition<"review", "review" | "intake" | "done" | "canceled">;
2
2
  export type ReviewBoardPhase = keyof typeof reviewBoard.phases;
3
3
  export declare function isReviewBoardPhase(value: string): value is ReviewBoardPhase;
4
4
  //# sourceMappingURL=review.d.ts.map
@@ -1,4 +1,4 @@
1
1
  export type WorkBoardPhase = 'intake' | 'triage' | 'planning' | 'execute' | 'review' | 'done' | 'canceled';
2
- export declare const workBoard: import("./define-board.js").BoardDefinition<"work", "intake" | "triage" | "planning" | "execute" | "review" | "done" | "canceled">;
2
+ export declare const workBoard: import("./define-board.js").BoardDefinition<"work", "review" | "intake" | "triage" | "planning" | "execute" | "done" | "canceled">;
3
3
  export declare function isWorkBoardPhase(value: string): value is WorkBoardPhase;
4
4
  //# sourceMappingURL=work.d.ts.map
@@ -1,6 +1,6 @@
1
- import { needsApproval } from "../rules/types.js";
2
1
  import { defineBoard } from "./define-board.js";
3
2
  import { workItemNumber } from "../work-item-branch.js";
3
+ import { needsApproval } from "../rules/types.js";
4
4
  import { advanceApprovedPlan } from "./work-tool-rules.js";
5
5
  import { workTransitionPolicy } from "./work-transition-policy.js";
6
6
  //#region src/boards/work.ts
@@ -1 +1 @@
1
- {"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../src/factory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAQH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAGlD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAWxD,OAAO,KAAK,EAAiB,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEvE,OAAO,KAAK,EAAE,kBAAkB,EAAgD,MAAM,wBAAwB,CAAC;AA2B/G,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAE/E,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAsCtE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAI1D,8EAA8E;AAC9E,MAAM,MAAM,UAAU,GAAG,WAAW,CAAC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