@mastra/factory 0.29.0-alpha.5 → 0.29.0-alpha.7
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 +55 -31
- package/dist/boards/semantics.d.ts.map +1 -1
- package/dist/boards/semantics.js +7 -1
- package/dist/boards/semantics.js.map +1 -1
- package/dist/factory.d.ts +10 -0
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +98 -41
- package/dist/factory.js.map +1 -1
- package/dist/integrations/github/issue-intake.d.ts +15 -0
- package/dist/integrations/github/issue-intake.d.ts.map +1 -0
- package/dist/integrations/github/issue-intake.js +50 -0
- package/dist/integrations/github/issue-intake.js.map +1 -0
- package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/github/issue-reconciler.js +10 -1
- package/dist/integrations/github/issue-reconciler.js.map +1 -1
- package/dist/integrations/github/rules.d.ts +2 -0
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +3 -0
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/platform/connect/routes.d.ts +43 -1
- package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
- package/dist/integrations/platform/connect/routes.js +82 -7
- package/dist/integrations/platform/connect/routes.js.map +1 -1
- package/dist/integrations/platform/connect/session-tools.d.ts +12 -0
- package/dist/integrations/platform/connect/session-tools.d.ts.map +1 -1
- package/dist/integrations/platform/connect/session-tools.js +28 -10
- package/dist/integrations/platform/connect/session-tools.js.map +1 -1
- package/dist/integrations/platform/vanta/integration.d.ts.map +1 -1
- package/dist/integrations/platform/vanta/integration.js +3 -3
- package/dist/integrations/platform/vanta/integration.js.map +1 -1
- package/dist/integrations/vanta/sync.d.ts +9 -0
- package/dist/integrations/vanta/sync.d.ts.map +1 -1
- package/dist/integrations/vanta/sync.js +10 -1
- package/dist/integrations/vanta/sync.js.map +1 -1
- package/dist/routes/board-snapshot.d.ts +5 -5
- package/dist/routes/board-snapshot.d.ts.map +1 -1
- package/dist/routes/board-snapshot.js +10 -14
- package/dist/routes/board-snapshot.js.map +1 -1
- package/dist/routes/config.d.ts +11 -2
- package/dist/routes/config.d.ts.map +1 -1
- package/dist/routes/config.js +242 -75
- package/dist/routes/config.js.map +1 -1
- package/dist/routes/contracts.d.ts +43 -14
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +27 -17
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/custom-endpoint-url.d.ts +8 -0
- package/dist/routes/custom-endpoint-url.d.ts.map +1 -0
- package/dist/routes/custom-endpoint-url.js +45 -0
- package/dist/routes/custom-endpoint-url.js.map +1 -0
- package/dist/routes/custom-provider-source.d.ts +24 -8
- package/dist/routes/custom-provider-source.d.ts.map +1 -1
- package/dist/routes/custom-provider-source.js +93 -43
- package/dist/routes/custom-provider-source.js.map +1 -1
- package/dist/routes/intake.d.ts +6 -0
- package/dist/routes/intake.d.ts.map +1 -1
- package/dist/routes/intake.js +20 -0
- package/dist/routes/intake.js.map +1 -1
- package/dist/routes/project-sessions.d.ts +15 -3
- package/dist/routes/project-sessions.d.ts.map +1 -1
- package/dist/routes/project-sessions.js +56 -14
- package/dist/routes/project-sessions.js.map +1 -1
- package/dist/routes/projects.d.ts +6 -1
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +19 -3
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/provider-credentials.d.ts +10 -1
- package/dist/routes/provider-credentials.d.ts.map +1 -1
- package/dist/routes/provider-credentials.js +13 -16
- package/dist/routes/provider-credentials.js.map +1 -1
- package/dist/routes/session-rows.d.ts +1 -1
- package/dist/routes/session-rows.d.ts.map +1 -1
- package/dist/routes/session-rows.js +38 -42
- package/dist/routes/session-rows.js.map +1 -1
- package/dist/routes/source-control-sessions.d.ts.map +1 -1
- package/dist/routes/source-control-sessions.js +4 -4
- package/dist/routes/source-control-sessions.js.map +1 -1
- package/dist/routes/surface.d.ts +3 -0
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +20 -7
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/tenant-credentials.d.ts.map +1 -1
- package/dist/routes/tenant-credentials.js +4 -4
- package/dist/routes/tenant-credentials.js.map +1 -1
- package/dist/routes/work-items.d.ts +9 -3
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +39 -16
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/binding-context.d.ts +5 -0
- package/dist/rules/binding-context.d.ts.map +1 -1
- package/dist/rules/binding-context.js +51 -5
- package/dist/rules/binding-context.js.map +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +2 -1
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/start-coordinator.d.ts.map +1 -1
- package/dist/rules/start-coordinator.js +2 -7
- package/dist/rules/start-coordinator.js.map +1 -1
- package/dist/sandbox/session-retirement.d.ts +6 -0
- package/dist/sandbox/session-retirement.d.ts.map +1 -1
- package/dist/sandbox/session-retirement.js +17 -0
- package/dist/sandbox/session-retirement.js.map +1 -1
- package/dist/session/factory-session.d.ts.map +1 -1
- package/dist/session/factory-session.js +2 -1
- package/dist/session/factory-session.js.map +1 -1
- package/dist/session/live-sessions.d.ts +6 -1
- package/dist/session/live-sessions.d.ts.map +1 -1
- package/dist/session/live-sessions.js +4 -0
- package/dist/session/live-sessions.js.map +1 -1
- package/dist/session/run-audit.d.ts +1 -1
- package/dist/session/run-audit.d.ts.map +1 -1
- package/dist/session/run-audit.js.map +1 -1
- package/dist/session/session-row-status.d.ts +3 -3
- package/dist/session/session-row-status.js +4 -4
- package/dist/session/session-row-status.js.map +1 -1
- package/dist/session/session-row-view.d.ts +3 -4
- package/dist/session/session-row-view.d.ts.map +1 -1
- package/dist/session/session-row-view.js +14 -21
- package/dist/session/session-row-view.js.map +1 -1
- package/dist/session/session-rows.d.ts +22 -8
- package/dist/session/session-rows.d.ts.map +1 -1
- package/dist/session/session-rows.js +158 -83
- package/dist/session/session-rows.js.map +1 -1
- package/dist/session/session-unloader.d.ts +101 -0
- package/dist/session/session-unloader.d.ts.map +1 -0
- package/dist/session/session-unloader.js +278 -0
- package/dist/session/session-unloader.js.map +1 -0
- package/dist/session/work-item-repository.d.ts +5 -1
- package/dist/session/work-item-repository.d.ts.map +1 -1
- package/dist/session/work-item-repository.js +39 -15
- package/dist/session/work-item-repository.js.map +1 -1
- package/dist/session-list-changes.d.ts +9 -0
- package/dist/session-list-changes.d.ts.map +1 -0
- package/dist/session-list-changes.js +54 -0
- package/dist/session-list-changes.js.map +1 -0
- package/dist/storage/announced-lists.d.ts +14 -0
- package/dist/storage/announced-lists.d.ts.map +1 -0
- package/dist/storage/announced-lists.js +78 -0
- package/dist/storage/announced-lists.js.map +1 -0
- package/dist/storage/domains/boards/base.d.ts +1 -1
- package/dist/storage/domains/boards/base.d.ts.map +1 -1
- package/dist/storage/domains/boards/base.js +27 -9
- package/dist/storage/domains/boards/base.js.map +1 -1
- package/dist/storage/domains/custom-providers/base.d.ts +62 -19
- package/dist/storage/domains/custom-providers/base.d.ts.map +1 -1
- package/dist/storage/domains/custom-providers/base.js +131 -100
- package/dist/storage/domains/custom-providers/base.js.map +1 -1
- package/dist/storage/domains/intake/base.d.ts +25 -7
- package/dist/storage/domains/intake/base.d.ts.map +1 -1
- package/dist/storage/domains/intake/base.js +83 -19
- package/dist/storage/domains/intake/base.js.map +1 -1
- package/dist/storage/domains/source-control/base.d.ts +8 -0
- package/dist/storage/domains/source-control/base.d.ts.map +1 -1
- package/dist/storage/domains/source-control/base.js +110 -64
- package/dist/storage/domains/source-control/base.js.map +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts +4 -0
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/source-control/inmemory.js +8 -5
- package/dist/storage/domains/source-control/inmemory.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +9 -1
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +43 -11
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/tools/read-tools.d.ts +9 -2
- package/dist/tools/read-tools.d.ts.map +1 -1
- package/dist/tools/read-tools.js +57 -12
- package/dist/tools/read-tools.js.map +1 -1
- package/dist/tools/session-tools.d.ts +0 -13
- package/dist/tools/session-tools.d.ts.map +1 -1
- package/dist/tools/session-tools.js +127 -336
- package/dist/tools/session-tools.js.map +1 -1
- package/dist/tools/work-item-tools.d.ts.map +1 -1
- package/dist/tools/work-item-tools.js +91 -23
- package/dist/tools/work-item-tools.js.map +1 -1
- package/dist/work-items/card-reference.d.ts +21 -0
- package/dist/work-items/card-reference.d.ts.map +1 -0
- package/dist/work-items/card-reference.js +58 -0
- package/dist/work-items/card-reference.js.map +1 -0
- package/package.json +7 -7
- package/dist/storage/probed-list.d.ts +0 -11
- package/dist/storage/probed-list.d.ts.map +0 -1
- package/dist/storage/probed-list.js +0 -52
- package/dist/storage/probed-list.js.map +0 -1
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Why a hosted Factory refuses to call `url`, or `undefined` when it may.
|
|
3
|
+
* The server makes these calls, so a hosted one must not be pointed at its own
|
|
4
|
+
* network or the cloud metadata service. Local and self-hosted Factories keep
|
|
5
|
+
* reaching endpoints on their machine or network (Ollama, vLLM).
|
|
6
|
+
*/
|
|
7
|
+
export declare function customEndpointUrlProblem(url: string): string | undefined;
|
|
8
|
+
//# sourceMappingURL=custom-endpoint-url.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"custom-endpoint-url.d.ts","sourceRoot":"","sources":["../../src/routes/custom-endpoint-url.ts"],"names":[],"mappings":"AA8BA;;;;;GAKG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAiBxE"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { BlockList, isIP } from "net";
|
|
2
|
+
// src/routes/custom-endpoint-url.ts
|
|
3
|
+
const LOCAL_ADDRESSES = new BlockList();
|
|
4
|
+
for (const [address, prefix] of [
|
|
5
|
+
["0.0.0.0", 8],
|
|
6
|
+
["10.0.0.0", 8],
|
|
7
|
+
["100.64.0.0", 10],
|
|
8
|
+
["127.0.0.0", 8],
|
|
9
|
+
["169.254.0.0", 16],
|
|
10
|
+
["172.16.0.0", 12],
|
|
11
|
+
["192.168.0.0", 16]
|
|
12
|
+
]) LOCAL_ADDRESSES.addSubnet(address, prefix, "ipv4");
|
|
13
|
+
for (const [address, prefix] of [
|
|
14
|
+
["::", 128],
|
|
15
|
+
["::1", 128],
|
|
16
|
+
["fc00::", 7],
|
|
17
|
+
["fe80::", 10]
|
|
18
|
+
]) LOCAL_ADDRESSES.addSubnet(address, prefix, "ipv6");
|
|
19
|
+
const LOCAL_HOSTNAME = /(^|\.)(localhost|local|internal)$/;
|
|
20
|
+
/** The platform stamps every deploy with its id; a Factory run anywhere else has none. */
|
|
21
|
+
function hostedOnPlatform() {
|
|
22
|
+
return Boolean(process.env.MASTRA_DEPLOYMENT_ID?.trim());
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Why a hosted Factory refuses to call `url`, or `undefined` when it may.
|
|
26
|
+
* The server makes these calls, so a hosted one must not be pointed at its own
|
|
27
|
+
* network or the cloud metadata service. Local and self-hosted Factories keep
|
|
28
|
+
* reaching endpoints on their machine or network (Ollama, vLLM).
|
|
29
|
+
*/
|
|
30
|
+
function customEndpointUrlProblem(url) {
|
|
31
|
+
if (!hostedOnPlatform()) return void 0;
|
|
32
|
+
let parsed;
|
|
33
|
+
try {
|
|
34
|
+
parsed = new URL(url);
|
|
35
|
+
} catch {
|
|
36
|
+
return "Enter a valid URL.";
|
|
37
|
+
}
|
|
38
|
+
if (parsed.protocol !== "https:") return "Use an HTTPS address: a hosted Factory only calls custom endpoints over HTTPS.";
|
|
39
|
+
const host = parsed.hostname.replace(/^\[|\]$/g, "").toLowerCase();
|
|
40
|
+
const family = isIP(host);
|
|
41
|
+
if (family ? LOCAL_ADDRESSES.check(host, family === 6 ? "ipv6" : "ipv4") : LOCAL_HOSTNAME.test(host.replace(/\.$/, ""))) return "Use an address reachable over the internet, not a local or private network one.";
|
|
42
|
+
}
|
|
43
|
+
export { customEndpointUrlProblem };
|
|
44
|
+
|
|
45
|
+
//# sourceMappingURL=custom-endpoint-url.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"custom-endpoint-url.js","names":[],"sources":["../../src/routes/custom-endpoint-url.ts"],"sourcesContent":["import { BlockList, isIP } from 'node:net';\n\nconst LOCAL_ADDRESSES = new BlockList();\nfor (const [address, prefix] of [\n ['0.0.0.0', 8],\n ['10.0.0.0', 8],\n ['100.64.0.0', 10],\n ['127.0.0.0', 8],\n ['169.254.0.0', 16],\n ['172.16.0.0', 12],\n ['192.168.0.0', 16],\n] as const) {\n LOCAL_ADDRESSES.addSubnet(address, prefix, 'ipv4');\n}\nfor (const [address, prefix] of [\n ['::', 128],\n ['::1', 128],\n ['fc00::', 7],\n ['fe80::', 10],\n] as const) {\n LOCAL_ADDRESSES.addSubnet(address, prefix, 'ipv6');\n}\n\nconst LOCAL_HOSTNAME = /(^|\\.)(localhost|local|internal)$/;\n\n/** The platform stamps every deploy with its id; a Factory run anywhere else has none. */\nfunction hostedOnPlatform(): boolean {\n return Boolean(process.env.MASTRA_DEPLOYMENT_ID?.trim());\n}\n\n/**\n * Why a hosted Factory refuses to call `url`, or `undefined` when it may.\n * The server makes these calls, so a hosted one must not be pointed at its own\n * network or the cloud metadata service. Local and self-hosted Factories keep\n * reaching endpoints on their machine or network (Ollama, vLLM).\n */\nexport function customEndpointUrlProblem(url: string): string | undefined {\n if (!hostedOnPlatform()) return undefined;\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return 'Enter a valid URL.';\n }\n if (parsed.protocol !== 'https:')\n return 'Use an HTTPS address: a hosted Factory only calls custom endpoints over HTTPS.';\n const host = parsed.hostname.replace(/^\\[|\\]$/g, '').toLowerCase();\n const family = isIP(host);\n const local = family\n ? LOCAL_ADDRESSES.check(host, family === 6 ? 'ipv6' : 'ipv4')\n : LOCAL_HOSTNAME.test(host.replace(/\\.$/, ''));\n if (local) return 'Use an address reachable over the internet, not a local or private network one.';\n return undefined;\n}\n"],"mappings":";;AAEA,MAAM,kBAAkB,IAAI,UAAU;AACtC,KAAK,MAAM,CAAC,SAAS,WAAW;CAC9B,CAAC,WAAW,CAAC;CACb,CAAC,YAAY,CAAC;CACd,CAAC,cAAc,EAAE;CACjB,CAAC,aAAa,CAAC;CACf,CAAC,eAAe,EAAE;CAClB,CAAC,cAAc,EAAE;CACjB,CAAC,eAAe,EAAE;AACpB,GACE,gBAAgB,UAAU,SAAS,QAAQ,MAAM;AAEnD,KAAK,MAAM,CAAC,SAAS,WAAW;CAC9B,CAAC,MAAM,GAAG;CACV,CAAC,OAAO,GAAG;CACX,CAAC,UAAU,CAAC;CACZ,CAAC,UAAU,EAAE;AACf,GACE,gBAAgB,UAAU,SAAS,QAAQ,MAAM;AAGnD,MAAM,iBAAiB;;AAGvB,SAAS,mBAA4B;CACnC,OAAO,QAAQ,QAAQ,IAAI,sBAAsB,KAAK,CAAC;AACzD;;;;;;;AAQA,SAAgB,yBAAyB,KAAiC;CACxE,IAAI,CAAC,iBAAiB,GAAG,OAAO,KAAA;CAChC,IAAI;CACJ,IAAI;EACF,SAAS,IAAI,IAAI,GAAG;CACtB,QAAQ;EACN,OAAO;CACT;CACA,IAAI,OAAO,aAAa,UACtB,OAAO;CACT,MAAM,OAAO,OAAO,SAAS,QAAQ,YAAY,EAAE,CAAC,CAAC,YAAY;CACjE,MAAM,SAAS,KAAK,IAAI;CAIxB,IAHc,SACV,gBAAgB,MAAM,MAAM,WAAW,IAAI,SAAS,MAAM,IAC1D,eAAe,KAAK,KAAK,QAAQ,OAAO,EAAE,CAAC,GACpC,OAAO;AAEpB"}
|
|
@@ -5,21 +5,37 @@
|
|
|
5
5
|
* `CustomProvidersSource` synchronously, so this module keeps a small per-org
|
|
6
6
|
* **snapshot** of custom provider rows hydrated from the `custom-providers`
|
|
7
7
|
* domain. Once registered the source is authoritative — the factory never
|
|
8
|
-
* reads `settings.json` custom providers, in either auth mode
|
|
8
|
+
* reads `settings.json` custom providers, in either auth mode.
|
|
9
9
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
10
|
+
* Whose rows a call sees is decided in one place, {@link customProviderOwner},
|
|
11
|
+
* which the settings routes and model catalogs use too. Calls without an
|
|
12
|
+
* authenticated tenant in tenant mode (the boot-time catalog) resolve to an
|
|
13
|
+
* empty list.
|
|
14
14
|
*
|
|
15
15
|
* Snapshots are primed per request by `createCustomProvidersPrimer` (mounted
|
|
16
16
|
* after the web auth gate) and invalidated on writes via
|
|
17
17
|
* `invalidateCustomProvidersSnapshots` so changes are visible immediately.
|
|
18
18
|
*/
|
|
19
|
+
import type { CredentialScope } from '@mastra/code-sdk/agents/credential-resolver';
|
|
19
20
|
import type { RequestContext } from '@mastra/core/request-context';
|
|
20
21
|
import type { MiddlewareHandler } from 'hono';
|
|
21
|
-
import type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';
|
|
22
|
+
import type { CustomProviderOwner, CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';
|
|
22
23
|
import type { RouteAuth } from './route.js';
|
|
24
|
+
/**
|
|
25
|
+
* Whose custom providers apply to a tenant at a credential scope, or
|
|
26
|
+
* `undefined` to fail closed (tenant mode without identity). Model
|
|
27
|
+
* resolution, the settings routes and the model catalogs all decide through
|
|
28
|
+
* this function, so what a user sees in Settings is what their models use.
|
|
29
|
+
*
|
|
30
|
+
* Scoped exactly like provider credentials: Factory-scoped work uses the
|
|
31
|
+
* organization's list, personal work the account's own, and the two never
|
|
32
|
+
* mix. No-auth mode has one shared list.
|
|
33
|
+
*/
|
|
34
|
+
export declare function customProviderOwner(tenant: {
|
|
35
|
+
orgId?: string;
|
|
36
|
+
userId: string;
|
|
37
|
+
credentialScope?: CredentialScope;
|
|
38
|
+
} | undefined, authEnabled: boolean): CustomProviderOwner | undefined;
|
|
23
39
|
/**
|
|
24
40
|
* Register the DB-backed custom providers source with the SDK. Called by the
|
|
25
41
|
* factory after storage init with the `custom-providers` domain handle; from
|
|
@@ -31,8 +47,8 @@ export declare function registerCustomProvidersSource({ storage, authEnabled, }:
|
|
|
31
47
|
authEnabled: boolean;
|
|
32
48
|
}): void;
|
|
33
49
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
50
|
+
* After a custom provider write, reload the org's snapshot on its next read
|
|
51
|
+
* instead of after the TTL, so the change reaches the next request at once.
|
|
36
52
|
*/
|
|
37
53
|
export declare function invalidateCustomProvidersSnapshots(tenant: {
|
|
38
54
|
orgId: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom-provider-source.d.ts","sourceRoot":"","sources":["../../src/routes/custom-provider-source.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;
|
|
1
|
+
{"version":3,"file":"custom-provider-source.d.ts","sourceRoot":"","sources":["../../src/routes/custom-provider-source.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAGH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,6CAA6C,CAAC;AAGnF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAE9C,OAAO,KAAK,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,6CAA6C,CAAC;AAG/G,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAW5C;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,eAAe,CAAC,EAAE,eAAe,CAAA;CAAE,GAAG,SAAS,EACzF,WAAW,EAAE,OAAO,GACnB,mBAAmB,GAAG,SAAS,CAKjC;AAiGD;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAAC,EAC5C,OAAO,EACP,WAAW,GACZ,EAAE;IACD,OAAO,EAAE,sBAAsB,CAAC;IAChC,WAAW,EAAE,OAAO,CAAC;CACtB,GAAG,IAAI,CASP;AAED;;;GAGG;AACH,wBAAgB,kCAAkC,CAAC,MAAM,EAAE;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAElF;AAED,8DAA8D;AAC9D,wBAAgB,kCAAkC,IAAI,IAAI,CAIzD;AAED;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAAC,EAC1C,IAAI,EACJ,OAAO,EACP,WAAW,GACZ,EAAE;IACD,IAAI,EAAE,SAAS,CAAC;IAChB,OAAO,EAAE,sBAAsB,CAAC;IAChC,WAAW,EAAE,OAAO,CAAC;CACtB,GAAG,iBAAiB,CAYpB;AAED;;;;;GAKG;AACH,wBAAsB,qCAAqC,CAAC,cAAc,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CASzG"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { customEndpointUrlProblem } from "./custom-endpoint-url.js";
|
|
1
2
|
import { tenantOrgId } from "./provider-credentials.js";
|
|
2
3
|
import { resolveTenantFromRequestContext } from "@mastra/code-sdk/agents/credential-resolver";
|
|
3
4
|
import { setCustomProvidersSource } from "@mastra/code-sdk/agents/custom-provider-source";
|
|
@@ -9,12 +10,12 @@ import { setCustomProvidersSource } from "@mastra/code-sdk/agents/custom-provide
|
|
|
9
10
|
* `CustomProvidersSource` synchronously, so this module keeps a small per-org
|
|
10
11
|
* **snapshot** of custom provider rows hydrated from the `custom-providers`
|
|
11
12
|
* domain. Once registered the source is authoritative — the factory never
|
|
12
|
-
* reads `settings.json` custom providers, in either auth mode
|
|
13
|
+
* reads `settings.json` custom providers, in either auth mode.
|
|
13
14
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
15
|
+
* Whose rows a call sees is decided in one place, {@link customProviderOwner},
|
|
16
|
+
* which the settings routes and model catalogs use too. Calls without an
|
|
17
|
+
* authenticated tenant in tenant mode (the boot-time catalog) resolve to an
|
|
18
|
+
* empty list.
|
|
18
19
|
*
|
|
19
20
|
* Snapshots are primed per request by `createCustomProvidersPrimer` (mounted
|
|
20
21
|
* after the web auth gate) and invalidated on writes via
|
|
@@ -24,41 +25,94 @@ import { setCustomProvidersSource } from "@mastra/code-sdk/agents/custom-provide
|
|
|
24
25
|
const SNAPSHOT_TTL_MS = 15e3;
|
|
25
26
|
/** Cap on cached org snapshots; oldest-inserted evicted beyond this. */
|
|
26
27
|
const MAX_CACHED_ORGS = 1e3;
|
|
27
|
-
/** Sentinel org for no-auth mode
|
|
28
|
+
/** Sentinel org for no-auth mode. */
|
|
28
29
|
const LOCAL_ORG = "local";
|
|
30
|
+
/**
|
|
31
|
+
* Whose custom providers apply to a tenant at a credential scope, or
|
|
32
|
+
* `undefined` to fail closed (tenant mode without identity). Model
|
|
33
|
+
* resolution, the settings routes and the model catalogs all decide through
|
|
34
|
+
* this function, so what a user sees in Settings is what their models use.
|
|
35
|
+
*
|
|
36
|
+
* Scoped exactly like provider credentials: Factory-scoped work uses the
|
|
37
|
+
* organization's list, personal work the account's own, and the two never
|
|
38
|
+
* mix. No-auth mode has one shared list.
|
|
39
|
+
*/
|
|
40
|
+
function customProviderOwner(tenant, authEnabled) {
|
|
41
|
+
if (!authEnabled) return { orgId: LOCAL_ORG };
|
|
42
|
+
if (!tenant) return void 0;
|
|
43
|
+
const orgId = tenantOrgId(tenant);
|
|
44
|
+
return tenant.credentialScope === "factory" ? { orgId } : {
|
|
45
|
+
orgId,
|
|
46
|
+
userId: tenant.userId
|
|
47
|
+
};
|
|
48
|
+
}
|
|
29
49
|
var OrgCustomProvidersSnapshot = class {
|
|
30
50
|
#orgId;
|
|
31
51
|
#storage;
|
|
32
|
-
#
|
|
52
|
+
#organization = [];
|
|
53
|
+
#members = /* @__PURE__ */ new Map();
|
|
33
54
|
#fetchedAt = 0;
|
|
55
|
+
/** Bumped by every write, so a load that started before it can't count as fresh. */
|
|
56
|
+
#generation = 0;
|
|
34
57
|
#hydrating;
|
|
35
58
|
constructor(orgId, storage) {
|
|
36
59
|
this.#orgId = orgId;
|
|
37
60
|
this.#storage = storage;
|
|
38
61
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
if (now - this.#fetchedAt < SNAPSHOT_TTL_MS) return;
|
|
42
|
-
this.#hydrating ??= this.#hydrate().finally(() => {
|
|
43
|
-
this.#hydrating = void 0;
|
|
44
|
-
});
|
|
45
|
-
await this.#hydrating;
|
|
62
|
+
#isStale() {
|
|
63
|
+
return Date.now() - this.#fetchedAt >= SNAPSHOT_TTL_MS;
|
|
46
64
|
}
|
|
65
|
+
/**
|
|
66
|
+
* Hydrate the snapshot when stale; coalesces concurrent callers. Loads again
|
|
67
|
+
* if a write lands while a load is in flight, so callers never settle for
|
|
68
|
+
* rows read before that write.
|
|
69
|
+
*/
|
|
70
|
+
async ensureFresh() {
|
|
71
|
+
while (this.#isStale()) {
|
|
72
|
+
this.#hydrating ??= this.#hydrate().finally(() => {
|
|
73
|
+
this.#hydrating = void 0;
|
|
74
|
+
});
|
|
75
|
+
await this.#hydrating;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* After a write: load again on the next read, but keep serving the current
|
|
80
|
+
* rows meanwhile, so runs already using these providers don't lose them.
|
|
81
|
+
*/
|
|
82
|
+
markStale() {
|
|
83
|
+
this.#generation += 1;
|
|
84
|
+
this.#fetchedAt = 0;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Loads the organization's providers and every member's in one pass: a
|
|
88
|
+
* session can run as its owner while another member's request primed the
|
|
89
|
+
* snapshot, so any owner in the org must be servable without a second query.
|
|
90
|
+
*/
|
|
47
91
|
async #hydrate() {
|
|
92
|
+
const generation = this.#generation;
|
|
48
93
|
await this.#storage.ensureReady();
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
94
|
+
const organization = [];
|
|
95
|
+
const members = /* @__PURE__ */ new Map();
|
|
96
|
+
for (const record of await this.#storage.listForOrg(this.#orgId)) {
|
|
97
|
+
if (customEndpointUrlProblem(record.url)) continue;
|
|
98
|
+
const provider = {
|
|
99
|
+
name: record.name,
|
|
100
|
+
url: record.url,
|
|
101
|
+
apiKey: record.apiKey ?? void 0,
|
|
102
|
+
models: record.models
|
|
103
|
+
};
|
|
104
|
+
const owned = record.userId === null ? organization : members.get(record.userId) ?? [];
|
|
105
|
+
owned.push(provider);
|
|
106
|
+
if (record.userId !== null) members.set(record.userId, owned);
|
|
107
|
+
}
|
|
108
|
+
this.#organization = organization;
|
|
109
|
+
this.#members = members;
|
|
110
|
+
if (generation === this.#generation) this.#fetchedAt = Date.now();
|
|
57
111
|
}
|
|
58
112
|
/** Sync by contract; kicks a background re-hydrate when the snapshot is stale. */
|
|
59
|
-
get() {
|
|
60
|
-
if (
|
|
61
|
-
return this.#
|
|
113
|
+
get(owner) {
|
|
114
|
+
if (this.#isStale()) this.ensureFresh().catch(() => {});
|
|
115
|
+
return owner.userId === void 0 ? this.#organization : this.#members.get(owner.userId) ?? [];
|
|
62
116
|
}
|
|
63
117
|
};
|
|
64
118
|
const orgSnapshots = /* @__PURE__ */ new Map();
|
|
@@ -75,11 +129,6 @@ function snapshotFor(orgId, storage) {
|
|
|
75
129
|
}
|
|
76
130
|
return snapshot;
|
|
77
131
|
}
|
|
78
|
-
/** The org a call resolves to, or `undefined` to fail closed (tenant mode without identity). */
|
|
79
|
-
function orgForTenant(tenant, authEnabled) {
|
|
80
|
-
if (!authEnabled) return LOCAL_ORG;
|
|
81
|
-
return tenant ? tenantOrgId(tenant) : void 0;
|
|
82
|
-
}
|
|
83
132
|
/**
|
|
84
133
|
* Register the DB-backed custom providers source with the SDK. Called by the
|
|
85
134
|
* factory after storage init with the `custom-providers` domain handle; from
|
|
@@ -91,18 +140,19 @@ function registerCustomProvidersSource({ storage, authEnabled }) {
|
|
|
91
140
|
storage,
|
|
92
141
|
authEnabled
|
|
93
142
|
};
|
|
143
|
+
orgSnapshots.clear();
|
|
94
144
|
setCustomProvidersSource((tenant) => {
|
|
95
|
-
const
|
|
96
|
-
if (!
|
|
97
|
-
return snapshotFor(orgId, storage).get();
|
|
145
|
+
const owner = customProviderOwner(tenant, authEnabled);
|
|
146
|
+
if (!owner) return [];
|
|
147
|
+
return snapshotFor(owner.orgId, storage).get(owner);
|
|
98
148
|
});
|
|
99
149
|
}
|
|
100
150
|
/**
|
|
101
|
-
*
|
|
102
|
-
*
|
|
151
|
+
* After a custom provider write, reload the org's snapshot on its next read
|
|
152
|
+
* instead of after the TTL, so the change reaches the next request at once.
|
|
103
153
|
*/
|
|
104
154
|
function invalidateCustomProvidersSnapshots(tenant) {
|
|
105
|
-
orgSnapshots.
|
|
155
|
+
orgSnapshots.get(tenant.orgId)?.markStale();
|
|
106
156
|
}
|
|
107
157
|
/** Test hook: clear registration and cached org snapshots. */
|
|
108
158
|
function resetCustomProvidersSourceForTests() {
|
|
@@ -118,9 +168,9 @@ function resetCustomProvidersSourceForTests() {
|
|
|
118
168
|
*/
|
|
119
169
|
function createCustomProvidersPrimer({ auth, storage, authEnabled }) {
|
|
120
170
|
return async (c, next) => {
|
|
121
|
-
const
|
|
122
|
-
if (
|
|
123
|
-
await snapshotFor(orgId, storage).ensureFresh();
|
|
171
|
+
const owner = customProviderOwner(auth.tenant(c), authEnabled);
|
|
172
|
+
if (owner) try {
|
|
173
|
+
await snapshotFor(owner.orgId, storage).ensureFresh();
|
|
124
174
|
} catch {}
|
|
125
175
|
await next();
|
|
126
176
|
};
|
|
@@ -133,12 +183,12 @@ function createCustomProvidersPrimer({ auth, storage, authEnabled }) {
|
|
|
133
183
|
*/
|
|
134
184
|
async function primeCustomProvidersForRequestContext(requestContext) {
|
|
135
185
|
if (!registered) return;
|
|
136
|
-
const
|
|
137
|
-
if (!
|
|
186
|
+
const owner = customProviderOwner(resolveTenantFromRequestContext(requestContext), registered.authEnabled);
|
|
187
|
+
if (!owner) return;
|
|
138
188
|
try {
|
|
139
|
-
await snapshotFor(orgId, registered.storage).ensureFresh();
|
|
189
|
+
await snapshotFor(owner.orgId, registered.storage).ensureFresh();
|
|
140
190
|
} catch {}
|
|
141
191
|
}
|
|
142
|
-
export { createCustomProvidersPrimer, invalidateCustomProvidersSnapshots, primeCustomProvidersForRequestContext, registerCustomProvidersSource, resetCustomProvidersSourceForTests };
|
|
192
|
+
export { createCustomProvidersPrimer, customProviderOwner, invalidateCustomProvidersSnapshots, primeCustomProvidersForRequestContext, registerCustomProvidersSource, resetCustomProvidersSourceForTests };
|
|
143
193
|
|
|
144
194
|
//# sourceMappingURL=custom-provider-source.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom-provider-source.js","names":[],"sources":["../../src/routes/custom-provider-source.ts"],"sourcesContent":["/**\n * DB-backed custom providers source for model resolution (factory mode).\n *\n * The SDK's `resolveModel` and gateway catalog ask the registered\n * `CustomProvidersSource` synchronously, so this module keeps a small per-org\n * **snapshot** of custom provider rows hydrated from the `custom-providers`\n * domain. Once registered the source is authoritative — the factory never\n * reads `settings.json` custom providers, in either auth mode:\n *\n * - tenant mode: rows are scoped per org (`tenantOrgId`); calls without an\n * authenticated tenant (boot-time catalog) resolve to an empty list.\n * - no-auth/local mode: rows live under the sentinel `local` org, matching the\n * custom provider routes.\n *\n * Snapshots are primed per request by `createCustomProvidersPrimer` (mounted\n * after the web auth gate) and invalidated on writes via\n * `invalidateCustomProvidersSnapshots` so changes are visible immediately.\n */\n\nimport { resolveTenantFromRequestContext } from '@mastra/code-sdk/agents/credential-resolver';\nimport { setCustomProvidersSource } from '@mastra/code-sdk/agents/custom-provider-source';\nimport type { MastraCodeCustomProvider } from '@mastra/code-sdk/agents/mastracode-gateway';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MiddlewareHandler } from 'hono';\n\nimport type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport { tenantOrgId } from './provider-credentials.js';\nimport type { RouteAuth } from './route.js';\n\n/** How long a hydrated snapshot is considered fresh. */\nconst SNAPSHOT_TTL_MS = 15_000;\n\n/** Cap on cached org snapshots; oldest-inserted evicted beyond this. */\nconst MAX_CACHED_ORGS = 1000;\n\n/** Sentinel org for no-auth mode — must match the custom provider routes. */\nconst LOCAL_ORG = 'local';\n\nclass OrgCustomProvidersSnapshot {\n readonly #orgId: string;\n readonly #storage: CustomProvidersStorage;\n #snapshot: MastraCodeCustomProvider[] = [];\n #fetchedAt = 0;\n #hydrating: Promise<void> | undefined;\n\n constructor(orgId: string, storage: CustomProvidersStorage) {\n this.#orgId = orgId;\n this.#storage = storage;\n }\n\n /** Hydrate the snapshot when stale; coalesces concurrent callers. */\n async ensureFresh(now = Date.now()): Promise<void> {\n if (now - this.#fetchedAt < SNAPSHOT_TTL_MS) return;\n this.#hydrating ??= this.#hydrate().finally(() => {\n this.#hydrating = undefined;\n });\n await this.#hydrating;\n }\n\n async #hydrate(): Promise<void> {\n await this.#storage.ensureReady();\n const records = await this.#storage.list({ orgId: this.#orgId });\n this.#snapshot = records.map(record => ({\n name: record.name,\n url: record.url,\n apiKey: record.apiKey ?? undefined,\n models: record.models,\n }));\n this.#fetchedAt = Date.now();\n }\n\n /** Sync by contract; kicks a background re-hydrate when the snapshot is stale. */\n get(): MastraCodeCustomProvider[] {\n if (Date.now() - this.#fetchedAt >= SNAPSHOT_TTL_MS) {\n void this.ensureFresh().catch(() => {});\n }\n return this.#snapshot;\n }\n}\n\nconst orgSnapshots = new Map<string, OrgCustomProvidersSnapshot>();\n\nlet registered: { storage: CustomProvidersStorage; authEnabled: boolean } | undefined;\n\nfunction snapshotFor(orgId: string, storage: CustomProvidersStorage): OrgCustomProvidersSnapshot {\n let snapshot = orgSnapshots.get(orgId);\n if (!snapshot) {\n if (orgSnapshots.size >= MAX_CACHED_ORGS) {\n const oldest = orgSnapshots.keys().next().value;\n if (oldest !== undefined) orgSnapshots.delete(oldest);\n }\n snapshot = new OrgCustomProvidersSnapshot(orgId, storage);\n orgSnapshots.set(orgId, snapshot);\n }\n return snapshot;\n}\n\n/** The org a call resolves to, or `undefined` to fail closed (tenant mode without identity). */\nfunction orgForTenant(\n tenant: { orgId?: string; userId: string } | undefined,\n authEnabled: boolean,\n): string | undefined {\n if (!authEnabled) return LOCAL_ORG;\n return tenant ? tenantOrgId(tenant) : undefined;\n}\n\n/**\n * Register the DB-backed custom providers source with the SDK. Called by the\n * factory after storage init with the `custom-providers` domain handle; from\n * then on model resolution and the gateway catalog never read settings.json\n * custom providers.\n */\nexport function registerCustomProvidersSource({\n storage,\n authEnabled,\n}: {\n storage: CustomProvidersStorage;\n authEnabled: boolean;\n}): void {\n registered = { storage, authEnabled };\n setCustomProvidersSource(tenant => {\n const orgId = orgForTenant(tenant, authEnabled);\n if (!orgId) return [];\n return snapshotFor(orgId, storage).get();\n });\n}\n\n/**\n * Drop the org's cached snapshot after a custom provider write so the change\n * is visible to the next model call immediately instead of after the TTL.\n */\nexport function invalidateCustomProvidersSnapshots(tenant: { orgId: string }): void {\n orgSnapshots.delete(tenant.orgId);\n}\n\n/** Test hook: clear registration and cached org snapshots. */\nexport function resetCustomProvidersSourceForTests(): void {\n setCustomProvidersSource(undefined);\n registered = undefined;\n orgSnapshots.clear();\n}\n\n/**\n * Middleware mounted after the web auth gate: primes the caller's org snapshot\n * so the request's first model call sees their custom providers without an\n * async seam in model resolution. Cheap when fresh (TTL check), best-effort\n * when not — a failed hydrate serves the last snapshot, never blocks a request.\n */\nexport function createCustomProvidersPrimer({\n auth,\n storage,\n authEnabled,\n}: {\n auth: RouteAuth;\n storage: CustomProvidersStorage;\n authEnabled: boolean;\n}): MiddlewareHandler {\n return async (c, next) => {\n const orgId = orgForTenant(auth.tenant(c), authEnabled);\n if (orgId) {\n try {\n await snapshotFor(orgId, storage).ensureFresh();\n } catch {\n // Fail open: model calls serve the last snapshot (or none).\n }\n }\n await next();\n };\n}\n\n/**\n * Prime the org snapshot for a run that has no inbound request (a notification\n * or peer-signal wake), so its first model call can resolve a custom-provider\n * model. Best-effort like the request primer: a failed hydrate serves the last\n * snapshot.\n */\nexport async function primeCustomProvidersForRequestContext(requestContext: RequestContext): Promise<void> {\n if (!registered) return;\n const orgId = orgForTenant(resolveTenantFromRequestContext(requestContext), registered.authEnabled);\n if (!orgId) return;\n try {\n await snapshotFor(orgId, registered.storage).ensureFresh();\n } catch {\n // Fail open: model calls serve the last snapshot (or none).\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAM,kBAAkB;;AAGxB,MAAM,kBAAkB;;AAGxB,MAAM,YAAY;AAElB,IAAM,6BAAN,MAAiC;CAC/B;CACA;CACA,YAAwC,CAAC;CACzC,aAAa;CACb;CAEA,YAAY,OAAe,SAAiC;EAC1D,KAAK,SAAS;EACd,KAAK,WAAW;CAClB;;CAGA,MAAM,YAAY,MAAM,KAAK,IAAI,GAAkB;EACjD,IAAI,MAAM,KAAK,aAAa,iBAAiB;EAC7C,KAAK,eAAe,KAAK,SAAS,CAAC,CAAC,cAAc;GAChD,KAAK,aAAa,KAAA;EACpB,CAAC;EACD,MAAM,KAAK;CACb;CAEA,MAAM,WAA0B;EAC9B,MAAM,KAAK,SAAS,YAAY;EAChC,MAAM,UAAU,MAAM,KAAK,SAAS,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC;EAC/D,KAAK,YAAY,QAAQ,KAAI,YAAW;GACtC,MAAM,OAAO;GACb,KAAK,OAAO;GACZ,QAAQ,OAAO,UAAU,KAAA;GACzB,QAAQ,OAAO;EACjB,EAAE;EACF,KAAK,aAAa,KAAK,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AAY;EAChD,QAAQ,CAER;EAEF,MAAM,KAAK;CACb;AACF;;;;;;;AAQA,eAAsB,sCAAsC,gBAA+C;CACzG,IAAI,CAAC,YAAY;CACjB,MAAM,QAAQ,aAAa,gCAAgC,cAAc,GAAG,WAAW,WAAW;CAClG,IAAI,CAAC,OAAO;CACZ,IAAI;EACF,MAAM,YAAY,OAAO,WAAW,OAAO,CAAC,CAAC,YAAY;CAC3D,QAAQ,CAER;AACF"}
|
|
1
|
+
{"version":3,"file":"custom-provider-source.js","names":[],"sources":["../../src/routes/custom-provider-source.ts"],"sourcesContent":["/**\n * DB-backed custom providers source for model resolution (factory mode).\n *\n * The SDK's `resolveModel` and gateway catalog ask the registered\n * `CustomProvidersSource` synchronously, so this module keeps a small per-org\n * **snapshot** of custom provider rows hydrated from the `custom-providers`\n * domain. Once registered the source is authoritative — the factory never\n * reads `settings.json` custom providers, in either auth mode.\n *\n * Whose rows a call sees is decided in one place, {@link customProviderOwner},\n * which the settings routes and model catalogs use too. Calls without an\n * authenticated tenant in tenant mode (the boot-time catalog) resolve to an\n * empty list.\n *\n * Snapshots are primed per request by `createCustomProvidersPrimer` (mounted\n * after the web auth gate) and invalidated on writes via\n * `invalidateCustomProvidersSnapshots` so changes are visible immediately.\n */\n\nimport { resolveTenantFromRequestContext } from '@mastra/code-sdk/agents/credential-resolver';\nimport type { CredentialScope } from '@mastra/code-sdk/agents/credential-resolver';\nimport { setCustomProvidersSource } from '@mastra/code-sdk/agents/custom-provider-source';\nimport type { MastraCodeCustomProvider } from '@mastra/code-sdk/agents/mastracode-gateway';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MiddlewareHandler } from 'hono';\n\nimport type { CustomProviderOwner, CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport { customEndpointUrlProblem } from './custom-endpoint-url.js';\nimport { tenantOrgId } from './provider-credentials.js';\nimport type { RouteAuth } from './route.js';\n\n/** How long a hydrated snapshot is considered fresh. */\nconst SNAPSHOT_TTL_MS = 15_000;\n\n/** Cap on cached org snapshots; oldest-inserted evicted beyond this. */\nconst MAX_CACHED_ORGS = 1000;\n\n/** Sentinel org for no-auth mode. */\nconst LOCAL_ORG = 'local';\n\n/**\n * Whose custom providers apply to a tenant at a credential scope, or\n * `undefined` to fail closed (tenant mode without identity). Model\n * resolution, the settings routes and the model catalogs all decide through\n * this function, so what a user sees in Settings is what their models use.\n *\n * Scoped exactly like provider credentials: Factory-scoped work uses the\n * organization's list, personal work the account's own, and the two never\n * mix. No-auth mode has one shared list.\n */\nexport function customProviderOwner(\n tenant: { orgId?: string; userId: string; credentialScope?: CredentialScope } | undefined,\n authEnabled: boolean,\n): CustomProviderOwner | undefined {\n if (!authEnabled) return { orgId: LOCAL_ORG };\n if (!tenant) return undefined;\n const orgId = tenantOrgId(tenant);\n return tenant.credentialScope === 'factory' ? { orgId } : { orgId, userId: tenant.userId };\n}\n\nclass OrgCustomProvidersSnapshot {\n readonly #orgId: string;\n readonly #storage: CustomProvidersStorage;\n #organization: MastraCodeCustomProvider[] = [];\n #members = new Map<string, MastraCodeCustomProvider[]>();\n #fetchedAt = 0;\n /** Bumped by every write, so a load that started before it can't count as fresh. */\n #generation = 0;\n #hydrating: Promise<void> | undefined;\n\n constructor(orgId: string, storage: CustomProvidersStorage) {\n this.#orgId = orgId;\n this.#storage = storage;\n }\n\n #isStale(): boolean {\n return Date.now() - this.#fetchedAt >= SNAPSHOT_TTL_MS;\n }\n\n /**\n * Hydrate the snapshot when stale; coalesces concurrent callers. Loads again\n * if a write lands while a load is in flight, so callers never settle for\n * rows read before that write.\n */\n async ensureFresh(): Promise<void> {\n while (this.#isStale()) {\n this.#hydrating ??= this.#hydrate().finally(() => {\n this.#hydrating = undefined;\n });\n await this.#hydrating;\n }\n }\n\n /**\n * After a write: load again on the next read, but keep serving the current\n * rows meanwhile, so runs already using these providers don't lose them.\n */\n markStale(): void {\n this.#generation += 1;\n this.#fetchedAt = 0;\n }\n\n /**\n * Loads the organization's providers and every member's in one pass: a\n * session can run as its owner while another member's request primed the\n * snapshot, so any owner in the org must be servable without a second query.\n */\n async #hydrate(): Promise<void> {\n const generation = this.#generation;\n await this.#storage.ensureReady();\n const organization: MastraCodeCustomProvider[] = [];\n const members = new Map<string, MastraCodeCustomProvider[]>();\n for (const record of await this.#storage.listForOrg(this.#orgId)) {\n if (customEndpointUrlProblem(record.url)) continue;\n const provider: MastraCodeCustomProvider = {\n name: record.name,\n url: record.url,\n apiKey: record.apiKey ?? undefined,\n models: record.models,\n };\n const owned = record.userId === null ? organization : (members.get(record.userId) ?? []);\n owned.push(provider);\n if (record.userId !== null) members.set(record.userId, owned);\n }\n this.#organization = organization;\n this.#members = members;\n if (generation === this.#generation) this.#fetchedAt = Date.now();\n }\n\n /** Sync by contract; kicks a background re-hydrate when the snapshot is stale. */\n get(owner: CustomProviderOwner): MastraCodeCustomProvider[] {\n if (this.#isStale()) {\n void this.ensureFresh().catch(() => {});\n }\n return owner.userId === undefined ? this.#organization : (this.#members.get(owner.userId) ?? []);\n }\n}\n\nconst orgSnapshots = new Map<string, OrgCustomProvidersSnapshot>();\n\nlet registered: { storage: CustomProvidersStorage; authEnabled: boolean } | undefined;\n\nfunction snapshotFor(orgId: string, storage: CustomProvidersStorage): OrgCustomProvidersSnapshot {\n let snapshot = orgSnapshots.get(orgId);\n if (!snapshot) {\n if (orgSnapshots.size >= MAX_CACHED_ORGS) {\n const oldest = orgSnapshots.keys().next().value;\n if (oldest !== undefined) orgSnapshots.delete(oldest);\n }\n snapshot = new OrgCustomProvidersSnapshot(orgId, storage);\n orgSnapshots.set(orgId, snapshot);\n }\n return snapshot;\n}\n\n/**\n * Register the DB-backed custom providers source with the SDK. Called by the\n * factory after storage init with the `custom-providers` domain handle; from\n * then on model resolution and the gateway catalog never read settings.json\n * custom providers.\n */\nexport function registerCustomProvidersSource({\n storage,\n authEnabled,\n}: {\n storage: CustomProvidersStorage;\n authEnabled: boolean;\n}): void {\n registered = { storage, authEnabled };\n // Snapshots read the storage they were created with.\n orgSnapshots.clear();\n setCustomProvidersSource(tenant => {\n const owner = customProviderOwner(tenant, authEnabled);\n if (!owner) return [];\n return snapshotFor(owner.orgId, storage).get(owner);\n });\n}\n\n/**\n * After a custom provider write, reload the org's snapshot on its next read\n * instead of after the TTL, so the change reaches the next request at once.\n */\nexport function invalidateCustomProvidersSnapshots(tenant: { orgId: string }): void {\n orgSnapshots.get(tenant.orgId)?.markStale();\n}\n\n/** Test hook: clear registration and cached org snapshots. */\nexport function resetCustomProvidersSourceForTests(): void {\n setCustomProvidersSource(undefined);\n registered = undefined;\n orgSnapshots.clear();\n}\n\n/**\n * Middleware mounted after the web auth gate: primes the caller's org snapshot\n * so the request's first model call sees their custom providers without an\n * async seam in model resolution. Cheap when fresh (TTL check), best-effort\n * when not — a failed hydrate serves the last snapshot, never blocks a request.\n */\nexport function createCustomProvidersPrimer({\n auth,\n storage,\n authEnabled,\n}: {\n auth: RouteAuth;\n storage: CustomProvidersStorage;\n authEnabled: boolean;\n}): MiddlewareHandler {\n return async (c, next) => {\n const owner = customProviderOwner(auth.tenant(c), authEnabled);\n if (owner) {\n try {\n await snapshotFor(owner.orgId, storage).ensureFresh();\n } catch {\n // Fail open: model calls serve the last snapshot (or none).\n }\n }\n await next();\n };\n}\n\n/**\n * Prime the org snapshot for a run that has no inbound request (a notification\n * or peer-signal wake), so its first model call can resolve a custom-provider\n * model. Best-effort like the request primer: a failed hydrate serves the last\n * snapshot.\n */\nexport async function primeCustomProvidersForRequestContext(requestContext: RequestContext): Promise<void> {\n if (!registered) return;\n const owner = customProviderOwner(resolveTenantFromRequestContext(requestContext), registered.authEnabled);\n if (!owner) return;\n try {\n await snapshotFor(owner.orgId, registered.storage).ensureFresh();\n } catch {\n // Fail open: model calls serve the last snapshot (or none).\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAM,kBAAkB;;AAGxB,MAAM,kBAAkB;;AAGxB,MAAM,YAAY;;;;;;;;;;;AAYlB,SAAg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K,OAAO,CAAC,GAAG,WAAW;EAC7D,IAAI,OACF,IAAI;GACF,MAAM,YAAY,MAAM,OAAO,OAAO,CAAC,CAAC,YAAY;EACtD,QAAQ,CAER;EAEF,MAAM,KAAK;CACb;AACF;;;;;;;AAQA,eAAsB,sCAAsC,gBAA+C;CACzG,IAAI,CAAC,YAAY;CACjB,MAAM,QAAQ,oBAAoB,gCAAgC,cAAc,GAAG,WAAW,WAAW;CACzG,IAAI,CAAC,OAAO;CACZ,IAAI;EACF,MAAM,YAAY,MAAM,OAAO,WAAW,OAAO,CAAC,CAAC,YAAY;CACjE,QAAQ,CAER;AACF"}
|
package/dist/routes/intake.d.ts
CHANGED
|
@@ -21,6 +21,12 @@ export interface IntakeRoutesDeps extends RouteDependencies {
|
|
|
21
21
|
}): Promise<unknown | null>;
|
|
22
22
|
};
|
|
23
23
|
integrations?: IntakeIntegration[];
|
|
24
|
+
/** Sources newly selected by a config save, so their existing items can be brought in. */
|
|
25
|
+
onSourcesSelected?: (args: {
|
|
26
|
+
orgId: string;
|
|
27
|
+
integrationId: string;
|
|
28
|
+
sourceIds: string[];
|
|
29
|
+
}) => void;
|
|
24
30
|
}
|
|
25
31
|
/** One integration that failed while the rest of the aggregation succeeded. */
|
|
26
32
|
export interface IntakeIntegrationFailure {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intake.d.ts","sourceRoot":"","sources":["../../src/routes/intake.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,MAAM,EAAc,MAAM,2BAA2B,CAAC;AACpE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AAEvE,OAAO,KAAK,EAAyB,YAAY,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAC5G,OAAO,KAAK,EAAE,iBAAiB,EAAE,MA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,iBAAiB;IACzD,KAAK,EAAE,YAAY,CAAC;IACpB,sCAAsC;IACtC,MAAM,EAAE,aAAa,CAAC;IACtB,uEAAuE;IACvE,QAAQ,CAAC,EAAE;QAAE,GAAG,CAAC,KAAK,EAAE;YAAE,KAAK,EAAE,MAAM,CAAC;YAAC,EAAE,EAAE,MAAM,CAAA;SAAE,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAAA;KAAE,CAAC;IAClF,YAAY,CAAC,EAAE,iBAAiB,EAAE,CAAC;IACnC,0FAA0F;IAC1F,iBAAiB,CAAC,EAAE,CAAC,IAAI,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,aAAa,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,EAAE,CAAA;KAAE,KAAK,IAAI,CAAC;CACnG;AAED,+EAA+E;AAC/E,MAAM,WAAW,wBAAwB;IACvC,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,EAAE,MAAM,CAAC;CACjB;AAuED,QAAA,MAAM,iBAAiB;;;;;iBAOrB,CAAC;AACH,KAAK,aAAa,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAExD,iEAAiE;AACjE,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,OAAO,GAAG,aAAa,GAAG,IAAI,CAGtE;AA4CD,+EAA+E;AAC/E,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,OAAO,GAAG,YAAY,GAAG,IAAI,CAqCpE;AAmBD,qBAAa,YAAa,SAAQ,KAAK,CAAC,gBAAgB,CAAC;;IAgBvD,MAAM,IAAI,QAAQ,EAAE,CA2SnB;CACF"}
|
package/dist/routes/intake.js
CHANGED
|
@@ -4,6 +4,9 @@ import { registerApiRoute } from "@mastra/core/server";
|
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
// src/routes/intake.ts
|
|
6
6
|
const PROVIDER_READ_TIMEOUT_MS = 15e3;
|
|
7
|
+
function syncedSourceIds(selection) {
|
|
8
|
+
return selection?.enabled ? selection.sourceIds ?? [] : [];
|
|
9
|
+
}
|
|
7
10
|
/** The Intake contract takes no abort signal, so a slow read is abandoned, not cancelled. */
|
|
8
11
|
function withTimeout(integrationId, read, timeoutMs = PROVIDER_READ_TIMEOUT_MS) {
|
|
9
12
|
return new Promise((resolve, reject) => {
|
|
@@ -176,10 +179,27 @@ var IntakeRoutes = class extends Route {
|
|
|
176
179
|
if (selection.enabled || selection.sourceIds?.length) return c.json({ error: "invalid_config" }, 400);
|
|
177
180
|
}
|
|
178
181
|
await intake.ensureReady();
|
|
182
|
+
const before = await intake.getConfig({
|
|
183
|
+
orgId: tenant.orgId,
|
|
184
|
+
integrationIds
|
|
185
|
+
});
|
|
179
186
|
await intake.mergeConfig({
|
|
180
187
|
orgId: tenant.orgId,
|
|
181
188
|
config: registeredConfig
|
|
182
189
|
});
|
|
190
|
+
const after = await intake.getConfig({
|
|
191
|
+
orgId: tenant.orgId,
|
|
192
|
+
integrationIds
|
|
193
|
+
});
|
|
194
|
+
for (const integrationId of Object.keys(registeredConfig)) {
|
|
195
|
+
const synced = new Set(syncedSourceIds(before[integrationId]));
|
|
196
|
+
const added = syncedSourceIds(after[integrationId]).filter((sourceId) => !synced.has(sourceId));
|
|
197
|
+
if (added.length > 0) this.deps.onSourcesSelected?.({
|
|
198
|
+
orgId: tenant.orgId,
|
|
199
|
+
integrationId,
|
|
200
|
+
sourceIds: added
|
|
201
|
+
});
|
|
202
|
+
}
|
|
183
203
|
await audit.emit({
|
|
184
204
|
context: loose(c),
|
|
185
205
|
input: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intake.js","names":[],"sources":["../../src/routes/intake.ts"],"sourcesContent":["import type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\nimport { z } from 'zod';\n\nimport type { Intake, IntakeItem } from '../capabilities/intake.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.js';\nimport { FactoryProjectNotFoundError, normalizeBindingLabels } from '../storage/domains/intake/base.js';\nimport type { IntakeBindingConflict, IntakeConfig, IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { RouteDependencies } from './route.js';\nimport { loose, Route } from './route.js';\n\nexport interface IntakeIntegration {\n id: string;\n intake: Pick<Intake, 'listSources' | 'listItems' | 'bindingLabelFilters'>;\n}\n\ninterface AggregatedIntakeItem extends Omit<IntakeItem, 'source'> {\n integrationId: string;\n externalSource: {\n integrationId: string;\n type: string;\n externalId: string;\n url?: string;\n };\n}\n\nexport interface IntakeRoutesDeps extends RouteDependencies {\n audit: AuditEmitter;\n /** Intake selection domain handle. */\n intake: IntakeStorage;\n /** Factory project domain handle, used to validate binding targets. */\n projects?: { get(input: { orgId: string; id: string }): Promise<unknown | null> };\n integrations?: IntakeIntegration[];\n}\n\n/** One integration that failed while the rest of the aggregation succeeded. */\nexport interface IntakeIntegrationFailure {\n integrationId: string;\n message: string;\n}\n\ntype SettledIntegration<T> = { integrationId: string; value: T } | IntakeIntegrationFailure;\n\nconst PROVIDER_READ_TIMEOUT_MS = 15_000;\n\n/** The Intake contract takes no abort signal, so a slow read is abandoned, not cancelled. */\nfunction withTimeout<T>(\n integrationId: string,\n read: () => Promise<T>,\n timeoutMs: number = PROVIDER_READ_TIMEOUT_MS,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n const budget = Math.max(0, timeoutMs);\n const timer = setTimeout(\n () => reject(new Error(`${integrationId} did not answer within ${Math.round(budget / 1000)}s`)),\n budget,\n );\n read()\n .then(resolve, reject)\n .finally(() => clearTimeout(timer));\n });\n}\n\n/**\n * Read every integration concurrently and isolate the ones that throw or hang, so a single\n * unreachable provider degrades to a per-source error instead of failing the listing.\n */\nasync function settleByIntegration<T>(\n requests: Array<{ integrationId: string; read: () => Promise<T> }>,\n): Promise<{ pages: Array<{ integrationId: string; value: T }>; failures: IntakeIntegrationFailure[] }> {\n const settled = await Promise.all(\n requests.map(async ({ integrationId, read }): Promise<SettledIntegration<T>> => {\n try {\n return { integrationId, value: await withTimeout(integrationId, read) };\n } catch (error) {\n console.error(`[factory] intake integration ${integrationId} is unavailable:`, error);\n return { integrationId, message: error instanceof Error ? error.message : String(error) };\n }\n }),\n );\n const pages: Array<{ integrationId: string; value: T }> = [];\n const failures: IntakeIntegrationFailure[] = [];\n for (const entry of settled) {\n if ('value' in entry) pages.push(entry);\n else failures.push(entry);\n }\n return { pages, failures };\n}\n\nconst MAX_INTAKE_SOURCE_ID_LENGTH = 1024;\n\nconst identifier = z.string().min(1).max(256);\nconst sourceIdentifier = z.string().min(1).max(MAX_INTAKE_SOURCE_ID_LENGTH);\n\n/** Labels a shared binding takes; `[]` is rejected because \"all issues\" is spelled `null`. Jira labels never hold spaces. */\nconst bindingLabelsSchema = z\n .array(\n z\n .string()\n .max(255)\n .refine(label => !/\\s/.test(label.trim()), 'labels cannot contain spaces'),\n )\n .max(50)\n .transform(normalizeBindingLabels)\n .refine(labels => labels.length > 0, 'labels must name at least one label; use null for all issues');\n\nconst bindingBodySchema = z.object({\n integrationId: identifier,\n sourceId: sourceIdentifier,\n /** `null` unbinds the source (integrations without label filters only). */\n factoryProjectId: identifier.nullable(),\n /** Label filter for integrations with `bindingLabelFilters`; `null` takes all issues, omitted keeps the current filter. */\n labels: bindingLabelsSchema.nullable().optional(),\n});\ntype ParsedBinding = z.output<typeof bindingBodySchema>;\n\n/** Validate a binding request body, rejecting unknown shapes. */\nexport function parseIntakeBinding(body: unknown): ParsedBinding | null {\n const parsed = bindingBodySchema.safeParse(body);\n return parsed.success ? parsed.data : null;\n}\n\nconst bindingDeleteQuerySchema = z.object({\n integrationId: identifier,\n sourceId: sourceIdentifier,\n factoryProjectId: identifier,\n});\n\nfunction bindingConflictMessage(conflicts: readonly IntakeBindingConflict[]): string {\n const labels = conflicts.flatMap(conflict => conflict.labels ?? []);\n return labels.length > 0\n ? `Already routed to another factory: ${labels.join(', ')}.`\n : 'Another factory already takes all issues from this source.';\n}\n\nfunction sanitizeIdList(value: unknown): string[] | null | undefined {\n if (value === null) return null;\n if (!Array.isArray(value) || value.length > 200) return undefined;\n const ids = value.filter(\n (item): item is string => typeof item === 'string' && item.length > 0 && item.length <= MAX_INTAKE_SOURCE_ID_LENGTH,\n );\n return ids.length === value.length && new Set(ids).size === ids.length ? ids : undefined;\n}\n\nfunction sanitizeLinearRepositoryMap(value: unknown): Record<string, string> | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n const entries = Object.entries(value);\n if (entries.length > 200) return undefined;\n const mapping: Record<string, string> = Object.create(null);\n for (const [projectId, slug] of entries) {\n if (\n !projectId ||\n projectId.length > MAX_INTAKE_SOURCE_ID_LENGTH ||\n typeof slug !== 'string' ||\n !slug.trim() ||\n slug.length > 512\n ) {\n return undefined;\n }\n mapping[projectId] = slug;\n }\n return mapping;\n}\n\n/** Validate a request body into an intake config, rejecting unknown shapes. */\nexport function parseIntakeConfig(body: unknown): IntakeConfig | null {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) return null;\n const entries = Object.entries(body);\n if (entries.length > 50) return null;\n\n // Null-prototype so an `__proto__` key lands as a real entry instead of silently\n // reassigning the prototype and disappearing from the validation below.\n const config: IntakeConfig = Object.create(null);\n for (const [integrationId, value] of entries) {\n if (\n !integrationId ||\n integrationId.length > 128 ||\n typeof value !== 'object' ||\n value === null ||\n Array.isArray(value)\n ) {\n return null;\n }\n const selection = value as { enabled?: unknown; sourceIds?: unknown; repositoryByLinearProject?: unknown };\n if (typeof selection.enabled !== 'boolean') return null;\n const sourceIds = sanitizeIdList(selection.sourceIds ?? null);\n if (sourceIds === undefined) return null;\n const repositoryByLinearProject =\n integrationId === 'linear' ? sanitizeLinearRepositoryMap(selection.repositoryByLinearProject) : undefined;\n if (\n integrationId === 'linear' &&\n selection.repositoryByLinearProject !== undefined &&\n repositoryByLinearProject === undefined\n )\n return null;\n config[integrationId] = {\n enabled: selection.enabled,\n sourceIds,\n ...(repositoryByLinearProject ? { repositoryByLinearProject } : {}),\n };\n }\n return config;\n}\n\nfunction encodeCursor(cursors: Record<string, string>): string | null {\n return Object.keys(cursors).length > 0 ? Buffer.from(JSON.stringify(cursors)).toString('base64url') : null;\n}\n\nfunction decodeCursor(value: string | undefined): Record<string, string> | null {\n if (!value) return {};\n try {\n const parsed = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) as unknown;\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null;\n const entries = Object.entries(parsed);\n if (entries.some(([key, cursor]) => !key || typeof cursor !== 'string')) return null;\n return Object.fromEntries(entries) as Record<string, string>;\n } catch {\n return null;\n }\n}\n\nexport class IntakeRoutes extends Route<IntakeRoutesDeps> {\n async #resolveTenant(c: Context): Promise<{ orgId: string; userId: string } | { response: Response }> {\n await this.deps.auth.ensureUser(c);\n const tenant = this.deps.auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n { error: 'organization_required', message: 'Intake configuration requires an organization.' },\n 403,\n ),\n };\n }\n return { orgId: tenant.orgId, userId: tenant.userId };\n }\n\n routes(): ApiRoute[] {\n const { audit, intake, projects, integrations = [] } = this.deps;\n const integrationIds = integrations.map(integration => integration.id);\n\n return [\n registerApiRoute('/web/intake/config', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: tenant.orgId, integrationIds });\n return c.json({ config });\n },\n }),\n registerApiRoute('/web/intake/config', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n\n let body: unknown;\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const config = parseIntakeConfig(body);\n if (!config) {\n return c.json({ error: 'invalid_config' }, 400);\n }\n\n const registeredConfig: IntakeConfig = Object.create(null);\n for (const [integrationId, selection] of Object.entries(config)) {\n if (integrationIds.includes(integrationId)) {\n registeredConfig[integrationId] = selection;\n continue;\n }\n if (selection.enabled || selection.sourceIds?.length) {\n return c.json({ error: 'invalid_config' }, 400);\n }\n }\n\n await intake.ensureReady();\n await intake.mergeConfig({ orgId: tenant.orgId, config: registeredConfig });\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.intake.config_updated',\n targets: [{ type: 'intake_config', id: tenant.orgId }],\n metadata: Object.fromEntries(\n Object.entries(registeredConfig).map(([integrationId, selection]) => [\n integrationId,\n { enabled: selection.enabled, sources: selection.sourceIds?.length ?? null },\n ]),\n ),\n },\n });\n return c.json({ config: await intake.getConfig({ orgId: tenant.orgId, integrationIds }) });\n },\n }),\n registerApiRoute('/web/intake/bindings', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n await intake.ensureReady();\n return c.json({ bindings: await intake.listBindings({ orgId: tenant.orgId }) });\n },\n }),\n registerApiRoute('/web/intake/bindings', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n\n let body: unknown;\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const binding = parseIntakeBinding(body);\n if (!binding || !integrationIds.includes(binding.integrationId)) {\n return c.json({ error: 'invalid_binding' }, 400);\n }\n const integration = integrations.find(candidate => candidate.id === binding.integrationId);\n // Sources of label-filtering integrations feed several Factory projects at once.\n const shared = integration?.intake.bindingLabelFilters === true;\n if (!shared && binding.labels) {\n return c.json(\n { error: 'invalid_binding', message: `${binding.integrationId} bindings do not support label filters.` },\n 400,\n );\n }\n if (shared && binding.factoryProjectId === null) {\n return c.json(\n {\n error: 'use_delete',\n message:\n \"Remove one factory's binding with DELETE /web/intake/bindings?integrationId=…&sourceId=…&factoryProjectId=….\",\n },\n 400,\n );\n }\n if (binding.factoryProjectId && projects) {\n const project = await projects.get({ orgId: tenant.orgId, id: binding.factoryProjectId });\n if (!project) return c.json({ error: 'factory_project_not_found' }, 404);\n }\n\n await intake.ensureReady();\n let auditFactoryProjectId = binding.factoryProjectId;\n let labels: string[] | null = null;\n if (binding.factoryProjectId === null) {\n const previousBinding = await intake.clearBinding({\n orgId: tenant.orgId,\n integrationId: binding.integrationId,\n sourceId: binding.sourceId,\n });\n auditFactoryProjectId = previousBinding?.factoryProjectId ?? null;\n } else {\n const previousBinding = await intake.getBinding({\n orgId: tenant.orgId,\n integrationId: binding.integrationId,\n sourceId: binding.sourceId,\n ...(shared ? { factoryProjectId: binding.factoryProjectId } : {}),\n });\n const target = {\n orgId: tenant.orgId,\n userId: tenant.userId,\n integrationId: binding.integrationId,\n sourceId: binding.sourceId,\n factoryProjectId: binding.factoryProjectId,\n };\n try {\n if (shared) {\n // Omitted labels keep the filter, so a save that doesn't name labels never widens what the binding takes.\n labels = binding.labels === undefined ? (previousBinding?.labels ?? null) : binding.labels;\n const { conflicts } = await intake.setSharedBinding({ ...target, labels });\n if (conflicts.length > 0) {\n return c.json(\n { error: 'binding_conflict', message: bindingConflictMessage(conflicts), conflicts },\n 409,\n );\n }\n } else {\n await intake.setBinding(target);\n }\n } catch (error) {\n if (error instanceof FactoryProjectNotFoundError) {\n return c.json({ error: 'factory_project_not_found' }, 404);\n }\n throw error;\n }\n }\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.intake.binding_updated',\n ...(auditFactoryProjectId ? { factoryProjectId: auditFactoryProjectId } : {}),\n targets: [{ type: 'intake_source', id: `${binding.integrationId}:${binding.sourceId}` }],\n metadata: { factoryProjectId: binding.factoryProjectId, labels },\n },\n });\n return c.json({ bindings: await intake.listBindings({ orgId: tenant.orgId }) });\n },\n }),\n // Removes exactly one Factory project's binding, so a shared source keeps feeding the others.\n // Identifiers travel in the query string because some clients and proxies drop DELETE bodies.\n registerApiRoute('/web/intake/bindings', {\n method: 'DELETE',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n\n const parsed = bindingDeleteQuerySchema.safeParse({\n integrationId: c.req.query('integrationId'),\n sourceId: c.req.query('sourceId'),\n factoryProjectId: c.req.query('factoryProjectId'),\n });\n if (!parsed.success || !integrationIds.includes(parsed.data.integrationId)) {\n return c.json({ error: 'invalid_binding' }, 400);\n }\n const binding = parsed.data;\n\n await intake.ensureReady();\n const removed = await intake.clearBinding({ orgId: tenant.orgId, ...binding });\n if (!removed) return c.json({ error: 'binding_not_found' }, 404);\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.intake.binding_updated',\n factoryProjectId: removed.factoryProjectId,\n targets: [{ type: 'intake_source', id: `${binding.integrationId}:${binding.sourceId}` }],\n metadata: { factoryProjectId: null, labels: null },\n },\n });\n return c.json({ bindings: await intake.listBindings({ orgId: tenant.orgId }) });\n },\n }),\n // Label routes are gone: a project's intake routes decide where its cards land.\n ...(['GET', 'PUT'] as const).map(method =>\n registerApiRoute('/web/intake/label-routes', {\n method,\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n return c.json(\n {\n error: 'label_routes_removed',\n message:\n \"Label routes were removed. Add an intake route on the project instead: POST /web/factory/projects/:id/intake-routes with a condition on 'item.labels'.\",\n },\n 410,\n );\n },\n }),\n ),\n registerApiRoute('/web/intake/sources', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n const requested = c.req.query('integrationId');\n const { pages, failures } = await settleByIntegration(\n (requested ? integrations.filter(integration => integration.id === requested) : integrations).map(\n integration => ({\n integrationId: integration.id,\n read: () => integration.intake.listSources(tenant),\n }),\n ),\n );\n return c.json({\n sources: pages.flatMap(({ integrationId, value }) => value.map(source => ({ integrationId, ...source }))),\n failures,\n });\n },\n }),\n registerApiRoute('/web/intake/items', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n const cursors = decodeCursor(c.req.query('cursor'));\n if (!cursors) return c.json({ error: 'invalid_cursor' }, 400);\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: tenant.orgId, integrationIds });\n const { pages, failures } = await settleByIntegration(\n integrations.flatMap(integration => {\n const selection = config[integration.id];\n if (!selection?.enabled || !selection.sourceIds?.length) return [];\n const sourceIds = selection.sourceIds;\n const cursor = cursors[integration.id];\n return [\n {\n integrationId: integration.id,\n read: () => integration.intake.listItems({ ...tenant, sourceIds, ...(cursor ? { cursor } : {}) }),\n },\n ];\n }),\n );\n\n const items: AggregatedIntakeItem[] = [];\n const nextCursors: Record<string, string> = {};\n for (const { integrationId, value } of pages) {\n items.push(\n ...value.items.map(item => {\n const { source, ...candidate } = item;\n return { ...candidate, integrationId, externalSource: { integrationId, ...source } };\n }),\n );\n if (value.nextCursor) nextCursors[integrationId] = value.nextCursor;\n }\n // Keep the cursor an unavailable integration came in with, so the next page resumes there instead of replaying it.\n for (const { integrationId } of failures) {\n const cursor = cursors[integrationId];\n if (cursor) nextCursors[integrationId] = cursor;\n }\n return c.json({ items, nextCursor: encodeCursor(nextCursors), failures });\n },\n }),\n ];\n }\n}\n"],"mappings":";;;;;AA4CA,MAAM,2BAA2B;;AAGjC,SAAS,YACP,eACA,MACA,YAAoB,0BACR;CACZ,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,SAAS,KAAK,IAAI,GAAG,SAAS;EACpC,MAAM,QAAQ,iBACN,uBAAO,IAAI,MAAM,GAAG,cAAc,yBAAyB,KAAK,MAAM,SAAS,GAAI,EAAE,EAAE,CAAC,GAC9F,MACF;EACA,KAAK,CAAC,CACH,KAAK,SAAS,MAAM,CAAC,CACrB,cAAc,aAAa,KAAK,CAAC;CACtC,CAAC;AACH;;;;;AAMA,eAAe,oBACb,UACsG;CAC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Q;MACvB,IAAI,QAAQ,YAAY,iBAAiB;KAC3C;KACA,OAAO,EAAE,KAAK;MAAE;MAAO,YAAY,aAAa,WAAW;MAAG;KAAS,CAAC;IAC1E;GACF,CAAC;EACH;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"intake.js","names":[],"sources":["../../src/routes/intake.ts"],"sourcesContent":["import type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\nimport { z } from 'zod';\n\nimport type { Intake, IntakeItem } from '../capabilities/intake.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.js';\nimport { FactoryProjectNotFoundError, normalizeBindingLabels } from '../storage/domains/intake/base.js';\nimport type { IntakeBindingConflict, IntakeConfig, IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { RouteDependencies } from './route.js';\nimport { loose, Route } from './route.js';\n\nexport interface IntakeIntegration {\n id: string;\n intake: Pick<Intake, 'listSources' | 'listItems' | 'bindingLabelFilters'>;\n}\n\ninterface AggregatedIntakeItem extends Omit<IntakeItem, 'source'> {\n integrationId: string;\n externalSource: {\n integrationId: string;\n type: string;\n externalId: string;\n url?: string;\n };\n}\n\nexport interface IntakeRoutesDeps extends RouteDependencies {\n audit: AuditEmitter;\n /** Intake selection domain handle. */\n intake: IntakeStorage;\n /** Factory project domain handle, used to validate binding targets. */\n projects?: { get(input: { orgId: string; id: string }): Promise<unknown | null> };\n integrations?: IntakeIntegration[];\n /** Sources newly selected by a config save, so their existing items can be brought in. */\n onSourcesSelected?: (args: { orgId: string; integrationId: string; sourceIds: string[] }) => void;\n}\n\n/** One integration that failed while the rest of the aggregation succeeded. */\nexport interface IntakeIntegrationFailure {\n integrationId: string;\n message: string;\n}\n\ntype SettledIntegration<T> = { integrationId: string; value: T } | IntakeIntegrationFailure;\n\nconst PROVIDER_READ_TIMEOUT_MS = 15_000;\n\nfunction syncedSourceIds(selection: { enabled: boolean; sourceIds: string[] | null } | undefined): string[] {\n return selection?.enabled ? (selection.sourceIds ?? []) : [];\n}\n\n/** The Intake contract takes no abort signal, so a slow read is abandoned, not cancelled. */\nfunction withTimeout<T>(\n integrationId: string,\n read: () => Promise<T>,\n timeoutMs: number = PROVIDER_READ_TIMEOUT_MS,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n const budget = Math.max(0, timeoutMs);\n const timer = setTimeout(\n () => reject(new Error(`${integrationId} did not answer within ${Math.round(budget / 1000)}s`)),\n budget,\n );\n read()\n .then(resolve, reject)\n .finally(() => clearTimeout(timer));\n });\n}\n\n/**\n * Read every integration concurrently and isolate the ones that throw or hang, so a single\n * unreachable provider degrades to a per-source error instead of failing the listing.\n */\nasync function settleByIntegration<T>(\n requests: Array<{ integrationId: string; read: () => Promise<T> }>,\n): Promise<{ pages: Array<{ integrationId: string; value: T }>; failures: IntakeIntegrationFailure[] }> {\n const settled = await Promise.all(\n requests.map(async ({ integrationId, read }): Promise<SettledIntegration<T>> => {\n try {\n return { integrationId, value: await withTimeout(integrationId, read) };\n } catch (error) {\n console.error(`[factory] intake integration ${integrationId} is unavailable:`, error);\n return { integrationId, message: error instanceof Error ? error.message : String(error) };\n }\n }),\n );\n const pages: Array<{ integrationId: string; value: T }> = [];\n const failures: IntakeIntegrationFailure[] = [];\n for (const entry of settled) {\n if ('value' in entry) pages.push(entry);\n else failures.push(entry);\n }\n return { pages, failures };\n}\n\nconst MAX_INTAKE_SOURCE_ID_LENGTH = 1024;\n\nconst identifier = z.string().min(1).max(256);\nconst sourceIdentifier = z.string().min(1).max(MAX_INTAKE_SOURCE_ID_LENGTH);\n\n/** Labels a shared binding takes; `[]` is rejected because \"all issues\" is spelled `null`. Jira labels never hold spaces. */\nconst bindingLabelsSchema = z\n .array(\n z\n .string()\n .max(255)\n .refine(label => !/\\s/.test(label.trim()), 'labels cannot contain spaces'),\n )\n .max(50)\n .transform(normalizeBindingLabels)\n .refine(labels => labels.length > 0, 'labels must name at least one label; use null for all issues');\n\nconst bindingBodySchema = z.object({\n integrationId: identifier,\n sourceId: sourceIdentifier,\n /** `null` unbinds the source (integrations without label filters only). */\n factoryProjectId: identifier.nullable(),\n /** Label filter for integrations with `bindingLabelFilters`; `null` takes all issues, omitted keeps the current filter. */\n labels: bindingLabelsSchema.nullable().optional(),\n});\ntype ParsedBinding = z.output<typeof bindingBodySchema>;\n\n/** Validate a binding request body, rejecting unknown shapes. */\nexport function parseIntakeBinding(body: unknown): ParsedBinding | null {\n const parsed = bindingBodySchema.safeParse(body);\n return parsed.success ? parsed.data : null;\n}\n\nconst bindingDeleteQuerySchema = z.object({\n integrationId: identifier,\n sourceId: sourceIdentifier,\n factoryProjectId: identifier,\n});\n\nfunction bindingConflictMessage(conflicts: readonly IntakeBindingConflict[]): string {\n const labels = conflicts.flatMap(conflict => conflict.labels ?? []);\n return labels.length > 0\n ? `Already routed to another factory: ${labels.join(', ')}.`\n : 'Another factory already takes all issues from this source.';\n}\n\nfunction sanitizeIdList(value: unknown): string[] | null | undefined {\n if (value === null) return null;\n if (!Array.isArray(value) || value.length > 200) return undefined;\n const ids = value.filter(\n (item): item is string => typeof item === 'string' && item.length > 0 && item.length <= MAX_INTAKE_SOURCE_ID_LENGTH,\n );\n return ids.length === value.length && new Set(ids).size === ids.length ? ids : undefined;\n}\n\nfunction sanitizeLinearRepositoryMap(value: unknown): Record<string, string> | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n const entries = Object.entries(value);\n if (entries.length > 200) return undefined;\n const mapping: Record<string, string> = Object.create(null);\n for (const [projectId, slug] of entries) {\n if (\n !projectId ||\n projectId.length > MAX_INTAKE_SOURCE_ID_LENGTH ||\n typeof slug !== 'string' ||\n !slug.trim() ||\n slug.length > 512\n ) {\n return undefined;\n }\n mapping[projectId] = slug;\n }\n return mapping;\n}\n\n/** Validate a request body into an intake config, rejecting unknown shapes. */\nexport function parseIntakeConfig(body: unknown): IntakeConfig | null {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) return null;\n const entries = Object.entries(body);\n if (entries.length > 50) return null;\n\n // Null-prototype so an `__proto__` key lands as a real entry instead of silently\n // reassigning the prototype and disappearing from the validation below.\n const config: IntakeConfig = Object.create(null);\n for (const [integrationId, value] of entries) {\n if (\n !integrationId ||\n integrationId.length > 128 ||\n typeof value !== 'object' ||\n value === null ||\n Array.isArray(value)\n ) {\n return null;\n }\n const selection = value as { enabled?: unknown; sourceIds?: unknown; repositoryByLinearProject?: unknown };\n if (typeof selection.enabled !== 'boolean') return null;\n const sourceIds = sanitizeIdList(selection.sourceIds ?? null);\n if (sourceIds === undefined) return null;\n const repositoryByLinearProject =\n integrationId === 'linear' ? sanitizeLinearRepositoryMap(selection.repositoryByLinearProject) : undefined;\n if (\n integrationId === 'linear' &&\n selection.repositoryByLinearProject !== undefined &&\n repositoryByLinearProject === undefined\n )\n return null;\n config[integrationId] = {\n enabled: selection.enabled,\n sourceIds,\n ...(repositoryByLinearProject ? { repositoryByLinearProject } : {}),\n };\n }\n return config;\n}\n\nfunction encodeCursor(cursors: Record<string, string>): string | null {\n return Object.keys(cursors).length > 0 ? Buffer.from(JSON.stringify(cursors)).toString('base64url') : null;\n}\n\nfunction decodeCursor(value: string | undefined): Record<string, string> | null {\n if (!value) return {};\n try {\n const parsed = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) as unknown;\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null;\n const entries = Object.entries(parsed);\n if (entries.some(([key, cursor]) => !key || typeof cursor !== 'string')) return null;\n return Object.fromEntries(entries) as Record<string, string>;\n } catch {\n return null;\n }\n}\n\nexport class IntakeRoutes extends Route<IntakeRoutesDeps> {\n async #resolveTenant(c: Context): Promise<{ orgId: string; userId: string } | { response: Response }> {\n await this.deps.auth.ensureUser(c);\n const tenant = this.deps.auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n { error: 'organization_required', message: 'Intake configuration requires an organization.' },\n 403,\n ),\n };\n }\n return { orgId: tenant.orgId, userId: tenant.userId };\n }\n\n routes(): ApiRoute[] {\n const { audit, intake, projects, integrations = [] } = this.deps;\n const integrationIds = integrations.map(integration => integration.id);\n\n return [\n registerApiRoute('/web/intake/config', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: tenant.orgId, integrationIds });\n return c.json({ config });\n },\n }),\n registerApiRoute('/web/intake/config', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n\n let body: unknown;\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const config = parseIntakeConfig(body);\n if (!config) {\n return c.json({ error: 'invalid_config' }, 400);\n }\n\n const registeredConfig: IntakeConfig = Object.create(null);\n for (const [integrationId, selection] of Object.entries(config)) {\n if (integrationIds.includes(integrationId)) {\n registeredConfig[integrationId] = selection;\n continue;\n }\n if (selection.enabled || selection.sourceIds?.length) {\n return c.json({ error: 'invalid_config' }, 400);\n }\n }\n\n await intake.ensureReady();\n const before = await intake.getConfig({ orgId: tenant.orgId, integrationIds });\n await intake.mergeConfig({ orgId: tenant.orgId, config: registeredConfig });\n const after = await intake.getConfig({ orgId: tenant.orgId, integrationIds });\n for (const integrationId of Object.keys(registeredConfig)) {\n const synced = new Set(syncedSourceIds(before[integrationId]));\n const added = syncedSourceIds(after[integrationId]).filter(sourceId => !synced.has(sourceId));\n if (added.length > 0)\n this.deps.onSourcesSelected?.({ orgId: tenant.orgId, integrationId, sourceIds: added });\n }\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.intake.config_updated',\n targets: [{ type: 'intake_config', id: tenant.orgId }],\n metadata: Object.fromEntries(\n Object.entries(registeredConfig).map(([integrationId, selection]) => [\n integrationId,\n { enabled: selection.enabled, sources: selection.sourceIds?.length ?? null },\n ]),\n ),\n },\n });\n return c.json({ config: await intake.getConfig({ orgId: tenant.orgId, integrationIds }) });\n },\n }),\n registerApiRoute('/web/intake/bindings', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n await intake.ensureReady();\n return c.json({ bindings: await intake.listBindings({ orgId: tenant.orgId }) });\n },\n }),\n registerApiRoute('/web/intake/bindings', {\n method: 'PUT',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n\n let body: unknown;\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: 'Invalid JSON body' }, 400);\n }\n const binding = parseIntakeBinding(body);\n if (!binding || !integrationIds.includes(binding.integrationId)) {\n return c.json({ error: 'invalid_binding' }, 400);\n }\n const integration = integrations.find(candidate => candidate.id === binding.integrationId);\n // Sources of label-filtering integrations feed several Factory projects at once.\n const shared = integration?.intake.bindingLabelFilters === true;\n if (!shared && binding.labels) {\n return c.json(\n { error: 'invalid_binding', message: `${binding.integrationId} bindings do not support label filters.` },\n 400,\n );\n }\n if (shared && binding.factoryProjectId === null) {\n return c.json(\n {\n error: 'use_delete',\n message:\n \"Remove one factory's binding with DELETE /web/intake/bindings?integrationId=…&sourceId=…&factoryProjectId=….\",\n },\n 400,\n );\n }\n if (binding.factoryProjectId && projects) {\n const project = await projects.get({ orgId: tenant.orgId, id: binding.factoryProjectId });\n if (!project) return c.json({ error: 'factory_project_not_found' }, 404);\n }\n\n await intake.ensureReady();\n let auditFactoryProjectId = binding.factoryProjectId;\n let labels: string[] | null = null;\n if (binding.factoryProjectId === null) {\n const previousBinding = await intake.clearBinding({\n orgId: tenant.orgId,\n integrationId: binding.integrationId,\n sourceId: binding.sourceId,\n });\n auditFactoryProjectId = previousBinding?.factoryProjectId ?? null;\n } else {\n const previousBinding = await intake.getBinding({\n orgId: tenant.orgId,\n integrationId: binding.integrationId,\n sourceId: binding.sourceId,\n ...(shared ? { factoryProjectId: binding.factoryProjectId } : {}),\n });\n const target = {\n orgId: tenant.orgId,\n userId: tenant.userId,\n integrationId: binding.integrationId,\n sourceId: binding.sourceId,\n factoryProjectId: binding.factoryProjectId,\n };\n try {\n if (shared) {\n // Omitted labels keep the filter, so a save that doesn't name labels never widens what the binding takes.\n labels = binding.labels === undefined ? (previousBinding?.labels ?? null) : binding.labels;\n const { conflicts } = await intake.setSharedBinding({ ...target, labels });\n if (conflicts.length > 0) {\n return c.json(\n { error: 'binding_conflict', message: bindingConflictMessage(conflicts), conflicts },\n 409,\n );\n }\n } else {\n await intake.setBinding(target);\n }\n } catch (error) {\n if (error instanceof FactoryProjectNotFoundError) {\n return c.json({ error: 'factory_project_not_found' }, 404);\n }\n throw error;\n }\n }\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.intake.binding_updated',\n ...(auditFactoryProjectId ? { factoryProjectId: auditFactoryProjectId } : {}),\n targets: [{ type: 'intake_source', id: `${binding.integrationId}:${binding.sourceId}` }],\n metadata: { factoryProjectId: binding.factoryProjectId, labels },\n },\n });\n return c.json({ bindings: await intake.listBindings({ orgId: tenant.orgId }) });\n },\n }),\n // Removes exactly one Factory project's binding, so a shared source keeps feeding the others.\n // Identifiers travel in the query string because some clients and proxies drop DELETE bodies.\n registerApiRoute('/web/intake/bindings', {\n method: 'DELETE',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n\n const parsed = bindingDeleteQuerySchema.safeParse({\n integrationId: c.req.query('integrationId'),\n sourceId: c.req.query('sourceId'),\n factoryProjectId: c.req.query('factoryProjectId'),\n });\n if (!parsed.success || !integrationIds.includes(parsed.data.integrationId)) {\n return c.json({ error: 'invalid_binding' }, 400);\n }\n const binding = parsed.data;\n\n await intake.ensureReady();\n const removed = await intake.clearBinding({ orgId: tenant.orgId, ...binding });\n if (!removed) return c.json({ error: 'binding_not_found' }, 404);\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.intake.binding_updated',\n factoryProjectId: removed.factoryProjectId,\n targets: [{ type: 'intake_source', id: `${binding.integrationId}:${binding.sourceId}` }],\n metadata: { factoryProjectId: null, labels: null },\n },\n });\n return c.json({ bindings: await intake.listBindings({ orgId: tenant.orgId }) });\n },\n }),\n // Label routes are gone: a project's intake routes decide where its cards land.\n ...(['GET', 'PUT'] as const).map(method =>\n registerApiRoute('/web/intake/label-routes', {\n method,\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n return c.json(\n {\n error: 'label_routes_removed',\n message:\n \"Label routes were removed. Add an intake route on the project instead: POST /web/factory/projects/:id/intake-routes with a condition on 'item.labels'.\",\n },\n 410,\n );\n },\n }),\n ),\n registerApiRoute('/web/intake/sources', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n const requested = c.req.query('integrationId');\n const { pages, failures } = await settleByIntegration(\n (requested ? integrations.filter(integration => integration.id === requested) : integrations).map(\n integration => ({\n integrationId: integration.id,\n read: () => integration.intake.listSources(tenant),\n }),\n ),\n );\n return c.json({\n sources: pages.flatMap(({ integrationId, value }) => value.map(source => ({ integrationId, ...source }))),\n failures,\n });\n },\n }),\n registerApiRoute('/web/intake/items', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n const cursors = decodeCursor(c.req.query('cursor'));\n if (!cursors) return c.json({ error: 'invalid_cursor' }, 400);\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: tenant.orgId, integrationIds });\n const { pages, failures } = await settleByIntegration(\n integrations.flatMap(integration => {\n const selection = config[integration.id];\n if (!selection?.enabled || !selection.sourceIds?.length) return [];\n const sourceIds = selection.sourceIds;\n const cursor = cursors[integration.id];\n return [\n {\n integrationId: integration.id,\n read: () => integration.intake.listItems({ ...tenant, sourceIds, ...(cursor ? { cursor } : {}) }),\n },\n ];\n }),\n );\n\n const items: AggregatedIntakeItem[] = [];\n const nextCursors: Record<string, string> = {};\n for (const { integrationId, value } of pages) {\n items.push(\n ...value.items.map(item => {\n const { source, ...candidate } = item;\n return { ...candidate, integrationId, externalSource: { integrationId, ...source } };\n }),\n );\n if (value.nextCursor) nextCursors[integrationId] = value.nextCursor;\n }\n // Keep the cursor an unavailable integration came in with, so the next page resumes there instead of replaying it.\n for (const { integrationId } of failures) {\n const cursor = cursors[integrationId];\n if (cursor) nextCursors[integrationId] = cursor;\n }\n return c.json({ items, nextCursor: encodeCursor(nextCursors), failures });\n },\n }),\n ];\n }\n}\n"],"mappings":";;;;;AA8CA,MAAM,2BAA2B;AAEjC,SAAS,gBAAgB,WAAmF;CAC1G,OAAO,WAAW,UAAW,UAAU,aAAa,CAAC,IAAK,CAAC;AAC7D;;AAGA,SAAS,YACP,eACA,MACA,YAAoB,0BACR;CACZ,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,SAAS,KAAK,IAAI,GAAG,SAAS;EACpC,MAAM,QAAQ,iBACN,uBAAO,IAAI,MAAM,GAAG,cAAc,yBAAyB,KAAK,MAAM,SAAS,GAAI,EAAE,EAAE,CAAC,GAC9F,MACF;EACA,KAAK,CAAC,CACH,KAAK,SAAS,MAAM,CAAC,CACrB,cAAc,aAAa,KAAK,CAAC;CACtC,CAAC;AACH;;;;;AAMA,eAAe,oBACb,UACsG;CACtG,MAAM,UAAU,MAAM,QAAQ,IAC5B,SAAS,IAAI,OAAO,EAAE,eAAe,WAA2C;EAC9E,IAAI;GACF,OAAO;IAAE;IAAe,OAAO,MAAM,YAAY,eAAe,IAAI;GAAE;EACxE,SAAS,OAAO;GACd,QAAQ,MAAM,gCAAgC,cAAc,mBAAmB,KAAK;GACpF,OAAO;IAAE;IAAe,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GAAE;EAC1F;CACF,CAAC,CACH;CACA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