@mastra/factory 0.24.0-alpha.9 → 0.25.0-alpha.0
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 +40 -13
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +18 -4
- package/dist/auth.js.map +1 -1
- package/dist/boards/review.d.ts.map +1 -1
- package/dist/boards/review.js +3 -2
- package/dist/boards/review.js.map +1 -1
- package/dist/environment/build-runner.js +2 -1
- package/dist/environment/build-runner.js.map +1 -1
- package/dist/environment/build-workflow.js +1 -1
- package/dist/environment/build-workflow.js.map +1 -1
- package/dist/environment/build.js +16 -14
- package/dist/environment/build.js.map +1 -1
- package/dist/factory.d.ts +3 -0
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +172 -88
- package/dist/factory.js.map +1 -1
- package/dist/integrations/base.d.ts +15 -2
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/github/app-identity.js.map +1 -1
- package/dist/integrations/github/integration.js +1 -1
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/reconcile-worker.js +1 -1
- package/dist/integrations/github/reconcile-worker.js.map +1 -1
- package/dist/integrations/github/routes.d.ts +1 -1
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +24 -13
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +53 -9
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/sandbox.js +2 -2
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/github/session-subscriptions.d.ts.map +1 -1
- package/dist/integrations/github/session-subscriptions.js +1 -2
- package/dist/integrations/github/session-subscriptions.js.map +1 -1
- package/dist/integrations/github/subscriptions.d.ts +7 -4
- package/dist/integrations/github/subscriptions.d.ts.map +1 -1
- package/dist/integrations/github/subscriptions.js +5 -5
- package/dist/integrations/github/subscriptions.js.map +1 -1
- package/dist/integrations/gitlab/api.js.map +1 -1
- package/dist/integrations/gitlab/integration.js.map +1 -1
- package/dist/integrations/gitlab/reconciliation-config.js +2 -1
- package/dist/integrations/gitlab/reconciliation-config.js.map +1 -1
- package/dist/integrations/gitlab/routes.d.ts.map +1 -1
- package/dist/integrations/gitlab/routes.js +10 -6
- package/dist/integrations/gitlab/routes.js.map +1 -1
- package/dist/integrations/gitlab/rules.js.map +1 -1
- package/dist/integrations/gitlab/session-subscriptions.d.ts.map +1 -1
- package/dist/integrations/gitlab/session-subscriptions.js +1 -2
- package/dist/integrations/gitlab/session-subscriptions.js.map +1 -1
- package/dist/integrations/gitlab/subscriptions.d.ts +7 -4
- package/dist/integrations/gitlab/subscriptions.d.ts.map +1 -1
- package/dist/integrations/gitlab/subscriptions.js +5 -5
- package/dist/integrations/gitlab/subscriptions.js.map +1 -1
- package/dist/integrations/incidentio/api.js.map +1 -1
- package/dist/integrations/incidentio/integration.js.map +1 -1
- package/dist/integrations/incidentio/rules.js.map +1 -1
- package/dist/integrations/issue-reconcile-worker.js +1 -1
- package/dist/integrations/issue-reconcile-worker.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/api.js.map +1 -1
- package/dist/integrations/jira/integration.js.map +1 -1
- package/dist/integrations/jira/rules.js.map +1 -1
- package/dist/integrations/linear/agent-tools.d.ts.map +1 -1
- package/dist/integrations/linear/agent-tools.js.map +1 -1
- package/dist/integrations/linear/integration.js.map +1 -1
- package/dist/integrations/linear/rules.js.map +1 -1
- package/dist/integrations/platform/api-client.js.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +1 -1
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.js +2 -2
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/gitlab/event-worker.js.map +1 -1
- package/dist/integrations/platform/gitlab/integration.js.map +1 -1
- package/dist/integrations/platform/incidentio/integration.js +2 -1
- package/dist/integrations/platform/incidentio/integration.js.map +1 -1
- package/dist/integrations/platform/jira/integration.js.map +1 -1
- package/dist/integrations/platform/linear/event-worker.js +1 -1
- package/dist/integrations/platform/linear/event-worker.js.map +1 -1
- package/dist/integrations/platform/linear/integration.js.map +1 -1
- package/dist/{session → integrations/slack}/channel-reply-processor.d.ts +11 -9
- package/dist/integrations/slack/channel-reply-processor.d.ts.map +1 -0
- package/dist/integrations/slack/channel-reply-processor.js +61 -0
- package/dist/integrations/slack/channel-reply-processor.js.map +1 -0
- package/dist/integrations/slack/channel-session-link-processor.d.ts.map +1 -0
- package/dist/{session → integrations/slack}/channel-session-link-processor.js +14 -4
- package/dist/integrations/slack/channel-session-link-processor.js.map +1 -0
- package/dist/integrations/slack/connect-route.js +1 -1
- package/dist/integrations/slack/connect-route.js.map +1 -1
- package/dist/integrations/slack/feed-publisher.js +1 -1
- package/dist/integrations/slack/feed-publisher.js.map +1 -1
- package/dist/integrations/slack/integration.d.ts +25 -1
- package/dist/integrations/slack/integration.d.ts.map +1 -1
- package/dist/integrations/slack/integration.js +56 -6
- package/dist/integrations/slack/integration.js.map +1 -1
- package/dist/integrations/slack/reply-reminder-processor.d.ts +23 -0
- package/dist/integrations/slack/reply-reminder-processor.d.ts.map +1 -0
- package/dist/integrations/slack/reply-reminder-processor.js +58 -0
- package/dist/integrations/slack/reply-reminder-processor.js.map +1 -0
- package/dist/integrations/slack/reply-tool.d.ts +31 -0
- package/dist/integrations/slack/reply-tool.d.ts.map +1 -0
- package/dist/integrations/slack/reply-tool.js +203 -0
- package/dist/integrations/slack/reply-tool.js.map +1 -0
- package/dist/integrations/slack/share-file-tool.d.ts +45 -0
- package/dist/integrations/slack/share-file-tool.d.ts.map +1 -0
- package/dist/integrations/slack/share-file-tool.js +106 -0
- package/dist/integrations/slack/share-file-tool.js.map +1 -0
- package/dist/integrations/slack/slack.d.ts +16 -5
- package/dist/integrations/slack/slack.d.ts.map +1 -1
- package/dist/integrations/slack/slack.js +141 -40
- package/dist/integrations/slack/slack.js.map +1 -1
- package/dist/integrations/subscription-session.d.ts +0 -1
- package/dist/integrations/subscription-session.d.ts.map +1 -1
- package/dist/integrations/subscription-session.js +1 -4
- package/dist/integrations/subscription-session.js.map +1 -1
- package/dist/integrations/workos/integration.js.map +1 -1
- package/dist/mcp/events.d.ts +73 -0
- package/dist/mcp/events.d.ts.map +1 -0
- package/dist/mcp/events.js +158 -0
- package/dist/mcp/events.js.map +1 -0
- package/dist/mcp/routes.d.ts +0 -1
- package/dist/mcp/routes.d.ts.map +1 -1
- package/dist/mcp/routes.js +31 -4
- package/dist/mcp/routes.js.map +1 -1
- package/dist/packages/_internals/workspace/dist/index.js +18 -1
- package/dist/packages/_internals/workspace/dist/index.js.map +1 -1
- package/dist/platform-auth-host.d.ts.map +1 -1
- package/dist/platform-auth-host.js +1 -1
- package/dist/platform-auth-host.js.map +1 -1
- package/dist/routes/attention-activity.js.map +1 -1
- package/dist/routes/attention-parked.js.map +1 -1
- package/dist/routes/attention-providers.js.map +1 -1
- package/dist/routes/automation-runs.js.map +1 -1
- package/dist/routes/config.d.ts +8 -7
- package/dist/routes/config.d.ts.map +1 -1
- package/dist/routes/config.js +70 -28
- package/dist/routes/config.js.map +1 -1
- package/dist/routes/contracts.d.ts +2 -0
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +2 -2
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/custom-provider-source.js.map +1 -1
- package/dist/routes/fs.d.ts +31 -23
- package/dist/routes/fs.d.ts.map +1 -1
- package/dist/routes/fs.js +218 -64
- package/dist/routes/fs.js.map +1 -1
- package/dist/routes/intake.js +2 -1
- package/dist/routes/intake.js.map +1 -1
- package/dist/routes/knowledge.js +1 -1
- package/dist/routes/knowledge.js.map +1 -1
- package/dist/routes/oauth.js +3 -2
- package/dist/routes/oauth.js.map +1 -1
- package/dist/routes/projects.d.ts +1 -1
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +33 -31
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/provider-credentials.d.ts.map +1 -1
- package/dist/routes/provider-credentials.js +6 -1
- package/dist/routes/provider-credentials.js.map +1 -1
- package/dist/routes/session-access.d.ts +60 -0
- package/dist/routes/session-access.d.ts.map +1 -0
- package/dist/routes/session-access.js +202 -0
- package/dist/routes/session-access.js.map +1 -0
- package/dist/routes/skills.d.ts +2 -4
- package/dist/routes/skills.d.ts.map +1 -1
- package/dist/routes/skills.js +23 -68
- package/dist/routes/skills.js.map +1 -1
- package/dist/routes/source-control-sessions.d.ts +8 -1
- package/dist/routes/source-control-sessions.d.ts.map +1 -1
- package/dist/routes/source-control-sessions.js +239 -19
- package/dist/routes/source-control-sessions.js.map +1 -1
- package/dist/routes/surface.d.ts +7 -0
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +20 -8
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/tenant-credentials.js.map +1 -1
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/binding-context.js +11 -9
- package/dist/rules/binding-context.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +21 -13
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/processor.d.ts +2 -2
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +3 -3
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/start-coordinator.d.ts +4 -0
- package/dist/rules/start-coordinator.d.ts.map +1 -1
- package/dist/rules/start-coordinator.js +36 -4
- package/dist/rules/start-coordinator.js.map +1 -1
- package/dist/rules/tools.js +2 -2
- package/dist/rules/tools.js.map +1 -1
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/sandbox/callback-factory-sandbox.js.map +1 -1
- package/dist/sandbox/local-factory-sandbox.js.map +1 -1
- package/dist/sandbox/session-retirement.d.ts +11 -0
- package/dist/sandbox/session-retirement.d.ts.map +1 -1
- package/dist/sandbox/session-retirement.js +38 -1
- package/dist/sandbox/session-retirement.js.map +1 -1
- package/dist/sandbox/session-sandbox.d.ts +2 -0
- package/dist/sandbox/session-sandbox.d.ts.map +1 -1
- package/dist/sandbox/session-sandbox.js +5 -1
- package/dist/sandbox/session-sandbox.js.map +1 -1
- package/dist/secret-encryption.d.ts.map +1 -1
- package/dist/secret-encryption.js +65 -25
- package/dist/secret-encryption.js.map +1 -1
- package/dist/session/credential-policy.d.ts +4 -2
- package/dist/session/credential-policy.d.ts.map +1 -1
- package/dist/session/credential-policy.js +18 -7
- package/dist/session/credential-policy.js.map +1 -1
- package/dist/session/default-model-hydration.d.ts +1 -0
- package/dist/session/default-model-hydration.d.ts.map +1 -1
- package/dist/session/default-model-hydration.js +3 -2
- package/dist/session/default-model-hydration.js.map +1 -1
- package/dist/session/environment-state-processor.js +1 -1
- package/dist/session/environment-state-processor.js.map +1 -1
- package/dist/session/factory-session.d.ts.map +1 -1
- package/dist/session/factory-session.js +14 -1
- package/dist/session/factory-session.js.map +1 -1
- package/dist/session/filesystem-capture.d.ts +3 -3
- package/dist/session/filesystem-capture.d.ts.map +1 -1
- package/dist/session/filesystem-capture.js +16 -17
- package/dist/session/filesystem-capture.js.map +1 -1
- package/dist/session/first-exec-capture.d.ts +1 -1
- package/dist/session/first-exec-capture.d.ts.map +1 -1
- package/dist/session/first-exec-capture.js +1 -1
- package/dist/session/first-exec-capture.js.map +1 -1
- package/dist/session/first-message-capture.d.ts +1 -1
- package/dist/session/first-message-capture.d.ts.map +1 -1
- package/dist/session/first-message-capture.js +1 -1
- package/dist/session/first-message-capture.js.map +1 -1
- package/dist/session/live-sessions.d.ts +1 -1
- package/dist/session/live-sessions.js +1 -1
- package/dist/session/live-sessions.js.map +1 -1
- package/dist/session/memory-settings-hydration.d.ts +1 -1
- package/dist/session/memory-settings-hydration.d.ts.map +1 -1
- package/dist/session/memory-settings-hydration.js +2 -1
- package/dist/session/memory-settings-hydration.js.map +1 -1
- package/dist/session/resource-migration.d.ts +105 -0
- package/dist/session/resource-migration.d.ts.map +1 -0
- package/dist/session/resource-migration.js +195 -0
- package/dist/session/resource-migration.js.map +1 -0
- package/dist/session/run-audit.d.ts +1 -0
- package/dist/session/run-audit.d.ts.map +1 -1
- package/dist/session/run-audit.js +7 -2
- package/dist/session/run-audit.js.map +1 -1
- package/dist/session/session-threads.d.ts +63 -0
- package/dist/session/session-threads.d.ts.map +1 -0
- package/dist/session/session-threads.js +97 -0
- package/dist/session/session-threads.js.map +1 -0
- package/dist/session/source-control-tools.js +8 -8
- package/dist/session/source-control-tools.js.map +1 -1
- package/dist/session/thinking-default.d.ts +6 -13
- package/dist/session/thinking-default.d.ts.map +1 -1
- package/dist/session/thinking-default.js +19 -24
- package/dist/session/thinking-default.js.map +1 -1
- package/dist/session/thread-session-stamp.d.ts +21 -0
- package/dist/session/thread-session-stamp.d.ts.map +1 -0
- package/dist/session/thread-session-stamp.js +20 -0
- package/dist/session/thread-session-stamp.js.map +1 -0
- package/dist/session/thread-title-mirror.d.ts +1 -1
- package/dist/session/thread-title-mirror.d.ts.map +1 -1
- package/dist/session/thread-title-mirror.js +1 -1
- package/dist/session/thread-title-mirror.js.map +1 -1
- package/dist/session-owner-signal.d.ts +2 -0
- package/dist/session-owner-signal.d.ts.map +1 -0
- package/dist/session-owner-signal.js +6 -0
- package/dist/session-owner-signal.js.map +1 -0
- package/dist/skills/service.d.ts +11 -14
- package/dist/skills/service.d.ts.map +1 -1
- package/dist/skills/service.js +12 -22
- package/dist/skills/service.js.map +1 -1
- package/dist/spa-static.js.map +1 -1
- package/dist/state-signing.js +1 -1
- package/dist/state-signing.js.map +1 -1
- package/dist/storage/domains/audit/actions.d.ts +1 -0
- package/dist/storage/domains/audit/actions.d.ts.map +1 -1
- package/dist/storage/domains/audit/actions.js +2 -1
- package/dist/storage/domains/audit/actions.js.map +1 -1
- package/dist/storage/domains/audit/agent-audit.d.ts.map +1 -1
- package/dist/storage/domains/audit/agent-audit.js +2 -2
- package/dist/storage/domains/audit/agent-audit.js.map +1 -1
- package/dist/storage/domains/audit/base.d.ts +18 -2
- package/dist/storage/domains/audit/base.d.ts.map +1 -1
- package/dist/storage/domains/audit/base.js +22 -4
- package/dist/storage/domains/audit/base.js.map +1 -1
- package/dist/storage/domains/audit/domain.js.map +1 -1
- package/dist/storage/domains/channel-identity/base.js.map +1 -1
- package/dist/storage/domains/comments/base.js.map +1 -1
- package/dist/storage/domains/comments/domain.js.map +1 -1
- package/dist/storage/domains/comments/feed-context.js.map +1 -1
- package/dist/storage/domains/credentials/base.js.map +1 -1
- package/dist/storage/domains/custom-providers/base.js.map +1 -1
- package/dist/storage/domains/intake/base.js.map +1 -1
- package/dist/storage/domains/integrations/base.d.ts +8 -0
- package/dist/storage/domains/integrations/base.d.ts.map +1 -1
- package/dist/storage/domains/integrations/base.js +7 -0
- package/dist/storage/domains/integrations/base.js.map +1 -1
- package/dist/storage/domains/memory-settings/base.js.map +1 -1
- package/dist/storage/domains/model-defaults/base.d.ts +8 -0
- package/dist/storage/domains/model-defaults/base.d.ts.map +1 -1
- package/dist/storage/domains/model-defaults/base.js +18 -0
- package/dist/storage/domains/model-defaults/base.js.map +1 -1
- package/dist/storage/domains/projects/base.js.map +1 -1
- package/dist/storage/domains/queue-health/base.js.map +1 -1
- package/dist/storage/domains/source-control/base.d.ts +44 -0
- package/dist/storage/domains/source-control/base.d.ts.map +1 -1
- package/dist/storage/domains/source-control/base.js +109 -3
- package/dist/storage/domains/source-control/base.js.map +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts +23 -1
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/source-control/inmemory.js +35 -0
- package/dist/storage/domains/source-control/inmemory.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +14 -0
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +25 -1
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/storage/domains/work-items/board-version.js.map +1 -1
- package/dist/storage/domains/work-items/metrics.js.map +1 -1
- package/dist/tools/approval-tools.js +1 -1
- package/dist/tools/approval-tools.js.map +1 -1
- package/dist/tools/deliver.d.ts +8 -5
- package/dist/tools/deliver.d.ts.map +1 -1
- package/dist/tools/deliver.js +22 -8
- package/dist/tools/deliver.js.map +1 -1
- package/dist/tools/messaging-tools.d.ts +1 -1
- package/dist/tools/messaging-tools.d.ts.map +1 -1
- package/dist/tools/messaging-tools.js +203 -72
- package/dist/tools/messaging-tools.js.map +1 -1
- package/dist/tools/permissions.d.ts +1 -1
- package/dist/tools/permissions.d.ts.map +1 -1
- package/dist/tools/permissions.js +3 -2
- package/dist/tools/permissions.js.map +1 -1
- package/dist/tools/reports.d.ts.map +1 -1
- package/dist/tools/reports.js +10 -3
- package/dist/tools/reports.js.map +1 -1
- package/dist/tools/run-watch.d.ts +2 -0
- package/dist/tools/run-watch.d.ts.map +1 -1
- package/dist/tools/run-watch.js +42 -2
- package/dist/tools/run-watch.js.map +1 -1
- package/dist/tools/sandbox-tools.d.ts +12 -0
- package/dist/tools/sandbox-tools.d.ts.map +1 -0
- package/dist/tools/sandbox-tools.js +40 -0
- package/dist/tools/sandbox-tools.js.map +1 -0
- package/dist/tools/scope.d.ts +2 -1
- package/dist/tools/scope.d.ts.map +1 -1
- package/dist/tools/scope.js +5 -7
- package/dist/tools/scope.js.map +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 +39 -18
- package/dist/tools/session-tools.js.map +1 -1
- package/dist/tools/sessions-state-processor.js +2 -2
- package/dist/tools/sessions-state-processor.js.map +1 -1
- package/dist/tools/side-sessions.d.ts +1 -1
- package/dist/tools/side-sessions.d.ts.map +1 -1
- package/dist/tools/side-sessions.js +1 -1
- package/dist/tools/side-sessions.js.map +1 -1
- package/dist/work-item-branch.d.ts +11 -3
- package/dist/work-item-branch.d.ts.map +1 -1
- package/dist/work-item-branch.js +34 -9
- package/dist/work-item-branch.js.map +1 -1
- package/dist/workspace.d.ts +7 -3
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +32 -17
- package/dist/workspace.js.map +1 -1
- package/factory-skills/configure-factory-rules/SKILL.md +2 -2
- package/package.json +16 -15
- package/dist/session/channel-reply-processor.d.ts.map +0 -1
- package/dist/session/channel-reply-processor.js +0 -46
- package/dist/session/channel-reply-processor.js.map +0 -1
- package/dist/session/channel-session-link-processor.d.ts.map +0 -1
- package/dist/session/channel-session-link-processor.js.map +0 -1
- /package/dist/{session → integrations/slack}/channel-session-link-processor.d.ts +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"secret-encryption.d.ts","sourceRoot":"","sources":["../src/secret-encryption.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"secret-encryption.d.ts","sourceRoot":"","sources":["../src/secret-encryption.ts"],"names":[],"mappings":"AAcA,MAAM,WAAW,sBAAsB,CAAC,CAAC;IACvC,KAAK,EAAE,CAAC,CAAC;IACT,iBAAiB,EAAE,OAAO,CAAC;CAC5B;AAED,kFAAkF;AAClF,MAAM,WAAW,uBAAuB;IACtC,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACtC,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAAC,CAAC,CAAC,CAAC;CAChE;AAED,MAAM,WAAW,0BAA0B;IACzC,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,EAAE,UAAU,CAAC;CACjB;AAED,MAAM,WAAW,6BAA6B;IAC5C,OAAO,EAAE,0BAA0B,CAAC;IACpC,QAAQ,CAAC,EAAE,0BAA0B,EAAE,CAAC;CACzC;AAgCD;;;GAGG;AACH,wBAAgB,6BAA6B,CAAC,MAAM,EAAE,6BAA6B,GAAG,uBAAuB,CA+E5G;AAED,+EAA+E;AAC/E,wBAAgB,sCAAsC,IAAI,uBAAuB,CA+BhF"}
|
|
@@ -3,6 +3,7 @@ import { createCipheriv, createDecipheriv } from "crypto";
|
|
|
3
3
|
const ENVELOPE_PREFIX = "mastra:factory-secret:v1:";
|
|
4
4
|
const ALGORITHM = "aes-256-gcm";
|
|
5
5
|
const IV_BYTES = 12;
|
|
6
|
+
const MAX_NESTED_ENVELOPES = 4;
|
|
6
7
|
function validateKey({ id, key }) {
|
|
7
8
|
if (!id) throw new Error("[FactorySecretEncryption] Key id is required.");
|
|
8
9
|
const buffer = Buffer.from(key);
|
|
@@ -43,38 +44,66 @@ function createFactorySecretEncryption(config) {
|
|
|
43
44
|
};
|
|
44
45
|
return `${ENVELOPE_PREFIX}${Buffer.from(JSON.stringify(envelope), "utf8").toString("base64url")}`;
|
|
45
46
|
},
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
47
|
+
decrypt
|
|
48
|
+
};
|
|
49
|
+
async function decrypt(value, depth = 0) {
|
|
50
|
+
if (typeof value !== "string") return {
|
|
51
|
+
value: structuredClone(value),
|
|
52
|
+
needsReencryption: true
|
|
53
|
+
};
|
|
54
|
+
if (!value.startsWith(ENVELOPE_PREFIX)) {
|
|
55
|
+
let parsed;
|
|
56
|
+
try {
|
|
57
|
+
parsed = JSON.parse(value);
|
|
56
58
|
} catch {
|
|
57
59
|
return {
|
|
58
60
|
value,
|
|
59
61
|
needsReencryption: true
|
|
60
62
|
};
|
|
61
63
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(envelope.iv, "base64url"));
|
|
67
|
-
decipher.setAuthTag(Buffer.from(envelope.tag, "base64url"));
|
|
68
|
-
const plaintext = Buffer.concat([decipher.update(Buffer.from(envelope.ciphertext, "base64url")), decipher.final()]).toString("utf8");
|
|
69
|
-
return {
|
|
70
|
-
value: JSON.parse(plaintext),
|
|
71
|
-
needsReencryption: envelope.keyId !== config.primary.id
|
|
72
|
-
};
|
|
73
|
-
} catch {
|
|
74
|
-
throw new Error("[FactorySecretEncryption] Unable to decrypt encrypted value.");
|
|
75
|
-
}
|
|
64
|
+
return {
|
|
65
|
+
value: await unwrapNestedEnvelope(parsed, depth) ?? parsed,
|
|
66
|
+
needsReencryption: true
|
|
67
|
+
};
|
|
76
68
|
}
|
|
77
|
-
|
|
69
|
+
const envelope = parseEnvelope(value);
|
|
70
|
+
const key = keys.get(envelope.keyId);
|
|
71
|
+
if (!key) throw new Error(`[FactorySecretEncryption] Unknown key id "${envelope.keyId}".`);
|
|
72
|
+
let decoded;
|
|
73
|
+
try {
|
|
74
|
+
const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(envelope.iv, "base64url"));
|
|
75
|
+
decipher.setAuthTag(Buffer.from(envelope.tag, "base64url"));
|
|
76
|
+
const plaintext = Buffer.concat([decipher.update(Buffer.from(envelope.ciphertext, "base64url")), decipher.final()]).toString("utf8");
|
|
77
|
+
decoded = JSON.parse(plaintext);
|
|
78
|
+
} catch {
|
|
79
|
+
throw new Error("[FactorySecretEncryption] Unable to decrypt encrypted value.");
|
|
80
|
+
}
|
|
81
|
+
const nested = await unwrapNestedEnvelope(decoded, depth);
|
|
82
|
+
if (nested !== void 0) return {
|
|
83
|
+
value: nested,
|
|
84
|
+
needsReencryption: true
|
|
85
|
+
};
|
|
86
|
+
return {
|
|
87
|
+
value: decoded,
|
|
88
|
+
needsReencryption: envelope.keyId !== config.primary.id
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Older plaintext encryptors treated an envelope as a raw legacy secret and
|
|
93
|
+
* rewrote it as JSON text, which a keyed boot then re-encrypted. Peel those
|
|
94
|
+
* layers back to the real value so the row is repaired on the next write.
|
|
95
|
+
* A user-supplied secret can also look like an envelope, so anything that
|
|
96
|
+
* does not decrypt with our keys is kept as the literal value.
|
|
97
|
+
*/
|
|
98
|
+
async function unwrapNestedEnvelope(value, depth) {
|
|
99
|
+
if (typeof value !== "string" || !value.startsWith(ENVELOPE_PREFIX)) return void 0;
|
|
100
|
+
if (depth >= MAX_NESTED_ENVELOPES) return void 0;
|
|
101
|
+
try {
|
|
102
|
+
return (await decrypt(value, depth + 1)).value;
|
|
103
|
+
} catch {
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
78
107
|
}
|
|
79
108
|
/** Explicit plaintext compatibility for local, no-auth Factory development. */
|
|
80
109
|
function createPlaintextFactorySecretEncryption() {
|
|
@@ -87,6 +116,17 @@ function createPlaintextFactorySecretEncryption() {
|
|
|
87
116
|
value: structuredClone(value),
|
|
88
117
|
needsReencryption: false
|
|
89
118
|
};
|
|
119
|
+
if (value.startsWith(ENVELOPE_PREFIX)) {
|
|
120
|
+
try {
|
|
121
|
+
parseEnvelope(value);
|
|
122
|
+
} catch {
|
|
123
|
+
return {
|
|
124
|
+
value,
|
|
125
|
+
needsReencryption: true
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
throw new Error("[FactorySecretEncryption] Value is encrypted, but this instance has no secret encryption key configured. Configure 'secretEncryption' with the same key on every Factory instance.");
|
|
129
|
+
}
|
|
90
130
|
try {
|
|
91
131
|
return {
|
|
92
132
|
value: JSON.parse(value),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"secret-encryption.js","names":[],"sources":["../src/secret-encryption.ts"],"sourcesContent":["import { createCipheriv, createDecipheriv } from 'node:crypto';\n\nconst ENVELOPE_PREFIX = 'mastra:factory-secret:v1:';\nconst ALGORITHM = 'aes-256-gcm';\nconst IV_BYTES = 12;\n\ninterface SecretEnvelopeV1 {\n keyId: string;\n iv: string;\n ciphertext: string;\n tag: string;\n}\n\nexport interface DecryptedFactorySecret<T> {\n value: T;\n needsReencryption: boolean;\n}\n\n/** Encrypts opaque JSON values before they cross the Factory storage boundary. */\nexport interface FactorySecretEncryption {\n encrypt<T>(value: T): Promise<string>;\n decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>>;\n}\n\nexport interface FactorySecretEncryptionKey {\n id: string;\n key: Uint8Array;\n}\n\nexport interface FactorySecretEncryptionConfig {\n primary: FactorySecretEncryptionKey;\n previous?: FactorySecretEncryptionKey[];\n}\n\nfunction validateKey({ id, key }: FactorySecretEncryptionKey): Buffer {\n if (!id) throw new Error('[FactorySecretEncryption] Key id is required.');\n const buffer = Buffer.from(key);\n if (buffer.byteLength !== 32) {\n throw new Error(`[FactorySecretEncryption] Key \"${id}\" must be exactly 32 bytes.`);\n }\n return buffer;\n}\n\nfunction parseEnvelope(value: string): SecretEnvelopeV1 {\n let parsed: unknown;\n try {\n parsed = JSON.parse(Buffer.from(value.slice(ENVELOPE_PREFIX.length), 'base64url').toString('utf8'));\n } catch {\n throw new Error('[FactorySecretEncryption] Invalid encrypted value.');\n }\n\n if (\n !parsed ||\n typeof parsed !== 'object' ||\n typeof (parsed as SecretEnvelopeV1).keyId !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).iv !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).ciphertext !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).tag !== 'string'\n ) {\n throw new Error('[FactorySecretEncryption] Invalid encrypted value.');\n }\n return parsed as SecretEnvelopeV1;\n}\n\n/**\n * Creates a versioned AES-256-GCM encryptor. The primary key is used for new\n * writes; previous keys remain decrypt-only until stored values are rotated.\n */\nexport function createFactorySecretEncryption(config: FactorySecretEncryptionConfig): FactorySecretEncryption {\n const primaryKey = validateKey(config.primary);\n const keys = new Map<string, Buffer>([[config.primary.id, primaryKey]]);\n for (const previous of config.previous ?? []) {\n if (keys.has(previous.id)) throw new Error(`[FactorySecretEncryption] Duplicate key id \"${previous.id}\".`);\n keys.set(previous.id, validateKey(previous));\n }\n\n return {\n async encrypt<T>(value: T): Promise<string> {\n const iv = Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(IV_BYTES)));\n const cipher = createCipheriv(ALGORITHM, primaryKey, iv);\n const ciphertext = Buffer.concat([cipher.update(JSON.stringify(value), 'utf8'), cipher.final()]);\n const envelope: SecretEnvelopeV1 = {\n keyId: config.primary.id,\n iv: iv.toString('base64url'),\n ciphertext: ciphertext.toString('base64url'),\n tag: cipher.getAuthTag().toString('base64url'),\n };\n return `${ENVELOPE_PREFIX}${Buffer.from(JSON.stringify(envelope), 'utf8').toString('base64url')}`;\n },\n\n async decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>> {\n if (typeof value !== 'string') {\n return { value: structuredClone(value) as T, needsReencryption: true };\n }\n if (!value.startsWith(ENVELOPE_PREFIX)) {\n // JSON text written by the plaintext encryptor, or a raw pre-encryption\n // secret string. Decode it the same way the plaintext encryptor does so\n // migration encrypts the original value, not its JSON text.\n try {\n return { value: JSON.parse(value) as T, needsReencryption: true };\n } catch {\n return { value: value as T, needsReencryption: true };\n }\n }\n\n const envelope = parseEnvelope(value);\n const key = keys.get(envelope.keyId);\n if (!key) throw new Error(`[FactorySecretEncryption] Unknown key id \"${envelope.keyId}\".`);\n\n try {\n const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(envelope.iv, 'base64url'));\n decipher.setAuthTag(Buffer.from(envelope.tag, 'base64url'));\n const plaintext = Buffer.concat([\n decipher.update(Buffer.from(envelope.ciphertext, 'base64url')),\n decipher.final(),\n ]).toString('utf8');\n return {\n value: JSON.parse(plaintext) as T,\n needsReencryption: envelope.keyId !== config.primary.id,\n };\n } catch {\n throw new Error('[FactorySecretEncryption] Unable to decrypt encrypted value.');\n }\n },\n };\n}\n\n/** Explicit plaintext compatibility for local, no-auth Factory development. */\nexport function createPlaintextFactorySecretEncryption(): FactorySecretEncryption {\n return {\n async encrypt<T>(value: T): Promise<string> {\n return JSON.stringify(value);\n },\n async decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>> {\n if (typeof value !== 'string') return { value: structuredClone(value) as T, needsReencryption: false };\n try {\n return { value: JSON.parse(value) as T, needsReencryption: false };\n } catch {\n // Pre-encryption rows stored raw secret strings (e.g. a bare\n // `custom_providers.api_key`), not JSON. Treat the raw string as the\n // value and flag it so migration rewrites it in the current format.\n return { value: value as T, needsReencryption: true };\n }\n },\n };\n}\n"],"mappings":";;AAEA,MAAM,kBAAkB;AACxB,MAAM,YAAY;AAClB,MAAM,WAAW;AA8BjB,SAAS,YAAY,EAAE,IAAI,OAA2C;CACpE,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C;CACxE,MAAM,SAAS,OAAO,KAAK,GAAG;CAC9B,IAAI,OAAO,eAAe,IACxB,MAAM,IAAI,MAAM,kCAAkC,GAAG,4BAA4B;CAEnF,OAAO;AACT;AAEA,SAAS,cAAc,OAAiC;CACtD,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,OAAO,KAAK,MAAM,MAAM,EAAsB,GAAG,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC;CACpG,QAAQ;EACN,MAAM,IAAI,MAAM,oDAAoD;CACtE;CAEA,IACE,CAAC,UACD,OAAO,WAAW,YAClB,OAAQ,OAA4B,UAAU,YAC9C,OAAQ,OAA4B,OAAO,YAC3C,OAAQ,OAA4B,eAAe,YACnD,OAAQ,OAA4B,QAAQ,UAE5C,MAAM,IAAI,MAAM,oDAAoD;CAEtE,OAAO;AACT;;;;;AAMA,SAAgB,8BAA8B,QAAgE;CAC5G,MAAM,aAAa,YAAY,OAAO,OAAO;CAC7C,MAAM,uBAAO,IAAI,IAAoB,CAAC,CAAC,OAAO,QAAQ,IAAI,UAAU,CAAC,CAAC;CACtE,KAAK,MAAM,YAAY,OAAO,YAAY,CAAC,GAAG;EAC5C,IAAI,KAAK,IAAI,SAAS,EAAE,GAAG,MAAM,IAAI,MAAM,+CAA+C,SAAS,GAAG,GAAG;EACzG,KAAK,IAAI,SAAS,IAAI,YAAY,QAAQ,CAAC;CAC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AAM;IAClB,OAAO;KACL,OAAO,KAAK,MAAM,SAAS;KAC3B,mBAAmB,SAAS,UAAU,OAAO,QAAQ;IACvD;GACF,QAAQ;IACN,MAAM,IAAI,MAAM,8DAA8D;GAChF;EACF;CACF;AACF;;AAGA,SAAgB,yCAAkE;CAChF,OAAO;EACL,MAAM,QAAW,OAA2B;GAC1C,OAAO,KAAK,UAAU,KAAK;EAC7B;EACA,MAAM,QAAW,OAAoD;GACnE,IAAI,OAAO,UAAU,UAAU,OAAO;IAAE,OAAO,gBAAgB,KAAK;IAAQ,mBAAmB;GAAM;GACrG,IAAI;IACF,OAAO;KAAE,OAAO,KAAK,MAAM,KAAK;KAAQ,mBAAmB;IAAM;GACnE,QAAQ;IAIN,OAAO;KAAS;KAAY,mBAAmB;IAAK;GACtD;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"secret-encryption.js","names":[],"sources":["../src/secret-encryption.ts"],"sourcesContent":["import { createCipheriv, createDecipheriv } from 'node:crypto';\n\nconst ENVELOPE_PREFIX = 'mastra:factory-secret:v1:';\nconst ALGORITHM = 'aes-256-gcm';\nconst IV_BYTES = 12;\nconst MAX_NESTED_ENVELOPES = 4;\n\ninterface SecretEnvelopeV1 {\n keyId: string;\n iv: string;\n ciphertext: string;\n tag: string;\n}\n\nexport interface DecryptedFactorySecret<T> {\n value: T;\n needsReencryption: boolean;\n}\n\n/** Encrypts opaque JSON values before they cross the Factory storage boundary. */\nexport interface FactorySecretEncryption {\n encrypt<T>(value: T): Promise<string>;\n decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>>;\n}\n\nexport interface FactorySecretEncryptionKey {\n id: string;\n key: Uint8Array;\n}\n\nexport interface FactorySecretEncryptionConfig {\n primary: FactorySecretEncryptionKey;\n previous?: FactorySecretEncryptionKey[];\n}\n\nfunction validateKey({ id, key }: FactorySecretEncryptionKey): Buffer {\n if (!id) throw new Error('[FactorySecretEncryption] Key id is required.');\n const buffer = Buffer.from(key);\n if (buffer.byteLength !== 32) {\n throw new Error(`[FactorySecretEncryption] Key \"${id}\" must be exactly 32 bytes.`);\n }\n return buffer;\n}\n\nfunction parseEnvelope(value: string): SecretEnvelopeV1 {\n let parsed: unknown;\n try {\n parsed = JSON.parse(Buffer.from(value.slice(ENVELOPE_PREFIX.length), 'base64url').toString('utf8'));\n } catch {\n throw new Error('[FactorySecretEncryption] Invalid encrypted value.');\n }\n\n if (\n !parsed ||\n typeof parsed !== 'object' ||\n typeof (parsed as SecretEnvelopeV1).keyId !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).iv !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).ciphertext !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).tag !== 'string'\n ) {\n throw new Error('[FactorySecretEncryption] Invalid encrypted value.');\n }\n return parsed as SecretEnvelopeV1;\n}\n\n/**\n * Creates a versioned AES-256-GCM encryptor. The primary key is used for new\n * writes; previous keys remain decrypt-only until stored values are rotated.\n */\nexport function createFactorySecretEncryption(config: FactorySecretEncryptionConfig): FactorySecretEncryption {\n const primaryKey = validateKey(config.primary);\n const keys = new Map<string, Buffer>([[config.primary.id, primaryKey]]);\n for (const previous of config.previous ?? []) {\n if (keys.has(previous.id)) throw new Error(`[FactorySecretEncryption] Duplicate key id \"${previous.id}\".`);\n keys.set(previous.id, validateKey(previous));\n }\n\n return {\n async encrypt<T>(value: T): Promise<string> {\n const iv = Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(IV_BYTES)));\n const cipher = createCipheriv(ALGORITHM, primaryKey, iv);\n const ciphertext = Buffer.concat([cipher.update(JSON.stringify(value), 'utf8'), cipher.final()]);\n const envelope: SecretEnvelopeV1 = {\n keyId: config.primary.id,\n iv: iv.toString('base64url'),\n ciphertext: ciphertext.toString('base64url'),\n tag: cipher.getAuthTag().toString('base64url'),\n };\n return `${ENVELOPE_PREFIX}${Buffer.from(JSON.stringify(envelope), 'utf8').toString('base64url')}`;\n },\n\n decrypt,\n };\n\n async function decrypt<T>(value: unknown, depth = 0): Promise<DecryptedFactorySecret<T>> {\n if (typeof value !== 'string') {\n return { value: structuredClone(value) as T, needsReencryption: true };\n }\n if (!value.startsWith(ENVELOPE_PREFIX)) {\n // JSON text written by the plaintext encryptor, or a raw pre-encryption\n // secret string. Decode it the same way the plaintext encryptor does so\n // migration encrypts the original value, not its JSON text.\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n return { value: value as T, needsReencryption: true };\n }\n return { value: (await unwrapNestedEnvelope<T>(parsed, depth)) ?? (parsed as T), needsReencryption: true };\n }\n\n const envelope = parseEnvelope(value);\n const key = keys.get(envelope.keyId);\n if (!key) throw new Error(`[FactorySecretEncryption] Unknown key id \"${envelope.keyId}\".`);\n\n let decoded: unknown;\n try {\n const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(envelope.iv, 'base64url'));\n decipher.setAuthTag(Buffer.from(envelope.tag, 'base64url'));\n const plaintext = Buffer.concat([\n decipher.update(Buffer.from(envelope.ciphertext, 'base64url')),\n decipher.final(),\n ]).toString('utf8');\n decoded = JSON.parse(plaintext);\n } catch {\n throw new Error('[FactorySecretEncryption] Unable to decrypt encrypted value.');\n }\n const nested = await unwrapNestedEnvelope<T>(decoded, depth);\n if (nested !== undefined) return { value: nested, needsReencryption: true };\n return { value: decoded as T, needsReencryption: envelope.keyId !== config.primary.id };\n }\n\n /**\n * Older plaintext encryptors treated an envelope as a raw legacy secret and\n * rewrote it as JSON text, which a keyed boot then re-encrypted. Peel those\n * layers back to the real value so the row is repaired on the next write.\n * A user-supplied secret can also look like an envelope, so anything that\n * does not decrypt with our keys is kept as the literal value.\n */\n async function unwrapNestedEnvelope<T>(value: unknown, depth: number): Promise<T | undefined> {\n if (typeof value !== 'string' || !value.startsWith(ENVELOPE_PREFIX)) return undefined;\n if (depth >= MAX_NESTED_ENVELOPES) return undefined;\n try {\n return (await decrypt<T>(value, depth + 1)).value;\n } catch {\n return undefined;\n }\n }\n}\n\n/** Explicit plaintext compatibility for local, no-auth Factory development. */\nexport function createPlaintextFactorySecretEncryption(): FactorySecretEncryption {\n return {\n async encrypt<T>(value: T): Promise<string> {\n return JSON.stringify(value);\n },\n async decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>> {\n if (typeof value !== 'string') return { value: structuredClone(value) as T, needsReencryption: false };\n if (value.startsWith(ENVELOPE_PREFIX)) {\n // Never hand an envelope back as the secret, and never let migration\n // rewrite it as plaintext JSON: that corrupts the row for keyed instances.\n // A raw legacy secret can merely start with the prefix; keep those as-is.\n try {\n parseEnvelope(value);\n } catch {\n return { value: value as T, needsReencryption: true };\n }\n throw new Error(\n '[FactorySecretEncryption] Value is encrypted, but this instance has no secret encryption key configured. ' +\n \"Configure 'secretEncryption' with the same key on every Factory instance.\",\n );\n }\n try {\n return { value: JSON.parse(value) as T, needsReencryption: false };\n } catch {\n // Pre-encryption rows stored raw secret strings (e.g. a bare\n // `custom_providers.api_key`), not JSON. Treat the raw string as the\n // value and flag it so migration rewrites it in the current format.\n return { value: value as T, needsReencryption: true };\n }\n },\n };\n}\n"],"mappings":";;AAEA,MAAM,kBAAkB;AACxB,MAAM,YAAY;AAClB,MAAM,WAAW;AACjB,MAAM,uBAAuB;AA8B7B,SAAS,YAAY,EAAE,IAAI,OAA2C;CACpE,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C;CACxE,MAAM,SAAS,OAAO,KAAK,GAAG;CAC9B,IAAI,OAAO,eAAe,IACxB,MAAM,IAAI,MAAM,kCAAkC,GAAG,4BAA4B;CAEnF,OAAO;AACT;AAEA,SAAS,cAAc,OAAiC;CACtD,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,OAAO,KAAK,MAAM,MAAM,EAAsB,GAAG,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC;CACpG,QAAQ;EACN,MAAM,IAAI,MAAM,oDAAoD;CACtE;CAEA,IACE,CAAC,UACD,OAAO,WAAW,YAClB,OAAQ,OAA4B,UAAU,YAC9C,OAAQ,OAA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AI,OAAO,UAAU,UAAU,OAAO;IAAE,OAAO,gBAAgB,KAAK;IAAQ,mBAAmB;GAAM;GACrG,IAAI,MAAM,WAAW,eAAe,GAAG;IAIrC,IAAI;KACF,cAAc,KAAK;IACrB,QAAQ;KACN,OAAO;MAAS;MAAY,mBAAmB;KAAK;IACtD;IACA,MAAM,IAAI,MACR,oLAEF;GACF;GACA,IAAI;IACF,OAAO;KAAE,OAAO,KAAK,MAAM,KAAK;KAAQ,mBAAmB;IAAM;GACnE,QAAQ;IAIN,OAAO;KAAS;KAAY,mBAAmB;IAAK;GACtD;EACF;CACF;AACF"}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import type { CredentialTenant } from '@mastra/code-sdk/agents/credential-resolver';
|
|
2
2
|
import type { RequestContext } from '@mastra/core/request-context';
|
|
3
|
+
import type { ModelDefaultRecord, ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';
|
|
3
4
|
import type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';
|
|
4
5
|
import type { WorkItemsStorage } from '../storage/domains/work-items/base.js';
|
|
5
6
|
import type { SourceControlSessionLookup } from './factory-session.js';
|
|
6
|
-
interface FactoryModelPolicyDependencies {
|
|
7
|
+
export interface FactoryModelPolicyDependencies {
|
|
7
8
|
projects: Pick<FactoryProjectsStorage, 'getById'>;
|
|
8
9
|
sourceControl: Pick<SourceControlSessionLookup, 'getBySessionId'>;
|
|
9
10
|
workItems: Pick<WorkItemsStorage, 'findRunBindingByThread'>;
|
|
@@ -16,5 +17,6 @@ export declare function resolveFactoryModelPolicy(requestContext: RequestContext
|
|
|
16
17
|
factoryProjectId?: string;
|
|
17
18
|
factoryDefaultModelId?: string | null;
|
|
18
19
|
} | undefined>;
|
|
19
|
-
|
|
20
|
+
/** The personal defaults a policy's tenant runs on; none on Factory routing. */
|
|
21
|
+
export declare function routedPersonalDefaults(tenant: CredentialTenant, modelDefaults: Pick<ModelDefaultsStorage, 'ensureReady' | 'get'>): Promise<ModelDefaultRecord | null>;
|
|
20
22
|
//# sourceMappingURL=credential-policy.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credential-policy.d.ts","sourceRoot":"","sources":["../../src/session/credential-policy.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6CAA6C,CAAC;AAEpF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAInE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAC9E,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAIvE,
|
|
1
|
+
{"version":3,"file":"credential-policy.d.ts","sourceRoot":"","sources":["../../src/session/credential-policy.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6CAA6C,CAAC;AAEpF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAInE,OAAO,KAAK,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAE1G,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAC9E,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAIvE,MAAM,WAAW,8BAA8B;IAC7C,QAAQ,EAAE,IAAI,CAAC,sBAAsB,EAAE,SAAS,CAAC,CAAC;IAClD,aAAa,EAAE,IAAI,CAAC,0BAA0B,EAAE,gBAAgB,CAAC,CAAC;IAClE,SAAS,EAAE,IAAI,CAAC,gBAAgB,EAAE,wBAAwB,CAAC,CAAC;CAC7D;AAED,uGAAuG;AACvG,wBAAsB,8BAA8B,CAClD,cAAc,EAAE,cAAc,EAC9B,IAAI,EAAE,8BAA8B,GACnC,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAEvC;AAED,+FAA+F;AAC/F,wBAAsB,yBAAyB,CAC7C,cAAc,EAAE,cAAc,EAC9B,IAAI,EAAE,8BAA8B,GACnC,OAAO,CAAC;IAAE,MAAM,EAAE,gBAAgB,CAAC;IAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAAC,qBAAqB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,GAAG,SAAS,CAAC,CAwDrH;AAED,gFAAgF;AAChF,wBAAsB,sBAAsB,CAC1C,MAAM,EAAE,gBAAgB,EACxB,aAAa,EAAE,IAAI,CAAC,oBAAoB,EAAE,aAAa,GAAG,KAAK,CAAC,GAC/D,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAIpC"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { tenantOrgId } from "../routes/provider-credentials.js";
|
|
1
2
|
import { effectiveModelScope } from "../storage/domains/projects/base.js";
|
|
2
3
|
import { UUID_PATTERN } from "../routes/contracts.js";
|
|
3
4
|
import { resolveAuthenticatedCredentialTenant } from "@mastra/code-sdk/agents/credential-resolver";
|
|
@@ -12,18 +13,19 @@ async function resolveFactoryModelPolicy(requestContext, deps) {
|
|
|
12
13
|
const principal = resolveAuthenticatedCredentialTenant(requestContext);
|
|
13
14
|
if (!principal) return void 0;
|
|
14
15
|
const controller = requestContext.get("controller");
|
|
15
|
-
if (!controller?.resourceId) return { tenant: principal };
|
|
16
|
-
const
|
|
16
|
+
if (!controller?.sessionId || !controller.resourceId) return { tenant: principal };
|
|
17
|
+
const { sessionId, resourceId } = controller;
|
|
18
|
+
const sourceSession = await deps.sourceControl.getBySessionId(sessionId);
|
|
17
19
|
const binding = principal.orgId && controller.threadId ? await deps.workItems.findRunBindingByThread({
|
|
18
20
|
orgId: principal.orgId,
|
|
19
|
-
resourceId
|
|
20
|
-
sessionId
|
|
21
|
+
resourceId,
|
|
22
|
+
sessionId,
|
|
21
23
|
threadId: controller.threadId,
|
|
22
24
|
rejectAmbiguous: true
|
|
23
25
|
}) : null;
|
|
24
26
|
if (!sourceSession) {
|
|
25
|
-
if (!binding && (
|
|
26
|
-
const factoryProject = !binding && FACTORY_PROJECT_ID.test(
|
|
27
|
+
if (!binding && (resourceId === principal.userId || resourceId.startsWith("channel:"))) return { tenant: principal };
|
|
28
|
+
const factoryProject = !binding && sessionId === resourceId && FACTORY_PROJECT_ID.test(resourceId) ? await deps.projects.getById({ id: resourceId }) : null;
|
|
27
29
|
if (factoryProject && factoryProject.orgId === principal.orgId) return {
|
|
28
30
|
factoryProjectId: factoryProject.id,
|
|
29
31
|
factoryDefaultModelId: factoryProject.defaultModelId,
|
|
@@ -49,7 +51,16 @@ async function resolveFactoryModelPolicy(requestContext, deps) {
|
|
|
49
51
|
}
|
|
50
52
|
};
|
|
51
53
|
}
|
|
54
|
+
/** The personal defaults a policy's tenant runs on; none on Factory routing. */
|
|
55
|
+
async function routedPersonalDefaults(tenant, modelDefaults) {
|
|
56
|
+
if (tenant.credentialScope === "factory") return null;
|
|
57
|
+
await modelDefaults.ensureReady();
|
|
58
|
+
return modelDefaults.get({
|
|
59
|
+
orgId: tenantOrgId(tenant),
|
|
60
|
+
userId: tenant.userId
|
|
61
|
+
});
|
|
62
|
+
}
|
|
52
63
|
//#endregion
|
|
53
|
-
export { resolveFactoryCredentialTenant, resolveFactoryModelPolicy };
|
|
64
|
+
export { resolveFactoryCredentialTenant, resolveFactoryModelPolicy, routedPersonalDefaults };
|
|
54
65
|
|
|
55
66
|
//# sourceMappingURL=credential-policy.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credential-policy.js","names":[],"sources":["../../src/session/credential-policy.ts"],"sourcesContent":["import { resolveAuthenticatedCredentialTenant } from '@mastra/code-sdk/agents/credential-resolver';\nimport type { CredentialTenant } from '@mastra/code-sdk/agents/credential-resolver';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nimport { UUID_PATTERN } from '../routes/contracts.js';\nimport { effectiveModelScope } from '../storage/domains/projects/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { SourceControlSessionLookup } from './factory-session.js';\n\nconst FACTORY_PROJECT_ID = new RegExp(UUID_PATTERN);\n\
|
|
1
|
+
{"version":3,"file":"credential-policy.js","names":[],"sources":["../../src/session/credential-policy.ts"],"sourcesContent":["import { resolveAuthenticatedCredentialTenant } from '@mastra/code-sdk/agents/credential-resolver';\nimport type { CredentialTenant } from '@mastra/code-sdk/agents/credential-resolver';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nimport { UUID_PATTERN } from '../routes/contracts.js';\nimport { tenantOrgId } from '../routes/provider-credentials.js';\nimport type { ModelDefaultRecord, ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { effectiveModelScope } from '../storage/domains/projects/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { SourceControlSessionLookup } from './factory-session.js';\n\nconst FACTORY_PROJECT_ID = new RegExp(UUID_PATTERN);\n\nexport interface FactoryModelPolicyDependencies {\n projects: Pick<FactoryProjectsStorage, 'getById'>;\n sourceControl: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n workItems: Pick<WorkItemsStorage, 'findRunBindingByThread'>;\n}\n\n/** Resolve billing authority from authenticated identity and durable bindings, never session state. */\nexport async function resolveFactoryCredentialTenant(\n requestContext: RequestContext,\n deps: FactoryModelPolicyDependencies,\n): Promise<CredentialTenant | undefined> {\n return (await resolveFactoryModelPolicy(requestContext, deps))?.tenant;\n}\n\n/** Shared invocation and model-picker policy; no client-supplied owner or scope is trusted. */\nexport async function resolveFactoryModelPolicy(\n requestContext: RequestContext,\n deps: FactoryModelPolicyDependencies,\n): Promise<{ tenant: CredentialTenant; factoryProjectId?: string; factoryDefaultModelId?: string | null } | undefined> {\n const principal = resolveAuthenticatedCredentialTenant(requestContext);\n if (!principal) return undefined;\n const controller = requestContext.get('controller') as AgentControllerRequestContext | undefined;\n if (!controller?.sessionId || !controller.resourceId) return { tenant: principal };\n const { sessionId, resourceId } = controller;\n\n const sourceSession = await deps.sourceControl.getBySessionId(sessionId);\n const binding =\n principal.orgId && controller.threadId\n ? await deps.workItems.findRunBindingByThread({\n orgId: principal.orgId,\n resourceId,\n sessionId,\n threadId: controller.threadId,\n rejectAmbiguous: true,\n })\n : null;\n if (!sourceSession) {\n if (!binding && (resourceId === principal.userId || resourceId.startsWith('channel:')))\n return { tenant: principal };\n // Session-less Factory pages address the Factory itself: session and resource are both the\n // project id. A run session under its Factory's resource whose row is gone is not a page.\n const factoryProject =\n !binding && sessionId === resourceId && FACTORY_PROJECT_ID.test(resourceId)\n ? await deps.projects.getById({ id: resourceId })\n : null;\n if (factoryProject && factoryProject.orgId === principal.orgId) {\n return {\n factoryProjectId: factoryProject.id,\n factoryDefaultModelId: factoryProject.defaultModelId,\n tenant: { ...principal, credentialScope: effectiveModelScope(factoryProject.modelScope, 'session') },\n };\n }\n throw new Error('Factory session ownership is unavailable.');\n }\n if (\n sourceSession.orgId !== principal.orgId ||\n (sourceSession.visibility === 'private' && sourceSession.userId !== principal.userId)\n ) {\n throw new Error('Factory session is not available to the current user.');\n }\n if (!sourceSession.factoryProjectId) throw new Error('Factory session ownership is unavailable.');\n const projectId = binding?.factoryProjectId ?? sourceSession.factoryProjectId;\n const project = await deps.projects.getById({ id: projectId });\n if (!project || project.orgId !== sourceSession.orgId) throw new Error('Factory model policy is unavailable.');\n // Work-item threads keep their billing scope after revocation; history never restores run authority.\n return {\n factoryProjectId: project.id,\n factoryDefaultModelId: project.defaultModelId,\n tenant: {\n orgId: project.orgId,\n userId: sourceSession.userId,\n credentialScope: effectiveModelScope(project.modelScope, binding ? 'run' : 'session'),\n },\n };\n}\n\n/** The personal defaults a policy's tenant runs on; none on Factory routing. */\nexport async function routedPersonalDefaults(\n tenant: CredentialTenant,\n modelDefaults: Pick<ModelDefaultsStorage, 'ensureReady' | 'get'>,\n): Promise<ModelDefaultRecord | null> {\n if (tenant.credentialScope === 'factory') return null;\n await modelDefaults.ensureReady();\n return modelDefaults.get({ orgId: tenantOrgId(tenant), userId: tenant.userId });\n}\n"],"mappings":";;;;;AAaA,MAAM,qBAAqB,IAAI,OAAO,YAAY;;AASlD,eAAsB,+BACpB,gBACA,MACuC;CACvC,QAAQ,MAAM,0BAA0B,gBAAgB,IAAI,EAAA,EAAI;AAClE;;AAGA,eAAsB,0BACpB,gBACA,MACqH;CACrH,MAAM,YAAY,qCAAqC,cAAc;CACrE,IAAI,CAAC,WAAW,OAAO,KAAA;CACvB,MAAM,aAAa,eAAe,IAAI,YAAY;CAClD,IAAI,CAAC,YAAY,aAAa,CAAC,WAAW,YAAY,OAAO,EAAE,QAAQ,UAAU;CACjF,MAAM,EAAE,WAAW,eAAe;CAElC,MAAM,gBAAgB,MAAM,KAAK,cAAc,eAAe,SAAS;CACvE,MAAM,UACJ,UAAU,SAAS,WAAW,WAC1B,MAAM,KAAK,UAAU,uBAAuB;EAC1C,OAAO,UAAU;EACjB;EACA;EACA,UAAU,WAAW;EACrB,iBAAiB;CACnB,CAAC,IACD;CACN,IAAI,CAAC,eAAe;EAClB,IAAI,CAAC,YAAY,eAAe,UAAU,UAAU,WAAW,WAAW,UAAU,IAClF,OAAO,EAAE,QAAQ,UAAU;EAG7B,MAAM,iBACJ,CAAC,WAAW,cAAc,cAAc,mBAAmB,KAAK,UAAU,IACtE,MAAM,KAAK,SAAS,QAAQ,EAAE,IAAI,WAAW,CAAC,IAC9C;EACN,IAAI,kBAAkB,eAAe,UAAU,UAAU,OACvD,OAAO;GACL,kBAAkB,eAAe;GACjC,uBAAuB,eAAe;GACtC,QAAQ;IAAE,GAAG;IAAW,iBAAiB,oBAAoB,eAAe,YAAY,SAAS;GAAE;EACrG;EAEF,MAAM,IAAI,MAAM,2CAA2C;CAC7D;CACA,IACE,cAAc,UAAU,UAAU,SACjC,cAAc,eAAe,aAAa,cAAc,WAAW,UAAU,QAE9E,MAAM,IAAI,MAAM,uDAAuD;CAEzE,IAAI,CAAC,cAAc,kBAAkB,MAAM,IAAI,MAAM,2CAA2C;CAChG,MAAM,YAAY,SAAS,oBAAoB,cAAc;CAC7D,MAAM,UAAU,MAAM,KAAK,SAAS,QAAQ,EAAE,IAAI,UAAU,CAAC;CAC7D,IAAI,CAAC,WAAW,QAAQ,UAAU,cAAc,OAAO,MAAM,IAAI,MAAM,sCAAsC;CAE7G,OAAO;EACL,kBAAkB,QAAQ;EAC1B,uBAAuB,QAAQ;EAC/B,QAAQ;GACN,OAAO,QAAQ;GACf,QAAQ,cAAc;GACtB,iBAAiB,oBAAoB,QAAQ,YAAY,UAAU,QAAQ,SAAS;EACtF;CACF;AACF;;AAGA,eAAsB,uBACpB,QACA,eACoC;CACpC,IAAI,OAAO,oBAAoB,WAAW,OAAO;CACjD,MAAM,cAAc,YAAY;CAChC,OAAO,cAAc,IAAI;EAAE,OAAO,YAAY,MAAM;EAAG,QAAQ,OAAO;CAAO,CAAC;AAChF"}
|
|
@@ -17,6 +17,7 @@ export interface DefaultModelApplicableSession {
|
|
|
17
17
|
}
|
|
18
18
|
export interface DefaultModelHydrationSession extends DefaultModelApplicableSession {
|
|
19
19
|
readonly identity: {
|
|
20
|
+
getId(): string;
|
|
20
21
|
getResourceId(): string;
|
|
21
22
|
};
|
|
22
23
|
model: DefaultModelApplicableSession['model'] & {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"default-model-hydration.d.ts","sourceRoot":"","sources":["../../src/session/default-model-hydration.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAEtF,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CA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, modelId) {
|
|
|
14
14
|
}
|
|
15
15
|
/** Seed a new chat's scoped default model; a chat with a user message keeps its model. */
|
|
16
16
|
async function hydrateSessionDefaultModel(session, { sourceControl, projects, workItems, modelDefaults }) {
|
|
17
|
+
const sessionId = session.identity.getId();
|
|
17
18
|
const resourceId = session.identity.getResourceId();
|
|
18
19
|
const initialState = session.state.get() ?? {};
|
|
19
20
|
if (initialState.factoryProjectId || typeof session.thread.firstUserMessage !== "function") return;
|
|
@@ -29,7 +30,7 @@ async function hydrateSessionDefaultModel(session, { sourceControl, projects, wo
|
|
|
29
30
|
});
|
|
30
31
|
let identityResolved = false;
|
|
31
32
|
try {
|
|
32
|
-
const sourceSession = await sourceControl.getBySessionId(
|
|
33
|
+
const sourceSession = await sourceControl.getBySessionId(sessionId);
|
|
33
34
|
if (!sourceSession) {
|
|
34
35
|
await clearFactoryIdentity();
|
|
35
36
|
return;
|
|
@@ -43,7 +44,7 @@ async function hydrateSessionDefaultModel(session, { sourceControl, projects, wo
|
|
|
43
44
|
orgId: sourceSession.orgId,
|
|
44
45
|
threadId,
|
|
45
46
|
resourceId,
|
|
46
|
-
sessionId
|
|
47
|
+
sessionId,
|
|
47
48
|
rejectAmbiguous: true
|
|
48
49
|
}) : null;
|
|
49
50
|
const project = await projects.getById({ id: binding?.factoryProjectId ?? sourceSession.factoryProjectId });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"default-model-hydration.js","names":[],"sources":["../../src/session/default-model-hydration.ts"],"sourcesContent":["import { primeTenantCredentialsForTenant, resolveTenantProviderDefaultModel } from '../routes/tenant-credentials.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { effectiveModelScope } from '../storage/domains/projects/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { SourceControlSessionLookup } from './factory-session.js';\n\nexport interface DefaultModelApplicableSession {\n model: { switch(modelId: string): Promise<unknown> };\n subagents: { model: { set(args: { modelId: string; agentType: string }): Promise<unknown> } };\n}\n\nexport interface DefaultModelHydrationSession extends DefaultModelApplicableSession {\n readonly identity: { getResourceId(): string };\n model: DefaultModelApplicableSession['model'] & { get(): string; setDefault(args: { modelId: string }): void };\n state: {\n get(): Record<string, unknown> | undefined;\n set(updates: Record<string, unknown>): Promise<unknown>;\n };\n thread: {\n getId(): string | null | undefined;\n firstUserMessage(args: { threadId: string }): Promise<unknown>;\n };\n}\n\nasync function applyDefaultModel(session: DefaultModelApplicableSession, modelId: string): Promise<void> {\n await session.model.switch(modelId);\n\n for (const agentType of ['explore', 'plan', 'execute']) {\n await session.subagents.model.set({ modelId, agentType });\n }\n}\n\nexport interface DefaultModelHydrationDependencies {\n sourceControl: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n projects: Pick<FactoryProjectsStorage, 'getById'>;\n workItems: Pick<WorkItemsStorage, 'findRunBindingByThread'>;\n modelDefaults: Pick<ModelDefaultsStorage, 'get'>;\n}\n\n/** Seed a new chat's scoped default model; a chat with a user message keeps its model. */\nexport async function hydrateSessionDefaultModel(\n session: DefaultModelHydrationSession,\n { sourceControl, projects, workItems, modelDefaults }: DefaultModelHydrationDependencies,\n): Promise<void> {\n const resourceId = session.identity.getResourceId();\n const initialState = session.state.get() ?? {};\n if (initialState.factoryProjectId || typeof session.thread.firstUserMessage !== 'function') return;\n const hadFactoryIdentity = initialState.factoryModelScope === 'factory' || initialState.factoryModelScope === 'user';\n const clearFactoryIdentity = () =>\n session.state.set({ factoryOrgId: undefined, factoryModelScope: undefined, factoryOwnerUserId: undefined });\n const failClosedWithoutIdentity = () =>\n session.state.set({ factoryModelScope: 'user', factoryOwnerUserId: undefined });\n let identityResolved = false;\n try {\n const sourceSession = await sourceControl.getBySessionId(
|
|
1
|
+
{"version":3,"file":"default-model-hydration.js","names":[],"sources":["../../src/session/default-model-hydration.ts"],"sourcesContent":["import { primeTenantCredentialsForTenant, resolveTenantProviderDefaultModel } from '../routes/tenant-credentials.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { effectiveModelScope } from '../storage/domains/projects/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { SourceControlSessionLookup } from './factory-session.js';\n\nexport interface DefaultModelApplicableSession {\n model: { switch(modelId: string): Promise<unknown> };\n subagents: { model: { set(args: { modelId: string; agentType: string }): Promise<unknown> } };\n}\n\nexport interface DefaultModelHydrationSession extends DefaultModelApplicableSession {\n readonly identity: { getId(): string; getResourceId(): string };\n model: DefaultModelApplicableSession['model'] & { get(): string; setDefault(args: { modelId: string }): void };\n state: {\n get(): Record<string, unknown> | undefined;\n set(updates: Record<string, unknown>): Promise<unknown>;\n };\n thread: {\n getId(): string | null | undefined;\n firstUserMessage(args: { threadId: string }): Promise<unknown>;\n };\n}\n\nasync function applyDefaultModel(session: DefaultModelApplicableSession, modelId: string): Promise<void> {\n await session.model.switch(modelId);\n\n for (const agentType of ['explore', 'plan', 'execute']) {\n await session.subagents.model.set({ modelId, agentType });\n }\n}\n\nexport interface DefaultModelHydrationDependencies {\n sourceControl: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n projects: Pick<FactoryProjectsStorage, 'getById'>;\n workItems: Pick<WorkItemsStorage, 'findRunBindingByThread'>;\n modelDefaults: Pick<ModelDefaultsStorage, 'get'>;\n}\n\n/** Seed a new chat's scoped default model; a chat with a user message keeps its model. */\nexport async function hydrateSessionDefaultModel(\n session: DefaultModelHydrationSession,\n { sourceControl, projects, workItems, modelDefaults }: DefaultModelHydrationDependencies,\n): Promise<void> {\n const sessionId = session.identity.getId();\n const resourceId = session.identity.getResourceId();\n const initialState = session.state.get() ?? {};\n if (initialState.factoryProjectId || typeof session.thread.firstUserMessage !== 'function') return;\n const hadFactoryIdentity = initialState.factoryModelScope === 'factory' || initialState.factoryModelScope === 'user';\n const clearFactoryIdentity = () =>\n session.state.set({ factoryOrgId: undefined, factoryModelScope: undefined, factoryOwnerUserId: undefined });\n const failClosedWithoutIdentity = () =>\n session.state.set({ factoryModelScope: 'user', factoryOwnerUserId: undefined });\n let identityResolved = false;\n try {\n const sourceSession = await sourceControl.getBySessionId(sessionId);\n if (!sourceSession) {\n await clearFactoryIdentity();\n return;\n }\n if (!sourceSession.factoryProjectId) {\n await clearFactoryIdentity();\n return;\n }\n // Historical thread membership keeps completed work items on Factory billing in hybrid scope.\n const threadId = session.thread.getId();\n const binding = threadId\n ? await workItems.findRunBindingByThread({\n orgId: sourceSession.orgId,\n threadId,\n resourceId,\n sessionId,\n rejectAmbiguous: true,\n })\n : null;\n const project = await projects.getById({ id: binding?.factoryProjectId ?? sourceSession.factoryProjectId });\n if (!project || project.orgId !== sourceSession.orgId) {\n await clearFactoryIdentity();\n return;\n }\n const modelScope = effectiveModelScope(project.modelScope, binding ? 'run' : 'session');\n await session.state.set({\n factoryOrgId: sourceSession.orgId,\n factoryModelScope: modelScope,\n factoryOwnerUserId: sourceSession.userId,\n });\n identityResolved = true;\n await primeTenantCredentialsForTenant({\n orgId: sourceSession.orgId,\n userId: sourceSession.userId,\n credentialScope: modelScope,\n });\n\n if (binding) return;\n if (threadId && (await session.thread.firstUserMessage({ threadId }))) return;\n\n const scopedModelId =\n (modelScope === 'factory'\n ? project.defaultModelId\n : (await modelDefaults.get({ orgId: sourceSession.orgId, userId: sourceSession.userId }))?.modelId) ??\n // No chosen default: a connected provider's default, unless the current model is usable.\n (await resolveTenantProviderDefaultModel(\n { orgId: sourceSession.orgId, userId: sourceSession.userId, credentialScope: modelScope },\n session.model.get() || undefined,\n ).catch(error => {\n console.warn('[Factory default-model hydration] Unable to resolve a provider default model.', error);\n return undefined;\n }));\n if (!scopedModelId) return;\n // A thread the session creates later (the UI binding its conventional\n // thread after a thread-agnostic request opened the session) starts from\n // the session default, not from the thread hydrated here.\n session.model.setDefault({ modelId: scopedModelId });\n await applyDefaultModel(session, scopedModelId);\n } catch (error) {\n if (!identityResolved && !hadFactoryIdentity) {\n try {\n await failClosedWithoutIdentity();\n } catch {}\n }\n console.warn('[Factory default-model hydration] Unable to apply the scoped default model.', error);\n }\n}\n"],"mappings":";;;AAyBA,eAAe,kBAAkB,SAAwC,SAAgC;CACvG,MAAM,QAAQ,MAAM,OAAO,OAAO;CAElC,KAAK,MAAM,aAAa;EAAC;EAAW;EAAQ;CAAS,GACnD,MAAM,QAAQ,UAAU,MAAM,IAAI;EAAE;EAAS;CAAU,CAAC;AAE5D;;AAUA,eAAsB,2BACpB,SACA,EAAE,eAAe,UAAU,WAAW,iBACvB;CACf,MAAM,YAAY,QAAQ,SAAS,MAAM;CACzC,MAAM,aAAa,QAAQ,SAAS,cAAc;CAClD,MAAM,eAAe,QAAQ,MAAM,IAAI,KAAK,CAAC;CAC7C,IAAI,aAAa,oBAAoB,OAAO,QAAQ,OAAO,qBAAqB,YAAY;CAC5F,MAAM,qBAAqB,aAAa,sBAAsB,aAAa,aAAa,sBAAsB;CAC9G,MAAM,6BACJ,QAAQ,MAAM,IAAI;EAAE,cAAc,KAAA;EAAW,mBAAmB,KAAA;EAAW,oBAAoB,KAAA;CAAU,CAAC;CAC5G,MAAM,kCACJ,QAAQ,MAAM,IAAI;EAAE,mBAAmB;EAAQ,oBAAoB,KAAA;CAAU,CAAC;CAChF,IAAI,mBAAmB;CACvB,IAAI;EACF,MAAM,gBAAgB,MAAM,cAAc,eAAe,SAAS;EAClE,IAAI,CAAC,eAAe;GAClB,MAAM,qBAAqB;GAC3B;EACF;EACA,IAAI,CAAC,cAAc,kBAAkB;GACnC,MAAM,qBAAqB;GAC3B;EACF;EAEA,MAAM,WAAW,QAAQ,OAAO,MAAM;EACtC,MAAM,UAAU,WACZ,MAAM,UAAU,uBAAuB;GACrC,OAAO,cAAc;GACrB;GACA;GACA;GACA,iBAAiB;EACnB,CAAC,IACD;EACJ,MAAM,UAAU,MAAM,SAAS,QAAQ,EAAE,IAAI,SAAS,oBAAoB,cAAc,iBAAiB,CAAC;EAC1G,IAAI,CAAC,WAAW,QAAQ,UAAU,cAAc,OAAO;GACrD,MAAM,qBAAqB;GAC3B;EACF;EACA,MAAM,aAAa,oBAAoB,QAAQ,YAAY,UAAU,QAAQ,SAAS;EACtF,MAAM,QAAQ,MAAM,IAAI;GACtB,cAAc,cAAc;GAC5B,mBAAmB;GACnB,oBAAoB,cAAc;EACpC,CAAC;EACD,mBAAmB;EACnB,MAAM,gCAAgC;GACpC,OAAO,cAAc;GACrB,QAAQ,cAAc;GACtB,iBAAiB;EACnB,CAAC;EAED,IAAI,SAAS;EACb,IAAI,YAAa,MAAM,QAAQ,OAAO,iBAAiB,EAAE,SAAS,CAAC,GAAI;EAEvE,MAAM,iBACH,eAAe,YACZ,QAAQ,kBACP,MAAM,cAAc,IAAI;GAAE,OAAO,cAAc;GAAO,QAAQ,cAAc;EAAO,CAAC,EAAA,EAAI,YAE5F,MAAM,kCACL;GAAE,OAAO,cAAc;GAAO,QAAQ,cAAc;GAAQ,iBAAiB;EAAW,GACxF,QAAQ,MAAM,IAAI,KAAK,KAAA,CACzB,CAAC,CAAC,OAAM,UAAS;GACf,QAAQ,KAAK,iFAAiF,KAAK;EAErG,CAAC;EACH,IAAI,CAAC,eAAe;EAIpB,QAAQ,MAAM,WAAW,EAAE,SAAS,cAAc,CAAC;EACnD,MAAM,kBAAkB,SAAS,aAAa;CAChD,SAAS,OAAO;EACd,IAAI,CAAC,oBAAoB,CAAC,oBACxB,IAAI;GACF,MAAM,0BAA0B;EAClC,QAAQ,CAAC;EAEX,QAAQ,KAAK,+EAA+E,KAAK;CACnG;AACF"}
|
|
@@ -60,7 +60,7 @@ function escapeText(value) {
|
|
|
60
60
|
function sessionIdFromContext(requestContext) {
|
|
61
61
|
if (!requestContext || typeof requestContext.get !== "function") return null;
|
|
62
62
|
const controller = requestContext.get("controller");
|
|
63
|
-
return typeof controller?.
|
|
63
|
+
return typeof controller?.sessionId === "string" && controller.sessionId ? controller.sessionId : null;
|
|
64
64
|
}
|
|
65
65
|
function environmentCacheKey(state) {
|
|
66
66
|
return `environment:${createHash("sha256").update(JSON.stringify(state)).digest("hex").slice(0, 16)}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"environment-state-processor.js","names":[],"sources":["../../src/session/environment-state-processor.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport type { ComputeStateSignalArgs, ComputeStateSignalResult, Processor } from '@mastra/core/processors';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nconst STATE_ID = 'factory-environment';\n\nexport type EnvironmentRepositorySetupStatus = 'ok' | 'failed' | 'skipped';\n\n/** One repository of the booted environment as the agent is told about it: never a token or a clone URL. */\nexport interface SessionEnvironmentRepositoryState {\n slug: string;\n /** Absolute directory of the checkout under the workspace root. */\n dir: string;\n /** The branch the checkout ended on after boot; `null` when it stays detached. */\n branch: string | null;\n defaultBranch: string;\n position: number;\n /** `ok` ran or was already set up, `failed` exited non-zero, `skipped` has no setup command. */\n setupStatus: EnvironmentRepositorySetupStatus;\n /** The change request this session opened in the repository, once it has. */\n changeRequestUrl?: string;\n}\n\nexport interface SessionEnvironmentState {\n /** The workspace root, the session's working directory; repositories sit beneath it. */\n workingDirectory: string;\n repositories: SessionEnvironmentRepositoryState[];\n /** One free-form line the boot wants the agent to know (never a credential), rendered last. */\n note?: string;\n}\n\n// The boot records what it materialized, keyed by the factory session id (the\n// agent's resource id); the processor reads it on the next model step. Boot\n// runs on every sandbox start, so a replacement process re-learns the state\n// the first time the session's sandbox starts again.\nconst environments = new Map<string, { state: SessionEnvironmentState; teardown: SessionEnvironmentTeardown[] }>();\n\n/** A repository's teardown command and the directory it runs in; kept beside the state, never rendered. */\nexport interface SessionEnvironmentTeardown {\n slug: string;\n dir: string;\n command: string;\n}\n\nexport function recordSessionEnvironment(\n sessionId: string,\n state: SessionEnvironmentState,\n teardown: SessionEnvironmentTeardown[] = [],\n): void {\n environments.set(sessionId, { state, teardown });\n}\n\n/**\n * Record what a source-control tool did in one environment repository (the\n * branch it pushed, the change request it opened) so the next signal snapshot\n * tells the agent. A no-op when the session's environment is not recorded in\n * this process or the slug is not part of it.\n */\nexport function updateSessionEnvironmentRepository(\n sessionId: string,\n slug: string,\n patch: { branch?: string; changeRequestUrl?: string },\n): void {\n const entry = environments.get(sessionId);\n if (!entry) return;\n const wanted = slug.toLowerCase();\n const repositories = entry.state.repositories.map(repo => {\n if (repo.slug.toLowerCase() !== wanted) return repo;\n return {\n ...repo,\n ...(patch.branch !== undefined ? { branch: patch.branch } : {}),\n ...(patch.changeRequestUrl !== undefined ? { changeRequestUrl: patch.changeRequestUrl } : {}),\n };\n });\n entry.state = { ...entry.state, repositories };\n}\n\n/** Set or clear the environment's note; a no-op when the session's environment is not recorded here. */\nexport function setSessionEnvironmentNote(sessionId: string, note: string | null): void {\n const entry = environments.get(sessionId);\n if (!entry) return;\n const { note: _previous, ...rest } = entry.state;\n entry.state = note ? { ...rest, note } : rest;\n}\n\nexport function clearSessionEnvironment(sessionId: string): void {\n environments.delete(sessionId);\n}\n\nexport function peekSessionEnvironment(sessionId: string): SessionEnvironmentState | undefined {\n return environments.get(sessionId)?.state;\n}\n\n/** Teardown commands of the booted environment, in position order. */\nexport function peekSessionEnvironmentTeardown(sessionId: string): SessionEnvironmentTeardown[] {\n return environments.get(sessionId)?.teardown ?? [];\n}\n\nexport function __clearSessionEnvironmentsForTests(): void {\n environments.clear();\n}\n\nfunction escapeText(value: string): string {\n return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');\n}\n\n//
|
|
1
|
+
{"version":3,"file":"environment-state-processor.js","names":[],"sources":["../../src/session/environment-state-processor.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport type { ComputeStateSignalArgs, ComputeStateSignalResult, Processor } from '@mastra/core/processors';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nconst STATE_ID = 'factory-environment';\n\nexport type EnvironmentRepositorySetupStatus = 'ok' | 'failed' | 'skipped';\n\n/** One repository of the booted environment as the agent is told about it: never a token or a clone URL. */\nexport interface SessionEnvironmentRepositoryState {\n slug: string;\n /** Absolute directory of the checkout under the workspace root. */\n dir: string;\n /** The branch the checkout ended on after boot; `null` when it stays detached. */\n branch: string | null;\n defaultBranch: string;\n position: number;\n /** `ok` ran or was already set up, `failed` exited non-zero, `skipped` has no setup command. */\n setupStatus: EnvironmentRepositorySetupStatus;\n /** The change request this session opened in the repository, once it has. */\n changeRequestUrl?: string;\n}\n\nexport interface SessionEnvironmentState {\n /** The workspace root, the session's working directory; repositories sit beneath it. */\n workingDirectory: string;\n repositories: SessionEnvironmentRepositoryState[];\n /** One free-form line the boot wants the agent to know (never a credential), rendered last. */\n note?: string;\n}\n\n// The boot records what it materialized, keyed by the factory session id (the\n// agent's resource id); the processor reads it on the next model step. Boot\n// runs on every sandbox start, so a replacement process re-learns the state\n// the first time the session's sandbox starts again.\nconst environments = new Map<string, { state: SessionEnvironmentState; teardown: SessionEnvironmentTeardown[] }>();\n\n/** A repository's teardown command and the directory it runs in; kept beside the state, never rendered. */\nexport interface SessionEnvironmentTeardown {\n slug: string;\n dir: string;\n command: string;\n}\n\nexport function recordSessionEnvironment(\n sessionId: string,\n state: SessionEnvironmentState,\n teardown: SessionEnvironmentTeardown[] = [],\n): void {\n environments.set(sessionId, { state, teardown });\n}\n\n/**\n * Record what a source-control tool did in one environment repository (the\n * branch it pushed, the change request it opened) so the next signal snapshot\n * tells the agent. A no-op when the session's environment is not recorded in\n * this process or the slug is not part of it.\n */\nexport function updateSessionEnvironmentRepository(\n sessionId: string,\n slug: string,\n patch: { branch?: string; changeRequestUrl?: string },\n): void {\n const entry = environments.get(sessionId);\n if (!entry) return;\n const wanted = slug.toLowerCase();\n const repositories = entry.state.repositories.map(repo => {\n if (repo.slug.toLowerCase() !== wanted) return repo;\n return {\n ...repo,\n ...(patch.branch !== undefined ? { branch: patch.branch } : {}),\n ...(patch.changeRequestUrl !== undefined ? { changeRequestUrl: patch.changeRequestUrl } : {}),\n };\n });\n entry.state = { ...entry.state, repositories };\n}\n\n/** Set or clear the environment's note; a no-op when the session's environment is not recorded here. */\nexport function setSessionEnvironmentNote(sessionId: string, note: string | null): void {\n const entry = environments.get(sessionId);\n if (!entry) return;\n const { note: _previous, ...rest } = entry.state;\n entry.state = note ? { ...rest, note } : rest;\n}\n\nexport function clearSessionEnvironment(sessionId: string): void {\n environments.delete(sessionId);\n}\n\nexport function peekSessionEnvironment(sessionId: string): SessionEnvironmentState | undefined {\n return environments.get(sessionId)?.state;\n}\n\n/** Teardown commands of the booted environment, in position order. */\nexport function peekSessionEnvironmentTeardown(sessionId: string): SessionEnvironmentTeardown[] {\n return environments.get(sessionId)?.teardown ?? [];\n}\n\nexport function __clearSessionEnvironmentsForTests(): void {\n environments.clear();\n}\n\nfunction escapeText(value: string): string {\n return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');\n}\n\n// Unlike factory runs, a user session carries no `factoryProjectId` in its\n// controller state, and the environment is recorded for both, so only the\n// session id is required.\nfunction sessionIdFromContext(requestContext: RequestContext | undefined): string | null {\n if (!requestContext || typeof requestContext.get !== 'function') return null;\n const controller = requestContext.get('controller') as { sessionId?: unknown } | undefined;\n return typeof controller?.sessionId === 'string' && controller.sessionId ? controller.sessionId : null;\n}\n\nfunction environmentCacheKey(state: SessionEnvironmentState): string {\n return `environment:${createHash('sha256').update(JSON.stringify(state)).digest('hex').slice(0, 16)}`;\n}\n\n/**\n * Tells the agent which repositories its sandbox holds and where: the\n * workspace root is the session's working directory and every environment\n * repository is a directory beneath it. Snapshot mode only; a new snapshot\n * is emitted when the booted set changes (a start after an environment edit).\n */\nexport class FactoryEnvironmentStateProcessor implements Processor<'factory-environment'> {\n readonly id = STATE_ID;\n readonly stateId = STATE_ID;\n\n async computeStateSignal(args: ComputeStateSignalArgs): Promise<ComputeStateSignalResult> {\n const sessionId = sessionIdFromContext(args.requestContext);\n if (!sessionId) return;\n const state = environments.get(sessionId)?.state;\n if (!state) return;\n const cacheKey = environmentCacheKey(state);\n const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot;\n if (hasBase && (args.tracking?.currentCacheKey ?? args.lastSnapshot?.metadata?.state?.cacheKey) === cacheKey)\n return;\n const lines = state.repositories.map(\n repo =>\n `${repo.position}. ${escapeText(repo.slug)} at ${escapeText(repo.dir)} on ${escapeText(repo.branch ?? '(detached)')} (default ${escapeText(repo.defaultBranch)}, setup ${repo.setupStatus})` +\n (repo.changeRequestUrl ? `, change request ${escapeText(repo.changeRequestUrl)}` : ''),\n );\n const only = state.repositories.length === 1 ? state.repositories[0] : undefined;\n const contents =\n (only\n ? `Factory environment: 1 repository, ${escapeText(only.slug)} at ${escapeText(only.dir)}, your working directory.\\n`\n : `Factory environment: ${state.repositories.length} repositories under ${escapeText(state.workingDirectory)}, your working directory.\\n`) +\n lines.join('\\n') +\n (only ? '' : '\\nRun git and project commands inside the repository directory they belong to.') +\n (state.note ? `\\n${escapeText(state.note)}` : '');\n return {\n id: STATE_ID,\n cacheKey,\n mode: 'snapshot',\n tagName: 'factory-environment',\n contents,\n value: { environment: state },\n attributes: { workingDirectory: only?.dir ?? state.workingDirectory, repositories: state.repositories.length },\n metadata: { value: { environment: state } },\n };\n }\n}\n"],"mappings":";;AAIA,MAAM,WAAW;AA+BjB,MAAM,+BAAe,IAAI,IAAwF;AASjH,SAAgB,yBACd,WACA,OACA,WAAyC,CAAC,GACpC;CACN,aAAa,IAAI,WAAW;EAAE;EAAO;CAAS,CAAC;AACjD;;;;;;;AAQA,SAAgB,mCACd,WACA,MACA,OACM;CACN,MAAM,QAAQ,aAAa,IAAI,SAAS;CACxC,IAAI,CAAC,OAAO;CACZ,MAAM,SAAS,KAAK,YAAY;CAChC,MAAM,eAAe,MAAM,MAAM,aAAa,KAAI,SAAQ;EACxD,IAAI,KAAK,KAAK,YAAY,MAAM,QAAQ,OAAO;EAC/C,OAAO;GACL,GAAG;GACH,GAAI,MAAM,WAAW,KAAA,IAAY,EAAE,QAAQ,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sB,mCAAmC,CAAC,IAAI,EAAE;IAC9D,aAAa,EAAE,0BAA0B,CAAC;IAC1C,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CAAC;IACzB,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B,GAAG,OAAO,CAAC,6BAA6B,CAAC,CAiBzC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,0BAA0B,CAC9C,IAAI,EAAE,8BAA8B,GACnC,OAAO,CAAC,2BAA2B,CAAC,CAsCtC;AAED,MAAM,WAAW,yBAAyB;IACxC,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,mBAAmB,CAAC;IAChC,WAAW,EAAE,MAAM,CAAC;IACpB;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;;;;;GAMG;AACH,wBAAsB,qBAAqB,CACzC,OAAO,EAAE,cAAc,EACvB,IAAI,EAAE,yBAAyB,GAC9B,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAmD7B"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { legacyGithubWorkItemBranch } from "../work-item-branch.js";
|
|
1
2
|
import { resolveEnvironmentRepositories } from "./environment-repositories.js";
|
|
2
3
|
import { resolveTenantProviderDefaultModel } from "../routes/tenant-credentials.js";
|
|
3
4
|
import { seedSessionOrg } from "./org-seed.js";
|
|
@@ -165,13 +166,25 @@ async function ensureFactorySourceSession(args) {
|
|
|
165
166
|
});
|
|
166
167
|
if (!resolved.found) throw new FactorySourceSessionResolutionError(resolved.reason);
|
|
167
168
|
const userId = args.attributeToUserId ?? resolved.connectedByUserId;
|
|
169
|
+
const legacyBranch = legacyGithubWorkItemBranch(branch);
|
|
170
|
+
const lookup = {
|
|
171
|
+
projectRepositoryId: resolved.projectRepositoryId,
|
|
172
|
+
userId
|
|
173
|
+
};
|
|
174
|
+
const existing = legacyBranch ? await sourceControl.sessions.getForBranch({
|
|
175
|
+
...lookup,
|
|
176
|
+
branch
|
|
177
|
+
}) ?? await sourceControl.sessions.getForBranch({
|
|
178
|
+
...lookup,
|
|
179
|
+
branch: legacyBranch
|
|
180
|
+
}) : null;
|
|
168
181
|
const session = await sourceControl.sessions.create({
|
|
169
182
|
sessionId: args.sessionId ?? globalThis.crypto.randomUUID(),
|
|
170
183
|
projectRepositoryId: resolved.projectRepositoryId,
|
|
171
184
|
factoryProjectId,
|
|
172
185
|
orgId,
|
|
173
186
|
userId,
|
|
174
|
-
branch,
|
|
187
|
+
branch: existing?.branch ?? branch,
|
|
175
188
|
baseBranch: resolved.baseBranch,
|
|
176
189
|
visibility: args.visibility ?? "org",
|
|
177
190
|
...args.origin ? { origin: args.origin } : {}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factory-session.js","names":[],"sources":["../../src/session/factory-session.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\n\nimport { resolveTenantProviderDefaultModel } from '../routes/tenant-credentials.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { effectiveModelScope } from '../storage/domains/projects/base.js';\nimport type { EffectiveModelScope, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport { SourceControlConnectionNotFoundError } from '../storage/domains/source-control/base.js';\nimport type {\n SourceControlSession,\n SourceControlSessionVisibility,\n SourceControlStorageHandle,\n} from '../storage/domains/source-control/base.js';\nimport { resolveEnvironmentRepositories } from './environment-repositories.js';\nimport { seedSessionOrg } from './org-seed.js';\n\ntype FactorySession = Awaited<ReturnType<AgentController<MastraCodeState>['createSession']>>;\n\nexport class FactorySourceControlConflictError extends Error {}\n\n/** Resolve the model and exclusive credential scope for a Factory session. */\nexport async function resolveFactorySessionModel(args: {\n projects: FactoryProjectsStorage | undefined;\n modelDefaults: ModelDefaultsStorage | undefined;\n factoryProjectId: string | undefined;\n orgId: string;\n ownerUserId: string;\n /** A work-item run or an interactive session; a hybrid Factory resolves a different scope for each. */\n context: 'run' | 'session';\n}): Promise<{ modelScope: EffectiveModelScope; modelId?: string }> {\n if (!args.projects || !args.factoryProjectId) throw new Error('Factory model policy is unavailable.');\n\n const project = await args.projects.getById({ id: args.factoryProjectId });\n if (!project || project.orgId !== args.orgId) throw new Error('Factory model policy is unavailable.');\n if (effectiveModelScope(project.modelScope, args.context) === 'factory') {\n return { modelScope: 'factory', ...(project.defaultModelId ? { modelId: project.defaultModelId } : {}) };\n }\n\n try {\n const userDefault = await args.modelDefaults?.get({ orgId: args.orgId, userId: args.ownerUserId });\n return { modelScope: 'user', ...(userDefault?.modelId ? { modelId: userDefault.modelId } : {}) };\n } catch (error) {\n console.warn('[Factory] Owner default model lookup failed; using the mode default model', {\n orgId: args.orgId,\n ownerUserId: args.ownerUserId,\n error: error instanceof Error ? error.message : String(error),\n });\n return { modelScope: 'user' };\n }\n}\n\nexport interface SourceControlSessionLookup {\n getBySessionId(sessionId: string): Promise<SourceControlSession | null>;\n getSourceControlBySessionId(sessionId: string): Promise<SourceControlStorageHandle | null>;\n /** Side sessions started by `originSessionId`, across every provider. */\n listByOrigin(args: { orgId: string; originSessionId: string }): Promise<SourceControlSession[]>;\n rename(args: { sessionId: string; title: string }): Promise<void>;\n setOriginMuted(args: { sessionId: string; muted: boolean }): Promise<void>;\n markFirstMessage(args: { sessionId: string }): Promise<void>;\n markFirstMeaningfulExec(args: { sessionId: string }): Promise<void>;\n}\n\n/**\n * Read or update a session across every registered source-control partition.\n * Session ids are globally generated, so more than one match is invalid and\n * fails closed instead of mutating an arbitrary provider.\n */\nexport function createSourceControlSessionLookup(\n sourceControls: readonly SourceControlStorageHandle[],\n): SourceControlSessionLookup {\n const resolve = async (\n sessionId: string,\n ): Promise<{ sourceControl: SourceControlStorageHandle; session: SourceControlSession } | null> => {\n const matches = (\n await Promise.all(\n sourceControls.map(async sourceControl => ({\n sourceControl,\n session: await sourceControl.sessions.getBySessionId(sessionId),\n })),\n )\n ).filter(\n (match): match is { sourceControl: SourceControlStorageHandle; session: SourceControlSession } =>\n match.session !== null,\n );\n if (matches.length > 1) throw new Error('Factory session exists in multiple source-control providers.');\n return matches[0] ?? null;\n };\n\n return {\n getBySessionId: async sessionId => (await resolve(sessionId))?.session ?? null,\n getSourceControlBySessionId: async sessionId => (await resolve(sessionId))?.sourceControl ?? null,\n listByOrigin: async args =>\n (await Promise.all(sourceControls.map(sourceControl => sourceControl.sessions.listByOrigin(args)))).flat(),\n rename: async args => (await resolve(args.sessionId))?.sourceControl.sessions.rename(args),\n setOriginMuted: async args => (await resolve(args.sessionId))?.sourceControl.sessions.setOriginMuted(args),\n markFirstMessage: async args => (await resolve(args.sessionId))?.sourceControl.sessions.markFirstMessage(args),\n markFirstMeaningfulExec: async args =>\n (await resolve(args.sessionId))?.sourceControl.sessions.markFirstMeaningfulExec(args),\n };\n}\n\n/**\n * Resolve the source-control provider from durable Factory repository links,\n * never from the issue tracker that happened to create the work item.\n */\nexport async function resolveFactorySourceControl(args: {\n sourceControls: readonly SourceControlStorageHandle[];\n orgId: string;\n factoryProjectId: string;\n sessionId?: string;\n}): Promise<SourceControlStorageHandle | undefined> {\n if (args.sessionId) {\n const sessionMatches = (\n await Promise.all(\n args.sourceControls.map(async sourceControl => ({\n sourceControl,\n session: await sourceControl.sessions.getBySessionId(args.sessionId!),\n })),\n )\n ).filter(match => match.session !== null);\n if (sessionMatches.length > 1) throw new Error('Factory session exists in multiple source-control providers.');\n if (sessionMatches[0]) return sessionMatches[0].sourceControl;\n }\n\n const linked = [];\n for (const sourceControl of args.sourceControls) {\n const connections = await sourceControl.connections.list({\n orgId: args.orgId,\n factoryProjectId: args.factoryProjectId,\n });\n let hasLinkedRepository = false;\n for (const connection of connections) {\n try {\n if (\n (await sourceControl.projectRepositories.list({ orgId: args.orgId, connectionId: connection.id })).length > 0\n ) {\n hasLinkedRepository = true;\n break;\n }\n } catch (error) {\n if (!(error instanceof SourceControlConnectionNotFoundError)) throw error;\n }\n }\n if (hasLinkedRepository) linked.push(sourceControl);\n }\n if (linked.length > 1)\n throw new FactorySourceControlConflictError(\n 'Factory project has repositories linked through multiple source-control providers.',\n );\n return linked[0];\n}\n\nexport interface EnsureFactorySourceSessionArgs {\n /**\n * Storage handle of the integration that owns source control. Nothing here is\n * provider-specific: the connection is matched by the handle's own\n * `integrationId`, so GitHub, Slack-on-behalf-of-GitHub, or any future owner\n * all resolve through the same traversal.\n */\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n branch: string;\n /**\n * The repository link the session is filed under: the one a work item\n * targets. Defaults to the factory's position-1 environment link (D1), for\n * callers where nothing names a repository (chat threads, user sessions).\n */\n projectRepositoryId?: string;\n /**\n * Attribute the run to this user instead of the repo connector. Set when the\n * run has an interactive user — e.g. the person who approved a proposed run.\n */\n attributeToUserId?: string;\n /** A pre-generated session id, so a caller can name the branch after it. Defaults to a fresh UUID. */\n sessionId?: string;\n /** Defaults to 'org'. A side session copies its parent's visibility. */\n visibility?: SourceControlSessionVisibility;\n /** The session and thread that started this one as a side session. */\n origin?: { sessionId: string; threadId: string };\n}\n\nexport interface EnsuredFactorySourceSession {\n sessionId: string;\n userId: string;\n projectRepositoryId: string;\n branch: string;\n baseBranch: string;\n}\n\nexport class FactorySourceSessionResolutionError extends Error {\n constructor(readonly reason: 'connection' | 'repository') {\n super(\n reason === 'connection'\n ? 'Factory source-control connection not found.'\n : 'Factory source-control repository not found.',\n );\n this.name = 'FactorySourceSessionResolutionError';\n }\n}\n\nexport interface ResolvedFactorySourceRepository {\n projectRepositoryId: string;\n /** The repository's pinned branch, else its default branch. */\n baseBranch: string;\n /** Who connected the repository. The attribution for runs with no interactive user. */\n connectedByUserId: string;\n}\n\n/**\n * Outcome of {@link resolvePrimaryEnvironmentRepository}. A miss carries which\n * step failed: callers differ on whether that is an error (an autonomous run\n * cannot proceed) or a routine fallback (a chat integration drops to a\n * chat-only session), and the two steps fail for different reasons worth\n * reporting apart.\n */\nexport type FactorySourceRepositoryResult =\n | ({ found: true } & ResolvedFactorySourceRepository)\n | { found: false; reason: 'connection' | 'repository' };\n\n/**\n * The repository link a new session is filed under. By default the position-1\n * `inEnvironment` link of the factory (decision D1); a work item that targets\n * a repository names its link through `projectRepositoryId`, which must be an\n * environment link of the same factory. Session start no longer picks a\n * repository to work in, the sandbox holds every environment repository. The\n * PR tools default to this link, and subscriptions, audit and the work item's\n * repository check still read it; moving them to the per-repository\n * `sessionRepositories` rows is a follow-up.\n *\n * The owner is whichever integration owns source control, matched by the\n * handle's own `integrationId` — nothing here is provider-specific.\n */\nexport async function resolvePrimaryEnvironmentRepository(args: {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n projectRepositoryId?: string;\n}): Promise<FactorySourceRepositoryResult> {\n const { sourceControl, orgId, factoryProjectId, projectRepositoryId } = args;\n const connections = await sourceControl.connections.list({ orgId, factoryProjectId });\n if (!connections.some(candidate => candidate.integrationId === sourceControl.integrationId)) {\n return { found: false, reason: 'connection' };\n }\n const repositories = await resolveEnvironmentRepositories({ sourceControl, orgId, factoryProjectId });\n const primary = repositories.find(\n candidate => projectRepositoryId === undefined || candidate.link.id === projectRepositoryId,\n );\n if (!primary) return { found: false, reason: 'repository' };\n return {\n found: true,\n projectRepositoryId: primary.link.id,\n baseBranch: primary.link.branch ?? primary.repository.defaultBranch,\n connectedByUserId: primary.connection.createdByUserId,\n };\n}\n\n/**\n * Create the source-control session a repo-backed factory run needs.\n *\n * `FactoryStartCoordinator.prepare` requires this record to already exist —\n * `resolveSourceSession` throws `Factory session not found` otherwise — so every\n * autonomous entry point has to produce one before it can start a run. This is\n * that step, in one place: the owner's connection on the factory project, the\n * work item's repository link (else the position-1 environment link, D1) as\n * the session's link, and a session on the requested branch with that\n * repository's pinned or default branch as the base. The sandbox itself boots\n * every environment repository.\n *\n * The run is attributed to `attributeToUserId` when the caller has an\n * interactive user (e.g. the approver of a proposed run), and otherwise falls\n * back to whoever connected the repository (`connection.createdByUserId`),\n * because a genuinely autonomous run has no interactive user of its own.\n */\nexport async function ensureFactorySourceSession(\n args: EnsureFactorySourceSessionArgs,\n): Promise<EnsuredFactorySourceSession> {\n const { sourceControl, orgId, factoryProjectId, branch, projectRepositoryId } = args;\n\n const resolved = await resolvePrimaryEnvironmentRepository({\n sourceControl,\n orgId,\n factoryProjectId,\n projectRepositoryId,\n });\n if (!resolved.found) throw new FactorySourceSessionResolutionError(resolved.reason);\n\n const userId = args.attributeToUserId ?? resolved.connectedByUserId;\n const session = await sourceControl.sessions.create({\n sessionId: args.sessionId ?? globalThis.crypto.randomUUID(),\n projectRepositoryId: resolved.projectRepositoryId,\n factoryProjectId,\n orgId,\n userId,\n branch,\n baseBranch: resolved.baseBranch,\n visibility: args.visibility ?? 'org',\n ...(args.origin ? { origin: args.origin } : {}),\n });\n return {\n sessionId: session.sessionId,\n userId,\n projectRepositoryId: resolved.projectRepositoryId,\n branch: session.branch,\n baseBranch: resolved.baseBranch,\n };\n}\n\nexport interface HydrateFactorySessionArgs {\n orgId: string;\n modelScope: EffectiveModelScope;\n ownerUserId: string;\n /**\n * The model selected by the Factory scope. Without it the provider default of a connected\n * provider is applied when the SDK mode default has no credential, else the mode default.\n */\n defaultModelId?: string;\n}\n\n/**\n * Apply a factory project's main model to a session on every run.\n *\n * The model switch is best-effort. A retired model id must not sink a run that\n * is otherwise ready, and the reason is logged. Observational-memory settings are resolved from the\n * authoritative row per invocation before memory processors run.\n */\nexport async function hydrateFactorySession(\n session: FactorySession,\n args: HydrateFactorySessionArgs,\n): Promise<string | undefined> {\n // The org rung knowledge curation scopes on. Seeded first so it lands even if\n // a later best-effort step fails; an empty org marks the session unresolved.\n await seedSessionOrg(session, args.orgId);\n await session.state.set({\n factoryModelScope: args.modelScope,\n factoryOwnerUserId: args.ownerUserId,\n });\n\n let selectedModelId = args.defaultModelId;\n if (!selectedModelId) {\n const modeModelId = session.mode.resolve().defaultModelId;\n const providerModelId = await resolveTenantProviderDefaultModel(\n { orgId: args.orgId, userId: args.ownerUserId, credentialScope: args.modelScope },\n modeModelId,\n ).catch(error => {\n console.warn('[Factory Start] Failed to resolve a provider default model', {\n error: error instanceof Error ? error.message : String(error),\n });\n return undefined;\n });\n selectedModelId = providerModelId ?? modeModelId;\n }\n if (!selectedModelId) return undefined;\n\n let switched = true;\n try {\n await session.model.switch(selectedModelId);\n } catch (error) {\n switched = false;\n console.warn('[Factory Start] Failed to apply scoped default model', {\n modelId: selectedModelId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n // Subagents otherwise keep the server-wide settings (or the SDK's built-in\n // default), which may name a provider this factory has no credentials for.\n // Each role is independent, so one failure doesn't strand the others.\n for (const agentType of ['explore', 'plan', 'execute']) {\n try {\n await session.subagents.model.set({ modelId: selectedModelId, agentType });\n } catch (error) {\n console.warn('[Factory Start] Failed to apply scoped default subagent model', {\n agentType,\n modelId: selectedModelId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n // Callers pin this id to the thread, so only report a model the session actually runs on.\n return switched ? selectedModelId : undefined;\n}\n"],"mappings":";;;;;;AAkBA,IAAa,oCAAb,cAAuD,MAAM,CAAC;;AAG9D,eAAsB,2BAA2B,MAQkB;CACjE,IAAI,CAAC,KAAK,YAAY,CAAC,KAAK,kBAAkB,MAAM,IAAI,MAAM,sCAAsC;CAEpG,MAAM,UAAU,MAAM,KAAK,SAAS,QAAQ,EAAE,IAAI,KAAK,iBAAiB,CAAC;CACzE,IAAI,CAAC,WAAW,QAAQ,UAAU,KAAK,OAAO,MAAM,IAAI,MAAM,sCAAsC;CACpG,IAAI,oBAAoB,QAAQ,YAAY,KAAK,OAAO,MAAM,WAC5D,OAAO;EAAE,YAAY;EAAW,GAAI,QAAQ,iBAAiB,EAAE,SAAS,QAAQ,eAAe,IAAI,CAAC;CAAG;CAGzG,IAAI;EACF,MAAM,cAAc,MAAM,KAAK,eAAe,IAAI;GAAE,OAAO,KAAK;GAAO,QAAQ,KAAK;EAAY,CAAC;EACjG,OAAO;GAAE,YAAY;G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AU3C,kBAAkB,MATY,kCAC5B;GAAE,OAAO,KAAK;GAAO,QAAQ,KAAK;GAAa,iBAAiB,KAAK;EAAW,GAChF,WACF,CAAC,CAAC,OAAM,UAAS;GACf,QAAQ,KAAK,8DAA8D,EACzE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAC9D,CAAC;EAEH,CAAC,KACoC;CACvC;CACA,IAAI,CAAC,iBAAiB,OAAO,KAAA;CAE7B,IAAI,WAAW;CACf,IAAI;EACF,MAAM,QAAQ,MAAM,OAAO,eAAe;CAC5C,SAAS,OAAO;EACd,WAAW;EACX,QAAQ,KAAK,wDAAwD;GACnE,SAAS;GACT,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC9D,CAAC;CACH;CAIA,KAAK,MAAM,aAAa;EAAC;EAAW;EAAQ;CAAS,GACnD,IAAI;EACF,MAAM,QAAQ,UAAU,MAAM,IAAI;GAAE,SAAS;GAAiB;EAAU,CAAC;CAC3E,SAAS,OAAO;EACd,QAAQ,KAAK,iEAAiE;GAC5E;GACA,SAAS;GACT,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC9D,CAAC;CACH;CAGF,OAAO,WAAW,kBAAkB,KAAA;AACtC"}
|
|
1
|
+
{"version":3,"file":"factory-session.js","names":[],"sources":["../../src/session/factory-session.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\n\nimport { resolveTenantProviderDefaultModel } from '../routes/tenant-credentials.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { effectiveModelScope } from '../storage/domains/projects/base.js';\nimport type { EffectiveModelScope, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport { SourceControlConnectionNotFoundError } from '../storage/domains/source-control/base.js';\nimport type {\n SourceControlSession,\n SourceControlSessionVisibility,\n SourceControlStorageHandle,\n} from '../storage/domains/source-control/base.js';\nimport { legacyGithubWorkItemBranch } from '../work-item-branch.js';\nimport { resolveEnvironmentRepositories } from './environment-repositories.js';\nimport { seedSessionOrg } from './org-seed.js';\n\ntype FactorySession = Awaited<ReturnType<AgentController<MastraCodeState>['createSession']>>;\n\nexport class FactorySourceControlConflictError extends Error {}\n\n/** Resolve the model and exclusive credential scope for a Factory session. */\nexport async function resolveFactorySessionModel(args: {\n projects: FactoryProjectsStorage | undefined;\n modelDefaults: ModelDefaultsStorage | undefined;\n factoryProjectId: string | undefined;\n orgId: string;\n ownerUserId: string;\n /** A work-item run or an interactive session; a hybrid Factory resolves a different scope for each. */\n context: 'run' | 'session';\n}): Promise<{ modelScope: EffectiveModelScope; modelId?: string }> {\n if (!args.projects || !args.factoryProjectId) throw new Error('Factory model policy is unavailable.');\n\n const project = await args.projects.getById({ id: args.factoryProjectId });\n if (!project || project.orgId !== args.orgId) throw new Error('Factory model policy is unavailable.');\n if (effectiveModelScope(project.modelScope, args.context) === 'factory') {\n return { modelScope: 'factory', ...(project.defaultModelId ? { modelId: project.defaultModelId } : {}) };\n }\n\n try {\n const userDefault = await args.modelDefaults?.get({ orgId: args.orgId, userId: args.ownerUserId });\n return { modelScope: 'user', ...(userDefault?.modelId ? { modelId: userDefault.modelId } : {}) };\n } catch (error) {\n console.warn('[Factory] Owner default model lookup failed; using the mode default model', {\n orgId: args.orgId,\n ownerUserId: args.ownerUserId,\n error: error instanceof Error ? error.message : String(error),\n });\n return { modelScope: 'user' };\n }\n}\n\nexport interface SourceControlSessionLookup {\n getBySessionId(sessionId: string): Promise<SourceControlSession | null>;\n getSourceControlBySessionId(sessionId: string): Promise<SourceControlStorageHandle | null>;\n /** Side sessions started by `originSessionId`, across every provider. */\n listByOrigin(args: { orgId: string; originSessionId: string }): Promise<SourceControlSession[]>;\n rename(args: { sessionId: string; title: string }): Promise<void>;\n setOriginMuted(args: { sessionId: string; muted: boolean }): Promise<void>;\n markFirstMessage(args: { sessionId: string }): Promise<void>;\n markFirstMeaningfulExec(args: { sessionId: string }): Promise<void>;\n}\n\n/**\n * Read or update a session across every registered source-control partition.\n * Session ids are globally generated, so more than one match is invalid and\n * fails closed instead of mutating an arbitrary provider.\n */\nexport function createSourceControlSessionLookup(\n sourceControls: readonly SourceControlStorageHandle[],\n): SourceControlSessionLookup {\n const resolve = async (\n sessionId: string,\n ): Promise<{ sourceControl: SourceControlStorageHandle; session: SourceControlSession } | null> => {\n const matches = (\n await Promise.all(\n sourceControls.map(async sourceControl => ({\n sourceControl,\n session: await sourceControl.sessions.getBySessionId(sessionId),\n })),\n )\n ).filter(\n (match): match is { sourceControl: SourceControlStorageHandle; session: SourceControlSession } =>\n match.session !== null,\n );\n if (matches.length > 1) throw new Error('Factory session exists in multiple source-control providers.');\n return matches[0] ?? null;\n };\n\n return {\n getBySessionId: async sessionId => (await resolve(sessionId))?.session ?? null,\n getSourceControlBySessionId: async sessionId => (await resolve(sessionId))?.sourceControl ?? null,\n listByOrigin: async args =>\n (await Promise.all(sourceControls.map(sourceControl => sourceControl.sessions.listByOrigin(args)))).flat(),\n rename: async args => (await resolve(args.sessionId))?.sourceControl.sessions.rename(args),\n setOriginMuted: async args => (await resolve(args.sessionId))?.sourceControl.sessions.setOriginMuted(args),\n markFirstMessage: async args => (await resolve(args.sessionId))?.sourceControl.sessions.markFirstMessage(args),\n markFirstMeaningfulExec: async args =>\n (await resolve(args.sessionId))?.sourceControl.sessions.markFirstMeaningfulExec(args),\n };\n}\n\n/**\n * Resolve the source-control provider from durable Factory repository links,\n * never from the issue tracker that happened to create the work item.\n */\nexport async function resolveFactorySourceControl(args: {\n sourceControls: readonly SourceControlStorageHandle[];\n orgId: string;\n factoryProjectId: string;\n sessionId?: string;\n}): Promise<SourceControlStorageHandle | undefined> {\n if (args.sessionId) {\n const sessionMatches = (\n await Promise.all(\n args.sourceControls.map(async sourceControl => ({\n sourceControl,\n session: await sourceControl.sessions.getBySessionId(args.sessionId!),\n })),\n )\n ).filter(match => match.session !== null);\n if (sessionMatches.length > 1) throw new Error('Factory session exists in multiple source-control providers.');\n if (sessionMatches[0]) return sessionMatches[0].sourceControl;\n }\n\n const linked = [];\n for (const sourceControl of args.sourceControls) {\n const connections = await sourceControl.connections.list({\n orgId: args.orgId,\n factoryProjectId: args.factoryProjectId,\n });\n let hasLinkedRepository = false;\n for (const connection of connections) {\n try {\n if (\n (await sourceControl.projectRepositories.list({ orgId: args.orgId, connectionId: connection.id })).length > 0\n ) {\n hasLinkedRepository = true;\n break;\n }\n } catch (error) {\n if (!(error instanceof SourceControlConnectionNotFoundError)) throw error;\n }\n }\n if (hasLinkedRepository) linked.push(sourceControl);\n }\n if (linked.length > 1)\n throw new FactorySourceControlConflictError(\n 'Factory project has repositories linked through multiple source-control providers.',\n );\n return linked[0];\n}\n\nexport interface EnsureFactorySourceSessionArgs {\n /**\n * Storage handle of the integration that owns source control. Nothing here is\n * provider-specific: the connection is matched by the handle's own\n * `integrationId`, so GitHub, Slack-on-behalf-of-GitHub, or any future owner\n * all resolve through the same traversal.\n */\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n branch: string;\n /**\n * The repository link the session is filed under: the one a work item\n * targets. Defaults to the factory's position-1 environment link (D1), for\n * callers where nothing names a repository (chat threads, user sessions).\n */\n projectRepositoryId?: string;\n /**\n * Attribute the run to this user instead of the repo connector. Set when the\n * run has an interactive user — e.g. the person who approved a proposed run.\n */\n attributeToUserId?: string;\n /** A pre-generated session id, so a caller can name the branch after it. Defaults to a fresh UUID. */\n sessionId?: string;\n /** Defaults to 'org'. A side session copies its parent's visibility. */\n visibility?: SourceControlSessionVisibility;\n /** The session and thread that started this one as a side session. */\n origin?: { sessionId: string; threadId: string };\n}\n\nexport interface EnsuredFactorySourceSession {\n sessionId: string;\n userId: string;\n projectRepositoryId: string;\n branch: string;\n baseBranch: string;\n}\n\nexport class FactorySourceSessionResolutionError extends Error {\n constructor(readonly reason: 'connection' | 'repository') {\n super(\n reason === 'connection'\n ? 'Factory source-control connection not found.'\n : 'Factory source-control repository not found.',\n );\n this.name = 'FactorySourceSessionResolutionError';\n }\n}\n\nexport interface ResolvedFactorySourceRepository {\n projectRepositoryId: string;\n /** The repository's pinned branch, else its default branch. */\n baseBranch: string;\n /** Who connected the repository. The attribution for runs with no interactive user. */\n connectedByUserId: string;\n}\n\n/**\n * Outcome of {@link resolvePrimaryEnvironmentRepository}. A miss carries which\n * step failed: callers differ on whether that is an error (an autonomous run\n * cannot proceed) or a routine fallback (a chat integration drops to a\n * chat-only session), and the two steps fail for different reasons worth\n * reporting apart.\n */\nexport type FactorySourceRepositoryResult =\n | ({ found: true } & ResolvedFactorySourceRepository)\n | { found: false; reason: 'connection' | 'repository' };\n\n/**\n * The repository link a new session is filed under. By default the position-1\n * `inEnvironment` link of the factory (decision D1); a work item that targets\n * a repository names its link through `projectRepositoryId`, which must be an\n * environment link of the same factory. Session start no longer picks a\n * repository to work in, the sandbox holds every environment repository. The\n * PR tools default to this link, and subscriptions, audit and the work item's\n * repository check still read it; moving them to the per-repository\n * `sessionRepositories` rows is a follow-up.\n *\n * The owner is whichever integration owns source control, matched by the\n * handle's own `integrationId` — nothing here is provider-specific.\n */\nexport async function resolvePrimaryEnvironmentRepository(args: {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n projectRepositoryId?: string;\n}): Promise<FactorySourceRepositoryResult> {\n const { sourceControl, orgId, factoryProjectId, projectRepositoryId } = args;\n const connections = await sourceControl.connections.list({ orgId, factoryProjectId });\n if (!connections.some(candidate => candidate.integrationId === sourceControl.integrationId)) {\n return { found: false, reason: 'connection' };\n }\n const repositories = await resolveEnvironmentRepositories({ sourceControl, orgId, factoryProjectId });\n const primary = repositories.find(\n candidate => projectRepositoryId === undefined || candidate.link.id === projectRepositoryId,\n );\n if (!primary) return { found: false, reason: 'repository' };\n return {\n found: true,\n projectRepositoryId: primary.link.id,\n baseBranch: primary.link.branch ?? primary.repository.defaultBranch,\n connectedByUserId: primary.connection.createdByUserId,\n };\n}\n\n/**\n * Create the source-control session a repo-backed factory run needs.\n *\n * `FactoryStartCoordinator.prepare` requires this record to already exist —\n * `resolveSourceSession` throws `Factory session not found` otherwise — so every\n * autonomous entry point has to produce one before it can start a run. This is\n * that step, in one place: the owner's connection on the factory project, the\n * work item's repository link (else the position-1 environment link, D1) as\n * the session's link, and a session on the requested branch with that\n * repository's pinned or default branch as the base. The sandbox itself boots\n * every environment repository.\n *\n * The run is attributed to `attributeToUserId` when the caller has an\n * interactive user (e.g. the approver of a proposed run), and otherwise falls\n * back to whoever connected the repository (`connection.createdByUserId`),\n * because a genuinely autonomous run has no interactive user of its own.\n */\nexport async function ensureFactorySourceSession(\n args: EnsureFactorySourceSessionArgs,\n): Promise<EnsuredFactorySourceSession> {\n const { sourceControl, orgId, factoryProjectId, branch, projectRepositoryId } = args;\n\n const resolved = await resolvePrimaryEnvironmentRepository({\n sourceControl,\n orgId,\n factoryProjectId,\n projectRepositoryId,\n });\n if (!resolved.found) throw new FactorySourceSessionResolutionError(resolved.reason);\n\n const userId = args.attributeToUserId ?? resolved.connectedByUserId;\n // Prefer an existing current branch, then the legacy branch on this exact\n // repository and owner. Never reuse another repository's same-number card.\n const legacyBranch = legacyGithubWorkItemBranch(branch);\n const lookup = { projectRepositoryId: resolved.projectRepositoryId, userId };\n const existing = legacyBranch\n ? ((await sourceControl.sessions.getForBranch({ ...lookup, branch })) ??\n (await sourceControl.sessions.getForBranch({ ...lookup, branch: legacyBranch })))\n : null;\n const session = await sourceControl.sessions.create({\n sessionId: args.sessionId ?? globalThis.crypto.randomUUID(),\n projectRepositoryId: resolved.projectRepositoryId,\n factoryProjectId,\n orgId,\n userId,\n branch: existing?.branch ?? branch,\n baseBranch: resolved.baseBranch,\n visibility: args.visibility ?? 'org',\n ...(args.origin ? { origin: args.origin } : {}),\n });\n return {\n sessionId: session.sessionId,\n userId,\n projectRepositoryId: resolved.projectRepositoryId,\n branch: session.branch,\n baseBranch: resolved.baseBranch,\n };\n}\n\nexport interface HydrateFactorySessionArgs {\n orgId: string;\n modelScope: EffectiveModelScope;\n ownerUserId: string;\n /**\n * The model selected by the Factory scope. Without it the provider default of a connected\n * provider is applied when the SDK mode default has no credential, else the mode default.\n */\n defaultModelId?: string;\n}\n\n/**\n * Apply a factory project's main model to a session on every run.\n *\n * The model switch is best-effort. A retired model id must not sink a run that\n * is otherwise ready, and the reason is logged. Observational-memory settings are resolved from the\n * authoritative row per invocation before memory processors run.\n */\nexport async function hydrateFactorySession(\n session: FactorySession,\n args: HydrateFactorySessionArgs,\n): Promise<string | undefined> {\n // The org rung knowledge curation scopes on. Seeded first so it lands even if\n // a later best-effort step fails; an empty org marks the session unresolved.\n await seedSessionOrg(session, args.orgId);\n await session.state.set({\n factoryModelScope: args.modelScope,\n factoryOwnerUserId: args.ownerUserId,\n });\n\n let selectedModelId = args.defaultModelId;\n if (!selectedModelId) {\n const modeModelId = session.mode.resolve().defaultModelId;\n const providerModelId = await resolveTenantProviderDefaultModel(\n { orgId: args.orgId, userId: args.ownerUserId, credentialScope: args.modelScope },\n modeModelId,\n ).catch(error => {\n console.warn('[Factory Start] Failed to resolve a provider default model', {\n error: error instanceof Error ? error.message : String(error),\n });\n return undefined;\n });\n selectedModelId = providerModelId ?? modeModelId;\n }\n if (!selectedModelId) return undefined;\n\n let switched = true;\n try {\n await session.model.switch(selectedModelId);\n } catch (error) {\n switched = false;\n console.warn('[Factory Start] Failed to apply scoped default model', {\n modelId: selectedModelId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n // Subagents otherwise keep the server-wide settings (or the SDK's built-in\n // default), which may name a provider this factory has no credentials for.\n // Each role is independent, so one failure doesn't strand the others.\n for (const agentType of ['explore', 'plan', 'execute']) {\n try {\n await session.subagents.model.set({ modelId: selectedModelId, agentType });\n } catch (error) {\n console.warn('[Factory Start] Failed to apply scoped default subagent model', {\n agentType,\n modelId: selectedModelId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n // Callers pin this id to the thread, so only report a model the session actually runs on.\n return switched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