@mastra/factory 0.28.0-alpha.0 → 0.28.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +528 -161
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +12 -6
- package/dist/auth.js.map +1 -1
- package/dist/boards/board-events.d.ts +54 -0
- package/dist/boards/board-events.d.ts.map +1 -0
- package/dist/boards/board-events.js +87 -0
- package/dist/boards/board-events.js.map +1 -0
- package/dist/boards/board-writes.d.ts +86 -0
- package/dist/boards/board-writes.d.ts.map +1 -0
- package/dist/boards/board-writes.js +266 -0
- package/dist/boards/board-writes.js.map +1 -0
- package/dist/boards/card-facts.d.ts +3 -1
- package/dist/boards/card-facts.d.ts.map +1 -1
- package/dist/boards/card-facts.js +30 -4
- package/dist/boards/card-facts.js.map +1 -1
- package/dist/boards/default-board.d.ts +7 -0
- package/dist/boards/default-board.d.ts.map +1 -0
- package/dist/boards/default-board.js +10 -0
- package/dist/boards/default-board.js.map +1 -0
- package/dist/boards/define-board.d.ts +56 -23
- package/dist/boards/define-board.d.ts.map +1 -1
- package/dist/boards/define-board.js +89 -45
- package/dist/boards/define-board.js.map +1 -1
- package/dist/boards/index.d.ts +6 -9
- package/dist/boards/index.d.ts.map +1 -1
- package/dist/boards/index.js +6 -20
- package/dist/boards/intake-routing.d.ts +55 -11
- package/dist/boards/intake-routing.d.ts.map +1 -1
- package/dist/boards/intake-routing.js +109 -19
- package/dist/boards/intake-routing.js.map +1 -1
- package/dist/boards/legacy-plan-role.d.ts.map +1 -1
- package/dist/boards/legacy-plan-role.js +14 -5
- package/dist/boards/legacy-plan-role.js.map +1 -1
- package/dist/boards/phase-automation.d.ts +7 -0
- package/dist/boards/phase-automation.d.ts.map +1 -1
- package/dist/boards/phase-automation.js +19 -3
- package/dist/boards/phase-automation.js.map +1 -1
- package/dist/boards/phase-runner.d.ts +18 -10
- package/dist/boards/phase-runner.d.ts.map +1 -1
- package/dist/boards/phase-runner.js +39 -34
- package/dist/boards/phase-runner.js.map +1 -1
- package/dist/boards/project-boards.d.ts +65 -8
- package/dist/boards/project-boards.d.ts.map +1 -1
- package/dist/boards/project-boards.js +217 -26
- package/dist/boards/project-boards.js.map +1 -1
- package/dist/boards/registry.d.ts +7 -1
- package/dist/boards/registry.d.ts.map +1 -1
- package/dist/boards/registry.js +19 -4
- package/dist/boards/registry.js.map +1 -1
- package/dist/boards/relocate.d.ts +1 -1
- package/dist/boards/relocate.d.ts.map +1 -1
- package/dist/boards/relocate.js +3 -2
- package/dist/boards/relocate.js.map +1 -1
- package/dist/boards/review.d.ts +5 -2
- package/dist/boards/review.d.ts.map +1 -1
- package/dist/boards/review.js +12 -11
- package/dist/boards/review.js.map +1 -1
- package/dist/boards/semantics.d.ts +160 -20
- package/dist/boards/semantics.d.ts.map +1 -1
- package/dist/boards/semantics.js +255 -23
- package/dist/boards/semantics.js.map +1 -1
- package/dist/boards/stored-board.d.ts +73 -1
- package/dist/boards/stored-board.d.ts.map +1 -1
- package/dist/boards/stored-board.js +157 -11
- package/dist/boards/stored-board.js.map +1 -1
- package/dist/boards/work-migrations.d.ts +43 -0
- package/dist/boards/work-migrations.d.ts.map +1 -0
- package/dist/boards/work-migrations.js +353 -0
- package/dist/boards/work-migrations.js.map +1 -0
- package/dist/boards/work-routes.d.ts +58 -0
- package/dist/boards/work-routes.d.ts.map +1 -0
- package/dist/boards/work-routes.js +270 -0
- package/dist/boards/work-routes.js.map +1 -0
- package/dist/boards/work-seeds.d.ts +9 -0
- package/dist/boards/work-seeds.d.ts.map +1 -0
- package/dist/boards/work-seeds.js +56 -0
- package/dist/boards/work-seeds.js.map +1 -0
- package/dist/boards/work.d.ts +8 -19
- package/dist/boards/work.d.ts.map +1 -1
- package/dist/boards/work.js +33 -281
- package/dist/boards/work.js.map +1 -1
- package/dist/environment/build-runner.d.ts.map +1 -1
- package/dist/environment/build-runner.js +2 -2
- package/dist/environment/build-runner.js.map +1 -1
- package/dist/environment/build-workflow.d.ts.map +1 -1
- package/dist/environment/build-workflow.js +6 -5
- package/dist/environment/build-workflow.js.map +1 -1
- package/dist/environment/build.d.ts +15 -2
- package/dist/environment/build.d.ts.map +1 -1
- package/dist/environment/build.js +32 -9
- package/dist/environment/build.js.map +1 -1
- package/dist/factory.d.ts +90 -9
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +334 -141
- package/dist/factory.js.map +1 -1
- package/dist/feed-events.d.ts +4 -4
- package/dist/feed-events.d.ts.map +1 -1
- package/dist/feed-events.js +6 -6
- package/dist/feed-events.js.map +1 -1
- package/dist/index.d.ts +10 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -4
- package/dist/integrations/base.d.ts +12 -13
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/closing-references.d.ts +15 -0
- package/dist/integrations/closing-references.d.ts.map +1 -0
- package/dist/integrations/closing-references.js +69 -0
- package/dist/integrations/closing-references.js.map +1 -0
- package/dist/integrations/github/acceptance-labels.d.ts +4 -0
- package/dist/integrations/github/acceptance-labels.d.ts.map +1 -1
- package/dist/integrations/github/acceptance-labels.js +1 -1
- package/dist/integrations/github/acceptance-labels.js.map +1 -1
- package/dist/integrations/github/default-rules.d.ts +17 -75
- package/dist/integrations/github/default-rules.d.ts.map +1 -1
- package/dist/integrations/github/default-rules.js +134 -77
- package/dist/integrations/github/default-rules.js.map +1 -1
- package/dist/integrations/github/integration.d.ts.map +1 -1
- package/dist/integrations/github/integration.js +7 -3
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/github/issue-reconciler.js +21 -3
- package/dist/integrations/github/issue-reconciler.js.map +1 -1
- package/dist/integrations/github/provenance.js +1 -1
- package/dist/integrations/github/provenance.js.map +1 -1
- package/dist/integrations/github/pull-request-source.d.ts +8 -0
- package/dist/integrations/github/pull-request-source.d.ts.map +1 -0
- package/dist/integrations/github/pull-request-source.js +17 -0
- package/dist/integrations/github/pull-request-source.js.map +1 -0
- package/dist/integrations/github/reconcile-worker.d.ts +5 -1
- package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
- package/dist/integrations/github/reconcile-worker.js +39 -6
- package/dist/integrations/github/reconcile-worker.js.map +1 -1
- package/dist/integrations/github/review-status-comment.d.ts +61 -0
- package/dist/integrations/github/review-status-comment.d.ts.map +1 -0
- package/dist/integrations/github/review-status-comment.js +217 -0
- package/dist/integrations/github/review-status-comment.js.map +1 -0
- package/dist/integrations/github/review-status-reporter.d.ts +42 -0
- package/dist/integrations/github/review-status-reporter.d.ts.map +1 -0
- package/dist/integrations/github/review-status-reporter.js +104 -0
- package/dist/integrations/github/review-status-reporter.js.map +1 -0
- package/dist/integrations/github/review-status.d.ts +28 -0
- package/dist/integrations/github/review-status.d.ts.map +1 -0
- package/dist/integrations/github/review-status.js +95 -0
- package/dist/integrations/github/review-status.js.map +1 -0
- package/dist/integrations/github/routes.d.ts +4 -3
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +11 -91
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/rules.d.ts +92 -8
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +498 -103
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/sandbox.d.ts +10 -2
- package/dist/integrations/github/sandbox.d.ts.map +1 -1
- package/dist/integrations/github/sandbox.js +20 -4
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/github/session-subscriptions.js +2 -2
- package/dist/integrations/github/session-subscriptions.js.map +1 -1
- package/dist/integrations/github/token-refresh.d.ts +2 -1
- package/dist/integrations/github/token-refresh.d.ts.map +1 -1
- package/dist/integrations/github/token-refresh.js.map +1 -1
- package/dist/integrations/gitlab/agent-tools.js +1 -1
- package/dist/integrations/gitlab/default-rules.d.ts +96 -39
- package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/default-rules.js +109 -46
- package/dist/integrations/gitlab/default-rules.js.map +1 -1
- package/dist/integrations/gitlab/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/gitlab/issue-reconciler.js +2 -1
- package/dist/integrations/gitlab/issue-reconciler.js.map +1 -1
- package/dist/integrations/gitlab/merge-request-reconciler.d.ts.map +1 -1
- package/dist/integrations/gitlab/merge-request-reconciler.js +12 -5
- package/dist/integrations/gitlab/merge-request-reconciler.js.map +1 -1
- package/dist/integrations/gitlab/routes.d.ts.map +1 -1
- package/dist/integrations/gitlab/routes.js +2 -6
- package/dist/integrations/gitlab/routes.js.map +1 -1
- package/dist/integrations/gitlab/rules.d.ts +22 -1
- package/dist/integrations/gitlab/rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/rules.js +188 -34
- package/dist/integrations/gitlab/rules.js.map +1 -1
- package/dist/integrations/gitlab/session-subscriptions.js +1 -1
- package/dist/integrations/incidentio/agent-tools.js +6 -6
- package/dist/integrations/incidentio/agent-tools.js.map +1 -1
- package/dist/integrations/incidentio/default-rules.d.ts +1 -9
- package/dist/integrations/incidentio/default-rules.d.ts.map +1 -1
- package/dist/integrations/incidentio/default-rules.js +6 -7
- package/dist/integrations/incidentio/default-rules.js.map +1 -1
- package/dist/integrations/incidentio/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/incidentio/issue-reconciler.js +2 -1
- package/dist/integrations/incidentio/issue-reconciler.js.map +1 -1
- package/dist/integrations/incidentio/routes.d.ts +2 -2
- package/dist/integrations/incidentio/routes.d.ts.map +1 -1
- package/dist/integrations/incidentio/routes.js +11 -17
- package/dist/integrations/incidentio/routes.js.map +1 -1
- package/dist/integrations/incidentio/rules.d.ts +11 -4
- package/dist/integrations/incidentio/rules.d.ts.map +1 -1
- package/dist/integrations/incidentio/rules.js +52 -16
- package/dist/integrations/incidentio/rules.js.map +1 -1
- package/dist/integrations/issue-reconciler.js +1 -1
- package/dist/integrations/issue-reconciler.js.map +1 -1
- package/dist/integrations/jira/agent-tools.js +1 -1
- package/dist/integrations/jira/binding-scope.d.ts +5 -6
- package/dist/integrations/jira/binding-scope.d.ts.map +1 -1
- package/dist/integrations/jira/binding-scope.js +9 -11
- package/dist/integrations/jira/binding-scope.js.map +1 -1
- package/dist/integrations/jira/default-rules.d.ts +1 -9
- package/dist/integrations/jira/default-rules.d.ts.map +1 -1
- package/dist/integrations/jira/default-rules.js +6 -7
- package/dist/integrations/jira/default-rules.js.map +1 -1
- package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/jira/issue-reconciler.js +2 -1
- package/dist/integrations/jira/issue-reconciler.js.map +1 -1
- package/dist/integrations/jira/routes.d.ts.map +1 -1
- package/dist/integrations/jira/routes.js +4 -9
- package/dist/integrations/jira/routes.js.map +1 -1
- package/dist/integrations/jira/rules.d.ts +11 -4
- package/dist/integrations/jira/rules.d.ts.map +1 -1
- package/dist/integrations/jira/rules.js +52 -16
- package/dist/integrations/jira/rules.js.map +1 -1
- package/dist/integrations/linear/agent-tools.d.ts +9 -1
- package/dist/integrations/linear/agent-tools.d.ts.map +1 -1
- package/dist/integrations/linear/agent-tools.js +81 -3
- package/dist/integrations/linear/agent-tools.js.map +1 -1
- package/dist/integrations/linear/default-rules.d.ts +1 -9
- package/dist/integrations/linear/default-rules.d.ts.map +1 -1
- package/dist/integrations/linear/default-rules.js +6 -7
- package/dist/integrations/linear/default-rules.js.map +1 -1
- package/dist/integrations/linear/integration.d.ts +4 -1
- package/dist/integrations/linear/integration.d.ts.map +1 -1
- package/dist/integrations/linear/integration.js +21 -1
- package/dist/integrations/linear/integration.js.map +1 -1
- package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/linear/issue-reconciler.js +2 -1
- package/dist/integrations/linear/issue-reconciler.js.map +1 -1
- package/dist/integrations/linear/routes.d.ts +2 -1
- package/dist/integrations/linear/routes.d.ts.map +1 -1
- package/dist/integrations/linear/routes.js +16 -21
- package/dist/integrations/linear/routes.js.map +1 -1
- package/dist/integrations/linear/rules.d.ts +11 -4
- package/dist/integrations/linear/rules.d.ts.map +1 -1
- package/dist/integrations/linear/rules.js +50 -17
- package/dist/integrations/linear/rules.js.map +1 -1
- package/dist/integrations/platform/connect/routes.d.ts +7 -1
- package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
- package/dist/integrations/platform/connect/routes.js +42 -5
- package/dist/integrations/platform/connect/routes.js.map +1 -1
- package/dist/integrations/platform/connect/session-tools.d.ts +12 -0
- package/dist/integrations/platform/connect/session-tools.d.ts.map +1 -0
- package/dist/integrations/platform/connect/session-tools.js +35 -0
- package/dist/integrations/platform/connect/session-tools.js.map +1 -0
- package/dist/integrations/platform/github/event-worker.d.ts +4 -1
- package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +39 -3
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts +8 -0
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +132 -90
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/jira/agent-tools.js +1 -1
- package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
- package/dist/integrations/platform/jira/routes.js +4 -9
- package/dist/integrations/platform/jira/routes.js.map +1 -1
- package/dist/integrations/platform/linear/event-worker.d.ts +1 -1
- package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/linear/event-worker.js +10 -1
- package/dist/integrations/platform/linear/event-worker.js.map +1 -1
- package/dist/integrations/platform/linear/integration.d.ts +1 -1
- package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
- package/dist/integrations/platform/linear/integration.js +7 -8
- package/dist/integrations/platform/linear/integration.js.map +1 -1
- package/dist/integrations/slack/channel-reply-processor.d.ts +2 -0
- package/dist/integrations/slack/channel-reply-processor.d.ts.map +1 -1
- package/dist/integrations/slack/channel-reply-processor.js +6 -1
- package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
- package/dist/integrations/slack/chat-tools.js +1 -1
- package/dist/integrations/slack/connect-route.d.ts.map +1 -1
- package/dist/integrations/slack/connect-route.js +1 -1
- package/dist/integrations/slack/connect-route.js.map +1 -1
- package/dist/integrations/slack/integration.d.ts +0 -2
- package/dist/integrations/slack/integration.d.ts.map +1 -1
- package/dist/integrations/slack/integration.js +2 -5
- package/dist/integrations/slack/integration.js.map +1 -1
- package/dist/integrations/slack/reply-tool.js +1 -1
- package/dist/integrations/slack/run-error-card.js +1 -0
- package/dist/integrations/slack/run-error-card.js.map +1 -1
- package/dist/integrations/slack/share-file-tool.js +1 -1
- package/dist/integrations/slack/slack.d.ts +23 -30
- package/dist/integrations/slack/slack.d.ts.map +1 -1
- package/dist/integrations/slack/slack.js +131 -125
- package/dist/integrations/slack/slack.js.map +1 -1
- package/dist/integrations/slack/voice-clips.d.ts +32 -0
- package/dist/integrations/slack/voice-clips.d.ts.map +1 -0
- package/dist/integrations/slack/voice-clips.js +201 -0
- package/dist/integrations/slack/voice-clips.js.map +1 -0
- package/dist/integrations/workos/integration.d.ts.map +1 -1
- package/dist/integrations/workos/integration.js +1 -3
- package/dist/integrations/workos/integration.js.map +1 -1
- package/dist/links.d.ts +1 -2
- package/dist/links.d.ts.map +1 -1
- package/dist/links.js +4 -4
- package/dist/links.js.map +1 -1
- package/dist/mcp/routes.js +2 -2
- package/dist/mcp/routes.js.map +1 -1
- package/dist/packages/_internals/workspace/dist/index.js +1 -1
- package/dist/provider-display-name.d.ts.map +1 -1
- package/dist/provider-display-name.js +1 -0
- package/dist/provider-display-name.js.map +1 -1
- package/dist/routes/attention-parked.d.ts +1 -0
- package/dist/routes/attention-parked.d.ts.map +1 -1
- package/dist/routes/attention-parked.js +2 -2
- package/dist/routes/attention-parked.js.map +1 -1
- package/dist/routes/attention-providers.d.ts +0 -25
- package/dist/routes/attention-providers.d.ts.map +1 -1
- package/dist/routes/attention-providers.js +3 -151
- package/dist/routes/attention-providers.js.map +1 -1
- package/dist/routes/attention.d.ts +0 -2
- package/dist/routes/attention.d.ts.map +1 -1
- package/dist/routes/attention.js +2 -13
- package/dist/routes/attention.js.map +1 -1
- package/dist/routes/automation-runs.d.ts +5 -1
- package/dist/routes/automation-runs.d.ts.map +1 -1
- package/dist/routes/automation-runs.js +16 -4
- package/dist/routes/automation-runs.js.map +1 -1
- package/dist/routes/board-snapshot.d.ts +15 -0
- package/dist/routes/board-snapshot.d.ts.map +1 -0
- package/dist/routes/board-snapshot.js +41 -0
- package/dist/routes/board-snapshot.js.map +1 -0
- package/dist/routes/boards.d.ts +9 -7
- package/dist/routes/boards.d.ts.map +1 -1
- package/dist/routes/boards.js +59 -145
- package/dist/routes/boards.js.map +1 -1
- package/dist/routes/config.d.ts +11 -1
- package/dist/routes/config.d.ts.map +1 -1
- package/dist/routes/config.js +122 -29
- package/dist/routes/config.js.map +1 -1
- package/dist/routes/contracts.d.ts +366 -34
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +179 -51
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/feed-events.d.ts +15 -0
- package/dist/routes/feed-events.d.ts.map +1 -0
- package/dist/routes/feed-events.js +68 -0
- package/dist/routes/feed-events.js.map +1 -0
- package/dist/routes/fs.d.ts +4 -0
- package/dist/routes/fs.d.ts.map +1 -1
- package/dist/routes/fs.js +9 -8
- package/dist/routes/fs.js.map +1 -1
- package/dist/routes/intake-routes.d.ts.map +1 -1
- package/dist/routes/intake-routes.js +25 -13
- package/dist/routes/intake-routes.js.map +1 -1
- package/dist/routes/intake.d.ts +0 -23
- package/dist/routes/intake.d.ts.map +1 -1
- package/dist/routes/intake.js +16 -314
- package/dist/routes/intake.js.map +1 -1
- package/dist/routes/knowledge.d.ts.map +1 -1
- package/dist/routes/knowledge.js +2 -5
- package/dist/routes/knowledge.js.map +1 -1
- package/dist/routes/mastra-gateway.d.ts +19 -0
- package/dist/routes/mastra-gateway.d.ts.map +1 -0
- package/dist/routes/mastra-gateway.js +120 -0
- package/dist/routes/mastra-gateway.js.map +1 -0
- package/dist/routes/oauth.d.ts.map +1 -1
- package/dist/routes/oauth.js +1 -4
- package/dist/routes/oauth.js.map +1 -1
- package/dist/routes/projects.d.ts +3 -0
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +80 -61
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/provider-credentials.d.ts +6 -1
- package/dist/routes/provider-credentials.d.ts.map +1 -1
- package/dist/routes/provider-credentials.js +44 -3
- package/dist/routes/provider-credentials.js.map +1 -1
- package/dist/routes/route.d.ts +8 -0
- package/dist/routes/route.d.ts.map +1 -1
- package/dist/routes/route.js +5 -1
- package/dist/routes/route.js.map +1 -1
- package/dist/routes/running-packages.d.ts +13 -0
- package/dist/routes/running-packages.d.ts.map +1 -0
- package/dist/routes/running-packages.js +45 -0
- package/dist/routes/running-packages.js.map +1 -0
- package/dist/routes/sandbox-envs.d.ts +26 -0
- package/dist/routes/sandbox-envs.d.ts.map +1 -0
- package/dist/routes/sandbox-envs.js +180 -0
- package/dist/routes/sandbox-envs.js.map +1 -0
- package/dist/routes/session-access.d.ts.map +1 -1
- package/dist/routes/session-access.js +12 -3
- package/dist/routes/session-access.js.map +1 -1
- package/dist/routes/skills.d.ts.map +1 -1
- package/dist/routes/skills.js +1 -4
- package/dist/routes/skills.js.map +1 -1
- package/dist/routes/source-control-sessions.d.ts.map +1 -1
- package/dist/routes/source-control-sessions.js +1 -3
- package/dist/routes/source-control-sessions.js.map +1 -1
- package/dist/routes/source-control-settings.d.ts.map +1 -1
- package/dist/routes/source-control-settings.js +3 -2
- package/dist/routes/source-control-settings.js.map +1 -1
- package/dist/routes/surface.d.ts +13 -9
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +116 -43
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/tenant-credentials.d.ts.map +1 -1
- package/dist/routes/tenant-credentials.js +5 -1
- package/dist/routes/tenant-credentials.js.map +1 -1
- package/dist/routes/voice.d.ts +48 -0
- package/dist/routes/voice.d.ts.map +1 -0
- package/dist/routes/voice.js +248 -0
- package/dist/routes/voice.js.map +1 -0
- package/dist/routes/work-items.d.ts +0 -3
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +39 -14
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/binding-context.d.ts.map +1 -1
- package/dist/rules/binding-context.js +1 -0
- package/dist/rules/binding-context.js.map +1 -1
- package/dist/rules/decision-applicability.js +1 -1
- package/dist/rules/dispatcher.d.ts +28 -9
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +734 -143
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/event-rules.d.ts +71 -1
- package/dist/rules/event-rules.d.ts.map +1 -1
- package/dist/rules/event-rules.js +94 -1
- package/dist/rules/event-rules.js.map +1 -1
- package/dist/rules/index.d.ts +2 -4
- package/dist/rules/index.d.ts.map +1 -1
- package/dist/rules/index.js +2 -3
- package/dist/rules/phase-goal.d.ts +54 -0
- package/dist/rules/phase-goal.d.ts.map +1 -0
- package/dist/rules/phase-goal.js +70 -0
- package/dist/rules/phase-goal.js.map +1 -0
- package/dist/rules/phase-tools.d.ts +11 -0
- package/dist/rules/phase-tools.d.ts.map +1 -0
- package/dist/rules/phase-tools.js +19 -0
- package/dist/rules/phase-tools.js.map +1 -0
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +116 -15
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/review-source-tool.d.ts +4 -1
- package/dist/rules/review-source-tool.d.ts.map +1 -1
- package/dist/rules/review-source-tool.js +24 -4
- package/dist/rules/review-source-tool.js.map +1 -1
- package/dist/rules/rule-group.d.ts +1 -1
- package/dist/rules/rule-group.d.ts.map +1 -1
- package/dist/rules/rule-group.js +15 -6
- package/dist/rules/rule-group.js.map +1 -1
- package/dist/rules/start-coordinator.d.ts +5 -1
- package/dist/rules/start-coordinator.d.ts.map +1 -1
- package/dist/rules/start-coordinator.js +9 -3
- package/dist/rules/start-coordinator.js.map +1 -1
- package/dist/rules/tools.d.ts.map +1 -1
- package/dist/rules/tools.js +39 -28
- package/dist/rules/tools.js.map +1 -1
- package/dist/rules/transition-service.d.ts +10 -7
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +63 -55
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/rules/types.d.ts +140 -39
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js +7 -41
- package/dist/rules/types.js.map +1 -1
- package/dist/rules/validation.d.ts.map +1 -1
- package/dist/rules/validation.js +89 -4
- package/dist/rules/validation.js.map +1 -1
- package/dist/run-error.d.ts +1 -1
- package/dist/run-error.d.ts.map +1 -1
- package/dist/run-error.js +38 -5
- package/dist/run-error.js.map +1 -1
- package/dist/sandbox/sandbox-env-cache.d.ts +33 -0
- package/dist/sandbox/sandbox-env-cache.d.ts.map +1 -0
- package/dist/sandbox/sandbox-env-cache.js +140 -0
- package/dist/sandbox/sandbox-env-cache.js.map +1 -0
- package/dist/sandbox/sandbox-env.d.ts +77 -0
- package/dist/sandbox/sandbox-env.d.ts.map +1 -0
- package/dist/sandbox/sandbox-env.js +130 -0
- package/dist/sandbox/sandbox-env.js.map +1 -0
- package/dist/secret-encryption.d.ts +21 -0
- package/dist/secret-encryption.d.ts.map +1 -1
- package/dist/secret-encryption.js +31 -4
- package/dist/secret-encryption.js.map +1 -1
- package/dist/session/credential-policy.d.ts +2 -2
- package/dist/session/credential-policy.d.ts.map +1 -1
- package/dist/session/credential-policy.js +3 -3
- package/dist/session/credential-policy.js.map +1 -1
- package/dist/session/default-model-hydration.d.ts +2 -2
- package/dist/session/default-model-hydration.d.ts.map +1 -1
- package/dist/session/default-model-hydration.js +4 -4
- package/dist/session/default-model-hydration.js.map +1 -1
- package/dist/session/live-sessions.d.ts +11 -4
- package/dist/session/live-sessions.d.ts.map +1 -1
- package/dist/session/live-sessions.js +31 -10
- package/dist/session/live-sessions.js.map +1 -1
- package/dist/session/self-review-gate.d.ts +6 -4
- package/dist/session/self-review-gate.d.ts.map +1 -1
- package/dist/session/self-review-gate.js +9 -12
- package/dist/session/self-review-gate.js.map +1 -1
- package/dist/session/session-threads.d.ts +10 -3
- package/dist/session/session-threads.d.ts.map +1 -1
- package/dist/session/session-threads.js +11 -1
- package/dist/session/session-threads.js.map +1 -1
- package/dist/session/source-control-tools.d.ts +39 -13
- package/dist/session/source-control-tools.d.ts.map +1 -1
- package/dist/session/source-control-tools.js +55 -61
- package/dist/session/source-control-tools.js.map +1 -1
- package/dist/session/work-item-state-processor.d.ts +24 -0
- package/dist/session/work-item-state-processor.d.ts.map +1 -0
- package/dist/session/work-item-state-processor.js +275 -0
- package/dist/session/work-item-state-processor.js.map +1 -0
- package/dist/skills/catalog.js +1 -1
- package/dist/storage/domains/audit/actions.d.ts +3 -2
- package/dist/storage/domains/audit/actions.d.ts.map +1 -1
- package/dist/storage/domains/audit/actions.js +7 -5
- package/dist/storage/domains/audit/actions.js.map +1 -1
- package/dist/storage/domains/audit/domain.d.ts.map +1 -1
- package/dist/storage/domains/audit/domain.js +1 -3
- package/dist/storage/domains/audit/domain.js.map +1 -1
- package/dist/storage/domains/boards/base.d.ts +107 -23
- package/dist/storage/domains/boards/base.d.ts.map +1 -1
- package/dist/storage/domains/boards/base.js +201 -65
- package/dist/storage/domains/boards/base.js.map +1 -1
- package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
- package/dist/storage/domains/boards/schemas.js +25 -1
- package/dist/storage/domains/boards/schemas.js.map +1 -1
- package/dist/storage/domains/channel-identity/base.d.ts +0 -4
- package/dist/storage/domains/channel-identity/base.d.ts.map +1 -1
- package/dist/storage/domains/channel-identity/base.js +0 -7
- package/dist/storage/domains/channel-identity/base.js.map +1 -1
- package/dist/storage/domains/intake/base.d.ts +5 -45
- package/dist/storage/domains/intake/base.d.ts.map +1 -1
- package/dist/storage/domains/intake/base.js +11 -89
- package/dist/storage/domains/intake/base.js.map +1 -1
- package/dist/storage/domains/memory-settings/base.d.ts +0 -8
- package/dist/storage/domains/memory-settings/base.d.ts.map +1 -1
- package/dist/storage/domains/memory-settings/base.js +1 -11
- package/dist/storage/domains/memory-settings/base.js.map +1 -1
- package/dist/storage/domains/projects/base.d.ts +23 -9
- package/dist/storage/domains/projects/base.d.ts.map +1 -1
- package/dist/storage/domains/projects/base.js +24 -8
- package/dist/storage/domains/projects/base.js.map +1 -1
- package/dist/storage/domains/sandbox-envs/base.d.ts +70 -0
- package/dist/storage/domains/sandbox-envs/base.d.ts.map +1 -0
- package/dist/storage/domains/sandbox-envs/base.js +227 -0
- package/dist/storage/domains/sandbox-envs/base.js.map +1 -0
- package/dist/storage/domains/voice-settings/base.d.ts +31 -0
- package/dist/storage/domains/voice-settings/base.d.ts.map +1 -0
- package/dist/storage/domains/voice-settings/base.js +81 -0
- package/dist/storage/domains/voice-settings/base.js.map +1 -0
- package/dist/storage/domains/work-items/base.d.ts +93 -24
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +413 -188
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/storage/domains/work-items/board-version.d.ts +6 -2
- package/dist/storage/domains/work-items/board-version.d.ts.map +1 -1
- package/dist/storage/domains/work-items/board-version.js +20 -9
- package/dist/storage/domains/work-items/board-version.js.map +1 -1
- package/dist/storage/domains/work-items/cards.d.ts +33 -5
- package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
- package/dist/storage/domains/work-items/cards.js +208 -25
- package/dist/storage/domains/work-items/cards.js.map +1 -1
- package/dist/storage/domains/work-items/legacy-review.d.ts +63 -0
- package/dist/storage/domains/work-items/legacy-review.d.ts.map +1 -0
- package/dist/storage/domains/work-items/legacy-review.js +109 -0
- package/dist/storage/domains/work-items/legacy-review.js.map +1 -0
- package/dist/storage/domains/work-items/metrics.d.ts +12 -4
- package/dist/storage/domains/work-items/metrics.d.ts.map +1 -1
- package/dist/storage/domains/work-items/metrics.js +14 -32
- package/dist/storage/domains/work-items/metrics.js.map +1 -1
- package/dist/storage/domains/work-items/work-item-schema.d.ts +6 -2
- package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
- package/dist/storage/domains/work-items/work-item-schema.js +83 -27
- package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
- package/dist/timing.d.ts +1 -0
- package/dist/timing.d.ts.map +1 -1
- package/dist/timing.js +1 -1
- package/dist/timing.js.map +1 -1
- package/dist/tools/approval-tools.d.ts.map +1 -1
- package/dist/tools/approval-tools.js +28 -9
- package/dist/tools/approval-tools.js.map +1 -1
- package/dist/tools/index.d.ts +1 -1
- package/dist/tools/index.js +1 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/messaging-tools.d.ts +3 -0
- package/dist/tools/messaging-tools.d.ts.map +1 -1
- package/dist/tools/messaging-tools.js +2 -1
- package/dist/tools/messaging-tools.js.map +1 -1
- package/dist/tools/read-tools.d.ts +10 -6
- package/dist/tools/read-tools.d.ts.map +1 -1
- package/dist/tools/read-tools.js +89 -39
- package/dist/tools/read-tools.js.map +1 -1
- package/dist/tools/reports.d.ts +1 -0
- package/dist/tools/reports.d.ts.map +1 -1
- package/dist/tools/reports.js +2 -1
- package/dist/tools/reports.js.map +1 -1
- package/dist/tools/run-watch.d.ts +1 -1
- package/dist/tools/run-watch.d.ts.map +1 -1
- package/dist/tools/run-watch.js +1 -0
- package/dist/tools/run-watch.js.map +1 -1
- package/dist/tools/sandbox-tools.js +1 -1
- package/dist/tools/session-tools.d.ts +1 -1
- package/dist/tools/session-tools.d.ts.map +1 -1
- package/dist/tools/session-tools.js +1 -1
- package/dist/tools/session-tools.js.map +1 -1
- package/dist/tools/sessions-state-processor.d.ts +3 -1
- package/dist/tools/sessions-state-processor.d.ts.map +1 -1
- package/dist/tools/sessions-state-processor.js +13 -4
- package/dist/tools/sessions-state-processor.js.map +1 -1
- package/dist/tools/side-sessions.d.ts +2 -0
- package/dist/tools/side-sessions.d.ts.map +1 -1
- package/dist/tools/side-sessions.js +2 -1
- package/dist/tools/side-sessions.js.map +1 -1
- package/dist/tools/work-item-tools.d.ts +0 -3
- package/dist/tools/work-item-tools.d.ts.map +1 -1
- package/dist/tools/work-item-tools.js +10 -20
- package/dist/tools/work-item-tools.js.map +1 -1
- package/dist/voice/rate-limit.d.ts +13 -0
- package/dist/voice/rate-limit.d.ts.map +1 -0
- package/dist/voice/rate-limit.js +36 -0
- package/dist/voice/rate-limit.js.map +1 -0
- package/dist/voice/realtime.d.ts +13 -0
- package/dist/voice/realtime.d.ts.map +1 -0
- package/dist/voice/realtime.js +56 -0
- package/dist/voice/realtime.js.map +1 -0
- package/dist/voice/transcription.d.ts +51 -0
- package/dist/voice/transcription.d.ts.map +1 -0
- package/dist/voice/transcription.js +112 -0
- package/dist/voice/transcription.js.map +1 -0
- package/dist/work-item-branch.d.ts +13 -0
- package/dist/work-item-branch.d.ts.map +1 -1
- package/dist/work-item-branch.js +16 -1
- package/dist/work-item-branch.js.map +1 -1
- package/dist/work-items/create-work-item.d.ts +6 -0
- package/dist/work-items/create-work-item.d.ts.map +1 -1
- package/dist/work-items/create-work-item.js +28 -3
- package/dist/work-items/create-work-item.js.map +1 -1
- package/dist/work-items/description-context.d.ts +5 -0
- package/dist/work-items/description-context.d.ts.map +1 -0
- package/dist/work-items/description-context.js +17 -0
- package/dist/work-items/description-context.js.map +1 -0
- package/dist/work-items/providers/base.d.ts +4 -1
- package/dist/work-items/providers/base.d.ts.map +1 -1
- package/dist/work-items/providers/base.js +6 -1
- package/dist/work-items/providers/base.js.map +1 -1
- package/dist/work-items/providers/github.d.ts.map +1 -1
- package/dist/work-items/providers/github.js +2 -1
- package/dist/work-items/providers/github.js.map +1 -1
- package/dist/work-items/providers/gitlab.d.ts.map +1 -1
- package/dist/work-items/providers/gitlab.js +2 -1
- package/dist/work-items/providers/gitlab.js.map +1 -1
- package/dist/work-items/providers/jira.d.ts.map +1 -1
- package/dist/work-items/providers/jira.js +3 -2
- package/dist/work-items/providers/jira.js.map +1 -1
- package/dist/work-items/providers/linear.d.ts.map +1 -1
- package/dist/work-items/providers/linear.js +3 -2
- package/dist/work-items/providers/linear.js.map +1 -1
- package/dist/work-items/providers/types.d.ts +6 -0
- package/dist/work-items/providers/types.d.ts.map +1 -1
- package/dist/work-items/split-backfill.d.ts +13 -0
- package/dist/work-items/split-backfill.d.ts.map +1 -0
- package/dist/work-items/split-backfill.js +32 -0
- package/dist/work-items/split-backfill.js.map +1 -0
- package/dist/work-items/split-migration.d.ts +39 -2
- package/dist/work-items/split-migration.d.ts.map +1 -1
- package/dist/work-items/split-migration.js +178 -70
- package/dist/work-items/split-migration.js.map +1 -1
- package/dist/workspace.d.ts +3 -1
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +118 -34
- package/dist/workspace.js.map +1 -1
- package/factory-skills/configure-factory-rules/SKILL.md +13 -11
- package/factory-skills/factory-build/SKILL.md +64 -0
- package/factory-skills/factory-gitlab-rereview/SKILL.md +4 -4
- package/factory-skills/factory-gitlab-review/SKILL.md +6 -6
- package/factory-skills/factory-plan/SKILL.md +8 -10
- package/factory-skills/factory-rereview/SKILL.md +74 -28
- package/factory-skills/factory-review/SKILL.md +85 -29
- package/factory-skills/factory-self-review/SKILL.md +32 -13
- package/factory-skills/factory-triage/SKILL.md +36 -32
- package/package.json +12 -11
- package/dist/boards/index.js.map +0 -1
- package/dist/boards/pull-request-review.d.ts +0 -14
- package/dist/boards/pull-request-review.d.ts.map +0 -1
- package/dist/boards/pull-request-review.js +0 -81
- package/dist/boards/pull-request-review.js.map +0 -1
- package/dist/boards/work-tool-rules.d.ts +0 -8
- package/dist/boards/work-tool-rules.d.ts.map +0 -1
- package/dist/boards/work-tool-rules.js +0 -19
- package/dist/boards/work-tool-rules.js.map +0 -1
- package/dist/integrations/slack/emoji-shortcodes.generated.d.ts +0 -8
- package/dist/integrations/slack/emoji-shortcodes.generated.d.ts.map +0 -1
- package/dist/integrations/slack/emoji-shortcodes.generated.js +0 -1984
- package/dist/integrations/slack/emoji-shortcodes.generated.js.map +0 -1
- package/dist/integrations/slack/emoji.d.ts +0 -3
- package/dist/integrations/slack/emoji.d.ts.map +0 -1
- package/dist/integrations/slack/emoji.js +0 -11
- package/dist/integrations/slack/emoji.js.map +0 -1
- package/dist/integrations/slack/feed-publisher.d.ts +0 -26
- package/dist/integrations/slack/feed-publisher.d.ts.map +0 -1
- package/dist/integrations/slack/feed-publisher.js +0 -43
- package/dist/integrations/slack/feed-publisher.js.map +0 -1
- package/dist/routes/attention-activity.d.ts +0 -23
- package/dist/routes/attention-activity.d.ts.map +0 -1
- package/dist/routes/attention-activity.js +0 -154
- package/dist/routes/attention-activity.js.map +0 -1
- package/dist/rules/resolve.d.ts +0 -15
- package/dist/rules/resolve.d.ts.map +0 -1
- package/dist/rules/resolve.js +0 -22
- package/dist/rules/resolve.js.map +0 -1
- package/dist/storage/domains/comments/activity.d.ts +0 -40
- package/dist/storage/domains/comments/activity.d.ts.map +0 -1
- package/dist/storage/domains/comments/activity.js +0 -93
- package/dist/storage/domains/comments/activity.js.map +0 -1
- package/dist/storage/domains/comments/actor.d.ts +0 -51
- package/dist/storage/domains/comments/actor.d.ts.map +0 -1
- package/dist/storage/domains/comments/actor.js +0 -37
- package/dist/storage/domains/comments/actor.js.map +0 -1
- package/dist/storage/domains/comments/base.d.ts +0 -245
- package/dist/storage/domains/comments/base.d.ts.map +0 -1
- package/dist/storage/domains/comments/base.js +0 -539
- package/dist/storage/domains/comments/base.js.map +0 -1
- package/dist/storage/domains/comments/domain.d.ts +0 -135
- package/dist/storage/domains/comments/domain.d.ts.map +0 -1
- package/dist/storage/domains/comments/domain.js +0 -284
- package/dist/storage/domains/comments/domain.js.map +0 -1
- package/dist/storage/domains/comments/feed-context.d.ts +0 -22
- package/dist/storage/domains/comments/feed-context.d.ts.map +0 -1
- package/dist/storage/domains/comments/feed-context.js +0 -88
- package/dist/storage/domains/comments/feed-context.js.map +0 -1
- package/dist/storage/domains/comments/feed-sync.d.ts +0 -21
- package/dist/storage/domains/comments/feed-sync.d.ts.map +0 -1
- package/dist/storage/domains/comments/feed-sync.js +0 -1
- package/dist/storage/domains/comments/parse.d.ts +0 -23
- package/dist/storage/domains/comments/parse.d.ts.map +0 -1
- package/dist/storage/domains/comments/parse.js +0 -89
- package/dist/storage/domains/comments/parse.js.map +0 -1
- package/dist/storage/domains/comments/routes.d.ts +0 -24
- package/dist/storage/domains/comments/routes.d.ts.map +0 -1
- package/dist/storage/domains/comments/routes.js +0 -301
- package/dist/storage/domains/comments/routes.js.map +0 -1
- package/dist/storage/domains/comments/schema.d.ts +0 -5
- package/dist/storage/domains/comments/schema.d.ts.map +0 -1
- package/dist/storage/domains/comments/schema.js +0 -178
- package/dist/storage/domains/comments/schema.js.map +0 -1
- package/dist/storage/domains/comments/wire.d.ts +0 -40
- package/dist/storage/domains/comments/wire.d.ts.map +0 -1
- package/dist/storage/domains/comments/wire.js +0 -36
- package/dist/storage/domains/comments/wire.js.map +0 -1
- package/factory-skills/factory-complete-issue/SKILL.md +0 -24
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intake.js","names":[],"sources":["../../src/routes/intake.ts"],"sourcesContent":["import type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\nimport { z } from 'zod';\n\nimport type { BoardRegistry } from '../boards/index.js';\nimport { placedByIntakeRoute } from '../boards/intake-routing.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { cardLabels, moveCardToBoard } from '../boards/relocate.js';\nimport type { Intake, IntakeItem } from '../capabilities/intake.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.js';\nimport {\n FactoryProjectNotFoundError,\n normalizeBindingLabels,\n normalizeIntakeLabel,\n resolveIntakeLabelRoute,\n} from '../storage/domains/intake/base.js';\nimport type {\n IntakeBindingConflict,\n IntakeConfig,\n IntakeLabelRoute,\n IntakeStorage,\n} from '../storage/domains/intake/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport type { Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { RouteDependencies } from './route.js';\nimport { Route } from './route.js';\n\nexport interface IntakeIntegration {\n id: string;\n intake: Pick<Intake, 'listSources' | 'listItems' | 'bindingLabelFilters'>;\n}\n\ninterface AggregatedIntakeItem extends Omit<IntakeItem, 'source'> {\n integrationId: string;\n externalSource: {\n integrationId: string;\n type: string;\n externalId: string;\n url?: string;\n };\n}\n\nexport interface IntakeRoutesDeps extends RouteDependencies {\n audit: AuditEmitter;\n /** Intake selection domain handle. */\n intake: IntakeStorage;\n /** Factory project domain handle, used to validate binding targets. */\n projects?: { get(input: { orgId: string; id: string }): Promise<unknown | null> };\n integrations?: IntakeIntegration[];\n /**\n * Installed boards, used to validate binding targets. Absent means only legacy routing is accepted.\n * Integrations place cards with the code boards, so a target must be a code board.\n */\n boardRegistry?: BoardRegistry | ProjectBoardSource;\n /** Work items domain handle; when present, rebinding a source to another board moves its resting cards. */\n workItems?: Pick<WorkItemsStorage, 'list' | 'update' | 'supersedeDecisionsForWorkItem'>;\n /** GitHub repositories, used to match a card to the repository binding its source id names. */\n githubRepositories?: Pick<SourceControlStorageHandle['repositories'], 'get'>;\n}\n\n/** Upper bound on source pages read while relocating cards, so a huge source cannot stall the request. */\nconst REBIND_MAX_PAGES = 20;\n/**\n * One deadline for the whole rebind read, not one per page: the binding is already saved when we\n * get here, so the caller is only waiting on relocation and a slow provider must not hold the\n * response for pages × timeout.\n */\nconst REBIND_READ_BUDGET_MS = 30_000;\n\n/**\n * Keys under which an intake item may be persisted as a work item. Providers key items by their\n * own id, while materialization uses the human identifier (`linear:MAS-44`), so both are accepted.\n */\nfunction intakeItemSourceKeys(integrationId: string, item: IntakeItem): string[] {\n const identifier = item.metadata?.identifier;\n return typeof identifier === 'string' && identifier.length > 0\n ? [item.source.externalId, `${integrationId}:${identifier}`]\n : [item.source.externalId];\n}\n\n/**\n * Move the cards that came from a rebound source onto its new board's initial phase. Terminal cards\n * stay put (they are history that belongs where it finished), as do cards with a session attached to\n * a current stage (a run owns them). Everything else moves, including cards parked in a working\n * phase that never started a run — auto-ingested issues sit in Work › Triage that way.\n */\nasync function relocateSourceCards({\n workItems,\n integration,\n boardRegistry,\n orgId,\n userId,\n factoryProjectId,\n sourceId,\n targetBoard,\n attributionSourceIds,\n}: {\n workItems: Pick<WorkItemsStorage, 'list' | 'update' | 'supersedeDecisionsForWorkItem'>;\n integration: IntakeIntegration;\n boardRegistry: BoardRegistry;\n orgId: string;\n userId: string;\n factoryProjectId: string;\n sourceId: string;\n targetBoard: string;\n attributionSourceIds: string[];\n}): Promise<{ moved: number; skipped: number }> {\n if (!boardRegistry.has(targetBoard)) return { moved: 0, skipped: 0 };\n\n const sourceKeys = new Set<string>();\n let cursor: string | undefined;\n const deadline = Date.now() + REBIND_READ_BUDGET_MS;\n for (let page = 0; page < REBIND_MAX_PAGES; page += 1) {\n const result = await withTimeout(\n integration.id,\n () =>\n integration.intake.listItems({\n orgId,\n userId,\n sourceIds: [sourceId],\n attributionSourceIds,\n cursor,\n }),\n deadline - Date.now(),\n );\n for (const item of result.items) {\n if (item.sourceId !== sourceId) continue;\n for (const key of intakeItemSourceKeys(integration.id, item)) sourceKeys.add(key);\n }\n if (!result.nextCursor) break;\n cursor = result.nextCursor;\n }\n if (sourceKeys.size === 0) return { moved: 0, skipped: 0 };\n\n let moved = 0;\n let skipped = 0;\n const items = await workItems.list({ orgId, factoryProjectId });\n for (const item of items) {\n const source = item.externalSource;\n if (!source || source.integrationId !== integration.id || !sourceKeys.has(source.externalId)) continue;\n // An intake route chose this card's board; a rebind doesn't override it.\n if (placedByIntakeRoute(item)) {\n skipped += 1;\n continue;\n }\n const outcome = await moveCardToBoard({ workItems, boardRegistry, userId, item, targetBoard });\n if (outcome === 'moved') moved += 1;\n else if (outcome === 'skipped') skipped += 1;\n }\n return { moved, skipped };\n}\n\n/**\n * After a label route changes, every issue card in the project that carries `label` is re-routed\n * under the project's current routes: to the board its labels now select, or — when none of them is\n * routed any more — to its GitHub repository binding's board, falling back to Work.\n */\nasync function relocateLabeledCards({\n workItems,\n boardRegistry,\n orgId,\n userId,\n factoryProjectId,\n integrationId,\n label,\n routes,\n intake,\n githubRepositories,\n}: {\n workItems: Pick<WorkItemsStorage, 'list' | 'update' | 'supersedeDecisionsForWorkItem'>;\n boardRegistry: BoardRegistry;\n orgId: string;\n userId: string;\n factoryProjectId: string;\n integrationId: string;\n label: string;\n routes: readonly IntakeLabelRoute[];\n intake: Pick<IntakeStorage, 'listBindings'>;\n githubRepositories?: Pick<SourceControlStorageHandle['repositories'], 'get'>;\n}): Promise<{ moved: number; skipped: number }> {\n const changed = normalizeIntakeLabel(label);\n const repositoryBoards =\n integrationId === 'github'\n ? await githubRepositoryBoards({ intake, githubRepositories, boardRegistry, orgId, factoryProjectId })\n : [];\n let moved = 0;\n let skipped = 0;\n for (const item of await workItems.list({ orgId, factoryProjectId })) {\n const source = item.externalSource;\n if (!source || source.integrationId !== integrationId || source.type !== 'issue') continue;\n const labels = cardLabels(item);\n if (!labels.some(candidate => normalizeIntakeLabel(candidate) === changed)) continue;\n // An intake route chose this card's board; a label route change doesn't override it.\n if (placedByIntakeRoute(item)) {\n skipped += 1;\n continue;\n }\n const targetBoard =\n resolveIntakeLabelRoute(routes, labels)?.board ??\n repositoryBoards.find(candidate => cardInRepository(item, candidate))?.board ??\n 'work';\n const outcome = await moveCardToBoard({ workItems, boardRegistry, userId, item, targetBoard });\n if (outcome === 'moved') moved += 1;\n else if (outcome === 'skipped') skipped += 1;\n }\n return { moved, skipped };\n}\n\ninterface GithubRepositoryBoard {\n board: string;\n slug: string;\n externalId?: string;\n}\n\n/**\n * The project's GitHub repository bindings that name an installed board. A binding's source id is\n * the internal repository id or the repository slug, so ids are resolved to the slug and external id\n * a card carries.\n */\nasync function githubRepositoryBoards({\n intake,\n githubRepositories,\n boardRegistry,\n orgId,\n factoryProjectId,\n}: {\n intake: Pick<IntakeStorage, 'listBindings'>;\n githubRepositories?: Pick<SourceControlStorageHandle['repositories'], 'get'>;\n boardRegistry: BoardRegistry;\n orgId: string;\n factoryProjectId: string;\n}): Promise<GithubRepositoryBoard[]> {\n const boards: GithubRepositoryBoard[] = [];\n for (const binding of await intake.listBindings({ orgId, integrationId: 'github' })) {\n if (binding.factoryProjectId !== factoryProjectId || !binding.board || !boardRegistry.has(binding.board)) continue;\n const repository = await githubRepositories?.get({ orgId, id: binding.sourceId });\n boards.push(\n repository\n ? { board: binding.board, slug: repository.slug.toLowerCase(), externalId: repository.externalId }\n : { board: binding.board, slug: binding.sourceId.toLowerCase() },\n );\n }\n return boards;\n}\n\nfunction cardInRepository(item: Card, repository: GithubRepositoryBoard): boolean {\n const repositoryId = item.workItem.metadata?.githubRepositoryId;\n if (\n repository.externalId !== undefined &&\n repositoryId !== undefined &&\n String(repositoryId) === repository.externalId\n )\n return true;\n const match = /^https?:\\/\\/[^/]+\\/(.+)\\/(?:issues|pull)\\/\\d+(?:[/?#]|$)/.exec(item.externalSource?.url ?? '');\n return match?.[1]?.toLowerCase() === repository.slug;\n}\n\n/** One integration that failed while the rest of the aggregation succeeded. */\nexport interface IntakeIntegrationFailure {\n integrationId: string;\n message: string;\n}\n\ntype SettledIntegration<T> = { integrationId: string; value: T } | IntakeIntegrationFailure;\n\nconst PROVIDER_READ_TIMEOUT_MS = 15_000;\n\n/** The Intake contract takes no abort signal, so a slow read is abandoned, not cancelled. */\nfunction withTimeout<T>(\n integrationId: string,\n read: () => Promise<T>,\n timeoutMs: number = PROVIDER_READ_TIMEOUT_MS,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n const budget = Math.max(0, timeoutMs);\n const timer = setTimeout(\n () => reject(new Error(`${integrationId} did not answer within ${Math.round(budget / 1000)}s`)),\n budget,\n );\n read()\n .then(resolve, reject)\n .finally(() => clearTimeout(timer));\n });\n}\n\n/**\n * Read every integration concurrently and isolate the ones that throw or hang, so a single\n * unreachable provider degrades to a per-source error instead of failing the listing.\n */\nasync function settleByIntegration<T>(\n requests: Array<{ integrationId: string; read: () => Promise<T> }>,\n): Promise<{ pages: Array<{ integrationId: string; value: T }>; failures: IntakeIntegrationFailure[] }> {\n const settled = await Promise.all(\n requests.map(async ({ integrationId, read }): Promise<SettledIntegration<T>> => {\n try {\n return { integrationId, value: await withTimeout(integrationId, read) };\n } catch (error) {\n console.error(`[factory] intake integration ${integrationId} is unavailable:`, error);\n return { integrationId, message: error instanceof Error ? error.message : String(error) };\n }\n }),\n );\n const pages: Array<{ integrationId: string; value: T }> = [];\n const failures: IntakeIntegrationFailure[] = [];\n for (const entry of settled) {\n if ('value' in entry) pages.push(entry);\n else failures.push(entry);\n }\n return { pages, failures };\n}\n\nconst MAX_INTAKE_SOURCE_ID_LENGTH = 1024;\n\nconst identifier = z.string().min(1).max(256);\nconst sourceIdentifier = z.string().min(1).max(MAX_INTAKE_SOURCE_ID_LENGTH);\n\n/** Labels a shared binding takes; `[]` is rejected because \"all issues\" is spelled `null`. Jira labels never hold spaces. */\nconst bindingLabelsSchema = z\n .array(\n z\n .string()\n .max(255)\n .refine(label => !/\\s/.test(label.trim()), 'labels cannot contain spaces'),\n )\n .max(50)\n .transform(normalizeBindingLabels)\n .refine(labels => labels.length > 0, 'labels must name at least one label; use null for all issues');\n\nconst bindingBodySchema = z.object({\n integrationId: identifier,\n sourceId: sourceIdentifier,\n /** `null` unbinds the source (integrations without label filters only). */\n factoryProjectId: identifier.nullable(),\n /** Installed board target; `null`/omitted keeps legacy source-type routing. */\n board: identifier.nullish().transform(board => board ?? null),\n /** Label filter for integrations with `bindingLabelFilters`; `null` takes all issues, omitted keeps the current filter. */\n labels: bindingLabelsSchema.nullable().optional(),\n});\ntype ParsedBinding = z.output<typeof bindingBodySchema>;\n\n/** Validate a binding request body, rejecting unknown shapes. */\nexport function parseIntakeBinding(body: unknown): ParsedBinding | null {\n const parsed = bindingBodySchema.safeParse(body);\n return parsed.success ? parsed.data : null;\n}\n\nconst bindingDeleteQuerySchema = z.object({\n integrationId: identifier,\n sourceId: sourceIdentifier,\n factoryProjectId: identifier,\n});\n\nfunction bindingConflictMessage(conflicts: readonly IntakeBindingConflict[]): string {\n const labels = conflicts.flatMap(conflict => conflict.labels ?? []);\n return labels.length > 0\n ? `Already routed to another factory: ${labels.join(', ')}.`\n : 'Another factory already takes all issues from this source.';\n}\nconst labelRouteBodySchema = z.object({\n factoryProjectId: identifier,\n integrationId: identifier,\n label: z\n .string()\n .max(256)\n .transform(normalizeIntakeLabel)\n .refine(label => label.length > 0, 'label must not be blank'),\n /** Installed board target; `null` removes the route so the label falls back to Work. */\n board: identifier.nullish().transform(board => board ?? null),\n});\ntype ParsedLabelRoute = z.output<typeof labelRouteBodySchema>;\n\n/** Validate a label-route request body, rejecting unknown shapes. */\nexport function parseIntakeLabelRoute(body: unknown): ParsedLabelRoute | null {\n const parsed = labelRouteBodySchema.safeParse(body);\n return parsed.success ? parsed.data : null;\n}\n\nfunction loose(c: unknown): Context {\n return c as Context;\n}\n\nfunction sanitizeIdList(value: unknown): string[] | null | undefined {\n if (value === null) return null;\n if (!Array.isArray(value) || value.length > 200) return undefined;\n const ids = value.filter(\n (item): item is string => typeof item === 'string' && item.length > 0 && item.length <= MAX_INTAKE_SOURCE_ID_LENGTH,\n );\n return ids.length === value.length && new Set(ids).size === ids.length ? ids : undefined;\n}\n\nfunction sanitizeLinearRepositoryMap(value: unknown): Record<string, string> | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n const entries = Object.entries(value);\n if (entries.length > 200) return undefined;\n const mapping: Record<string, string> = Object.create(null);\n for (const [projectId, slug] of entries) {\n if (\n !projectId ||\n projectId.length > MAX_INTAKE_SOURCE_ID_LENGTH ||\n typeof slug !== 'string' ||\n !slug.trim() ||\n slug.length > 512\n ) {\n return undefined;\n }\n mapping[projectId] = slug;\n }\n return mapping;\n}\n\n/** Validate a request body into an intake config, rejecting unknown shapes. */\nexport function parseIntakeConfig(body: unknown): IntakeConfig | null {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) return null;\n const entries = Object.entries(body);\n if (entries.length > 50) return null;\n\n // Null-prototype so an `__proto__` key lands as a real entry instead of silently\n // reassigning the prototype and disappearing from the validation below.\n const config: IntakeConfig = Object.create(null);\n for (const [integrationId, value] of entries) {\n if (\n !integrationId ||\n integrationId.length > 128 ||\n typeof value !== 'object' ||\n value === null ||\n Array.isArray(value)\n ) {\n return null;\n }\n const selection = value as { enabled?: unknown; sourceIds?: unknown; repositoryByLinearProject?: unknown };\n if (typeof selection.enabled !== 'boolean') return null;\n const sourceIds = sanitizeIdList(selection.sourceIds ?? null);\n if (sourceIds === undefined) return null;\n const repositoryByLinearProject =\n integrationId === 'linear' ? sanitizeLinearRepositoryMap(selection.repositoryByLinearProject) : undefined;\n if (\n integrationId === 'linear' &&\n selection.repositoryByLinearProject !== undefined &&\n repositoryByLinearProject === undefined\n )\n return null;\n config[integrationId] = {\n enabled: selection.enabled,\n sourceIds,\n ...(repositoryByLinearProject ? { repositoryByLinearProject } : {}),\n };\n }\n return config;\n}\n\nfunction encodeCursor(cursors: Record<string, string>): string | null {\n return Object.keys(cursors).length > 0 ? Buffer.from(JSON.stringify(cursors)).toString('base64url') : null;\n}\n\nfunction decodeCursor(value: string | undefined): Record<string, string> | null {\n if (!value) return {};\n try {\n const parsed = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) as unknown;\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null;\n const entries = Object.entries(parsed);\n if (entries.some(([key, cursor]) => !key || typeof cursor !== 'string')) return null;\n return Object.fromEntries(entries) as Record<string, string>;\n } catch {\n return null;\n }\n}\n\nexport class IntakeRoutes extends Route<IntakeRoutesDeps> {\n async #resolveTenant(c: Context): Promise<{ orgId: string; userId: string } | { response: Response }> {\n await this.deps.auth.ensureUser(c);\n const tenant = this.deps.auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n { error: 'organization_required', message: 'Intake configuration requires an organization.' },\n 403,\n ),\n };\n }\n return { orgId: tenant.orgId, userId: tenant.userId };\n }\n\n routes(): ApiRoute[] {\n const { audit, intake, projects, integrations = [], workItems, githubRepositories } = this.deps;\n const integrationIds = integrations.map(integration => integration.id);\n const boardSource = this.deps.boardRegistry ? toBoardSource(this.deps.boardRegistry) : undefined;\n const projectBoards = (orgId: string, factoryProjectId: string | null) =>\n boardSource && factoryProjectId ? boardSource.load({ orgId, factoryProjectId }) : undefined;\n const installed = (board: string) => boardSource?.codeRegistry.has(board) === true;\n\n return [\n registerApiRoute('/web/intake/config', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: tenant.orgId, integrationIds });\n return c.json({ config });\n },\n }),\n registerApiRoute('/web/intake/config', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n\n let body: unknown;\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const config = parseIntakeConfig(body);\n if (!config) {\n return c.json({ error: 'invalid_config' }, 400);\n }\n\n const registeredConfig: IntakeConfig = Object.create(null);\n for (const [integrationId, selection] of Object.entries(config)) {\n if (integrationIds.includes(integrationId)) {\n registeredConfig[integrationId] = selection;\n continue;\n }\n if (selection.enabled || selection.sourceIds?.length) {\n return c.json({ error: 'invalid_config' }, 400);\n }\n }\n\n await intake.ensureReady();\n await intake.mergeConfig({ orgId: tenant.orgId, config: registeredConfig });\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.intake.config_updated',\n targets: [{ type: 'intake_config', id: tenant.orgId }],\n metadata: Object.fromEntries(\n Object.entries(registeredConfig).map(([integrationId, selection]) => [\n integrationId,\n { enabled: selection.enabled, sources: selection.sourceIds?.length ?? null },\n ]),\n ),\n },\n });\n return c.json({ config: await intake.getConfig({ orgId: tenant.orgId, integrationIds }) });\n },\n }),\n registerApiRoute('/web/intake/bindings', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n await intake.ensureReady();\n return c.json({ bindings: await intake.listBindings({ orgId: tenant.orgId }) });\n },\n }),\n registerApiRoute('/web/intake/bindings', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n\n let body: unknown;\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const binding = parseIntakeBinding(body);\n if (!binding || !integrationIds.includes(binding.integrationId)) {\n return c.json({ error: 'invalid_binding' }, 400);\n }\n const integration = integrations.find(candidate => candidate.id === binding.integrationId);\n // Sources of label-filtering integrations feed several Factory projects at once.\n const shared = integration?.intake.bindingLabelFilters === true;\n if (!shared && binding.labels) {\n return c.json(\n { error: 'invalid_binding', message: `${binding.integrationId} bindings do not support label filters.` },\n 400,\n );\n }\n if (shared && binding.factoryProjectId === null) {\n return c.json(\n {\n error: 'use_delete',\n message:\n \"Remove one factory's binding with DELETE /web/intake/bindings?integrationId=…&sourceId=…&factoryProjectId=….\",\n },\n 400,\n );\n }\n if (binding.factoryProjectId && projects) {\n const project = await projects.get({ orgId: tenant.orgId, id: binding.factoryProjectId });\n if (!project) return c.json({ error: 'factory_project_not_found' }, 404);\n }\n if (binding.board !== null && !installed(binding.board)) {\n return c.json({ error: 'invalid_board', message: `Board '${binding.board}' is not installed.` }, 422);\n }\n // Load before writing, so a failed load can't leave a saved binding with its cards unmoved.\n const boardRegistry = await projectBoards(tenant.orgId, binding.factoryProjectId);\n\n await intake.ensureReady();\n let auditFactoryProjectId = binding.factoryProjectId;\n let labels: string[] | null = null;\n let relocated: { moved: number; skipped: number } | null = null;\n if (binding.factoryProjectId === null) {\n const previousBinding = await intake.clearBinding({\n orgId: tenant.orgId,\n integrationId: binding.integrationId,\n sourceId: binding.sourceId,\n });\n auditFactoryProjectId = previousBinding?.factoryProjectId ?? null;\n } else {\n const previousBinding = await intake.getBinding({\n orgId: tenant.orgId,\n integrationId: binding.integrationId,\n sourceId: binding.sourceId,\n ...(shared ? { factoryProjectId: binding.factoryProjectId } : {}),\n });\n const target = {\n orgId: tenant.orgId,\n userId: tenant.userId,\n integrationId: binding.integrationId,\n sourceId: binding.sourceId,\n factoryProjectId: binding.factoryProjectId,\n board: binding.board,\n };\n try {\n if (shared) {\n // Omitted labels keep the filter, so changing only the board never widens what the binding takes.\n labels = binding.labels === undefined ? (previousBinding?.labels ?? null) : binding.labels;\n const { conflicts } = await intake.setSharedBinding({ ...target, labels });\n if (conflicts.length > 0) {\n return c.json(\n { error: 'binding_conflict', message: bindingConflictMessage(conflicts), conflicts },\n 409,\n );\n }\n } else {\n await intake.setBinding(target);\n }\n } catch (error) {\n if (error instanceof FactoryProjectNotFoundError) {\n return c.json({ error: 'factory_project_not_found' }, 404);\n }\n throw error;\n }\n // A source that stays in the same project but is pointed at a different board\n // takes its resting cards along. Bindings that predate persisted boards have a\n // null board yet still fed Work/Review, so relocation compares each card's\n // effective board rather than trusting the previous binding value.\n const nextBoard = binding.board;\n if (\n workItems &&\n boardRegistry &&\n integration &&\n previousBinding?.factoryProjectId === binding.factoryProjectId &&\n nextBoard !== null &&\n previousBinding.board !== nextBoard\n ) {\n try {\n const config = await intake.getConfig({\n orgId: tenant.orgId,\n integrationIds: [binding.integrationId],\n });\n const configuredSourceIds = config[binding.integrationId]?.sourceIds ?? [];\n const attributionSourceIds = configuredSourceIds.includes(binding.sourceId)\n ? configuredSourceIds\n : [...configuredSourceIds, binding.sourceId];\n relocated = await relocateSourceCards({\n workItems,\n integration,\n boardRegistry,\n orgId: tenant.orgId,\n userId: tenant.userId,\n factoryProjectId: binding.factoryProjectId,\n sourceId: binding.sourceId,\n attributionSourceIds,\n targetBoard: nextBoard,\n });\n } catch (error) {\n // The binding is saved; the cards can be moved by hand if the provider was unreachable.\n console.error(`[factory] intake rebind could not relocate ${binding.integrationId} cards:`, error);\n }\n }\n }\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.intake.binding_updated',\n ...(auditFactoryProjectId ? { factoryProjectId: auditFactoryProjectId } : {}),\n targets: [{ type: 'intake_source', id: `${binding.integrationId}:${binding.sourceId}` }],\n metadata: {\n factoryProjectId: binding.factoryProjectId,\n board: binding.board,\n labels,\n ...(relocated ? { relocated } : {}),\n },\n },\n });\n return c.json({\n bindings: await intake.listBindings({ orgId: tenant.orgId }),\n ...(relocated ? { relocated } : {}),\n });\n },\n }),\n // Removes exactly one Factory project's binding, so a shared source keeps feeding the others.\n // Identifiers travel in the query string because some clients and proxies drop DELETE bodies.\n registerApiRoute('/web/intake/bindings', {\n method: 'DELETE',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n\n const parsed = bindingDeleteQuerySchema.safeParse({\n integrationId: c.req.query('integrationId'),\n sourceId: c.req.query('sourceId'),\n factoryProjectId: c.req.query('factoryProjectId'),\n });\n if (!parsed.success || !integrationIds.includes(parsed.data.integrationId)) {\n return c.json({ error: 'invalid_binding' }, 400);\n }\n const binding = parsed.data;\n\n await intake.ensureReady();\n const removed = await intake.clearBinding({ orgId: tenant.orgId, ...binding });\n if (!removed) return c.json({ error: 'binding_not_found' }, 404);\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.intake.binding_updated',\n factoryProjectId: removed.factoryProjectId,\n targets: [{ type: 'intake_source', id: `${binding.integrationId}:${binding.sourceId}` }],\n metadata: { factoryProjectId: null, board: null, labels: null },\n },\n });\n return c.json({ bindings: await intake.listBindings({ orgId: tenant.orgId }) });\n },\n }),\n registerApiRoute('/web/intake/label-routes', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n const factoryProjectId = c.req.query('factoryProjectId');\n await intake.ensureReady();\n return c.json({\n routes: await intake.listLabelRoutes({\n orgId: tenant.orgId,\n ...(factoryProjectId ? { factoryProjectId } : {}),\n }),\n });\n },\n }),\n registerApiRoute('/web/intake/label-routes', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n\n let body: unknown;\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const route = parseIntakeLabelRoute(body);\n if (!route || !integrationIds.includes(route.integrationId)) {\n return c.json({ error: 'invalid_label_route' }, 400);\n }\n if (projects) {\n const project = await projects.get({ orgId: tenant.orgId, id: route.factoryProjectId });\n if (!project) return c.json({ error: 'factory_project_not_found' }, 404);\n }\n if (route.board !== null && !installed(route.board)) {\n return c.json({ error: 'invalid_board', message: `Board '${route.board}' is not installed.` }, 422);\n }\n // Load before writing, so a failed load can't leave a saved route with its cards unmoved.\n const boardRegistry = await projectBoards(tenant.orgId, route.factoryProjectId);\n\n await intake.ensureReady();\n const scope = {\n orgId: tenant.orgId,\n factoryProjectId: route.factoryProjectId,\n integrationId: route.integrationId,\n };\n const previous = (await intake.listLabelRoutes(scope)).find(existing => existing.label === route.label);\n if (route.board === null) {\n await intake.clearLabelRoute({ ...scope, label: route.label });\n } else {\n await intake.setLabelRoute({ ...scope, label: route.label, board: route.board, userId: tenant.userId });\n }\n\n // Cards already carrying the label follow the route: onto the new board, or — when the\n // label is no longer routed anywhere — to the repository binding's board or Work.\n let relocated: { moved: number; skipped: number } | null = null;\n if (workItems && boardRegistry && (previous?.board ?? null) !== route.board) {\n try {\n relocated = await relocateLabeledCards({\n workItems,\n boardRegistry,\n orgId: tenant.orgId,\n userId: tenant.userId,\n factoryProjectId: route.factoryProjectId,\n integrationId: route.integrationId,\n label: route.label,\n routes: await intake.listLabelRoutes(scope),\n intake,\n githubRepositories,\n });\n } catch (error) {\n // The route is saved; the cards can be moved by hand.\n console.error(`[factory] intake label route could not relocate ${route.integrationId} cards:`, error);\n }\n }\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.intake.label_route_updated',\n factoryProjectId: route.factoryProjectId,\n targets: [{ type: 'intake_label_route', id: `${route.integrationId}:${route.label}` }],\n metadata: { board: route.board, ...(relocated ? { relocated } : {}) },\n },\n });\n return c.json({\n routes: await intake.listLabelRoutes({ orgId: tenant.orgId, factoryProjectId: route.factoryProjectId }),\n ...(relocated ? { relocated } : {}),\n });\n },\n }),\n registerApiRoute('/web/intake/sources', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n const { pages, failures } = await settleByIntegration(\n integrations.map(integration => ({\n integrationId: integration.id,\n read: () => integration.intake.listSources(tenant),\n })),\n );\n return c.json({\n sources: pages.flatMap(({ integrationId, value }) => value.map(source => ({ integrationId, ...source }))),\n failures,\n });\n },\n }),\n registerApiRoute('/web/intake/items', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n const cursors = decodeCursor(c.req.query('cursor'));\n if (!cursors) return c.json({ error: 'invalid_cursor' }, 400);\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: tenant.orgId, integrationIds });\n const { pages, failures } = await settleByIntegration(\n integrations.flatMap(integration => {\n const selection = config[integration.id];\n if (!selection?.enabled || !selection.sourceIds?.length) return [];\n const sourceIds = selection.sourceIds;\n const cursor = cursors[integration.id];\n return [\n {\n integrationId: integration.id,\n read: () => integration.intake.listItems({ ...tenant, sourceIds, ...(cursor ? { cursor } : {}) }),\n },\n ];\n }),\n );\n\n const items: AggregatedIntakeItem[] = [];\n const nextCursors: Record<string, string> = {};\n for (const { integrationId, value } of pages) {\n items.push(\n ...value.items.map(item => {\n const { source, ...candidate } = item;\n return { ...candidate, integrationId, externalSource: { integrationId, ...source } };\n }),\n );\n if (value.nextCursor) nextCursors[integrationId] = value.nextCursor;\n }\n // Keep the cursor an unavailable integration came in with, so the next page resumes there instead of replaying it.\n for (const { integrationId } of failures) {\n const cursor = cursors[integrationId];\n if (cursor) nextCursors[integrationId] = cursor;\n }\n return c.json({ items, nextCursor: encodeCursor(nextCursors), failures });\n },\n }),\n ];\n }\n}\n"],"mappings":";;;;;;;;;AA+DA,MAAM,mBAAmB;;;;;;AAMzB,MAAM,wBAAwB;;;;;AAM9B,SAAS,qBAAqB,eAAuB,MAA4B;CAC/E,MAAM,aAAa,KAAK,UAAU;CAClC,OAAO,OAAO,eAAe,YAAY,WAAW,SAAS,IACzD,CAAC,KAAK,OAAO,YAAY,GAAG,cAAc,GAAG,YAAY,IACzD,CAAC,KAAK,OAAO,UAAU;AAC7B;;;;;;;AAQA,eAAe,oBAAoB,EACjC,WACA,aACA,eACA,OACA,QACA,kBACA,UACA,aACA,wBAW8C;CAC9C,IAAI,CAAC,cAAc,IAAI,WAAW,GAAG,OAAO;EAAE,OAAO;EAAG,SAAS;CAAE;CAEnE,MAAM,6BAAa,IAAI,IAAY;CACnC,IAAI;CACJ,MAAM,WAAW,KAAK,IAAI,IAAI;CAC9B,KAAK,IAAI,OAAO,GAAG,OAAO,kBAAkB,QAAQ,GAAG;EACrD,MAAM,SAAS,MAAM,YACnB,YAAY,UAEV,YAAY,OAAO,UAAU;GAC3B;GACA;GACA,WAAW,CAAC,QAAQ;GACpB;GACA;EACF,CAAC,GACH,WAAW,KAAK,IAAI,CACtB;EACA,KAAK,MAAM,QAAQ,OAAO,OAAO;GAC/B,IAAI,KAAK,aAAa,UAAU;GAChC,KAAK,MAAM,OAAO,qBAAqB,YAAY,IAAI,IAAI,GAAG,WAAW,IAAI,GAAG;EAClF;EACA,IAAI,CAAC,OAAO,YAAY;EACxB,SAAS,OAAO;CAClB;CACA,IAAI,WAA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,IAAI,MAAM,YAAY,YAAY,iBAAiB,MAAM;KAC3D;KAEA,KAAK,MAAM,EAAE,mBAAmB,UAAU;MACxC,MAAM,SAAS,QAAQ;MACvB,IAAI,QAAQ,YAAY,iBAAiB;KAC3C;KACA,OAAO,EAAE,KAAK;MAAE;MAAO,YAAY,aAAa,WAAW;MAAG;KAAS,CAAC;IAC1E;GACF,CAAC;EACH;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"intake.js","names":[],"sources":["../../src/routes/intake.ts"],"sourcesContent":["import type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\nimport { z } from 'zod';\n\nimport type { Intake, IntakeItem } from '../capabilities/intake.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.js';\nimport { FactoryProjectNotFoundError, normalizeBindingLabels } from '../storage/domains/intake/base.js';\nimport type { IntakeBindingConflict, IntakeConfig, IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { RouteDependencies } from './route.js';\nimport { loose, Route } from './route.js';\n\nexport interface IntakeIntegration {\n id: string;\n intake: Pick<Intake, 'listSources' | 'listItems' | 'bindingLabelFilters'>;\n}\n\ninterface AggregatedIntakeItem extends Omit<IntakeItem, 'source'> {\n integrationId: string;\n externalSource: {\n integrationId: string;\n type: string;\n externalId: string;\n url?: string;\n };\n}\n\nexport interface IntakeRoutesDeps extends RouteDependencies {\n audit: AuditEmitter;\n /** Intake selection domain handle. */\n intake: IntakeStorage;\n /** Factory project domain handle, used to validate binding targets. */\n projects?: { get(input: { orgId: string; id: string }): Promise<unknown | null> };\n integrations?: IntakeIntegration[];\n}\n\n/** One integration that failed while the rest of the aggregation succeeded. */\nexport interface IntakeIntegrationFailure {\n integrationId: string;\n message: string;\n}\n\ntype SettledIntegration<T> = { integrationId: string; value: T } | IntakeIntegrationFailure;\n\nconst PROVIDER_READ_TIMEOUT_MS = 15_000;\n\n/** The Intake contract takes no abort signal, so a slow read is abandoned, not cancelled. */\nfunction withTimeout<T>(\n integrationId: string,\n read: () => Promise<T>,\n timeoutMs: number = PROVIDER_READ_TIMEOUT_MS,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n const budget = Math.max(0, timeoutMs);\n const timer = setTimeout(\n () => reject(new Error(`${integrationId} did not answer within ${Math.round(budget / 1000)}s`)),\n budget,\n );\n read()\n .then(resolve, reject)\n .finally(() => clearTimeout(timer));\n });\n}\n\n/**\n * Read every integration concurrently and isolate the ones that throw or hang, so a single\n * unreachable provider degrades to a per-source error instead of failing the listing.\n */\nasync function settleByIntegration<T>(\n requests: Array<{ integrationId: string; read: () => Promise<T> }>,\n): Promise<{ pages: Array<{ integrationId: string; value: T }>; failures: IntakeIntegrationFailure[] }> {\n const settled = await Promise.all(\n requests.map(async ({ integrationId, read }): Promise<SettledIntegration<T>> => {\n try {\n return { integrationId, value: await withTimeout(integrationId, read) };\n } catch (error) {\n console.error(`[factory] intake integration ${integrationId} is unavailable:`, error);\n return { integrationId, message: error instanceof Error ? error.message : String(error) };\n }\n }),\n );\n const pages: Array<{ integrationId: string; value: T }> = [];\n const failures: IntakeIntegrationFailure[] = [];\n for (const entry of settled) {\n if ('value' in entry) pages.push(entry);\n else failures.push(entry);\n }\n return { pages, failures };\n}\n\nconst MAX_INTAKE_SOURCE_ID_LENGTH = 1024;\n\nconst identifier = z.string().min(1).max(256);\nconst sourceIdentifier = z.string().min(1).max(MAX_INTAKE_SOURCE_ID_LENGTH);\n\n/** Labels a shared binding takes; `[]` is rejected because \"all issues\" is spelled `null`. Jira labels never hold spaces. */\nconst bindingLabelsSchema = z\n .array(\n z\n .string()\n .max(255)\n .refine(label => !/\\s/.test(label.trim()), 'labels cannot contain spaces'),\n )\n .max(50)\n .transform(normalizeBindingLabels)\n .refine(labels => labels.length > 0, 'labels must name at least one label; use null for all issues');\n\nconst bindingBodySchema = z.object({\n integrationId: identifier,\n sourceId: sourceIdentifier,\n /** `null` unbinds the source (integrations without label filters only). */\n factoryProjectId: identifier.nullable(),\n /** Label filter for integrations with `bindingLabelFilters`; `null` takes all issues, omitted keeps the current filter. */\n labels: bindingLabelsSchema.nullable().optional(),\n});\ntype ParsedBinding = z.output<typeof bindingBodySchema>;\n\n/** Validate a binding request body, rejecting unknown shapes. */\nexport function parseIntakeBinding(body: unknown): ParsedBinding | null {\n const parsed = bindingBodySchema.safeParse(body);\n return parsed.success ? parsed.data : null;\n}\n\nconst bindingDeleteQuerySchema = z.object({\n integrationId: identifier,\n sourceId: sourceIdentifier,\n factoryProjectId: identifier,\n});\n\nfunction bindingConflictMessage(conflicts: readonly IntakeBindingConflict[]): string {\n const labels = conflicts.flatMap(conflict => conflict.labels ?? []);\n return labels.length > 0\n ? `Already routed to another factory: ${labels.join(', ')}.`\n : 'Another factory already takes all issues from this source.';\n}\n\nfunction sanitizeIdList(value: unknown): string[] | null | undefined {\n if (value === null) return null;\n if (!Array.isArray(value) || value.length > 200) return undefined;\n const ids = value.filter(\n (item): item is string => typeof item === 'string' && item.length > 0 && item.length <= MAX_INTAKE_SOURCE_ID_LENGTH,\n );\n return ids.length === value.length && new Set(ids).size === ids.length ? ids : undefined;\n}\n\nfunction sanitizeLinearRepositoryMap(value: unknown): Record<string, string> | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n const entries = Object.entries(value);\n if (entries.length > 200) return undefined;\n const mapping: Record<string, string> = Object.create(null);\n for (const [projectId, slug] of entries) {\n if (\n !projectId ||\n projectId.length > MAX_INTAKE_SOURCE_ID_LENGTH ||\n typeof slug !== 'string' ||\n !slug.trim() ||\n slug.length > 512\n ) {\n return undefined;\n }\n mapping[projectId] = slug;\n }\n return mapping;\n}\n\n/** Validate a request body into an intake config, rejecting unknown shapes. */\nexport function parseIntakeConfig(body: unknown): IntakeConfig | null {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) return null;\n const entries = Object.entries(body);\n if (entries.length > 50) return null;\n\n // Null-prototype so an `__proto__` key lands as a real entry instead of silently\n // reassigning the prototype and disappearing from the validation below.\n const config: IntakeConfig = Object.create(null);\n for (const [integrationId, value] of entries) {\n if (\n !integrationId ||\n integrationId.length > 128 ||\n typeof value !== 'object' ||\n value === null ||\n Array.isArray(value)\n ) {\n return null;\n }\n const selection = value as { enabled?: unknown; sourceIds?: unknown; repositoryByLinearProject?: unknown };\n if (typeof selection.enabled !== 'boolean') return null;\n const sourceIds = sanitizeIdList(selection.sourceIds ?? null);\n if (sourceIds === undefined) return null;\n const repositoryByLinearProject =\n integrationId === 'linear' ? sanitizeLinearRepositoryMap(selection.repositoryByLinearProject) : undefined;\n if (\n integrationId === 'linear' &&\n selection.repositoryByLinearProject !== undefined &&\n repositoryByLinearProject === undefined\n )\n return null;\n config[integrationId] = {\n enabled: selection.enabled,\n sourceIds,\n ...(repositoryByLinearProject ? { repositoryByLinearProject } : {}),\n };\n }\n return config;\n}\n\nfunction encodeCursor(cursors: Record<string, string>): string | null {\n return Object.keys(cursors).length > 0 ? Buffer.from(JSON.stringify(cursors)).toString('base64url') : null;\n}\n\nfunction decodeCursor(value: string | undefined): Record<string, string> | null {\n if (!value) return {};\n try {\n const parsed = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) as unknown;\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null;\n const entries = Object.entries(parsed);\n if (entries.some(([key, cursor]) => !key || typeof cursor !== 'string')) return null;\n return Object.fromEntries(entries) as Record<string, string>;\n } catch {\n return null;\n }\n}\n\nexport class IntakeRoutes extends Route<IntakeRoutesDeps> {\n async #resolveTenant(c: Context): Promise<{ orgId: string; userId: string } | { response: Response }> {\n await this.deps.auth.ensureUser(c);\n const tenant = this.deps.auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n { error: 'organization_required', message: 'Intake configuration requires an organization.' },\n 403,\n ),\n };\n }\n return { orgId: tenant.orgId, userId: tenant.userId };\n }\n\n routes(): ApiRoute[] {\n const { audit, intake, projects, integrations = [] } = this.deps;\n const integrationIds = integrations.map(integration => integration.id);\n\n return [\n registerApiRoute('/web/intake/config', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: tenant.orgId, integrationIds });\n return c.json({ config });\n },\n }),\n registerApiRoute('/web/intake/config', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n\n let body: unknown;\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const config = parseIntakeConfig(body);\n if (!config) {\n return c.json({ error: 'invalid_config' }, 400);\n }\n\n const registeredConfig: IntakeConfig = Object.create(null);\n for (const [integrationId, selection] of Object.entries(config)) {\n if (integrationIds.includes(integrationId)) {\n registeredConfig[integrationId] = selection;\n continue;\n }\n if (selection.enabled || selection.sourceIds?.length) {\n return c.json({ error: 'invalid_config' }, 400);\n }\n }\n\n await intake.ensureReady();\n await intake.mergeConfig({ orgId: tenant.orgId, config: registeredConfig });\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.intake.config_updated',\n targets: [{ type: 'intake_config', id: tenant.orgId }],\n metadata: Object.fromEntries(\n Object.entries(registeredConfig).map(([integrationId, selection]) => [\n integrationId,\n { enabled: selection.enabled, sources: selection.sourceIds?.length ?? null },\n ]),\n ),\n },\n });\n return c.json({ config: await intake.getConfig({ orgId: tenant.orgId, integrationIds }) });\n },\n }),\n registerApiRoute('/web/intake/bindings', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n await intake.ensureReady();\n return c.json({ bindings: await intake.listBindings({ orgId: tenant.orgId }) });\n },\n }),\n registerApiRoute('/web/intake/bindings', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n\n let body: unknown;\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const binding = parseIntakeBinding(body);\n if (!binding || !integrationIds.includes(binding.integrationId)) {\n return c.json({ error: 'invalid_binding' }, 400);\n }\n const integration = integrations.find(candidate => candidate.id === binding.integrationId);\n // Sources of label-filtering integrations feed several Factory projects at once.\n const shared = integration?.intake.bindingLabelFilters === true;\n if (!shared && binding.labels) {\n return c.json(\n { error: 'invalid_binding', message: `${binding.integrationId} bindings do not support label filters.` },\n 400,\n );\n }\n if (shared && binding.factoryProjectId === null) {\n return c.json(\n {\n error: 'use_delete',\n message:\n \"Remove one factory's binding with DELETE /web/intake/bindings?integrationId=…&sourceId=…&factoryProjectId=….\",\n },\n 400,\n );\n }\n if (binding.factoryProjectId && projects) {\n const project = await projects.get({ orgId: tenant.orgId, id: binding.factoryProjectId });\n if (!project) return c.json({ error: 'factory_project_not_found' }, 404);\n }\n\n await intake.ensureReady();\n let auditFactoryProjectId = binding.factoryProjectId;\n let labels: string[] | null = null;\n if (binding.factoryProjectId === null) {\n const previousBinding = await intake.clearBinding({\n orgId: tenant.orgId,\n integrationId: binding.integrationId,\n sourceId: binding.sourceId,\n });\n auditFactoryProjectId = previousBinding?.factoryProjectId ?? null;\n } else {\n const previousBinding = await intake.getBinding({\n orgId: tenant.orgId,\n integrationId: binding.integrationId,\n sourceId: binding.sourceId,\n ...(shared ? { factoryProjectId: binding.factoryProjectId } : {}),\n });\n const target = {\n orgId: tenant.orgId,\n userId: tenant.userId,\n integrationId: binding.integrationId,\n sourceId: binding.sourceId,\n factoryProjectId: binding.factoryProjectId,\n };\n try {\n if (shared) {\n // Omitted labels keep the filter, so a save that doesn't name labels never widens what the binding takes.\n labels = binding.labels === undefined ? (previousBinding?.labels ?? null) : binding.labels;\n const { conflicts } = await intake.setSharedBinding({ ...target, labels });\n if (conflicts.length > 0) {\n return c.json(\n { error: 'binding_conflict', message: bindingConflictMessage(conflicts), conflicts },\n 409,\n );\n }\n } else {\n await intake.setBinding(target);\n }\n } catch (error) {\n if (error instanceof FactoryProjectNotFoundError) {\n return c.json({ error: 'factory_project_not_found' }, 404);\n }\n throw error;\n }\n }\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.intake.binding_updated',\n ...(auditFactoryProjectId ? { factoryProjectId: auditFactoryProjectId } : {}),\n targets: [{ type: 'intake_source', id: `${binding.integrationId}:${binding.sourceId}` }],\n metadata: { factoryProjectId: binding.factoryProjectId, labels },\n },\n });\n return c.json({ bindings: await intake.listBindings({ orgId: tenant.orgId }) });\n },\n }),\n // Removes exactly one Factory project's binding, so a shared source keeps feeding the others.\n // Identifiers travel in the query string because some clients and proxies drop DELETE bodies.\n registerApiRoute('/web/intake/bindings', {\n method: 'DELETE',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n\n const parsed = bindingDeleteQuerySchema.safeParse({\n integrationId: c.req.query('integrationId'),\n sourceId: c.req.query('sourceId'),\n factoryProjectId: c.req.query('factoryProjectId'),\n });\n if (!parsed.success || !integrationIds.includes(parsed.data.integrationId)) {\n return c.json({ error: 'invalid_binding' }, 400);\n }\n const binding = parsed.data;\n\n await intake.ensureReady();\n const removed = await intake.clearBinding({ orgId: tenant.orgId, ...binding });\n if (!removed) return c.json({ error: 'binding_not_found' }, 404);\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.intake.binding_updated',\n factoryProjectId: removed.factoryProjectId,\n targets: [{ type: 'intake_source', id: `${binding.integrationId}:${binding.sourceId}` }],\n metadata: { factoryProjectId: null, labels: null },\n },\n });\n return c.json({ bindings: await intake.listBindings({ orgId: tenant.orgId }) });\n },\n }),\n // Label routes are gone: a project's intake routes decide where its cards land.\n ...(['GET', 'PUT'] as const).map(method =>\n registerApiRoute('/web/intake/label-routes', {\n method,\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n return c.json(\n {\n error: 'label_routes_removed',\n message:\n \"Label routes were removed. Add an intake route on the project instead: POST /web/factory/projects/:id/intake-routes with a condition on 'item.labels'.\",\n },\n 410,\n );\n },\n }),\n ),\n registerApiRoute('/web/intake/sources', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n const requested = c.req.query('integrationId');\n const { pages, failures } = await settleByIntegration(\n (requested ? integrations.filter(integration => integration.id === requested) : integrations).map(\n integration => ({\n integrationId: integration.id,\n read: () => integration.intake.listSources(tenant),\n }),\n ),\n );\n return c.json({\n sources: pages.flatMap(({ integrationId, value }) => value.map(source => ({ integrationId, ...source }))),\n failures,\n });\n },\n }),\n registerApiRoute('/web/intake/items', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n const cursors = decodeCursor(c.req.query('cursor'));\n if (!cursors) return c.json({ error: 'invalid_cursor' }, 400);\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: tenant.orgId, integrationIds });\n const { pages, failures } = await settleByIntegration(\n integrations.flatMap(integration => {\n const selection = config[integration.id];\n if (!selection?.enabled || !selection.sourceIds?.length) return [];\n const sourceIds = selection.sourceIds;\n const cursor = cursors[integration.id];\n return [\n {\n integrationId: integration.id,\n read: () => integration.intake.listItems({ ...tenant, sourceIds, ...(cursor ? { cursor } : {}) }),\n },\n ];\n }),\n );\n\n const items: AggregatedIntakeItem[] = [];\n const nextCursors: Record<string, string> = {};\n for (const { integrationId, value } of pages) {\n items.push(\n ...value.items.map(item => {\n const { source, ...candidate } = item;\n return { ...candidate, integrationId, externalSource: { integrationId, ...source } };\n }),\n );\n if (value.nextCursor) nextCursors[integrationId] = value.nextCursor;\n }\n // Keep the cursor an unavailable integration came in with, so the next page resumes there instead of replaying it.\n for (const { integrationId } of failures) {\n const cursor = cursors[integrationId];\n if (cursor) nextCursors[integrationId] = cursor;\n }\n return c.json({ items, nextCursor: encodeCursor(nextCursors), failures });\n },\n }),\n ];\n }\n}\n"],"mappings":";;;;;AA4CA,MAAM,2BAA2B;;AAGjC,SAAS,YACP,eACA,MACA,YAAoB,0BACR;CACZ,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,SAAS,KAAK,IAAI,GAAG,SAAS;EACpC,MAAM,QAAQ,iBACN,uBAAO,IAAI,MAAM,GAAG,cAAc,yBAAyB,KAAK,MAAM,SAAS,GAAI,EAAE,EAAE,CAAC,GAC9F,MACF;EACA,KAAK,CAAC,CACH,KAAK,SAAS,MAAM,CAAC,CACrB,cAAc,aAAa,KAAK,CAAC;CACtC,CAAC;AACH;;;;;AAMA,eAAe,oBACb,UACsG;CACtG,MAAM,UAAU,MAAM,QAAQ,IAC5B,SAAS,IAAI,OAAO,EAAE,eAAe,WAA2C;EAC9E,IAAI;GACF,OAAO;IAAE;IAAe,OAAO,MAAM,YAAY,eAAe,IAAI;GAAE;EACxE,SAAS,OAAO;GACd,QAAQ,MAAM,gCAAgC,cAAc,mBAAmB,KAAK;GACpF,OAAO;IAAE;IAAe,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GAAE;EAC1F;CACF,CAAC,CACH;CACA,MAAM,QAAoD,CAAC;CAC3D,MAAM,WAAuC,CAAC;CAC9C,KAAK,MAAM,SAAS,SAClB,IAAI,WAAW,OAAO,MAAM,KAAK,KAAK;MACjC,SAAS,KAAK,KAAK;CAE1B,OAAO;EAAE;EAAO;CAAS;AAC3B;AAEA,MAAM,8BAA8B;AAEpC,MAAM,aAAa,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG;AAC5C,MAAM,mBAAmB,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,2BAA2B;;AAG1E,MAAM,sBAAsB,EACzB,MACC,EACG,OAAO,CAAC,CACR,IAAI,GAAG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O,UAAU;QAAE,GAAG;QAAQ;QAAW,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;OAAG,CAAC;MAClG,CACF;KACF,CAAC,CACH;KAEA,MAAM,QAAgC,CAAC;KACvC,MAAM,cAAsC,CAAC;KAC7C,KAAK,MAAM,EAAE,eAAe,WAAW,OAAO;MAC5C,MAAM,KACJ,GAAG,MAAM,MAAM,KAAI,SAAQ;OACzB,MAAM,EAAE,QAAQ,GAAG,cAAc;OACjC,OAAO;QAAE,GAAG;QAAW;QAAe,gBAAgB;SAAE;SAAe,GAAG;QAAO;OAAE;MACrF,CAAC,CACH;MACA,IAAI,MAAM,YAAY,YAAY,iBAAiB,MAAM;KAC3D;KAEA,KAAK,MAAM,EAAE,mBAAmB,UAAU;MACxC,MAAM,SAAS,QAAQ;MACvB,IAAI,QAAQ,YAAY,iBAAiB;KAC3C;KACA,OAAO,EAAE,KAAK;MAAE;MAAO,YAAY,aAAa,WAAW;MAAG;KAAS,CAAC;IAC1E;GACF,CAAC;EACH;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"knowledge.d.ts","sourceRoot":"","sources":["../../src/routes/knowledge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAwB,MAAM,wBAAwB,CAAC;AAU9E,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAMpD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACpD,OAAO,
|
|
1
|
+
{"version":3,"file":"knowledge.d.ts","sourceRoot":"","sources":["../../src/routes/knowledge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAwB,MAAM,wBAAwB,CAAC;AAU9E,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAMpD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACpD,OAAO,EAAS,KAAK,EAAE,MAAM,YAAY,CAAC;AAgB1C,MAAM,WAAW,mBAAoB,SAAQ,iBAAiB;IAC5D,6FAA6F;IAC7F,QAAQ,EAAE,sBAAsB,CAAC;IACjC,uFAAuF;IACvF,SAAS,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC,CAAC;IAC3D,gEAAgE;IAChE,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAyDD,qBAAa,eAAgB,SAAQ,KAAK,CAAC,mBAAmB,CAAC;;IA8C7D,MAAM,IAAI,QAAQ,EAAE,CA2KnB;CACF"}
|
package/dist/routes/knowledge.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { Route } from "./route.js";
|
|
1
|
+
import { Route, loose } from "./route.js";
|
|
2
2
|
import { registerApiRoute } from "@mastra/core/server";
|
|
3
|
-
import { KnowledgeDeclarationError, listKnowledgeTreeChildren, readKnowledgePage, readKnowledgePageActivity, readKnowledgePageGraph, readKnowledgeScopeGrants, searchKnowledgeExplorerPages } from "@mastra/core/knowledge";
|
|
4
3
|
import { streamSSE } from "hono/streaming";
|
|
4
|
+
import { KnowledgeDeclarationError, listKnowledgeTreeChildren, readKnowledgePage, readKnowledgePageActivity, readKnowledgePageGraph, readKnowledgeScopeGrants, searchKnowledgeExplorerPages } from "@mastra/core/knowledge";
|
|
5
5
|
// src/routes/knowledge.ts
|
|
6
6
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
7
7
|
/** Ids and cursors are opaque, but bounded so an unbounded query string never reaches storage. */
|
|
@@ -64,9 +64,6 @@ function withDisplayLabel(knowledge, page) {
|
|
|
64
64
|
displayLabel
|
|
65
65
|
} : page;
|
|
66
66
|
}
|
|
67
|
-
function loose(c) {
|
|
68
|
-
return c;
|
|
69
|
-
}
|
|
70
67
|
var KnowledgeRoutes = class extends Route {
|
|
71
68
|
/** Tenant, org-owned project, Knowledge runtime and the caller's read scope: the one seam every route shares. */
|
|
72
69
|
async #resolveView(c) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"knowledge.js","names":[],"sources":["../../src/routes/knowledge.ts"],"sourcesContent":["/**\n * Read-only Mastra `apiRoutes` behind Factory's Knowledge page: the schema-4 page tree, a page with its\n * notes, the bounded page graph, search and activity, all through the same core page readers Studio uses,\n * plus a change stream (`/events`, SSE) naming the pages and scopes each committed write touched.\n * Every endpoint is a GET; this module never writes Knowledge.\n *\n * Scoping is fail-closed and server-side. The caller must be signed in to an org that owns the `:id`\n * project, and reads are limited to what the Knowledge's own declarations give the principals\n * `org:<orgId>` and `project:<projectId>`: the scopes a run in that project holds at org and project\n * level. Session (`resource:`/`thread:`) scopes are not principals here, so no member browses another\n * member's session pages. The host must declare `project:$projectId` (as its session runs need); without\n * it reads fail with 500 `knowledge_misconfigured`.\n */\n\nimport type { Knowledge, KnowledgeChangeEvent } from '@mastra/core/knowledge';\nimport {\n KnowledgeDeclarationError,\n listKnowledgeTreeChildren,\n readKnowledgePage,\n readKnowledgePageActivity,\n readKnowledgePageGraph,\n readKnowledgeScopeGrants,\n searchKnowledgeExplorerPages,\n} from '@mastra/core/knowledge';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { KnowledgeReadScope, KnowledgeStorage } from '@mastra/core/storage';\nimport type { Context } from 'hono';\nimport { streamSSE } from 'hono/streaming';\n\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { RouteDependencies } from './route.js';\nimport { Route } from './route.js';\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n/** Ids and cursors are opaque, but bounded so an unbounded query string never reaches storage. */\nconst ID_LIMIT = 256;\nconst SEARCH_QUERY_LIMIT = 128;\nconst MAX_PAGE_LIMIT = 100;\nconst MAX_GRAPH_PAGES = 500;\n/** Comment frames only: proxies drop an idle stream. */\nconst EVENTS_KEEPALIVE_MS = 25_000;\n/**\n * The read scope is resolved when the stream opens. Closing it after this long makes the browser reconnect,\n * which re-checks membership and the read scope, so a revoked member stops hearing about changes.\n */\nconst EVENTS_MAX_AGE_MS = 5 * 60_000;\n\nexport interface KnowledgeRoutesDeps extends RouteDependencies {\n /** Factory projects domain: validates that the `:id` project belongs to the caller's org. */\n projects: FactoryProjectsStorage;\n /** Lazy handle to the host-registered Knowledge runtime; endpoints 503 when absent. */\n knowledge: (key: string) => Promise<Knowledge | undefined>;\n /** Host-selected Knowledge key. Requests cannot override it. */\n defaultKnowledgeKey?: string;\n}\n\ninterface ResolvedView {\n knowledge: Knowledge;\n store: KnowledgeStorage;\n read: KnowledgeReadScope;\n}\n\nfunction boundedId(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n const trimmed = value.trim();\n return trimmed && trimmed.length <= ID_LIMIT ? trimmed : undefined;\n}\n\nfunction boundedLimit(value: string | undefined, max: number): number | undefined | null {\n if (value === undefined) return undefined;\n const parsed = Number(value);\n return Number.isInteger(parsed) && parsed >= 1 && parsed <= max ? parsed : null;\n}\n\n/**\n * The ids of a change this caller may see, or null when they may see none of it. Events carry ids only, so\n * readability is checked against the store now: a page moved out of reach is withheld, but the scope it\n * left still tells the caller to refresh.\n */\nasync function visibleChange(store: KnowledgeStorage, read: KnowledgeReadScope, event: KnowledgeChangeEvent) {\n const readable = async (id: string | undefined) =>\n id !== undefined && (read === 'all' || (await store.getPage({ id, read })) !== null);\n const scopeId = 'scopeId' in event ? event.scopeId : undefined;\n const fromScopeId = 'fromScopeId' in event ? event.fromScopeId : undefined;\n const [page, scope, fromScope] = await Promise.all([\n readable(event.pageId),\n readable(scopeId),\n readable(fromScopeId),\n ]);\n if (!page && !scope && !fromScope) return null;\n return {\n kind: event.kind,\n op: event.op,\n ...(page ? { pageId: event.pageId } : {}),\n ...(scope ? { scopeId } : {}),\n at: event.at.toISOString(),\n };\n}\n\ntype LabelablePage = { isScope: boolean; address?: string };\n\n/**\n * Adds a scope page's declared `displayLabel` with the address's `$params` filled in (`'$orgId policy'`\n * → `'acme policy'`); declarations live in config, not storage.\n */\nfunction withDisplayLabel<T extends LabelablePage>(knowledge: Knowledge, page: T): T & { displayLabel?: string } {\n if (!page.isScope || !page.address) return page;\n const displayLabel = knowledge.scopeLabel(page.address);\n return displayLabel ? { ...page, displayLabel } : page;\n}\n\nfunction loose(c: unknown): Context {\n return c as Context;\n}\n\nexport class KnowledgeRoutes extends Route<KnowledgeRoutesDeps> {\n /** Tenant, org-owned project, Knowledge runtime and the caller's read scope: the one seam every route shares. */\n async #resolveView(c: Context): Promise<ResolvedView | { response: Response }> {\n await this.deps.auth.ensureUser(c);\n const tenant = this.deps.auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json({ error: 'organization_required', message: 'Knowledge requires an organization.' }, 403),\n };\n }\n\n const projectId = c.req.param('id');\n if (!projectId || !UUID_RE.test(projectId)) return { response: c.json({ error: 'Project not found' }, 404) };\n await this.deps.projects.ensureReady();\n const project = await this.deps.projects.get({ orgId: tenant.orgId, id: projectId });\n if (!project) return { response: c.json({ error: 'Project not found' }, 404) };\n\n let knowledge: Knowledge | undefined;\n let store: KnowledgeStorage | undefined;\n try {\n knowledge = await this.deps.knowledge(this.deps.defaultKnowledgeKey ?? 'default');\n store = knowledge ? await knowledge.getStorage() : undefined;\n } catch {\n store = undefined;\n }\n if (!knowledge || !store) {\n return {\n response: c.json(\n { error: 'knowledge_unavailable', message: 'The configured Knowledge runtime is unavailable.' },\n 503,\n ),\n };\n }\n try {\n return { knowledge, store, read: await knowledge.readScopeFor([`org:${tenant.orgId}`, `project:${projectId}`]) };\n } catch (error) {\n // The host's Knowledge does not declare the scopes a Factory run holds (`org:` and `project:`): a\n // deployment misconfiguration, which its session runs hit too. Never fall back to a guessed scope.\n if (error instanceof KnowledgeDeclarationError) {\n return { response: c.json({ error: 'knowledge_misconfigured', message: error.message }, 500) };\n }\n throw error;\n }\n }\n\n routes(): ApiRoute[] {\n const badRequest = (c: Context, message: string) => c.json({ error: 'bad_request', message }, 400);\n return [\n registerApiRoute('/web/factory/projects/:id/knowledge/tree', {\n method: 'GET',\n requiresAuth: false,\n handler: async raw => {\n const c = loose(raw);\n const view = await this.#resolveView(c);\n if ('response' in view) return view.response;\n const parentId = boundedId(c.req.query('parentId'));\n const cursor = boundedId(c.req.query('cursor'));\n const limit = boundedLimit(c.req.query('limit'), MAX_PAGE_LIMIT);\n if (limit === null) return badRequest(c, `limit must be an integer from 1 to ${MAX_PAGE_LIMIT}.`);\n const level = await listKnowledgeTreeChildren(view.store, {\n parentId: parentId ?? null,\n read: view.read,\n cursor,\n limit,\n });\n return c.json({ ...level, pages: level.pages.map(page => withDisplayLabel(view.knowledge, page)) });\n },\n }),\n registerApiRoute('/web/factory/projects/:id/knowledge/pages/:pageId', {\n method: 'GET',\n requiresAuth: false,\n handler: async raw => {\n const c = loose(raw);\n const view = await this.#resolveView(c);\n if ('response' in view) return view.response;\n const pageId = boundedId(c.req.param('pageId'));\n if (!pageId) return c.json({ error: 'page_not_found' }, 404);\n const noteLimit = boundedLimit(c.req.query('noteLimit'), MAX_PAGE_LIMIT);\n if (noteLimit === null) return badRequest(c, `noteLimit must be an integer from 1 to ${MAX_PAGE_LIMIT}.`);\n const page = await readKnowledgePage(view.store, {\n pageId,\n read: view.read,\n noteCursor: boundedId(c.req.query('noteCursor')),\n noteLimit,\n });\n if (!page) return c.json({ error: 'page_not_found' }, 404);\n const label = <T extends LabelablePage>(entry: T) => withDisplayLabel(view.knowledge, entry);\n return c.json({\n ...page,\n page: label(page.page),\n ancestors: page.ancestors.map(label),\n related: page.related.map(label),\n });\n },\n }),\n registerApiRoute('/web/factory/projects/:id/knowledge/graph', {\n method: 'GET',\n requiresAuth: false,\n handler: async raw => {\n const c = loose(raw);\n const view = await this.#resolveView(c);\n if ('response' in view) return view.response;\n const maxPages = boundedLimit(c.req.query('maxPages'), MAX_GRAPH_PAGES);\n if (maxPages === null) return badRequest(c, `maxPages must be an integer from 1 to ${MAX_GRAPH_PAGES}.`);\n const graph = await readKnowledgePageGraph(view.store, {\n read: view.read,\n rootId: boundedId(c.req.query('rootId')) ?? null,\n ...(maxPages ? { limits: { maxPages } } : {}),\n });\n if (!graph) return c.json({ error: 'page_not_found' }, 404);\n // Declared grants between the scopes shown, limited to principal scopes this caller can read.\n const grants = await readKnowledgeScopeGrants(view.store, {\n pages: graph.pages,\n read: view.read,\n grantsFor: scope => view.knowledge.scopeGrants(scope),\n });\n return c.json({\n ...graph,\n pages: graph.pages.map(page => withDisplayLabel(view.knowledge, page)),\n grants: grants.map(grant => {\n const principalLabel = view.knowledge.scopeLabel(grant.principal);\n return principalLabel ? { ...grant, principalLabel } : grant;\n }),\n });\n },\n }),\n registerApiRoute('/web/factory/projects/:id/knowledge/search', {\n method: 'GET',\n requiresAuth: false,\n handler: async raw => {\n const c = loose(raw);\n const view = await this.#resolveView(c);\n if ('response' in view) return view.response;\n const query = (c.req.query('q') ?? '').trim();\n if (!query) return c.json({ results: [] });\n if (query.length > SEARCH_QUERY_LIMIT) {\n return badRequest(c, `q must be at most ${SEARCH_QUERY_LIMIT} characters.`);\n }\n const limit = boundedLimit(c.req.query('limit'), MAX_PAGE_LIMIT);\n if (limit === null) return badRequest(c, `limit must be an integer from 1 to ${MAX_PAGE_LIMIT}.`);\n const scopeIds = c.req.queries('scopeId')?.flatMap(id => boundedId(id) ?? []);\n const results = await searchKnowledgeExplorerPages(view.store, {\n query,\n read: view.read,\n ...(scopeIds?.length ? { scopeIds } : {}),\n limit,\n });\n return c.json({\n results: results.map(hit => ({ ...hit, page: withDisplayLabel(view.knowledge, hit.page) })),\n });\n },\n }),\n registerApiRoute('/web/factory/projects/:id/knowledge/events', {\n method: 'GET',\n requiresAuth: false,\n handler: async raw => {\n const c = loose(raw);\n const view = await this.#resolveView(c);\n if ('response' in view) return view.response;\n const { knowledge, store, read } = view;\n return streamSSE(c, async stream => {\n const closed = new Promise<void>(resolve => stream.onAbort(resolve));\n // Filtering reads the store, so changes are queued to keep them in commit order.\n let queue = Promise.resolve();\n const unsubscribe = knowledge.onChange(event => {\n queue = queue.then(async () => {\n if (stream.aborted) return;\n const change = await visibleChange(store, read, event).catch(() => null);\n if (!change || stream.aborted) return;\n try {\n await stream.writeSSE({ event: 'change', data: JSON.stringify(change) });\n } catch {\n // The tab went away mid-write; abort cleans up.\n }\n });\n });\n const keepalive = setInterval(() => {\n if (!stream.aborted) void stream.write(': ping\\n\\n');\n }, EVENTS_KEEPALIVE_MS);\n let expire: ReturnType<typeof setTimeout> | undefined;\n try {\n await stream.write(': connected\\n\\n');\n // `streamSSE` closes the stream the moment this callback returns.\n await Promise.race([\n closed,\n new Promise<void>(resolve => (expire = setTimeout(resolve, EVENTS_MAX_AGE_MS))),\n ]);\n } finally {\n clearTimeout(expire);\n clearInterval(keepalive);\n unsubscribe();\n }\n });\n },\n }),\n registerApiRoute('/web/factory/projects/:id/knowledge/activity', {\n method: 'GET',\n requiresAuth: false,\n handler: async raw => {\n const c = loose(raw);\n const view = await this.#resolveView(c);\n if ('response' in view) return view.response;\n const limit = boundedLimit(c.req.query('limit'), MAX_PAGE_LIMIT);\n if (limit === null) return badRequest(c, `limit must be an integer from 1 to ${MAX_PAGE_LIMIT}.`);\n return c.json(\n await readKnowledgePageActivity(view.store, {\n read: view.read,\n scopeId: boundedId(c.req.query('scopeId')),\n pageId: boundedId(c.req.query('pageId')),\n cursor: boundedId(c.req.query('cursor')),\n limit,\n }),\n );\n },\n }),\n ];\n }\n}\n"],"mappings":";;;;;AAkCA,MAAM,UAAU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MAAM,OAAO,WAAW,GAAG,sCAAsC,eAAe,EAAE;KAChG,OAAO,EAAE,KACP,MAAM,0BAA0B,KAAK,OAAO;MAC1C,MAAM,KAAK;MACX,SAAS,UAAU,EAAE,IAAI,MAAM,SAAS,CAAC;MACzC,QAAQ,UAAU,EAAE,IAAI,MAAM,QAAQ,CAAC;MACvC,QAAQ,UAAU,EAAE,IAAI,MAAM,QAAQ,CAAC;MACvC;KACF,CAAC,CACH;IACF;GACF,CAAC;EACH;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"knowledge.js","names":[],"sources":["../../src/routes/knowledge.ts"],"sourcesContent":["/**\n * Read-only Mastra `apiRoutes` behind Factory's Knowledge page: the schema-4 page tree, a page with its\n * notes, the bounded page graph, search and activity, all through the same core page readers Studio uses,\n * plus a change stream (`/events`, SSE) naming the pages and scopes each committed write touched.\n * Every endpoint is a GET; this module never writes Knowledge.\n *\n * Scoping is fail-closed and server-side. The caller must be signed in to an org that owns the `:id`\n * project, and reads are limited to what the Knowledge's own declarations give the principals\n * `org:<orgId>` and `project:<projectId>`: the scopes a run in that project holds at org and project\n * level. Session (`resource:`/`thread:`) scopes are not principals here, so no member browses another\n * member's session pages. The host must declare `project:$projectId` (as its session runs need); without\n * it reads fail with 500 `knowledge_misconfigured`.\n */\n\nimport type { Knowledge, KnowledgeChangeEvent } from '@mastra/core/knowledge';\nimport {\n KnowledgeDeclarationError,\n listKnowledgeTreeChildren,\n readKnowledgePage,\n readKnowledgePageActivity,\n readKnowledgePageGraph,\n readKnowledgeScopeGrants,\n searchKnowledgeExplorerPages,\n} from '@mastra/core/knowledge';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { KnowledgeReadScope, KnowledgeStorage } from '@mastra/core/storage';\nimport type { Context } from 'hono';\nimport { streamSSE } from 'hono/streaming';\n\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { RouteDependencies } from './route.js';\nimport { loose, Route } from './route.js';\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n/** Ids and cursors are opaque, but bounded so an unbounded query string never reaches storage. */\nconst ID_LIMIT = 256;\nconst SEARCH_QUERY_LIMIT = 128;\nconst MAX_PAGE_LIMIT = 100;\nconst MAX_GRAPH_PAGES = 500;\n/** Comment frames only: proxies drop an idle stream. */\nconst EVENTS_KEEPALIVE_MS = 25_000;\n/**\n * The read scope is resolved when the stream opens. Closing it after this long makes the browser reconnect,\n * which re-checks membership and the read scope, so a revoked member stops hearing about changes.\n */\nconst EVENTS_MAX_AGE_MS = 5 * 60_000;\n\nexport interface KnowledgeRoutesDeps extends RouteDependencies {\n /** Factory projects domain: validates that the `:id` project belongs to the caller's org. */\n projects: FactoryProjectsStorage;\n /** Lazy handle to the host-registered Knowledge runtime; endpoints 503 when absent. */\n knowledge: (key: string) => Promise<Knowledge | undefined>;\n /** Host-selected Knowledge key. Requests cannot override it. */\n defaultKnowledgeKey?: string;\n}\n\ninterface ResolvedView {\n knowledge: Knowledge;\n store: KnowledgeStorage;\n read: KnowledgeReadScope;\n}\n\nfunction boundedId(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n const trimmed = value.trim();\n return trimmed && trimmed.length <= ID_LIMIT ? trimmed : undefined;\n}\n\nfunction boundedLimit(value: string | undefined, max: number): number | undefined | null {\n if (value === undefined) return undefined;\n const parsed = Number(value);\n return Number.isInteger(parsed) && parsed >= 1 && parsed <= max ? parsed : null;\n}\n\n/**\n * The ids of a change this caller may see, or null when they may see none of it. Events carry ids only, so\n * readability is checked against the store now: a page moved out of reach is withheld, but the scope it\n * left still tells the caller to refresh.\n */\nasync function visibleChange(store: KnowledgeStorage, read: KnowledgeReadScope, event: KnowledgeChangeEvent) {\n const readable = async (id: string | undefined) =>\n id !== undefined && (read === 'all' || (await store.getPage({ id, read })) !== null);\n const scopeId = 'scopeId' in event ? event.scopeId : undefined;\n const fromScopeId = 'fromScopeId' in event ? event.fromScopeId : undefined;\n const [page, scope, fromScope] = await Promise.all([\n readable(event.pageId),\n readable(scopeId),\n readable(fromScopeId),\n ]);\n if (!page && !scope && !fromScope) return null;\n return {\n kind: event.kind,\n op: event.op,\n ...(page ? { pageId: event.pageId } : {}),\n ...(scope ? { scopeId } : {}),\n at: event.at.toISOString(),\n };\n}\n\ntype LabelablePage = { isScope: boolean; address?: string };\n\n/**\n * Adds a scope page's declared `displayLabel` with the address's `$params` filled in (`'$orgId policy'`\n * → `'acme policy'`); declarations live in config, not storage.\n */\nfunction withDisplayLabel<T extends LabelablePage>(knowledge: Knowledge, page: T): T & { displayLabel?: string } {\n if (!page.isScope || !page.address) return page;\n const displayLabel = knowledge.scopeLabel(page.address);\n return displayLabel ? { ...page, displayLabel } : page;\n}\n\nexport class KnowledgeRoutes extends Route<KnowledgeRoutesDeps> {\n /** Tenant, org-owned project, Knowledge runtime and the caller's read scope: the one seam every route shares. */\n async #resolveView(c: Context): Promise<ResolvedView | { response: Response }> {\n await this.deps.auth.ensureUser(c);\n const tenant = this.deps.auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json({ error: 'organization_required', message: 'Knowledge requires an organization.' }, 403),\n };\n }\n\n const projectId = c.req.param('id');\n if (!projectId || !UUID_RE.test(projectId)) return { response: c.json({ error: 'Project not found' }, 404) };\n await this.deps.projects.ensureReady();\n const project = await this.deps.projects.get({ orgId: tenant.orgId, id: projectId });\n if (!project) return { response: c.json({ error: 'Project not found' }, 404) };\n\n let knowledge: Knowledge | undefined;\n let store: KnowledgeStorage | undefined;\n try {\n knowledge = await this.deps.knowledge(this.deps.defaultKnowledgeKey ?? 'default');\n store = knowledge ? await knowledge.getStorage() : undefined;\n } catch {\n store = undefined;\n }\n if (!knowledge || !store) {\n return {\n response: c.json(\n { error: 'knowledge_unavailable', message: 'The configured Knowledge runtime is unavailable.' },\n 503,\n ),\n };\n }\n try {\n return { knowledge, store, read: await knowledge.readScopeFor([`org:${tenant.orgId}`, `project:${projectId}`]) };\n } catch (error) {\n // The host's Knowledge does not declare the scopes a Factory run holds (`org:` and `project:`): a\n // deployment misconfiguration, which its session runs hit too. Never fall back to a guessed scope.\n if (error instanceof KnowledgeDeclarationError) {\n return { response: c.json({ error: 'knowledge_misconfigured', message: error.message }, 500) };\n }\n throw error;\n }\n }\n\n routes(): ApiRoute[] {\n const badRequest = (c: Context, message: string) => c.json({ error: 'bad_request', message }, 400);\n return [\n registerApiRoute('/web/factory/projects/:id/knowledge/tree', {\n method: 'GET',\n requiresAuth: false,\n handler: async raw => {\n const c = loose(raw);\n const view = await this.#resolveView(c);\n if ('response' in view) return view.response;\n const parentId = boundedId(c.req.query('parentId'));\n const cursor = boundedId(c.req.query('cursor'));\n const limit = boundedLimit(c.req.query('limit'), MAX_PAGE_LIMIT);\n if (limit === null) return badRequest(c, `limit must be an integer from 1 to ${MAX_PAGE_LIMIT}.`);\n const level = await listKnowledgeTreeChildren(view.store, {\n parentId: parentId ?? null,\n read: view.read,\n cursor,\n limit,\n });\n return c.json({ ...level, pages: level.pages.map(page => withDisplayLabel(view.knowledge, page)) });\n },\n }),\n registerApiRoute('/web/factory/projects/:id/knowledge/pages/:pageId', {\n method: 'GET',\n requiresAuth: false,\n handler: async raw => {\n const c = loose(raw);\n const view = await this.#resolveView(c);\n if ('response' in view) return view.response;\n const pageId = boundedId(c.req.param('pageId'));\n if (!pageId) return c.json({ error: 'page_not_found' }, 404);\n const noteLimit = boundedLimit(c.req.query('noteLimit'), MAX_PAGE_LIMIT);\n if (noteLimit === null) return badRequest(c, `noteLimit must be an integer from 1 to ${MAX_PAGE_LIMIT}.`);\n const page = await readKnowledgePage(view.store, {\n pageId,\n read: view.read,\n noteCursor: boundedId(c.req.query('noteCursor')),\n noteLimit,\n });\n if (!page) return c.json({ error: 'page_not_found' }, 404);\n const label = <T extends LabelablePage>(entry: T) => withDisplayLabel(view.knowledge, entry);\n return c.json({\n ...page,\n page: label(page.page),\n ancestors: page.ancestors.map(label),\n related: page.related.map(label),\n });\n },\n }),\n registerApiRoute('/web/factory/projects/:id/knowledge/graph', {\n method: 'GET',\n requiresAuth: false,\n handler: async raw => {\n const c = loose(raw);\n const view = await this.#resolveView(c);\n if ('response' in view) return view.response;\n const maxPages = boundedLimit(c.req.query('maxPages'), MAX_GRAPH_PAGES);\n if (maxPages === null) return badRequest(c, `maxPages must be an integer from 1 to ${MAX_GRAPH_PAGES}.`);\n const graph = await readKnowledgePageGraph(view.store, {\n read: view.read,\n rootId: boundedId(c.req.query('rootId')) ?? null,\n ...(maxPages ? { limits: { maxPages } } : {}),\n });\n if (!graph) return c.json({ error: 'page_not_found' }, 404);\n // Declared grants between the scopes shown, limited to principal scopes this caller can read.\n const grants = await readKnowledgeScopeGrants(view.store, {\n pages: graph.pages,\n read: view.read,\n grantsFor: scope => view.knowledge.scopeGrants(scope),\n });\n return c.json({\n ...graph,\n pages: graph.pages.map(page => withDisplayLabel(view.knowledge, page)),\n grants: grants.map(grant => {\n const principalLabel = view.knowledge.scopeLabel(grant.principal);\n return principalLabel ? { ...grant, principalLabel } : grant;\n }),\n });\n },\n }),\n registerApiRoute('/web/factory/projects/:id/knowledge/search', {\n method: 'GET',\n requiresAuth: false,\n handler: async raw => {\n const c = loose(raw);\n const view = await this.#resolveView(c);\n if ('response' in view) return view.response;\n const query = (c.req.query('q') ?? '').trim();\n if (!query) return c.json({ results: [] });\n if (query.length > SEARCH_QUERY_LIMIT) {\n return badRequest(c, `q must be at most ${SEARCH_QUERY_LIMIT} characters.`);\n }\n const limit = boundedLimit(c.req.query('limit'), MAX_PAGE_LIMIT);\n if (limit === null) return badRequest(c, `limit must be an integer from 1 to ${MAX_PAGE_LIMIT}.`);\n const scopeIds = c.req.queries('scopeId')?.flatMap(id => boundedId(id) ?? []);\n const results = await searchKnowledgeExplorerPages(view.store, {\n query,\n read: view.read,\n ...(scopeIds?.length ? { scopeIds } : {}),\n limit,\n });\n return c.json({\n results: results.map(hit => ({ ...hit, page: withDisplayLabel(view.knowledge, hit.page) })),\n });\n },\n }),\n registerApiRoute('/web/factory/projects/:id/knowledge/events', {\n method: 'GET',\n requiresAuth: false,\n handler: async raw => {\n const c = loose(raw);\n const view = await this.#resolveView(c);\n if ('response' in view) return view.response;\n const { knowledge, store, read } = view;\n return streamSSE(c, async stream => {\n const closed = new Promise<void>(resolve => stream.onAbort(resolve));\n // Filtering reads the store, so changes are queued to keep them in commit order.\n let queue = Promise.resolve();\n const unsubscribe = knowledge.onChange(event => {\n queue = queue.then(async () => {\n if (stream.aborted) return;\n const change = await visibleChange(store, read, event).catch(() => null);\n if (!change || stream.aborted) return;\n try {\n await stream.writeSSE({ event: 'change', data: JSON.stringify(change) });\n } catch {\n // The tab went away mid-write; abort cleans up.\n }\n });\n });\n const keepalive = setInterval(() => {\n if (!stream.aborted) void stream.write(': ping\\n\\n');\n }, EVENTS_KEEPALIVE_MS);\n let expire: ReturnType<typeof setTimeout> | undefined;\n try {\n await stream.write(': connected\\n\\n');\n // `streamSSE` closes the stream the moment this callback returns.\n await Promise.race([\n closed,\n new Promise<void>(resolve => (expire = setTimeout(resolve, EVENTS_MAX_AGE_MS))),\n ]);\n } finally {\n clearTimeout(expire);\n clearInterval(keepalive);\n unsubscribe();\n }\n });\n },\n }),\n registerApiRoute('/web/factory/projects/:id/knowledge/activity', {\n method: 'GET',\n requiresAuth: false,\n handler: async raw => {\n const c = loose(raw);\n const view = await this.#resolveView(c);\n if ('response' in view) return view.response;\n const limit = boundedLimit(c.req.query('limit'), MAX_PAGE_LIMIT);\n if (limit === null) return badRequest(c, `limit must be an integer from 1 to ${MAX_PAGE_LIMIT}.`);\n return c.json(\n await readKnowledgePageActivity(view.store, {\n read: view.read,\n scopeId: boundedId(c.req.query('scopeId')),\n pageId: boundedId(c.req.query('pageId')),\n cursor: boundedId(c.req.query('cursor')),\n limit,\n }),\n );\n },\n }),\n ];\n }\n}\n"],"mappings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,GAAG,sCAAsC,eAAe,EAAE;KAChG,OAAO,EAAE,KACP,MAAM,0BAA0B,KAAK,OAAO;MAC1C,MAAM,KAAK;MACX,SAAS,UAAU,EAAE,IAAI,MAAM,SAAS,CAAC;MACzC,QAAQ,UAAU,EAAE,IAAI,MAAM,QAAQ,CAAC;MACvC,QAAQ,UAAU,EAAE,IAAI,MAAM,QAAQ,CAAC;MACvC;KACF,CAAC,CACH;IACF;GACF,CAAC;EACH;CACF;AACF"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
import type { RouteAuth } from './route.js';
|
|
3
|
+
export declare const MASTRA_SIGN_IN_REQUIRED = "The Mastra Gateway needs a Factory signed in with a Mastra account.";
|
|
4
|
+
export declare class MastraGatewayError extends Error {
|
|
5
|
+
readonly status: 400 | 403 | 409 | 502;
|
|
6
|
+
constructor(status: 400 | 403 | 409 | 502, message: string);
|
|
7
|
+
}
|
|
8
|
+
export declare function createGatewayKey(auth: RouteAuth, c: Context, orgId: string, scope: 'org' | 'user'): Promise<string>;
|
|
9
|
+
export interface MastraGatewayCredits {
|
|
10
|
+
/** Dollars (1 credit = $1); absent when the platform reports no balance for the pool. */
|
|
11
|
+
remaining?: number;
|
|
12
|
+
unlimited: boolean;
|
|
13
|
+
/** Mastra lets only organization admins buy credits. */
|
|
14
|
+
canAddCredits: boolean;
|
|
15
|
+
addCreditsUrl: string;
|
|
16
|
+
}
|
|
17
|
+
/** Read like the platform dashboard's `useCreditBalance`. */
|
|
18
|
+
export declare function getGatewayCredits(auth: RouteAuth, c: Context, orgId: string): Promise<MastraGatewayCredits>;
|
|
19
|
+
//# sourceMappingURL=mastra-gateway.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mastra-gateway.d.ts","sourceRoot":"","sources":["../../src/routes/mastra-gateway.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAGpC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAiB5C,eAAO,MAAM,uBAAuB,wEAAwE,CAAC;AAE7G,qBAAa,kBAAmB,SAAQ,KAAK;IAEzC,QAAQ,CAAC,MAAM,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG;IADxC,YACW,MAAM,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,EACtC,OAAO,EAAE,MAAM,EAGhB;CACF;AAwDD,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,SAAS,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,GAAG,MAAM,mBAkBvG;AA6BD,MAAM,WAAW,oBAAoB;IACnC,yFAAyF;IACzF,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,OAAO,CAAC;IACnB,wDAAwD;IACxD,aAAa,EAAE,OAAO,CAAC;IACvB,aAAa,EAAE,MAAM,CAAC;CACvB;AAQD,6DAA6D;AAC7D,wBAAsB,iBAAiB,CAAC,IAAI,EAAE,SAAS,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAcjH"}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
// src/routes/mastra-gateway.ts
|
|
3
|
+
const MASTRA_PROJECTS_URL = process.env.MASTRA_PROJECTS_URL || "https://projects.mastra.ai";
|
|
4
|
+
/** The Starter plan's gateway credit pool, used when the customer names none. */
|
|
5
|
+
const STARTER_CREDIT_POOL = "gateway_credits";
|
|
6
|
+
/**
|
|
7
|
+
* Provisions a Gateway project with a v1 key, which the live gateway accepts. Organization (v2) keys
|
|
8
|
+
* aren't released yet, so Factory doesn't ask for one (the CLI does the same).
|
|
9
|
+
*/
|
|
10
|
+
const GATEWAY_PROVISION_PATH = "/gateway/projects/provision";
|
|
11
|
+
const PLATFORM_TIMEOUT_MS = 15e3;
|
|
12
|
+
const PLATFORM_UNREACHABLE = "Could not reach Mastra. Try again.";
|
|
13
|
+
const MASTRA_SIGN_IN_REQUIRED = "The Mastra Gateway needs a Factory signed in with a Mastra account.";
|
|
14
|
+
var MastraGatewayError = class extends Error {
|
|
15
|
+
status;
|
|
16
|
+
constructor(status, message) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.status = status;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
function platformUnavailable(message) {
|
|
22
|
+
return new MastraGatewayError(502, message);
|
|
23
|
+
}
|
|
24
|
+
async function platformFetch(auth, c, path, init = {}, unreachable = PLATFORM_UNREACHABLE) {
|
|
25
|
+
if (!auth.fetchPlatformAsUser) throw new MastraGatewayError(400, MASTRA_SIGN_IN_REQUIRED);
|
|
26
|
+
let res;
|
|
27
|
+
try {
|
|
28
|
+
res = await auth.fetchPlatformAsUser(c, path, {
|
|
29
|
+
...init,
|
|
30
|
+
signal: AbortSignal.timeout(PLATFORM_TIMEOUT_MS)
|
|
31
|
+
});
|
|
32
|
+
} catch {
|
|
33
|
+
throw platformUnavailable(unreachable);
|
|
34
|
+
}
|
|
35
|
+
if (!res || res.status === 401) throw new MastraGatewayError(400, "Your Mastra sign-in expired. Sign in again.");
|
|
36
|
+
return res;
|
|
37
|
+
}
|
|
38
|
+
async function readJson(res, schema, failure) {
|
|
39
|
+
const parsed = schema.safeParse(await res.json().catch(() => void 0));
|
|
40
|
+
if (!parsed.success) throw platformUnavailable(failure);
|
|
41
|
+
return parsed.data;
|
|
42
|
+
}
|
|
43
|
+
const PlatformMe = z.object({
|
|
44
|
+
organizationId: z.string().nullish(),
|
|
45
|
+
role: z.string().nullish(),
|
|
46
|
+
user: z.object({ email: z.string().nullish() }).nullish()
|
|
47
|
+
});
|
|
48
|
+
/**
|
|
49
|
+
* The signed-in user on Mastra, once their session is confirmed to be on this
|
|
50
|
+
* Factory's organization. Platform keys and billing follow the session's
|
|
51
|
+
* active organization, which differs from a Factory pinned to another one.
|
|
52
|
+
*/
|
|
53
|
+
async function platformMember(auth, c, orgId) {
|
|
54
|
+
const res = await platformFetch(auth, c, "/auth/me");
|
|
55
|
+
if (!res.ok) throw platformUnavailable(PLATFORM_UNREACHABLE);
|
|
56
|
+
const me = await readJson(res, PlatformMe, PLATFORM_UNREACHABLE);
|
|
57
|
+
if (me.organizationId !== orgId) throw new MastraGatewayError(409, "Your Mastra sign-in is on a different organization than this Factory. Sign in again with this Factory’s organization.");
|
|
58
|
+
return {
|
|
59
|
+
email: me.user?.email ?? void 0,
|
|
60
|
+
isAdmin: me.role === "admin" || me.role === "owner"
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
const CreatedGatewayKey = z.object({ apiKey: z.string().min(1) });
|
|
64
|
+
async function createGatewayKey(auth, c, orgId, scope) {
|
|
65
|
+
const { email } = await platformMember(auth, c, orgId);
|
|
66
|
+
const label = scope === "org" ? "Factory · Shared" : `Factory · ${email ?? "Personal"}`;
|
|
67
|
+
const res = await platformFetch(auth, c, GATEWAY_PROVISION_PATH, {
|
|
68
|
+
method: "POST",
|
|
69
|
+
headers: { "Content-Type": "application/json" },
|
|
70
|
+
body: JSON.stringify({
|
|
71
|
+
name: label,
|
|
72
|
+
keyLabel: label
|
|
73
|
+
})
|
|
74
|
+
});
|
|
75
|
+
if (res.status === 403) throw new MastraGatewayError(403, "Your Mastra role cannot create gateway keys for this organization. Ask an admin to connect it.");
|
|
76
|
+
const failure = "Could not create a Mastra Gateway key. Try again.";
|
|
77
|
+
if (!res.ok) throw platformUnavailable(failure);
|
|
78
|
+
const { apiKey } = await readJson(res, CreatedGatewayKey, failure);
|
|
79
|
+
return apiKey;
|
|
80
|
+
}
|
|
81
|
+
const CustomerBalance = z.object({
|
|
82
|
+
featureId: z.string().nullish(),
|
|
83
|
+
remaining: z.number().nullish(),
|
|
84
|
+
granted: z.number().nullish(),
|
|
85
|
+
usage: z.number().nullish(),
|
|
86
|
+
unlimited: z.boolean().nullish()
|
|
87
|
+
});
|
|
88
|
+
const BillingCustomer = z.object({ customer: z.object({
|
|
89
|
+
balances: z.record(z.string(), CustomerBalance.nullish()).nullish(),
|
|
90
|
+
creditPool: z.object({ featureId: z.string().nullish() }).nullish()
|
|
91
|
+
}).nullish() });
|
|
92
|
+
async function billingCustomer(auth, c, failure) {
|
|
93
|
+
const res = await platformFetch(auth, c, "/billing/customer");
|
|
94
|
+
if (!res.ok) throw platformUnavailable(failure);
|
|
95
|
+
return (await readJson(res, BillingCustomer, failure)).customer ?? void 0;
|
|
96
|
+
}
|
|
97
|
+
function addCreditsUrl(orgId) {
|
|
98
|
+
return `${MASTRA_PROJECTS_URL}/add-credits/${encodeURIComponent(orgId)}`;
|
|
99
|
+
}
|
|
100
|
+
function remainingCredits(balance) {
|
|
101
|
+
if (balance?.remaining != null) return Math.max(0, balance.remaining);
|
|
102
|
+
if (balance?.granted != null) return Math.max(0, balance.granted - (balance.usage ?? 0));
|
|
103
|
+
}
|
|
104
|
+
/** Read like the platform dashboard's `useCreditBalance`. */
|
|
105
|
+
async function getGatewayCredits(auth, c, orgId) {
|
|
106
|
+
const member = await platformMember(auth, c, orgId);
|
|
107
|
+
const customer = await billingCustomer(auth, c, "Could not read Mastra Gateway credits. Try again.");
|
|
108
|
+
const featureId = customer?.creditPool?.featureId ?? STARTER_CREDIT_POOL;
|
|
109
|
+
const balances = customer?.balances;
|
|
110
|
+
const balance = balances ? Object.values(balances).find((entry) => entry?.featureId === featureId) ?? balances[featureId] : void 0;
|
|
111
|
+
return {
|
|
112
|
+
remaining: remainingCredits(balance),
|
|
113
|
+
unlimited: balance?.unlimited === true,
|
|
114
|
+
canAddCredits: member.isAdmin,
|
|
115
|
+
addCreditsUrl: addCreditsUrl(orgId)
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
export { MASTRA_SIGN_IN_REQUIRED, MastraGatewayError, createGatewayKey, getGatewayCredits };
|
|
119
|
+
|
|
120
|
+
//# sourceMappingURL=mastra-gateway.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mastra-gateway.js","names":[],"sources":["../../src/routes/mastra-gateway.ts"],"sourcesContent":["import type { Context } from 'hono';\nimport { z } from 'zod';\n\nimport type { RouteAuth } from './route.js';\n\nconst MASTRA_PROJECTS_URL = process.env.MASTRA_PROJECTS_URL || 'https://projects.mastra.ai';\n\n/** The Starter plan's gateway credit pool, used when the customer names none. */\nconst STARTER_CREDIT_POOL = 'gateway_credits';\n\n/**\n * Provisions a Gateway project with a v1 key, which the live gateway accepts. Organization (v2) keys\n * aren't released yet, so Factory doesn't ask for one (the CLI does the same).\n */\nconst GATEWAY_PROVISION_PATH = '/gateway/projects/provision';\n\nconst PLATFORM_TIMEOUT_MS = 15_000;\n\nconst PLATFORM_UNREACHABLE = 'Could not reach Mastra. Try again.';\n\nexport const MASTRA_SIGN_IN_REQUIRED = 'The Mastra Gateway needs a Factory signed in with a Mastra account.';\n\nexport class MastraGatewayError extends Error {\n constructor(\n readonly status: 400 | 403 | 409 | 502,\n message: string,\n ) {\n super(message);\n }\n}\n\nfunction platformUnavailable(message: string): MastraGatewayError {\n return new MastraGatewayError(502, message);\n}\n\nasync function platformFetch(\n auth: RouteAuth,\n c: Context,\n path: string,\n init: RequestInit = {},\n unreachable = PLATFORM_UNREACHABLE,\n): Promise<Response> {\n if (!auth.fetchPlatformAsUser) throw new MastraGatewayError(400, MASTRA_SIGN_IN_REQUIRED);\n let res: Response | null;\n try {\n res = await auth.fetchPlatformAsUser(c, path, { ...init, signal: AbortSignal.timeout(PLATFORM_TIMEOUT_MS) });\n } catch {\n throw platformUnavailable(unreachable);\n }\n if (!res || res.status === 401) throw new MastraGatewayError(400, 'Your Mastra sign-in expired. Sign in again.');\n return res;\n}\n\nasync function readJson<T>(res: Response, schema: z.ZodType<T>, failure: string): Promise<T> {\n const parsed = schema.safeParse(await res.json().catch(() => undefined));\n if (!parsed.success) throw platformUnavailable(failure);\n return parsed.data;\n}\n\nconst PlatformMe = z.object({\n organizationId: z.string().nullish(),\n role: z.string().nullish(),\n user: z.object({ email: z.string().nullish() }).nullish(),\n});\n\n/**\n * The signed-in user on Mastra, once their session is confirmed to be on this\n * Factory's organization. Platform keys and billing follow the session's\n * active organization, which differs from a Factory pinned to another one.\n */\nasync function platformMember(auth: RouteAuth, c: Context, orgId: string) {\n const res = await platformFetch(auth, c, '/auth/me');\n if (!res.ok) throw platformUnavailable(PLATFORM_UNREACHABLE);\n const me = await readJson(res, PlatformMe, PLATFORM_UNREACHABLE);\n if (me.organizationId !== orgId) {\n throw new MastraGatewayError(\n 409,\n 'Your Mastra sign-in is on a different organization than this Factory. Sign in again with this Factory’s organization.',\n );\n }\n return { email: me.user?.email ?? undefined, isAdmin: me.role === 'admin' || me.role === 'owner' };\n}\n\nconst CreatedGatewayKey = z.object({ apiKey: z.string().min(1) });\n\nexport async function createGatewayKey(auth: RouteAuth, c: Context, orgId: string, scope: 'org' | 'user') {\n const { email } = await platformMember(auth, c, orgId);\n const label = scope === 'org' ? 'Factory · Shared' : `Factory · ${email ?? 'Personal'}`;\n const res = await platformFetch(auth, c, GATEWAY_PROVISION_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ name: label, keyLabel: label }),\n });\n if (res.status === 403) {\n throw new MastraGatewayError(\n 403,\n 'Your Mastra role cannot create gateway keys for this organization. Ask an admin to connect it.',\n );\n }\n const failure = 'Could not create a Mastra Gateway key. Try again.';\n if (!res.ok) throw platformUnavailable(failure);\n const { apiKey } = await readJson(res, CreatedGatewayKey, failure);\n return apiKey;\n}\n\nconst CustomerBalance = z.object({\n featureId: z.string().nullish(),\n remaining: z.number().nullish(),\n granted: z.number().nullish(),\n usage: z.number().nullish(),\n unlimited: z.boolean().nullish(),\n});\n\nconst BillingCustomer = z.object({\n customer: z\n .object({\n balances: z.record(z.string(), CustomerBalance.nullish()).nullish(),\n creditPool: z.object({ featureId: z.string().nullish() }).nullish(),\n })\n .nullish(),\n});\n\nasync function billingCustomer(auth: RouteAuth, c: Context, failure: string) {\n const res = await platformFetch(auth, c, '/billing/customer');\n if (!res.ok) throw platformUnavailable(failure);\n return (await readJson(res, BillingCustomer, failure)).customer ?? undefined;\n}\n\nfunction addCreditsUrl(orgId: string): string {\n return `${MASTRA_PROJECTS_URL}/add-credits/${encodeURIComponent(orgId)}`;\n}\n\nexport interface MastraGatewayCredits {\n /** Dollars (1 credit = $1); absent when the platform reports no balance for the pool. */\n remaining?: number;\n unlimited: boolean;\n /** Mastra lets only organization admins buy credits. */\n canAddCredits: boolean;\n addCreditsUrl: string;\n}\n\nfunction remainingCredits(balance: z.infer<typeof CustomerBalance> | null | undefined): number | undefined {\n if (balance?.remaining != null) return Math.max(0, balance.remaining);\n if (balance?.granted != null) return Math.max(0, balance.granted - (balance.usage ?? 0));\n return undefined;\n}\n\n/** Read like the platform dashboard's `useCreditBalance`. */\nexport async function getGatewayCredits(auth: RouteAuth, c: Context, orgId: string): Promise<MastraGatewayCredits> {\n const member = await platformMember(auth, c, orgId);\n const customer = await billingCustomer(auth, c, 'Could not read Mastra Gateway credits. Try again.');\n const featureId = customer?.creditPool?.featureId ?? STARTER_CREDIT_POOL;\n const balances = customer?.balances;\n const balance = balances\n ? (Object.values(balances).find(entry => entry?.featureId === featureId) ?? balances[featureId])\n : undefined;\n return {\n remaining: remainingCredits(balance),\n unlimited: balance?.unlimited === true,\n canAddCredits: member.isAdmin,\n addCreditsUrl: addCreditsUrl(orgId),\n };\n}\n"],"mappings":";;AAKA,MAAM,sBAAsB,QAAQ,IAAI,uBAAuB;;AAG/D,MAAM,sBAAsB;;;;;AAM5B,MAAM,yBAAyB;AAE/B,MAAM,sBAAsB;AAE5B,MAAM,uBAAuB;AAE7B,MAAa,0BAA0B;AAEvC,IAAa,qBAAb,cAAwC,MAAM;CAEjC;CADX,YACE,QACA,SACA;EACA,MAAM,OAAO;EAHJ,KAAA,SAAA;CAIX;AACF;AAEA,SAAS,oBAAoB,SA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src/routes/oauth.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAcH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAEjE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAIpD,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AAIjF,OAAO,EAAS,KAAK,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAsMpD,MAAM,WAAW,eAAgB,SAAQ,iBAAiB;IACxD,kEAAkE;IAClE,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,qEAAqE;IACrE,gBAAgB,CAAC,EAAE,uBAAuB,CAAC;IAC3C,kFAAkF;IAClF,oBAAoB,CAAC,EAAE,CAAC,MAAM,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC;CAC7E;AAED;;;;;;;GAOG;AACH,qBAAa,WAAY,SAAQ,KAAK,CAAC,eAAe,CAAC;IACrD,MAAM,IAAI,QAAQ,EAAE,CAkQnB;CACF"}
|
package/dist/routes/oauth.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ModelCredentialsStorage } from "../storage/domains/credentials/base.js";
|
|
2
2
|
import { getAuthProviderId, resolveCredentialContext } from "./provider-credentials.js";
|
|
3
|
-
import { Route } from "./route.js";
|
|
3
|
+
import { Route, loose } from "./route.js";
|
|
4
4
|
import { registerApiRoute } from "@mastra/core/server";
|
|
5
5
|
import { nextPollDelayMs } from "@mastra/code-sdk/auth/device-code";
|
|
6
6
|
import { completeAnthropicLogin, startAnthropicLogin } from "@mastra/code-sdk/auth/providers/anthropic";
|
|
@@ -135,9 +135,6 @@ const OAUTH_FLOWS = {
|
|
|
135
135
|
}
|
|
136
136
|
}
|
|
137
137
|
};
|
|
138
|
-
function loose(c) {
|
|
139
|
-
return c;
|
|
140
|
-
}
|
|
141
138
|
/**
|
|
142
139
|
* Local-mode login sessions. Flows in local mode are single-process, so a
|
|
143
140
|
* process-local libsql `:memory:` database (which already handles TTL
|