@opengeni/db 2.0.1 → 2.0.2-canary.38789554071001

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/dist/attached-browser-devices.d.ts +21 -0
  2. package/dist/boot-connect.d.ts +16 -0
  3. package/dist/browser-sessions.d.ts +17 -0
  4. package/dist/canonical-human-identities.js +4 -4
  5. package/dist/capability-reconciliation.js +3 -3
  6. package/dist/{chunk-VQH2IP4E.js → chunk-2DV4KOMH.js} +9 -3
  7. package/dist/chunk-2DV4KOMH.js.map +1 -0
  8. package/dist/{chunk-I6HYVEFV.js → chunk-2GZRWV36.js} +2 -2
  9. package/dist/{chunk-VTH2TKNI.js → chunk-5TXWWAJP.js} +3 -3
  10. package/dist/{chunk-UWJCRJC5.js → chunk-6ZSZIMC7.js} +2 -2
  11. package/dist/{chunk-YS3D7KV5.js → chunk-77VCFW25.js} +2 -2
  12. package/dist/{chunk-5JRYRG7Z.js → chunk-BSRJZ6M5.js} +3 -3
  13. package/dist/{chunk-5HD6PLH4.js → chunk-EIYWCPZN.js} +2 -2
  14. package/dist/{chunk-PYBW3KGM.js → chunk-F4BP3GNU.js} +2 -2
  15. package/dist/{chunk-3VEDJM6S.js → chunk-F5JG7FDH.js} +43 -20
  16. package/dist/chunk-F5JG7FDH.js.map +1 -0
  17. package/dist/{chunk-DSTAGKBM.js → chunk-FBCKAXU5.js} +6 -6
  18. package/dist/{chunk-HFNTVT5I.js → chunk-GDMYQ55A.js} +25 -1
  19. package/dist/chunk-GDMYQ55A.js.map +1 -0
  20. package/dist/{chunk-HDIZTTOV.js → chunk-OUNXSEJQ.js} +3 -3
  21. package/dist/{chunk-3JHBH7LA.js → chunk-PGR5FMGQ.js} +5 -7
  22. package/dist/{chunk-3JHBH7LA.js.map → chunk-PGR5FMGQ.js.map} +1 -1
  23. package/dist/{chunk-GYQABR2L.js → chunk-Q5GMQEM6.js} +58 -45
  24. package/dist/chunk-Q5GMQEM6.js.map +1 -0
  25. package/dist/{chunk-IYUTXSFX.js → chunk-RK3MKIHK.js} +84 -8
  26. package/dist/chunk-RK3MKIHK.js.map +1 -0
  27. package/dist/{chunk-PGZ34T44.js → chunk-SMCA7PNJ.js} +16 -7
  28. package/dist/chunk-SMCA7PNJ.js.map +1 -0
  29. package/dist/{chunk-3CSN5YUS.js → chunk-TE7RZJPE.js} +43 -2
  30. package/dist/{chunk-3CSN5YUS.js.map → chunk-TE7RZJPE.js.map} +1 -1
  31. package/dist/{chunk-BR4TNIVA.js → chunk-TUQFQNUY.js} +3929 -3769
  32. package/dist/chunk-TUQFQNUY.js.map +1 -0
  33. package/dist/{chunk-7GORHVP2.js → chunk-YZM4S667.js} +4981 -2498
  34. package/dist/{chunk-7GORHVP2.js.map → chunk-YZM4S667.js.map} +1 -1
  35. package/dist/{chunk-Y5E2ZZ5Z.js → chunk-ZSDWWZU4.js} +19 -2
  36. package/dist/chunk-ZSDWWZU4.js.map +1 -0
  37. package/dist/computer-sessions.d.ts +4 -0
  38. package/dist/connect-attempts.js +4 -4
  39. package/dist/editable-artifact-durable-export.js +3 -3
  40. package/dist/editable-artifacts.d.ts +5 -0
  41. package/dist/editable-artifacts.js +6 -4
  42. package/dist/inbox-execution-context.d.ts +2 -2
  43. package/dist/index.d.ts +96 -1
  44. package/dist/index.js +227 -22
  45. package/dist/managed-auth-session-sets.js +4 -4
  46. package/dist/mcp-operations.js +3 -3
  47. package/dist/migrate.js +20 -21
  48. package/dist/organization-integration-policy.js +4 -4
  49. package/dist/provision-roles.js +2 -2
  50. package/dist/retained-provider-commands.js +7 -8
  51. package/dist/runtime-posture.d.ts +3 -3
  52. package/dist/schema.d.ts +14 -10
  53. package/dist/schema.js +1 -1
  54. package/dist/session-background-commands.d.ts +78 -0
  55. package/dist/session-background-commands.js +8 -6
  56. package/dist/session-command-output.d.ts +3 -0
  57. package/dist/session-command-output.js +10 -9
  58. package/dist/session-event-slices.js +4 -4
  59. package/dist/session-execution-policy.d.ts +55 -5
  60. package/dist/session-mcp-credential-rotation.js +7 -7
  61. package/dist/session-tenancy.js +7 -7
  62. package/dist/site-data-policy.d.ts +16 -0
  63. package/dist/site-data.d.ts +13 -2
  64. package/dist/site-platform.d.ts +138 -0
  65. package/dist/site-publishing.d.ts +682 -0
  66. package/dist/site-runtime-admission.d.ts +16 -0
  67. package/dist/site-sql.d.ts +140 -0
  68. package/dist/subscription-core/operations.d.ts +19 -2
  69. package/dist/subscription-core/turns.d.ts +6 -0
  70. package/dist/subscription-core-claude-adapter.d.ts +10 -0
  71. package/dist/subscription-core-claude-usage.d.ts +23 -1
  72. package/dist/{subscription-core-codex-XG2FNEPR.js → subscription-core-codex-OYICRF7V.js} +7 -7
  73. package/dist/{subscription-core-codex-compat-3NPCY6YG.js → subscription-core-codex-compat-USP5LONZ.js} +9 -9
  74. package/dist/subscription-core-codex.d.ts +1 -0
  75. package/dist/video-generation.js +4 -4
  76. package/dist/workspace-tool-defaults.js +6 -6
  77. package/drizzle/0782_published_sites.sql +431 -0
  78. package/drizzle/0783_site_sql.sql +148 -0
  79. package/drizzle/0784_message_fork_as_of_history.sql +266 -0
  80. package/drizzle/0785_editable_spreadsheet_ordered_operation_ids.sql +86 -0
  81. package/drizzle/0786_session_turns_finished_order_index.sql +5 -0
  82. package/drizzle/0787_session_system_updates_delivered_turn_index.sql +5 -0
  83. package/drizzle/0788_session_events_command_output_client_index.sql +5 -0
  84. package/drizzle/0790_site_limits_and_platform_usage.sql +137 -0
  85. package/drizzle/0791_site_limit_profiles_new_defaults.sql +10 -0
  86. package/drizzle/README.md +34 -0
  87. package/package.json +9 -9
  88. package/src/attached-browser-devices.ts +51 -0
  89. package/src/boot-connect.ts +34 -10
  90. package/src/browser-sessions.ts +119 -3
  91. package/src/computer-sessions.ts +25 -3
  92. package/src/connection-token-resolver.ts +8 -1
  93. package/src/editable-artifacts.ts +22 -0
  94. package/src/index.ts +111 -27
  95. package/src/runtime-posture.ts +41 -0
  96. package/src/schema.ts +30 -0
  97. package/src/session-background-commands.ts +43 -24
  98. package/src/session-command-output.ts +7 -1
  99. package/src/session-control.ts +5 -0
  100. package/src/session-execution-policy.ts +73 -43
  101. package/src/site-data-policy.ts +48 -0
  102. package/src/site-data.ts +80 -10
  103. package/src/site-platform.ts +511 -0
  104. package/src/site-publishing.ts +2750 -0
  105. package/src/site-runtime-admission.ts +40 -0
  106. package/src/site-sql.ts +546 -0
  107. package/src/subscription-core/administered-connections.ts +2 -3
  108. package/src/subscription-core/operation-connections.ts +16 -8
  109. package/src/subscription-core/operations.ts +87 -19
  110. package/src/subscription-core/personal-connections.ts +7 -7
  111. package/src/subscription-core/settlement.ts +1 -0
  112. package/src/subscription-core/turns.ts +55 -17
  113. package/src/subscription-core-claude-adapter.ts +63 -5
  114. package/src/subscription-core-claude-usage.ts +55 -0
  115. package/src/subscription-core-repository.ts +37 -1
  116. package/dist/chunk-3VEDJM6S.js.map +0 -1
  117. package/dist/chunk-BR4TNIVA.js.map +0 -1
  118. package/dist/chunk-FJNSQ3K3.js +0 -141
  119. package/dist/chunk-FJNSQ3K3.js.map +0 -1
  120. package/dist/chunk-GYQABR2L.js.map +0 -1
  121. package/dist/chunk-HFNTVT5I.js.map +0 -1
  122. package/dist/chunk-IYUTXSFX.js.map +0 -1
  123. package/dist/chunk-PGZ34T44.js.map +0 -1
  124. package/dist/chunk-VQH2IP4E.js.map +0 -1
  125. package/dist/chunk-Y5E2ZZ5Z.js.map +0 -1
  126. /package/dist/{chunk-I6HYVEFV.js.map → chunk-2GZRWV36.js.map} +0 -0
  127. /package/dist/{chunk-VTH2TKNI.js.map → chunk-5TXWWAJP.js.map} +0 -0
  128. /package/dist/{chunk-UWJCRJC5.js.map → chunk-6ZSZIMC7.js.map} +0 -0
  129. /package/dist/{chunk-YS3D7KV5.js.map → chunk-77VCFW25.js.map} +0 -0
  130. /package/dist/{chunk-5JRYRG7Z.js.map → chunk-BSRJZ6M5.js.map} +0 -0
  131. /package/dist/{chunk-5HD6PLH4.js.map → chunk-EIYWCPZN.js.map} +0 -0
  132. /package/dist/{chunk-PYBW3KGM.js.map → chunk-F4BP3GNU.js.map} +0 -0
  133. /package/dist/{chunk-DSTAGKBM.js.map → chunk-FBCKAXU5.js.map} +0 -0
  134. /package/dist/{chunk-HDIZTTOV.js.map → chunk-OUNXSEJQ.js.map} +0 -0
  135. /package/dist/{subscription-core-codex-XG2FNEPR.js.map → subscription-core-codex-OYICRF7V.js.map} +0 -0
  136. /package/dist/{subscription-core-codex-compat-3NPCY6YG.js.map → subscription-core-codex-compat-USP5LONZ.js.map} +0 -0
@@ -58,4 +58,25 @@ export declare function listAttachedBrowserDevices(db: Database, input: Attached
58
58
  export declare function getAttachedBrowserDevice(db: Database, input: AttachedBrowserViewer & {
59
59
  deviceId: string;
60
60
  }): Promise<AttachedBrowserDeviceValue>;
61
+ /** Where a browser or computer's controller runs, as far as ending it needs. */
62
+ export type InteractionControllerPlacement = {
63
+ kind: "connected_machine";
64
+ sandboxId: string;
65
+ } | {
66
+ kind: "attached_device";
67
+ deviceId: string;
68
+ } | {
69
+ kind: string;
70
+ };
71
+ /** True when a browser or computer's controller can never be reached again,
72
+ * so ending it completes in the control plane:
73
+ * - on a Connected Machine that was removed (revoked); that machine can no
74
+ * longer run or keep it;
75
+ * - in a person's own Chrome whose device is disconnected, or whose machine
76
+ * was removed. Such a session holds no Opengeni process or profile; the
77
+ * tabs it opened stay with the person as ordinary tabs.
78
+ * A machine that is only offline still holds its sessions' processes and
79
+ * private profiles, so it is not gone. Both checks go through the viewer's
80
+ * own owner-aware machine listing: a machine hidden from them is never gone. */
81
+ export declare function interactionControllerGone(db: Database, viewer: AttachedBrowserViewer, placement: InteractionControllerPlacement | null): Promise<boolean>;
61
82
  export {};
@@ -31,10 +31,18 @@ export type BootGraceSocketDependencies = {
31
31
  now?: () => number;
32
32
  sleep?: (ms: number) => Promise<void>;
33
33
  connect?: (endpoint: DatabaseConnectEndpoint, timeoutMs: number | null) => Promise<net.Socket>;
34
+ open?: (endpoint: DatabaseConnectEndpoint) => net.Socket;
34
35
  };
35
36
  export declare function isDatabaseBootTransientConnectError(error: unknown): boolean;
36
37
  /** Jittered delay before the next boot connect attempt: 100 ms doubling to 1 s. */
37
38
  export declare function databaseBootConnectRetryDelayMs(attempt: number, random?: () => number): number;
39
+ /**
40
+ * Starts connecting and returns the socket at once, like postgres.js's own
41
+ * connection path: a failure arrives as the socket's `error` and `close`
42
+ * events, which postgres.js handles by failing the waiting query and putting
43
+ * the connection back in its pool to reconnect later.
44
+ */
45
+ export declare function openDatabaseSocket(endpoint: DatabaseConnectEndpoint): net.Socket;
38
46
  /** Opens one connected socket, failing on the first socket error or timeout. */
39
47
  export declare function connectDatabaseSocket(endpoint: DatabaseConnectEndpoint, timeoutMs: number | null): Promise<net.Socket>;
40
48
  /**
@@ -44,6 +52,14 @@ export declare function connectDatabaseSocket(endpoint: DatabaseConnectEndpoint,
44
52
  * reached the server" state, so the grace ends at the first success or when the
45
53
  * window since client creation has elapsed, whichever comes first. Each attempt
46
54
  * keeps the client's own `connect_timeout`.
55
+ *
56
+ * The factory never rejects. postgres.js does not recover a pooled connection
57
+ * whose socket factory rejects: it fails the waiting query but never returns
58
+ * the connection to its pool, so after a database restart every connection
59
+ * leaked one by one and the client hung for good, even once the database was
60
+ * back. Outside the grace, and when the grace gives up, the factory instead
61
+ * returns a socket that is still connecting, so a failure reaches postgres.js
62
+ * as socket events and the connection reconnects like any other.
47
63
  */
48
64
  export declare function createBootGraceDatabaseSocket(dependencies?: BootGraceSocketDependencies): (target: DatabaseSocketTarget) => Promise<net.Socket>;
49
65
  /**
@@ -195,6 +195,10 @@ export declare function browserSessionCreateRequestDigest(input: PrepareBrowserS
195
195
  export declare function listBrowserSessions(db: Database, input: {
196
196
  accountId: string;
197
197
  workspaceId: string;
198
+ /** Only sessions with any association to this agent session. */
199
+ associatedSessionId?: string;
200
+ /** Defaults to true (complete history). */
201
+ includeTerminal?: boolean;
198
202
  }): Promise<BrowserSessionListResponseValue>;
199
203
  /** Managed browsers that may still have a live browser process on one
200
204
  * Connected Machine: every non-terminal browser except a saved one whose
@@ -404,6 +408,19 @@ export declare function settleExpiredBrowserSessionResume(db: Database, input: {
404
408
  browserSessionId: string;
405
409
  expectedControllerGeneration: string | null;
406
410
  }): Promise<boolean>;
411
+ /** Continue an expired resume on its retained controller generation after that
412
+ * controller re-adopted the generation's own working copy. The browser keeps
413
+ * its record, history and working profile; nothing is restored or discarded.
414
+ * The new resume operation completes on that generation, and the expired one
415
+ * stays settled as `outcome_unknown`. */
416
+ export declare function continueExpiredBrowserSessionResume(db: Database, input: {
417
+ accountId: string;
418
+ workspaceId: string;
419
+ browserSessionId: string;
420
+ operationId: string;
421
+ actorSubjectId: string;
422
+ controller: InteractionControllerBinding;
423
+ }): Promise<BrowserSessionMutationResponseValue>;
407
424
  export declare function failBrowserSessionSuspension(db: Database, input: {
408
425
  accountId: string;
409
426
  workspaceId: string;
@@ -11,10 +11,10 @@ import {
11
11
  getCanonicalHumanIdentityProjection,
12
12
  synchronizeCanonicalHumanLoginBindings,
13
13
  validateCanonicalHumanSession
14
- } from "./chunk-5HD6PLH4.js";
15
- import "./chunk-VTH2TKNI.js";
16
- import "./chunk-PGZ34T44.js";
17
- import "./chunk-HFNTVT5I.js";
14
+ } from "./chunk-EIYWCPZN.js";
15
+ import "./chunk-5TXWWAJP.js";
16
+ import "./chunk-SMCA7PNJ.js";
17
+ import "./chunk-GDMYQ55A.js";
18
18
  import "./chunk-PZ5AY32C.js";
19
19
  export {
20
20
  CanonicalHumanIdentityAuthorityError,
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  withWorkspaceRls
3
- } from "./chunk-VTH2TKNI.js";
4
- import "./chunk-PGZ34T44.js";
5
- import "./chunk-HFNTVT5I.js";
3
+ } from "./chunk-5TXWWAJP.js";
4
+ import "./chunk-SMCA7PNJ.js";
5
+ import "./chunk-GDMYQ55A.js";
6
6
  import "./chunk-PZ5AY32C.js";
7
7
 
8
8
  // src/capability-reconciliation.ts
@@ -1,10 +1,14 @@
1
1
  import {
2
2
  setSubjectRlsContext,
3
3
  withRlsContext
4
- } from "./chunk-VTH2TKNI.js";
4
+ } from "./chunk-5TXWWAJP.js";
5
5
 
6
6
  // src/connection-token-resolver.ts
7
- import { normalizeSlackScopes, OFFICIAL_SLACK_MCP_URL } from "@opengeni/contracts/slack-rest-mcp";
7
+ import {
8
+ isSlackPrivateFileUrl,
9
+ normalizeSlackScopes,
10
+ OFFICIAL_SLACK_MCP_URL
11
+ } from "@opengeni/contracts/slack-rest-mcp";
8
12
  import { beginMcpPhase, measureMcpPhase } from "@opengeni/observability";
9
13
  import {
10
14
  PERSONAL_GITHUB_REQUESTED_SCOPES,
@@ -532,6 +536,7 @@ function isOfficialSlackRestDestination(destinationUrl, ref) {
532
536
  if (ref.providerDomain.toLowerCase() !== "slack.com" || ref.kind !== "oauth2" || ref.subjectScope !== void 0 && ref.subjectScope !== "subject" && ref.subjectScope !== "workspace")
533
537
  return false;
534
538
  const url = new URL(destinationUrl);
539
+ if (isSlackPrivateFileUrl(url)) return true;
535
540
  return url.origin === "https://slack.com" && !url.username && !url.password && [
536
541
  "auth.test",
537
542
  "conversations.list",
@@ -541,6 +546,7 @@ function isOfficialSlackRestDestination(destinationUrl, ref) {
541
546
  "users.info",
542
547
  "conversations.history",
543
548
  "conversations.replies",
549
+ "files.info",
544
550
  "conversations.open",
545
551
  "chat.postMessage"
546
552
  ].some((method) => url.pathname === `/api/${method}`);
@@ -857,4 +863,4 @@ export {
857
863
  refreshOAuthConnectionCredential,
858
864
  isPrivateAddress
859
865
  };
860
- //# sourceMappingURL=chunk-VQH2IP4E.js.map
866
+ //# sourceMappingURL=chunk-2DV4KOMH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/connection-token-resolver.ts","../src/connection-refresh-lock.ts","../src/connection-scopes.ts"],"sourcesContent":["import {\n isSlackPrivateFileUrl,\n normalizeSlackScopes,\n OFFICIAL_SLACK_MCP_URL,\n} from \"@opengeni/contracts/slack-rest-mcp\";\nimport { beginMcpPhase, measureMcpPhase } from \"@opengeni/observability\";\nimport {\n environmentsEncryptionKeyBytes,\n type McpServerConnectionRef,\n type Settings,\n} from \"@opengeni/config\";\nimport type {\n ConnectionCredentialPlacement,\n ConnectionKind,\n ConnectionStatus,\n ConnectionMetadata,\n McpConnectionResourceScope,\n McpCredentialAuthNeededReason,\n} from \"@opengeni/contracts\";\n\nimport { type ConnectionUseAttribution } from \"@opengeni/contracts/connection-authority\";\nimport {\n PERSONAL_GITHUB_REQUESTED_SCOPES,\n PERSONAL_GITHUB_PROVIDER_DOMAIN,\n PERSONAL_GITHUB_TOKEN_URL,\n PersonalGitHubConnectionMetadata,\n} from \"@opengeni/contracts/personal-github\";\nimport { createHash } from \"node:crypto\";\nimport {\n OAUTH_MAX_RESPONSE_BYTES,\n pinnedFetch,\n readResponseJsonBounded,\n undiciFetch,\n validateHttpUrl,\n type DnsLookup,\n type FetchLike,\n} from \"@opengeni/network\";\nexport { isPrivateAddress } from \"@opengeni/network\";\nimport { Buffer } from \"node:buffer\";\nimport { encryptEnvironmentValue } from \"./environment-crypto\";\nimport type { Database } from \"./database\";\nimport { withConnectionRefreshLock } from \"./connection-refresh-lock\";\nimport type {\n AcceptedConnectionUseContext,\n AcceptedConnectionUseResolution,\n} from \"./connection-authority\";\nimport { connectionScopeKey } from \"./connection-scopes\";\n\nconst MAX_CREDENTIAL_PLACEMENTS = 32;\nconst MAX_CREDENTIAL_NAME_BYTES = 256;\nconst MAX_CREDENTIAL_VALUE_BYTES = 16_384;\nconst HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;\nconst QUERY_NAME_PATTERN = /^[A-Za-z0-9._~-]+$/;\nconst COOKIE_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\nconst FORBIDDEN_CREDENTIAL_HEADERS = new Set([\n \"connection\",\n \"content-length\",\n \"host\",\n \"proxy-authorization\",\n \"proxy-connection\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n]);\n\nexport type ConnectionCredentialForBroker = {\n id: string;\n accountId: string;\n workspaceId: string;\n subjectId: string | null;\n providerDomain: string;\n kind: ConnectionKind;\n status: ConnectionStatus;\n credential: Record<string, unknown>;\n grantedScopes: string[];\n expiresAt: Date | null;\n lastRefreshAt: Date | null;\n version: number;\n /** Immutable execution authority generation; distinct from token refresh version. */\n authorityGeneration?: number;\n metadata: Record<string, unknown>;\n};\n\nexport type ConnectionCredentialLookupInput = {\n workspaceId: string;\n connectionId?: string;\n providerDomain: string;\n kind?: ConnectionKind;\n subjectId?: string | null;\n allowSubjectOwned?: boolean;\n expectedAuthorityGeneration?: number;\n};\n\nexport type ConnectionTokenRefreshInput = {\n id: string;\n version: number;\n workspaceId: string;\n credentialEncrypted: string;\n expiresAt: Date | null;\n grantedScopes?: string[];\n metadata?: Record<string, unknown>;\n lastRefreshAt: Date;\n subjectId?: string | null;\n};\n\nexport type ConnectionStatusGuard = {\n id: string;\n version: number;\n subjectId?: string | null;\n};\n\nexport type ResolveConnectionCredentialResult =\n | {\n status: \"ok\";\n headers: Record<string, string>;\n /** Credential authority is owned by the embedding host, not the native connection store. */\n authoritySource?: \"host\";\n /** Present when the credential bundle or embedding host supplied explicit placements. */\n placements?: ConnectionCredentialPlacement[];\n connectionId: string;\n /** Exact durable version when the credential came from the local connection store. */\n connectionVersion?: number;\n /** Actual provider grants; never inferred from requested connection scopes. */\n grantedScopes?: string[];\n /** Metadata-only owner attribution from the immediate pre-use fence. */\n connectionUseAttribution?: ConnectionUseAttribution;\n /** Metadata-only equality key from current live authority; never credentials or authorization. */\n operationAuthorityDigest?: string;\n /**\n * Revalidate the exact accepted attempt immediately before one target\n * provider request. Credential lookup/refresh is a separate audited\n * boundary and must not manufacture a provider-request fact by itself.\n */\n authorizeProviderRequest?: () => Promise<boolean>;\n expiresAt?: Date | null;\n }\n | {\n status: \"auth_needed\";\n reason: McpCredentialAuthNeededReason;\n providerDomain: string;\n /** Credential authority is owned by the embedding host, not the native connection store. */\n authoritySource?: \"host\";\n provider?: string;\n connectionId?: string;\n scopes?: string[];\n resource?: string;\n selectedResources?: McpConnectionResourceScope[];\n authorizationUrl?: string;\n };\ntype AuthNeededReason = Extract<\n ResolveConnectionCredentialResult,\n { status: \"auth_needed\" }\n>[\"reason\"];\n\nexport type ResolveConnectionCredentialInput = {\n workspaceId: string;\n subjectId?: string;\n serverId: string;\n toolName?: string;\n /** @deprecated Use toolName. Retained for the API's pre-existing broker call shape. */\n toolId?: string;\n connectionRef: McpServerConnectionRef;\n /** Exact MCP destination whose request would receive the resolved headers. */\n destinationUrl: string;\n /** Defaults to header-only MCP transport. */\n credentialTarget?: \"mcp\" | \"http_api\";\n forceRefresh?: boolean;\n /** Internal lookup mode. Preflight must not refresh credentials or record provider usage. */\n credentialResolutionMode?: \"execution\" | \"preflight\";\n /** Frozen provider authority generation captured by the calling integration/catalog. */\n expectedAuthorityGeneration?: number;\n /** Attribution already authorized for forwarding to a host resolver; never authorizes local use. */\n hostConnectionUseAttribution?: ConnectionUseAttribution;\n /** Exact accepted attempt plus one stable physical-provider request id. */\n connectionUseContext?: AcceptedConnectionUseContext;\n};\n\nconst OFFICIAL_GMAIL_MCP_RESOURCE = \"https://gmailmcp.googleapis.com/mcp/v1\";\nconst OFFICIAL_GMAIL_REST_HOST = \"gmail.googleapis.com\";\n\n/**\n * The Gmail bridge reuses the exact OAuth grant created for the official\n * hosted Gmail MCP resource, executing every tool against Gmail's REST API\n * instead of Google's Developer Preview MCP endpoint. Keep this exception\n * narrower than ordinary provider-domain binding: HTTPS only, Google's\n * canonical Gmail API host, and the authenticated `users/me` path.\n */\nfunction isOfficialGmailRestDestination(\n destinationUrl: string,\n ref: McpServerConnectionRef,\n): boolean {\n if (\n ref.providerDomain.toLowerCase() !== \"gmailmcp.googleapis.com\" ||\n ref.kind !== \"oauth2\" ||\n ref.subjectScope !== \"subject\"\n ) {\n return false;\n }\n const destination = new URL(destinationUrl);\n return (\n destination.protocol === \"https:\" &&\n destination.hostname.toLowerCase() === OFFICIAL_GMAIL_REST_HOST &&\n (destination.pathname === \"/gmail/v1/users/me\" ||\n destination.pathname.startsWith(\"/gmail/v1/users/me/\"))\n );\n}\n\n/**\n * Adapts the public embedding credential port to the runtime's connection\n * resolver contract. Scope echoes are checked before credential headers can\n * reach a request; the returned object is a fresh copy so a host cannot mutate\n * headers after resolution.\n */\n\nfunction copySelectedResources(\n resources: McpConnectionResourceScope[],\n): McpConnectionResourceScope[] {\n if (resources.length === 0 || resources.length > 256) {\n throw new Error(\"connection credential returned an invalid selected resource count\");\n }\n const seen = new Set<string>();\n return resources.map((resource) => {\n if (\n resource.kind !== \"repository\" ||\n typeof resource.id !== \"string\" ||\n resource.id.length === 0 ||\n resource.id.length > 512\n ) {\n throw new Error(\"connection credential returned an invalid selected resource\");\n }\n const key = `${resource.kind}\\0${resource.id}`;\n if (seen.has(key)) {\n throw new Error(\"connection credential returned duplicate selected resources\");\n }\n seen.add(key);\n return { kind: resource.kind, id: resource.id };\n });\n}\n\nexport function normalizedCredentialHeaders(\n headers: Record<string, string>,\n allowEmpty = false,\n): Record<string, string> {\n const entries = Object.entries(headers);\n if ((!allowEmpty && entries.length === 0) || entries.length > 32) {\n throw new Error(\"connection credential returned an invalid header count\");\n }\n const normalized: Record<string, string> = {};\n for (const [name, value] of entries) {\n if (\n name.length > 256 ||\n !HEADER_NAME_PATTERN.test(name) ||\n value.length === 0 ||\n value.length > 16_384 ||\n /[\\r\\n\\0]/.test(value) ||\n FORBIDDEN_CREDENTIAL_HEADERS.has(name.toLowerCase()) ||\n name.toLowerCase().startsWith(\"sec-\")\n ) {\n throw new Error(\"connection credential returned an invalid header\");\n }\n if (Object.keys(normalized).some((existing) => existing.toLowerCase() === name.toLowerCase())) {\n throw new Error(\"connection credential returned duplicate headers\");\n }\n normalized[name] = value;\n }\n return normalized;\n}\n\nexport const BROKERED_CREDENTIAL_SHAPE_HINT =\n 'store { headers: { \"<Header-Name>\": \"<value>\" } } or { placements: [{ carrier: \"header\" | \"query\" | \"cookie\", name, value, prefix? }] }';\n\n/**\n * Why a non-OAuth credential bundle cannot be placed on a brokered request,\n * or null when the runtime broker can use it. Mirrors\n * `credentialMaterialForConnection` exactly so create-time validation and\n * execution never disagree.\n */\nexport function brokeredCredentialBundleProblem(\n credential: Record<string, unknown>,\n): string | null {\n if (credential.placements !== undefined) {\n try {\n normalizedCredentialPlacements(credential.placements);\n return null;\n } catch (error) {\n return `invalid credential placements (${credentialProblemDetail(error)}); ${BROKERED_CREDENTIAL_SHAPE_HINT}`;\n }\n }\n if (credential.headers !== undefined) {\n const headers = stringRecord(credential.headers);\n if (!headers) {\n return `credential.headers must map header names to string values; ${BROKERED_CREDENTIAL_SHAPE_HINT}`;\n }\n try {\n normalizedCredentialHeaders(headers);\n return null;\n } catch (error) {\n return `invalid credential headers (${credentialProblemDetail(error)}); ${BROKERED_CREDENTIAL_SHAPE_HINT}`;\n }\n }\n const unplaced = Object.keys(credential).filter(\n (key) => key !== \"headers\" && key !== \"placements\",\n );\n return `an api_key credential must say where the secret goes on each request${\n unplaced.length > 0\n ? ` (fields such as ${unplaced\n .slice(0, 3)\n .map((key) => JSON.stringify(key.slice(0, 64)))\n .join(\", \")} are never sent)`\n : \"\"\n }; ${BROKERED_CREDENTIAL_SHAPE_HINT}`;\n}\n\nfunction credentialProblemDetail(error: unknown): string {\n return error instanceof Error\n ? error.message.replace(/^connection credential returned /, \"\")\n : \"invalid value\";\n}\n\nfunction normalizedCredentialPlacements(value: unknown): ConnectionCredentialPlacement[] {\n if (!Array.isArray(value) || value.length === 0 || value.length > MAX_CREDENTIAL_PLACEMENTS) {\n throw new Error(\"connection credential returned an invalid placement count\");\n }\n const seen = new Set<string>();\n return value.map((raw) => {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) {\n throw new Error(\"connection credential returned an invalid placement\");\n }\n const record = raw as Record<string, unknown>;\n if (\n Object.keys(record).some(\n (key) => key !== \"carrier\" && key !== \"name\" && key !== \"value\" && key !== \"prefix\",\n )\n ) {\n throw new Error(\"connection credential returned an invalid placement\");\n }\n const carrier = record.carrier;\n const name = record.name;\n const credentialValue = record.value;\n const prefix = record.prefix;\n if (\n (carrier !== \"header\" && carrier !== \"query\" && carrier !== \"cookie\") ||\n typeof name !== \"string\" ||\n name.length === 0 ||\n Buffer.byteLength(name) > MAX_CREDENTIAL_NAME_BYTES ||\n typeof credentialValue !== \"string\" ||\n credentialValue.length === 0 ||\n (typeof prefix !== \"undefined\" && typeof prefix !== \"string\") ||\n /[\\r\\n\\0]/.test(name) ||\n /[\\r\\n\\0]/.test(credentialValue) ||\n (typeof prefix === \"string\" && /[\\r\\n\\0]/.test(prefix)) ||\n Buffer.byteLength(`${typeof prefix === \"string\" ? prefix : \"\"}${credentialValue}`) >\n MAX_CREDENTIAL_VALUE_BYTES\n ) {\n throw new Error(\"connection credential returned an invalid placement\");\n }\n const normalizedName = carrier === \"header\" ? name.toLowerCase() : name;\n if (\n (carrier === \"header\" &&\n (!HEADER_NAME_PATTERN.test(name) ||\n FORBIDDEN_CREDENTIAL_HEADERS.has(normalizedName) ||\n normalizedName.startsWith(\"sec-\"))) ||\n (carrier === \"query\" && !QUERY_NAME_PATTERN.test(name)) ||\n (carrier === \"cookie\" &&\n (!COOKIE_NAME_PATTERN.test(name) || /;/.test(`${prefix ?? \"\"}${credentialValue}`)))\n ) {\n throw new Error(\"connection credential returned an invalid placement\");\n }\n const key = `${carrier}\\0${normalizedName}`;\n if (seen.has(key)) {\n throw new Error(\"connection credential returned duplicate placements\");\n }\n seen.add(key);\n return {\n carrier,\n name,\n value: credentialValue,\n ...(typeof prefix === \"string\" && prefix.length > 0 ? { prefix } : {}),\n };\n });\n}\n\nfunction headerMapForPlacements(\n placements: readonly ConnectionCredentialPlacement[],\n): Record<string, string> {\n const headers: Record<string, string> = {};\n for (const placement of placements) {\n if (placement.carrier === \"header\") {\n headers[placement.name] = `${placement.prefix ?? \"\"}${placement.value}`;\n }\n }\n return headers;\n}\n\nexport type ConnectionBrokerDeps = {\n loadCredential: (\n db: Database,\n settings: Settings,\n input: ConnectionCredentialLookupInput,\n ) => Promise<ConnectionCredentialForBroker | null>;\n recordRefresh: (db: Database, input: ConnectionTokenRefreshInput) => Promise<boolean>;\n setStatus: (\n db: Database,\n workspaceId: string,\n status: ConnectionStatus,\n lastError: string | null,\n guard: ConnectionStatusGuard,\n ) => Promise<boolean>;\n recordUsed: (\n db: Database,\n workspaceId: string,\n connectionId: string,\n subjectId?: string | null,\n ) => Promise<void>;\n refresh: typeof refreshOAuthConnectionCredential;\n /** Test/adapter seam; standalone defaults to the database-backed refresh lock. */\n withRefreshLock?: typeof withConnectionRefreshLock;\n encrypt: typeof encryptEnvironmentValue;\n keyBytes: typeof environmentsEncryptionKeyBytes;\n now: () => Date;\n authorizeAcceptedUse?: (\n db: Database,\n input: AcceptedConnectionUseContext & {\n serverId: string;\n connectionId?: string;\n providerDomain: string;\n connectionKind?: ConnectionKind;\n subjectScope?: \"workspace\" | \"subject\";\n ownerSubjectId?: string;\n },\n ) => Promise<AcceptedConnectionUseResolution>;\n};\n\nexport type PermanentConnectionRefreshFailure = {\n workspaceId: string;\n connectionId: string;\n connectionVersion: number;\n subjectId: string | null;\n providerDomain: string;\n httpStatus: number;\n oauthErrorCode: string | null;\n};\n\nexport type ConnectionTokenResolverOptions = {\n /** Provider-aware transport override used by local/integration adapters. */\n refreshTransport?: RefreshTransportOptions;\n /**\n * Optional provider adapter for an atomic, metadata-aware permanent refresh\n * transition. Returning true means the adapter owned the transition (even if\n * its CAS lost to newer truth); false falls back to generic needs_reauth.\n */\n transitionPermanentRefreshFailure?: (\n failure: PermanentConnectionRefreshFailure,\n ) => Promise<boolean>;\n};\n\nexport type RefreshTransportOptions = {\n fetchImpl?: FetchLike;\n dnsLookup?: DnsLookup;\n};\n\nconst inflight = new Map<string, Promise<ConnectionCredentialForBroker>>();\nconst REFRESH_WINDOW_MS = 60_000;\nconst CONNECTION_REFRESH_TIMEOUT_MS = 10_000;\n\nexport function buildConnectionTokenResolver(\n db: Database,\n settings: Settings,\n deps: ConnectionBrokerDeps,\n options: ConnectionTokenResolverOptions = {},\n): (input: ResolveConnectionCredentialInput) => Promise<ResolveConnectionCredentialResult> {\n type CredentialLookupInput = Pick<\n ResolveConnectionCredentialInput,\n \"workspaceId\" | \"connectionRef\" | \"subjectId\"\n > & { expectedAuthorityGeneration?: number };\n const load = async (\n input: CredentialLookupInput,\n lookupDb: Database = db,\n ): Promise<ConnectionCredentialForBroker | null> => {\n const subjectOwned = input.connectionRef.subjectScope === \"subject\";\n if (subjectOwned && !input.subjectId) {\n return null;\n }\n const request: ConnectionCredentialLookupInput = {\n workspaceId: input.workspaceId,\n providerDomain: input.connectionRef.providerDomain,\n allowSubjectOwned: subjectOwned,\n ...(subjectOwned ? { subjectId: input.subjectId! } : {}),\n ...(input.expectedAuthorityGeneration !== undefined\n ? { expectedAuthorityGeneration: input.expectedAuthorityGeneration }\n : {}),\n };\n if (input.connectionRef.connectionId !== undefined) {\n request.connectionId = input.connectionRef.connectionId;\n }\n if (input.connectionRef.kind !== undefined) {\n request.kind = input.connectionRef.kind;\n }\n const credential = await deps.loadCredential(lookupDb, settings, request);\n if (!credential) return null;\n if (\n input.expectedAuthorityGeneration !== undefined &&\n credential.authorityGeneration !== input.expectedAuthorityGeneration\n ) {\n return null;\n }\n if (subjectOwned) {\n return credential.subjectId === input.subjectId ? credential : null;\n }\n return credential.subjectId === null ? credential : null;\n };\n\n const snapshot = async (\n cred: ConnectionCredentialForBroker,\n ref: McpServerConnectionRef,\n destinationUrl: string,\n inputCredentialTarget: \"mcp\" | \"http_api\",\n connectionUseAttribution?: ConnectionUseAttribution,\n recordUsage = true,\n ): Promise<ResolveConnectionCredentialResult> => {\n if (cred.status !== \"active\") {\n return authNeededForStatus(cred, ref);\n }\n if (!connectionBindingMatches(cred, ref, destinationUrl)) {\n return authNeeded(ref, \"missing_connection\", cred.id);\n }\n const missingScopes = missingRequestedScopes(\n ref.scopes,\n cred.grantedScopes,\n cred.providerDomain,\n );\n if (missingScopes.length > 0) {\n return {\n status: \"auth_needed\",\n reason: \"insufficient_scope\",\n providerDomain: ref.providerDomain,\n ...(ref.provider ? { provider: ref.provider } : {}),\n connectionId: cred.id,\n scopes: missingScopes,\n ...(ref.resource ? { resource: ref.resource } : {}),\n ...(ref.selectedResources\n ? { selectedResources: copySelectedResources(ref.selectedResources) }\n : {}),\n };\n }\n const material = credentialMaterialForConnection(cred, inputCredentialTarget);\n if (material.status !== \"ok\") {\n return {\n status: \"auth_needed\",\n reason: material.status === \"unsupported\" ? \"unsupported_auth\" : \"refresh_failed\",\n providerDomain: ref.providerDomain,\n ...(ref.provider ? { provider: ref.provider } : {}),\n connectionId: cred.id,\n ...(ref.scopes ? { scopes: ref.scopes } : {}),\n ...(ref.resource ? { resource: ref.resource } : {}),\n ...(ref.selectedResources\n ? { selectedResources: copySelectedResources(ref.selectedResources) }\n : {}),\n };\n }\n if (recordUsage) {\n await deps.recordUsed(db, cred.workspaceId, cred.id, cred.subjectId);\n }\n return {\n status: \"ok\",\n headers: material.headers,\n ...(material.placements ? { placements: material.placements } : {}),\n connectionId: cred.id,\n connectionVersion: cred.version,\n ...(cred.providerDomain.toLowerCase() === \"slack.com\"\n ? { grantedScopes: normalizeSlackScopes(cred.grantedScopes) }\n : {}),\n ...(connectionUseAttribution ? { connectionUseAttribution } : {}),\n expiresAt: cred.expiresAt,\n };\n };\n\n const performRefresh = async (\n cred: ConnectionCredentialForBroker,\n ref: McpServerConnectionRef,\n lockedDb: Database,\n ): Promise<ConnectionCredentialForBroker> => {\n const key = deps.keyBytes(settings);\n if (!key) {\n throw new Error(\"OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY is not configured\");\n }\n const refreshed = await measureMcpPhase(\"oauth_refresh\", () =>\n deps.refresh(cred, ref, settings, options.refreshTransport),\n );\n const refreshRecord: ConnectionTokenRefreshInput = {\n id: cred.id,\n version: cred.version,\n workspaceId: cred.workspaceId,\n credentialEncrypted: deps.encrypt(key, JSON.stringify(refreshed.credential)),\n expiresAt: refreshed.expiresAt,\n lastRefreshAt: deps.now(),\n subjectId: cred.subjectId,\n };\n if (refreshed.grantedScopes !== undefined) {\n refreshRecord.grantedScopes = refreshed.grantedScopes;\n }\n if (refreshed.metadata !== undefined) {\n refreshRecord.metadata = refreshed.metadata;\n }\n const persisted = await deps.recordRefresh(lockedDb, refreshRecord);\n if (persisted) {\n const current = await load(\n {\n workspaceId: cred.workspaceId,\n connectionRef: { ...ref, connectionId: cred.id },\n ...(cred.subjectId ? { subjectId: cred.subjectId } : {}),\n },\n lockedDb,\n );\n if (current) {\n return current;\n }\n }\n const winner = await load(\n {\n workspaceId: cred.workspaceId,\n connectionRef: { ...ref, connectionId: cred.id },\n ...(cred.subjectId ? { subjectId: cred.subjectId } : {}),\n },\n lockedDb,\n );\n if (winner?.status === \"active\") {\n return winner;\n }\n throw new Error(\"connection credential changed during token refresh\");\n };\n\n const refreshSingleFlight = (\n cred: ConnectionCredentialForBroker,\n ref: McpServerConnectionRef,\n ): Promise<ConnectionCredentialForBroker> => {\n const key = `${cred.subjectId ?? \"workspace\"}:${cred.id}:${cred.version}`;\n const existing = inflight.get(key);\n if (existing) {\n return measureMcpPhase(\"oauth_wait\", () => existing);\n }\n const lockWait = beginMcpPhase(\"oauth_wait\");\n const promise = (deps.withRefreshLock ?? withConnectionRefreshLock)(\n db,\n cred,\n async (lockedDb) => {\n lockWait.end();\n // A different worker may have rotated while this request waited. Never\n // exchange the old token again, or switch to another authority generation.\n const current = await load(\n {\n workspaceId: cred.workspaceId,\n connectionRef: { ...ref, connectionId: cred.id },\n ...(cred.subjectId ? { subjectId: cred.subjectId } : {}),\n },\n lockedDb,\n );\n if (!current || current.authorityGeneration !== cred.authorityGeneration)\n throw new Error(\"Connection authority changed before token refresh\");\n if (current.status !== \"active\" || current.version !== cred.version) return current;\n return performRefresh(current, ref, lockedDb);\n },\n ).finally(() => {\n // A lock acquisition failure must also close the diagnostic interval.\n lockWait.end(\"failed\");\n if (inflight.get(key) === promise) {\n inflight.delete(key);\n }\n });\n inflight.set(key, promise);\n return promise;\n };\n\n return async (input) => {\n const credentialResolutionMode = input.credentialResolutionMode ?? \"execution\";\n let ref = input.connectionRef;\n let subjectId = input.subjectId;\n let credentialWorkspaceId = input.workspaceId;\n let expectedAuthorityGeneration = input.expectedAuthorityGeneration;\n let connectionUseAttribution: ConnectionUseAttribution | undefined;\n if (ref.authoritySource === \"host\") {\n return authNeeded(ref, \"unsupported_auth\", ref.connectionId);\n }\n // Repository-scoped provider bindings require a broker that can prove the\n // selected-resource boundary. The generic standalone credential store has\n // no provider-specific containment adapter, so it must fail closed instead\n // of handing an account-wide token to the configured endpoint.\n if (ref.selectedResources) {\n return authNeeded(ref, \"resource_scope_unavailable\", ref.connectionId);\n }\n if (input.connectionUseContext !== undefined) {\n if (!deps.authorizeAcceptedUse) {\n return authNeeded(\n ref,\n ref.subjectScope === \"subject\" ? \"personal_authority_unavailable\" : \"missing_connection\",\n ref.connectionId,\n );\n }\n const connectionUseContext = input.connectionUseContext;\n const authorization = await measureMcpPhase(\n \"provider_authorization\",\n () =>\n deps.authorizeAcceptedUse!(db, {\n ...connectionUseContext,\n serverId: input.serverId,\n ...(ref.connectionId ? { connectionId: ref.connectionId } : {}),\n providerDomain: ref.providerDomain,\n ...(ref.kind ? { connectionKind: ref.kind } : {}),\n subjectScope: ref.subjectScope === \"subject\" ? \"subject\" : \"workspace\",\n // An owner binding belongs only to the personal lanes. Interactive\n // turns stamp the initiating human's subjectId on every credential\n // request regardless of ref scope; forwarding it for a workspace ref\n // would make the 0279 workspace lane deny the ambient shared row.\n ...(ref.subjectScope === \"subject\" && subjectId ? { ownerSubjectId: subjectId } : {}),\n }),\n (result) => (result.status === \"authorized\" ? \"completed\" : \"rejected\"),\n );\n if (authorization.status === \"denied\") {\n return authNeeded(\n ref,\n ref.subjectScope === \"subject\" ? \"personal_authority_unavailable\" : \"missing_connection\",\n ref.connectionId,\n );\n }\n if (\n expectedAuthorityGeneration !== undefined &&\n authorization.attribution.connectionGeneration !== expectedAuthorityGeneration\n ) {\n return authNeeded(\n ref,\n authorityReasonForScope(ref.subjectScope === \"subject\"),\n ref.connectionId,\n );\n }\n connectionUseAttribution = authorization.attribution;\n expectedAuthorityGeneration = authorization.attribution.connectionGeneration;\n const expectedPersonal = authorization.attribution.scope !== \"workspace\";\n credentialWorkspaceId = authorization.originWorkspaceId;\n subjectId = authorization.attribution.ownerSubjectId ?? undefined;\n ref = {\n ...ref,\n connectionId: authorization.attribution.connectionId,\n kind: authorization.connectionKind,\n subjectScope: expectedPersonal ? \"subject\" : \"workspace\",\n };\n }\n if (ref.subjectScope === \"subject\" && !subjectId) {\n return authNeeded(ref, \"personal_authority_unavailable\", ref.connectionId);\n }\n let cred: ConnectionCredentialForBroker | null;\n try {\n cred = await load({\n workspaceId: credentialWorkspaceId,\n connectionRef: ref,\n ...(subjectId ? { subjectId } : {}),\n ...(expectedAuthorityGeneration !== undefined ? { expectedAuthorityGeneration } : {}),\n });\n } catch {\n return authNeeded(ref, \"refresh_failed\");\n }\n if (!cred) {\n return authNeeded(ref, \"missing_connection\");\n }\n if (cred.status !== \"active\") {\n return authNeededForStatus(cred, ref);\n }\n // Reject an audience/destination mismatch before any provider-side refresh\n // or usage update. Refreshing first would still create an unauthorized\n // external side effect even though the token was never sent to the target.\n if (!connectionBindingMatches(cred, ref, input.destinationUrl)) {\n return authNeeded(ref, \"missing_connection\", cred.id);\n }\n const now = deps.now();\n if (\n credentialResolutionMode === \"preflight\" &&\n cred.kind === \"oauth2\" &&\n (input.forceRefresh === true ||\n (cred.expiresAt !== null && cred.expiresAt.getTime() <= now.getTime()))\n ) {\n return authNeeded(ref, \"refresh_failed\", cred.id);\n }\n if (\n credentialResolutionMode === \"execution\" &&\n shouldRefresh(cred, input.forceRefresh === true, now)\n ) {\n try {\n cred = await refreshSingleFlight(cred, ref);\n } catch (error) {\n // Only a rejected grant may poison the connection; transient failures\n // (network errors, AS 5xx) leave it active so the next resolve retries.\n if (isPermanentRefreshError(error)) {\n let handled = false;\n if (options.transitionPermanentRefreshFailure) {\n try {\n handled = await options.transitionPermanentRefreshFailure({\n workspaceId: cred.workspaceId,\n connectionId: cred.id,\n connectionVersion: cred.version,\n subjectId: cred.subjectId,\n providerDomain: cred.providerDomain,\n httpStatus: error.httpStatus,\n oauthErrorCode: error.oauthErrorCode,\n });\n } catch {\n handled = false;\n }\n }\n if (!handled) {\n await deps\n // A personal credential may originate outside the workspace\n // consuming it. Apply the CAS to the same row we refreshed.\n .setStatus(db, cred.workspaceId, \"needs_reauth\", error.message, {\n id: cred.id,\n version: cred.version,\n subjectId: cred.subjectId,\n })\n .catch(() => undefined);\n }\n }\n return authNeeded(ref, \"refresh_failed\", cred.id);\n }\n }\n if (\n expectedAuthorityGeneration !== undefined &&\n cred.authorityGeneration !== expectedAuthorityGeneration\n ) {\n return authNeeded(ref, authorityReasonForScope(ref.subjectScope === \"subject\"), cred.id);\n }\n return await snapshot(\n cred,\n ref,\n input.destinationUrl,\n input.credentialTarget ?? \"mcp\",\n connectionUseAttribution,\n credentialResolutionMode === \"execution\",\n );\n };\n}\n\nfunction authorityReasonForScope(personal: boolean): AuthNeededReason {\n return personal ? \"personal_authority_unavailable\" : \"missing_connection\";\n}\n\nfunction connectionBindingMatches(\n cred: Pick<ConnectionCredentialForBroker, \"providerDomain\" | \"kind\" | \"credential\" | \"metadata\">,\n ref: McpServerConnectionRef,\n destinationUrl: string,\n): boolean {\n if (cred.providerDomain.toLowerCase() !== ref.providerDomain.toLowerCase()) return false;\n if (ref.kind && cred.kind !== ref.kind) return false;\n\n const credential = cred.credential as Record<string, unknown>;\n const metadata = cred.metadata as Record<string, unknown>;\n const boundMcpUrl = stringValue(credential.mcp_url) ?? stringValue(metadata.mcpUrl);\n const destination = canonicalHttpUrl(destinationUrl);\n if (!destination) return false;\n if (boundMcpUrl) {\n const binding = canonicalHttpUrl(boundMcpUrl);\n if (\n !binding ||\n (destination !== binding &&\n !(\n binding === canonicalHttpUrl(OFFICIAL_GMAIL_MCP_RESOURCE) &&\n isOfficialGmailRestDestination(destination, ref)\n ) &&\n !(\n binding === canonicalHttpUrl(OFFICIAL_SLACK_MCP_URL) &&\n isOfficialSlackRestDestination(destination, ref)\n ))\n ) {\n return false;\n }\n } else if (!destinationHostMatchesProvider(destination, cred.providerDomain)) {\n // Legacy/manual API-key rows may predate mcpUrl metadata. They are still\n // host-bound to their canonical provider domain, never usable as an\n // arbitrary bearer/header source for an unrelated MCP destination.\n return false;\n }\n if (cred.kind !== \"oauth2\") return true;\n const boundResource = stringValue(credential.resource) ?? stringValue(metadata.resource);\n if (ref.resource) {\n if (!boundResource) return false;\n if (canonicalResource(ref.resource) !== canonicalResource(boundResource)) return false;\n }\n return true;\n}\n\n/** Credential-free preflight only. Physical requests still resolve credentials\n * and enforce their binding, current status and accepted-use authority. */\nexport function connectionMetadataMatchesBinding(\n connection: ConnectionMetadata,\n ref: McpServerConnectionRef,\n destinationUrl: string,\n): boolean {\n return (\n connectionBindingMatches({ ...connection, credential: {} }, ref, destinationUrl) &&\n missingRequestedScopes(ref.scopes, connection.grantedScopes, connection.providerDomain)\n .length === 0\n );\n}\n\n/** Only the reviewed Slack bridge methods may reuse the hosted resource grant. */\nfunction isOfficialSlackRestDestination(\n destinationUrl: string,\n ref: McpServerConnectionRef,\n): boolean {\n if (\n ref.providerDomain.toLowerCase() !== \"slack.com\" ||\n ref.kind !== \"oauth2\" ||\n (ref.subjectScope !== undefined &&\n ref.subjectScope !== \"subject\" &&\n ref.subjectScope !== \"workspace\")\n )\n return false;\n const url = new URL(destinationUrl);\n // Private file bytes for files.info results are a separate reviewed host.\n if (isSlackPrivateFileUrl(url)) return true;\n return (\n url.origin === \"https://slack.com\" &&\n !url.username &&\n !url.password &&\n [\n \"auth.test\",\n \"conversations.list\",\n \"conversations.info\",\n \"conversations.members\",\n \"users.list\",\n \"users.info\",\n \"conversations.history\",\n \"conversations.replies\",\n \"files.info\",\n \"conversations.open\",\n \"chat.postMessage\",\n ].some((method) => url.pathname === `/api/${method}`)\n );\n}\n\nfunction destinationHostMatchesProvider(destinationUrl: string, providerDomain: string): boolean {\n const destinationHost = new URL(destinationUrl).hostname.toLowerCase();\n const provider = providerDomain\n .trim()\n .toLowerCase()\n .replace(/^\\.+|\\.+$/g, \"\");\n return (\n Boolean(provider) && (destinationHost === provider || destinationHost.endsWith(`.${provider}`))\n );\n}\n\nfunction canonicalHttpUrl(value: string): string | null {\n try {\n const url = new URL(value);\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") return null;\n url.hash = \"\";\n url.hostname = url.hostname.toLowerCase();\n if (\n (url.protocol === \"https:\" && url.port === \"443\") ||\n (url.protocol === \"http:\" && url.port === \"80\")\n ) {\n url.port = \"\";\n }\n url.pathname = url.pathname.replace(/\\/+$/, \"\") || \"/\";\n return url.toString();\n } catch {\n return null;\n }\n}\n\nfunction canonicalResource(value: string): string {\n return canonicalHttpUrl(value) ?? value.trim();\n}\n\nexport class ConnectionRefreshHttpError extends Error {\n readonly httpStatus: number;\n readonly oauthErrorCode: string | null;\n\n constructor(httpStatus: number, oauthErrorCode: string | null = null) {\n super(`connection refresh failed with HTTP ${httpStatus}`);\n this.name = \"ConnectionRefreshHttpError\";\n this.httpStatus = httpStatus;\n this.oauthErrorCode = oauthErrorCode;\n }\n}\n\n// The token endpoint rejecting the grant itself means re-auth is the only way\n// forward. 429 (throttling) and 408 are transient despite being 4xx; network\n// failures and AS 5xx are likewise retryable.\nfunction isPermanentRefreshError(error: unknown): error is ConnectionRefreshHttpError {\n return (\n error instanceof ConnectionRefreshHttpError &&\n error.httpStatus >= 400 &&\n error.httpStatus < 500 &&\n error.httpStatus !== 408 &&\n error.httpStatus !== 429\n );\n}\n\nfunction shouldRefresh(cred: ConnectionCredentialForBroker, force: boolean, now: Date): boolean {\n if (cred.kind !== \"oauth2\") {\n return false;\n }\n if (force) {\n return true;\n }\n if (!cred.expiresAt) {\n return false;\n }\n return cred.expiresAt.getTime() <= now.getTime() + REFRESH_WINDOW_MS;\n}\n\nfunction authNeeded(\n ref: McpServerConnectionRef,\n reason: AuthNeededReason,\n connectionId?: string,\n): ResolveConnectionCredentialResult {\n return {\n status: \"auth_needed\",\n reason,\n providerDomain: ref.providerDomain,\n ...(ref.provider ? { provider: ref.provider } : {}),\n ...(connectionId ? { connectionId } : {}),\n ...(ref.scopes ? { scopes: ref.scopes } : {}),\n ...(ref.resource ? { resource: ref.resource } : {}),\n ...(ref.selectedResources\n ? { selectedResources: copySelectedResources(ref.selectedResources) }\n : {}),\n };\n}\n\nfunction authNeededForStatus(\n cred: ConnectionCredentialForBroker,\n ref: McpServerConnectionRef,\n): ResolveConnectionCredentialResult {\n if (cred.status === \"revoked\") {\n return authNeeded(ref, \"missing_connection\", cred.id);\n }\n return authNeeded(\n ref,\n cred.expiresAt && cred.expiresAt.getTime() <= Date.now() ? \"expired\" : \"refresh_failed\",\n cred.id,\n );\n}\n\nfunction missingRequestedScopes(\n requested: string[] | undefined,\n granted: string[],\n providerDomain: string,\n): string[] {\n if (!requested?.length) {\n return [];\n }\n const actual =\n providerDomain.toLowerCase() === \"slack.com\" ? normalizeSlackScopes(granted) : granted;\n const grantedSet = new Set(actual.map((scope) => connectionScopeKey(providerDomain, scope)));\n return requested.filter((scope) => !grantedSet.has(connectionScopeKey(providerDomain, scope)));\n}\n\n/**\n * Normalizes an OAuth token_type into the Authorization scheme to send. RFC 6750\n * says the scheme is case-insensitive, but some MCP servers (e.g. Linear) reject\n * a lowercase `bearer` — so a `bearer`/`BEARER` (or absent) token_type is sent as\n * the canonical `Bearer`. A non-bearer scheme is passed through unchanged.\n */\nexport function normalizeBearerScheme(tokenType: string | null | undefined): string {\n return !tokenType || /^bearer$/i.test(tokenType) ? \"Bearer\" : tokenType;\n}\n\ntype ConnectionCredentialMaterial =\n | {\n status: \"ok\";\n headers: Record<string, string>;\n placements?: ConnectionCredentialPlacement[];\n }\n | { status: \"invalid\" | \"unsupported\" };\n\nfunction credentialMaterialForConnection(\n cred: ConnectionCredentialForBroker,\n target: \"mcp\" | \"http_api\",\n): ConnectionCredentialMaterial {\n if (cred.kind === \"oauth2\") {\n const accessToken = stringValue((cred.credential as { access_token?: unknown }).access_token);\n if (!accessToken) {\n return { status: \"invalid\" };\n }\n return {\n status: \"ok\",\n headers: {\n authorization: `${normalizeBearerScheme(stringValue((cred.credential as { token_type?: unknown }).token_type))} ${accessToken}`,\n },\n };\n }\n const rawPlacements = (cred.credential as { placements?: unknown }).placements;\n if (rawPlacements !== undefined) {\n let placements: ConnectionCredentialPlacement[];\n try {\n placements = normalizedCredentialPlacements(rawPlacements);\n } catch {\n return { status: \"invalid\" };\n }\n if (target !== \"http_api\" && placements.some((placement) => placement.carrier !== \"header\")) {\n return { status: \"unsupported\" };\n }\n return {\n status: \"ok\",\n headers: headerMapForPlacements(placements),\n placements,\n };\n }\n try {\n const headers = normalizedCredentialHeaders(\n stringRecord((cred.credential as { headers?: unknown }).headers) ?? {},\n );\n return { status: \"ok\", headers };\n } catch {\n return { status: \"invalid\" };\n }\n}\n\nexport async function refreshOAuthConnectionCredential(\n cred: ConnectionCredentialForBroker,\n ref: McpServerConnectionRef,\n settings: Settings,\n transportOptions: RefreshTransportOptions = {},\n): Promise<{\n credential: Record<string, unknown>;\n expiresAt: Date | null;\n grantedScopes?: string[];\n metadata?: Record<string, unknown>;\n}> {\n if (cred.kind !== \"oauth2\") {\n return {\n credential: cred.credential,\n expiresAt: cred.expiresAt,\n grantedScopes: cred.grantedScopes,\n };\n }\n const refreshToken = stringValue((cred.credential as { refresh_token?: unknown }).refresh_token);\n const personalGitHubMetadata = PersonalGitHubConnectionMetadata.safeParse(cred.metadata);\n const personalGitHub =\n cred.providerDomain.toLowerCase() === PERSONAL_GITHUB_PROVIDER_DOMAIN &&\n personalGitHubMetadata.success;\n const storedTokenEndpoint =\n stringValue((cred.credential as { token_endpoint?: unknown }).token_endpoint) ??\n stringValue((cred.metadata as { tokenEndpoint?: unknown }).tokenEndpoint) ??\n stringValue((cred.metadata as { token_endpoint?: unknown }).token_endpoint);\n const tokenEndpoint = personalGitHub ? PERSONAL_GITHUB_TOKEN_URL : storedTokenEndpoint;\n if (!refreshToken || !tokenEndpoint) {\n throw new Error(\"connection has no refresh token endpoint\");\n }\n if (personalGitHub && storedTokenEndpoint !== PERSONAL_GITHUB_TOKEN_URL) {\n throw new ConnectionRefreshHttpError(401, \"client_unavailable\");\n }\n let validatedTokenEndpoint: string;\n try {\n validatedTokenEndpoint = validateHttpUrl(tokenEndpoint, {\n label: \"OAuth refresh token endpoint\",\n allowLoopbackHttp: settings.environment === \"local\" || settings.environment === \"test\",\n });\n } catch {\n throw new Error(\"connection has an invalid refresh token endpoint\");\n }\n const body = new URLSearchParams();\n body.set(\"grant_type\", \"refresh_token\");\n body.set(\"refresh_token\", refreshToken);\n // Public clients (token_endpoint_auth_method \"none\") must identify themselves\n // in the token request body (RFC 6749 §3.2.1); grant flows persist the\n // client_id they authorized with into the bundle/metadata.\n const clientId =\n stringValue((cred.credential as { client_id?: unknown }).client_id) ??\n stringValue((cred.metadata as { clientId?: unknown }).clientId) ??\n stringValue((cred.metadata as { client_id?: unknown }).client_id);\n const clientSecret = personalGitHub\n ? settings.githubPersonalOauthClientSecret\n : stringValue((cred.credential as { client_secret?: unknown }).client_secret);\n const authMethod =\n stringValue(\n (cred.credential as { token_endpoint_auth_method?: unknown }).token_endpoint_auth_method,\n ) ?? \"none\";\n if (\n personalGitHub &&\n (!settings.githubPersonalOauthEnabled ||\n !clientId ||\n clientId !== settings.githubPersonalOauthClientId ||\n personalGitHubMetadata.data.oauthEnvironment !== settings.environment ||\n personalGitHubMetadata.data.oauthClientMarker !==\n createHash(\"sha256\").update(clientId).digest(\"hex\").slice(0, 32) ||\n !clientSecret)\n ) {\n throw new ConnectionRefreshHttpError(401, \"client_unavailable\");\n }\n if (clientId) {\n body.set(\"client_id\", clientId);\n }\n const tokenRequestEncoding =\n stringValue(\n (cred.credential as { token_request_encoding?: unknown }).token_request_encoding,\n ) === \"json\"\n ? \"json\"\n : \"form\";\n const headers: Record<string, string> = {\n \"content-type\":\n tokenRequestEncoding === \"json\" ? \"application/json\" : \"application/x-www-form-urlencoded\",\n };\n if (clientSecret && authMethod === \"client_secret_post\") {\n body.set(\"client_secret\", clientSecret);\n } else if (clientId && clientSecret && authMethod === \"client_secret_basic\") {\n headers.authorization = `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString(\"base64\")}`;\n }\n const resource =\n ref.resource ?? stringValue((cred.credential as { resource?: unknown }).resource);\n const resourceParameterSupported =\n (cred.credential as { resource_parameter_supported?: unknown }).resource_parameter_supported !==\n false;\n if (resource && resourceParameterSupported) {\n body.set(\"resource\", resource);\n }\n const scopeParameterSupported =\n (cred.credential as { scope_parameter_supported?: unknown }).scope_parameter_supported !==\n false;\n if (ref.scopes?.length && scopeParameterSupported) {\n body.set(\"scope\", ref.scopes.join(\" \"));\n }\n const requestBody: BodyInit =\n tokenRequestEncoding === \"json\" ? JSON.stringify(Object.fromEntries(body.entries())) : body;\n const response = await pinnedFetch(\n validatedTokenEndpoint,\n {\n method: \"POST\",\n headers,\n body: requestBody,\n signal: AbortSignal.timeout(CONNECTION_REFRESH_TIMEOUT_MS),\n },\n settings,\n {\n fetchImpl: transportOptions.fetchImpl ?? undiciFetch,\n ...(transportOptions.dnsLookup ? { dnsLookup: transportOptions.dnsLookup } : {}),\n label: \"OAuth token endpoint\",\n requireHttpsOutsideLocalTest: true,\n },\n );\n if (response.status >= 300 && response.status < 400) {\n await cancelResponseBody(response);\n throw new ConnectionRefreshHttpError(response.status);\n }\n if (!response.ok) {\n throw new ConnectionRefreshHttpError(\n response.status,\n await readOAuthRefreshErrorCode(response),\n );\n }\n const payload = await readResponseJsonBounded<Record<string, unknown>>(\n response,\n OAUTH_MAX_RESPONSE_BYTES,\n \"OAuth refresh token response\",\n );\n const accessToken = stringValue(payload.access_token);\n if (!accessToken) {\n throw new Error(\"connection refresh response did not include access_token\");\n }\n const expiresAt = expiresAtFromTokenResponse(payload, cred.expiresAt);\n const scopeText = stringValue(payload.scope);\n const returnedScopes = scopeText?.split(/[\\s,]+/).filter(Boolean) ?? [];\n // A successful Microsoft refresh proves offline access, although Microsoft\n // reports only access-token permissions in the response's scope field.\n if (\n scopeText &&\n ref.providerDomain.toLowerCase() === \"graph.microsoft.com\" &&\n !returnedScopes.some((scope) => scope.toLowerCase() === \"offline_access\")\n ) {\n returnedScopes.push(\"offline_access\");\n }\n const refreshTokenExpiresIn =\n typeof payload.refresh_token_expires_in === \"number\"\n ? payload.refresh_token_expires_in\n : undefined;\n const refreshTokenExpiresAt =\n personalGitHub && refreshTokenExpiresIn && refreshTokenExpiresIn > 0\n ? new Date(Date.now() + refreshTokenExpiresIn * 1000).toISOString()\n : null;\n if (\n personalGitHub &&\n scopeText &&\n (returnedScopes.length !== PERSONAL_GITHUB_REQUESTED_SCOPES.length ||\n returnedScopes.some((scope) => !PERSONAL_GITHUB_REQUESTED_SCOPES.includes(scope as \"repo\")))\n ) {\n throw new ConnectionRefreshHttpError(401, \"scope_changed\");\n }\n const nextCredential = {\n ...cred.credential,\n access_token: accessToken,\n refresh_token: stringValue(payload.refresh_token) ?? refreshToken,\n token_type:\n stringValue(payload.token_type) ??\n stringValue((cred.credential as { token_type?: unknown }).token_type) ??\n \"Bearer\",\n ...(expiresAt ? { expires_at: expiresAt.toISOString() } : {}),\n ...(resource ? { resource } : {}),\n ...(scopeText\n ? {\n scope:\n ref.providerDomain.toLowerCase() === \"graph.microsoft.com\"\n ? returnedScopes.join(\" \")\n : scopeText,\n }\n : {}),\n ...(refreshTokenExpiresAt ? { refresh_token_expires_at: refreshTokenExpiresAt } : {}),\n ...(clientSecret && !personalGitHub\n ? { client_secret: clientSecret, token_endpoint_auth_method: authMethod }\n : {}),\n };\n return {\n credential: nextCredential,\n expiresAt,\n ...(personalGitHub\n ? { grantedScopes: [...PERSONAL_GITHUB_REQUESTED_SCOPES] }\n : scopeText\n ? { grantedScopes: returnedScopes }\n : {}),\n ...(refreshTokenExpiresAt\n ? {\n metadata: PersonalGitHubConnectionMetadata.parse({\n ...personalGitHubMetadata.data,\n refreshTokenExpiresAt,\n }),\n }\n : {}),\n };\n}\n\nasync function readOAuthRefreshErrorCode(response: Response): Promise<string | null> {\n try {\n const payload = await readResponseJsonBounded<Record<string, unknown>>(\n response,\n OAUTH_MAX_RESPONSE_BYTES,\n \"OAuth refresh error response\",\n );\n const code = stringValue(payload.error);\n return code && /^[a-z0-9_.-]{1,64}$/i.test(code) ? code : null;\n } catch {\n await cancelResponseBody(response);\n return null;\n }\n}\n\nfunction expiresAtFromTokenResponse(\n payload: Record<string, unknown>,\n fallback: Date | null,\n): Date | null {\n const expiresAt = stringValue(payload.expires_at);\n if (expiresAt) {\n const parsed = new Date(expiresAt);\n return Number.isNaN(parsed.getTime()) ? fallback : parsed;\n }\n const expiresIn = typeof payload.expires_in === \"number\" ? payload.expires_in : undefined;\n if (expiresIn && Number.isFinite(expiresIn) && expiresIn > 0) {\n return new Date(Date.now() + expiresIn * 1000);\n }\n return fallback;\n}\n\nfunction stringRecord(value: unknown): Record<string, string> | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return null;\n }\n const out: Record<string, string> = {};\n for (const [key, raw] of Object.entries(value)) {\n if (typeof raw !== \"string\") {\n return null;\n }\n out[key] = raw;\n }\n return out;\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nasync function cancelResponseBody(response: Response): Promise<void> {\n await response.body?.cancel().catch(() => undefined);\n}\n","import { sql } from \"drizzle-orm\";\nimport { setSubjectRlsContext, withRlsContext, type Database } from \"./database\";\nimport type { ConnectionCredentialForBroker } from \"./connection-token-resolver\";\n\n/** Serialize rotating-token exchange across workers, not only within one process. */\nexport async function withConnectionRefreshLock<T>(\n db: Database,\n credential: ConnectionCredentialForBroker,\n work: (lockedDb: Database) => Promise<T>,\n): Promise<T> {\n return withRlsContext(\n db,\n { accountId: credential.accountId, workspaceId: credential.workspaceId },\n async (tx) => {\n if (credential.subjectId) await setSubjectRlsContext(tx, credential.subjectId);\n await tx.execute(\n sql`select pg_advisory_xact_lock(hashtextextended(${`connection-refresh:${credential.id}`}, 0))`,\n );\n return work(tx);\n },\n );\n}\n","/**\n * Canonical comparison key for provider-reported OAuth scopes.\n *\n * Google may return the canonical userinfo scope URLs after the application\n * requested the standard `email` / `profile` aliases. Microsoft scope names\n * are case-insensitive. All other providers retain exact comparison.\n */\nexport function connectionScopeKey(providerDomain: string, value: string): string {\n const scope = value.trim();\n const domain = providerDomain.toLowerCase();\n if (domain === \"googleapis.com\" || domain.endsWith(\".googleapis.com\")) {\n if (scope === \"email\" || scope === \"https://www.googleapis.com/auth/userinfo.email\") {\n return \"google:email\";\n }\n if (scope === \"profile\" || scope === \"https://www.googleapis.com/auth/userinfo.profile\") {\n return \"google:profile\";\n }\n }\n return domain === \"graph.microsoft.com\" ? scope.toLowerCase() : scope;\n}\n"],"mappings":";;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAAe,uBAAuB;AAgB/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,wBAAwB;AACjC,SAAS,cAAc;;;ACtCvB,SAAS,WAAW;AAKpB,eAAsB,0BACpB,IACA,YACA,MACY;AACZ,SAAO;AAAA,IACL;AAAA,IACA,EAAE,WAAW,WAAW,WAAW,aAAa,WAAW,YAAY;AAAA,IACvE,OAAO,OAAO;AACZ,UAAI,WAAW,UAAW,OAAM,qBAAqB,IAAI,WAAW,SAAS;AAC7E,YAAM,GAAG;AAAA,QACP,oDAAoD,sBAAsB,WAAW,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AAM,YAAY,OAAO,QAAQ,eAAe,WAAW,QAAQ,aAAa;AAChF,MAAI,aAAa,OAAO,SAAS,SAAS,KAAK,YAAY,GAAG;AAC5D,WAAO,IAAI,KAAK,KAAK,IAAI,IAAI,YAAY,GAAI;AAAA,EAC/C;AACA,SAAO;AACT;AAEA,SAAS,aAAa,OAA+C;AACnE,MAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG;AAC/D,WAAO;AAAA,EACT;AACA,QAAM,MAA8B,CAAC;AACrC,aAAW,CAAC,KAAK,GAAG,KAAK,OAAO,QAAQ,KAAK,GAAG;AAC9C,QAAI,OAAO,QAAQ,UAAU;AAC3B,aAAO;AAAA,IACT;AACA,QAAI,GAAG,IAAI;AAAA,EACb;AACA,SAAO;AACT;AAEA,SAAS,YAAY,OAAoC;AACvD,SAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ;AACjE;AAEA,eAAe,mBAAmB,UAAmC;AACnE,QAAM,SAAS,MAAM,OAAO,EAAE,MAAM,MAAM,MAAS;AACrD;","names":["key"]}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  rawRows,
3
3
  withWorkspaceSubjectRls
4
- } from "./chunk-VTH2TKNI.js";
4
+ } from "./chunk-5TXWWAJP.js";
5
5
 
6
6
  // src/connect-attempts.ts
7
7
  import { createHash } from "crypto";
@@ -245,4 +245,4 @@ export {
245
245
  claimConnectOperation,
246
246
  finishConnectOperation
247
247
  };
248
- //# sourceMappingURL=chunk-I6HYVEFV.js.map
248
+ //# sourceMappingURL=chunk-2GZRWV36.js.map
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  databaseBootConnectOptions
3
- } from "./chunk-PGZ34T44.js";
3
+ } from "./chunk-SMCA7PNJ.js";
4
4
  import {
5
5
  LOSSLESS_CONTENT_WRITER_APPLICATION_NAME,
6
6
  schema_exports,
7
7
  sessions,
8
8
  workspaceSessionActivityRevisions,
9
9
  workspaces
10
- } from "./chunk-HFNTVT5I.js";
10
+ } from "./chunk-GDMYQ55A.js";
11
11
 
12
12
  // src/persistence-errors.ts
13
13
  var SQLSTATE_KEYS = ["sqlState", "sqlstate", "code"];
@@ -985,4 +985,4 @@ export {
985
985
  withAccountRls,
986
986
  dbBindingFor
987
987
  };
988
- //# sourceMappingURL=chunk-VTH2TKNI.js.map
988
+ //# sourceMappingURL=chunk-5TXWWAJP.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  subscriptionCoreProvider
3
- } from "./chunk-IYUTXSFX.js";
3
+ } from "./chunk-RK3MKIHK.js";
4
4
 
5
5
  // src/subscription-core/provider.ts
6
6
  function subscriptionCoreProviderId(provider) {
@@ -32,4 +32,4 @@ export {
32
32
  subscriptionCoreConnectionKind,
33
33
  memoByProvider
34
34
  };
35
- //# sourceMappingURL=chunk-UWJCRJC5.js.map
35
+ //# sourceMappingURL=chunk-6ZSZIMC7.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  nestedPostgresSqlState,
3
3
  rawRows
4
- } from "./chunk-VTH2TKNI.js";
4
+ } from "./chunk-5TXWWAJP.js";
5
5
 
6
6
  // src/managed-auth-session-sets.ts
7
7
  import {
@@ -296,4 +296,4 @@ export {
296
296
  reapManagedAuthIsolatedSessions,
297
297
  reapExpiredManagedAuthSessionSets
298
298
  };
299
- //# sourceMappingURL=chunk-YS3D7KV5.js.map
299
+ //# sourceMappingURL=chunk-77VCFW25.js.map
@@ -7,7 +7,7 @@ import {
7
7
  withAccountRls,
8
8
  withRlsContext,
9
9
  withWorkspaceRls
10
- } from "./chunk-VTH2TKNI.js";
10
+ } from "./chunk-5TXWWAJP.js";
11
11
  import {
12
12
  connections,
13
13
  creditDebitAllocations,
@@ -20,7 +20,7 @@ import {
20
20
  workspaceVideoGenerationPolicies,
21
21
  workspaceVideoGenerationQuotas,
22
22
  workspaces
23
- } from "./chunk-HFNTVT5I.js";
23
+ } from "./chunk-GDMYQ55A.js";
24
24
 
25
25
  // src/video-generation.ts
26
26
  import {
@@ -1412,4 +1412,4 @@ export {
1412
1412
  mediaGenerationResultForStoredOperation,
1413
1413
  getVideoGenerationOperationSummary
1414
1414
  };
1415
- //# sourceMappingURL=chunk-5JRYRG7Z.js.map
1415
+ //# sourceMappingURL=chunk-BSRJZ6M5.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  nestedPostgresSqlState,
3
3
  rawRows
4
- } from "./chunk-VTH2TKNI.js";
4
+ } from "./chunk-5TXWWAJP.js";
5
5
 
6
6
  // src/canonical-human-identities.ts
7
7
  import { createHash } from "crypto";
@@ -318,4 +318,4 @@ export {
318
318
  getCanonicalHumanIdentityProjection,
319
319
  applyCanonicalHumanIdentityOperation
320
320
  };
321
- //# sourceMappingURL=chunk-5HD6PLH4.js.map
321
+ //# sourceMappingURL=chunk-EIYWCPZN.js.map
@@ -6,7 +6,7 @@ import {
6
6
  rlsContextForWorkspace,
7
7
  setSubjectRlsContext,
8
8
  withRlsContext
9
- } from "./chunk-VTH2TKNI.js";
9
+ } from "./chunk-5TXWWAJP.js";
10
10
 
11
11
  // src/organization-integration-policy.ts
12
12
  import {
@@ -153,4 +153,4 @@ export {
153
153
  withOrganizationIntegrationPolicyFence,
154
154
  withOrganizationIntegrationAcquisition
155
155
  };
156
- //# sourceMappingURL=chunk-PYBW3KGM.js.map
156
+ //# sourceMappingURL=chunk-F4BP3GNU.js.map
@@ -2,7 +2,7 @@ import {
2
2
  memoByProvider,
3
3
  subscriptionCoreConnectionKind,
4
4
  subscriptionCoreProviderId
5
- } from "./chunk-UWJCRJC5.js";
5
+ } from "./chunk-6ZSZIMC7.js";
6
6
  import {
7
7
  SUBSCRIPTION_CORE_CODEX,
8
8
  SubscriptionCoreCodexAccessLostError,
@@ -20,12 +20,12 @@ import {
20
20
  releaseSubscriptionTurnLease,
21
21
  subscriptionCoreCodexProvider,
22
22
  writeSubscriptionSessionBinding
23
- } from "./chunk-IYUTXSFX.js";
23
+ } from "./chunk-RK3MKIHK.js";
24
24
  import {
25
25
  rawRows,
26
26
  withRlsContext,
27
27
  withSessionRlsActorContext
28
- } from "./chunk-VTH2TKNI.js";
28
+ } from "./chunk-5TXWWAJP.js";
29
29
 
30
30
  // src/subscription-core-codex.ts
31
31
  import { CodexReloginRequired } from "@opengeni/codex";
@@ -128,6 +128,7 @@ import {
128
128
  personalFallbackActive,
129
129
  decidePlacement,
130
130
  quotaCapacity,
131
+ storedQuotaDocument,
131
132
  subscriptionCoreCredentialRefresher as subscriptionCoreCredentialRefresher2
132
133
  } from "@opengeni/subscriptions";
133
134
 
@@ -537,6 +538,7 @@ var SubscriptionBindingConflict = class extends Error {
537
538
  }
538
539
  };
539
540
  var BINDING_CONFLICT_RETRIES = 3;
541
+ var SUBSCRIPTION_CORE_REFUSAL_CLAIM_MS = 2 * 6e4;
540
542
  var DELETED_EXPLICIT_WAIT = {
541
543
  kind: "wait",
542
544
  reason: "pinned_account_ineligible",
@@ -947,6 +949,7 @@ var subscriptionCoreTurns = memoByProvider((provider) => {
947
949
  }
948
950
  async function recordSubscriptionCoreModelCooldown(db, identity, lease, input) {
949
951
  if (!input.modelId.trim() || input.modelId.length > 256) return false;
952
+ const claimSince = input.refusedAt === void 0 ? null : input.refusedAt - SUBSCRIPTION_CORE_REFUSAL_CLAIM_MS;
950
953
  const access = await withLeasedConnection(db, identity, lease, async (tx) => {
951
954
  const [connection] = await rawRows(
952
955
  tx,
@@ -963,6 +966,28 @@ var subscriptionCoreTurns = memoByProvider((provider) => {
963
966
  exhaustedKind: null,
964
967
  source: "refusal"
965
968
  };
969
+ const stored = sql2`subscription_connection_quota.quota`;
970
+ const until = sql2`greatest(
971
+ coalesce((${stored}->'modelCooldowns'->>${input.modelId}::text)::bigint, 0),
972
+ ${input.until.getTime()}::bigint
973
+ )`;
974
+ const claim = sql2`(${stored}->'modelCooldownClaims'->${input.modelId}::text)`;
975
+ const cooled = sql2`jsonb_set(
976
+ case when jsonb_typeof(${stored}->'modelCooldowns') = 'object'
977
+ then ${stored}
978
+ else jsonb_set(${stored}, '{modelCooldowns}', '{}'::jsonb)
979
+ end,
980
+ array['modelCooldowns', ${input.modelId}],
981
+ to_jsonb(${until})
982
+ )`;
983
+ const keepClaim = sql2`(
984
+ ${claimSince}::bigint is not null
985
+ and jsonb_typeof(${claim}) = 'object'
986
+ and ${claim}->'until' = ${stored}->'modelCooldowns'->${input.modelId}::text
987
+ and case when jsonb_typeof(${claim}->'observedAt') = 'number'
988
+ then (${claim}->>'observedAt')::numeric >= ${claimSince}::bigint
989
+ else false end
990
+ )`;
966
991
  const rows = await rawRows(
967
992
  tx,
968
993
  sql2`insert into subscription_connection_quota (
@@ -982,16 +1007,20 @@ var subscriptionCoreTurns = memoByProvider((provider) => {
982
1007
  when subscription_connection_quota.observed_refresh_generation
983
1008
  is distinct from excluded.observed_refresh_generation
984
1009
  then excluded.quota
1010
+ when ${stored}->'modelCooldownClaims' is null then ${cooled}
1011
+ when jsonb_typeof(${stored}->'modelCooldownClaims') <> 'object'
1012
+ then ${cooled} - 'modelCooldownClaims'
985
1013
  else jsonb_set(
986
- case when jsonb_typeof(subscription_connection_quota.quota->'modelCooldowns') = 'object'
987
- then subscription_connection_quota.quota
988
- else jsonb_set(subscription_connection_quota.quota, '{modelCooldowns}', '{}'::jsonb)
989
- end,
990
- array['modelCooldowns', ${input.modelId}],
991
- to_jsonb(greatest(
992
- coalesce((subscription_connection_quota.quota->'modelCooldowns'->>${input.modelId})::bigint, 0),
993
- ${input.until.getTime()}::bigint
994
- ))
1014
+ ${cooled},
1015
+ '{modelCooldownClaims}',
1016
+ ((${stored}->'modelCooldownClaims') - ${input.modelId}::text) ||
1017
+ case when ${keepClaim}
1018
+ then jsonb_build_object(
1019
+ ${input.modelId}::text,
1020
+ ${claim} || jsonb_build_object('until', ${until})
1021
+ )
1022
+ else '{}'::jsonb
1023
+ end
995
1024
  )
996
1025
  end,
997
1026
  updated_at = case
@@ -1292,13 +1321,7 @@ var subscriptionCoreTurns = memoByProvider((provider) => {
1292
1321
  if (!next || next === current) return { applied: false, recovered: false };
1293
1322
  const observedNow = observation.observedAt ?? Date.now();
1294
1323
  const recovered = current !== null && quotaCapacity(current, observedNow).kind === "exhausted" && quotaCapacity(next, observedNow).kind !== "exhausted";
1295
- const stored = {
1296
- windows: next.windows,
1297
- modelCooldowns: next.modelCooldowns,
1298
- exhaustedUntil: next.exhaustedUntil,
1299
- exhaustedKind: next.exhaustedKind,
1300
- source: next.source
1301
- };
1324
+ const stored = storedQuotaDocument(next);
1302
1325
  const observedAt = new Date(next.observedAt ?? Date.now()).toISOString();
1303
1326
  await tx.execute(
1304
1327
  sql2`insert into subscription_connection_quota (
@@ -1515,4 +1538,4 @@ export {
1515
1538
  refreshSubscriptionCoreCodexCredential,
1516
1539
  buildSubscriptionCoreCodexTokenResolver
1517
1540
  };
1518
- //# sourceMappingURL=chunk-3VEDJM6S.js.map
1541
+ //# sourceMappingURL=chunk-F5JG7FDH.js.map