@agent-native/core 0.231.0 → 0.232.0-nightly-20261118152333

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 (71) hide show
  1. package/dist/a2a/call-hooks.d.ts +135 -0
  2. package/dist/a2a/call-hooks.js +164 -0
  3. package/dist/a2a/client.d.ts +5 -0
  4. package/dist/a2a/client.js +22 -0
  5. package/dist/a2a/foreground-call-scope.d.ts +6 -0
  6. package/dist/a2a/foreground-call-scope.js +26 -0
  7. package/dist/a2a/handlers.js +119 -2
  8. package/dist/a2a/index.d.ts +3 -0
  9. package/dist/a2a/index.js +2 -0
  10. package/dist/a2a/invoke.js +17 -0
  11. package/dist/a2a/server.js +3 -0
  12. package/dist/action.js +3 -1
  13. package/dist/agent/durable-background.d.ts +6 -0
  14. package/dist/agent/durable-background.js +6 -0
  15. package/dist/agent/durable-turn-grant.d.ts +53 -0
  16. package/dist/agent/durable-turn-grant.js +83 -0
  17. package/dist/agent/production-agent.js +54 -2
  18. package/dist/app-config/agent.d.ts +1 -0
  19. package/dist/app-config/agent.js +7 -0
  20. package/dist/app-config/schema.d.ts +1 -0
  21. package/dist/cli/doctor.d.ts +1 -0
  22. package/dist/cli/doctor.js +10 -4
  23. package/dist/client/sharing/useShareButtonController.d.ts +5 -0
  24. package/dist/client/sharing/useShareButtonController.js +2 -1
  25. package/dist/client/use-chat-threads.js +3 -0
  26. package/dist/client/use-db-sync.js +22 -0
  27. package/dist/collab/routes.d.ts +1 -1
  28. package/dist/deploy/build.d.ts +4 -1
  29. package/dist/deploy/build.js +25 -15
  30. package/dist/file-upload/actions/upload-image.d.ts +2 -2
  31. package/dist/framework-package-versions.json +7 -7
  32. package/dist/guards/index.d.ts +1 -1
  33. package/dist/guards/index.js +1 -1
  34. package/dist/guards/no-env-credentials.d.ts +15 -1
  35. package/dist/guards/no-env-credentials.js +27 -0
  36. package/dist/integrations/internal-token.d.ts +15 -0
  37. package/dist/integrations/internal-token.js +19 -0
  38. package/dist/mcp/build-server.js +18 -2
  39. package/dist/mcp/index.d.ts +1 -0
  40. package/dist/mcp/index.js +1 -0
  41. package/dist/mcp/turn-grant-admitters.d.ts +61 -0
  42. package/dist/mcp/turn-grant-admitters.js +83 -0
  43. package/dist/mcp/turn-grant-store.d.ts +5 -0
  44. package/dist/mcp/turn-grant-store.js +19 -0
  45. package/dist/org/index.d.ts +2 -2
  46. package/dist/org/workspace-app-access.js +30 -11
  47. package/dist/provider-api/actions/custom-provider-registration.d.ts +16 -16
  48. package/dist/provider-api/actions/provider-api.d.ts +8 -8
  49. package/dist/provider-api/call-gates.d.ts +71 -2
  50. package/dist/provider-api/call-gates.js +157 -3
  51. package/dist/provider-api/corpus-jobs.d.ts +2 -2
  52. package/dist/provider-api/index.d.ts +1 -1
  53. package/dist/provider-api/index.js +1 -1
  54. package/dist/provider-api/interactive-scope.d.ts +2 -1
  55. package/dist/provider-api/interactive-scope.js +17 -4
  56. package/dist/server/agent-chat-plugin.js +9 -2
  57. package/dist/server/agent-run-context.d.ts +1 -1
  58. package/dist/server/agent-run-context.js +34 -3
  59. package/dist/server/entry-server.js +3 -1
  60. package/dist/server/transcribe-voice.d.ts +1 -1
  61. package/dist/shared/build-id.d.ts +14 -0
  62. package/dist/shared/build-id.js +21 -0
  63. package/dist/vite/client.d.ts +16 -0
  64. package/dist/vite/client.js +6 -3
  65. package/dist/vitest-config.js +1 -0
  66. package/dist/workspace-connections/workspace-credential-actions.d.ts +1 -0
  67. package/dist/workspace-connections/workspace-credential-actions.js +1 -0
  68. package/dist/workspace-connections/workspace-credentials.d.ts +4 -0
  69. package/dist/workspace-connections/workspace-credentials.js +40 -4
  70. package/docs/workspace-credential-drafts.md +28 -0
  71. package/package.json +5 -4
@@ -77,6 +77,30 @@ const DEV_ONLY_PATH_PATTERNS = [
77
77
  /^scripts\//,
78
78
  ];
79
79
  const DEV_ONLY_KEYS = new Set(["ANTHROPIC_API_KEY"]);
80
+ const TEST_PATH = /(?:^|\/)tests\/|\.(?:spec|test)\.[cm]?[tj]sx?$/;
81
+ /** Key names a test-only allowance can never cover: those are credentials. */
82
+ const CREDENTIAL_LIKE_KEY = /KEY|TOKEN|SECRET|PASSW(?:OR)?D|PASSPHRASE|PWD|WEBHOOK|CREDENTIAL|AUTH|COOKIE|SESSION|PRIVATE|CERT|(?:^|_)PAT(?:_|$)|(?:^|_)JWT(?:_|$)|(?:^|_)DSN(?:_|$)|CONNECTION_STRING|(?:^|_)(?:DATABASE|DB|POSTGRES(?:QL)?|PG|MYSQL|REDIS|MONGO(?:DB)?|AMQP|RABBITMQ)_UR[LI](?:_|$)/;
83
+ /**
84
+ * Validates `doctor.testEnvKeys`. Throws on anything but env key names, and on
85
+ * a credential-like name, so a bad entry fails the guard rather than reading
86
+ * as an empty list or widening it to a secret.
87
+ */
88
+ export function parseTestEnvKeys(value) {
89
+ if (value === undefined)
90
+ return [];
91
+ if (!Array.isArray(value)) {
92
+ throw new Error("doctor.testEnvKeys must be an array of env key names.");
93
+ }
94
+ for (const key of value) {
95
+ if (typeof key !== "string" || !/^[A-Z][A-Z0-9_]*$/.test(key)) {
96
+ throw new Error(`doctor.testEnvKeys entry ${JSON.stringify(key)} is not an env key name.`);
97
+ }
98
+ if (CREDENTIAL_LIKE_KEY.test(key)) {
99
+ throw new Error(`doctor.testEnvKeys entry "${key}" looks like a credential; tests read credentials through the vault, not process.env.`);
100
+ }
101
+ }
102
+ return value;
103
+ }
80
104
  const OPT_OUT_MARKER = /\/\/\s*guard:allow-env-credential\b[^\n]*/;
81
105
  const OPT_OUT_REQUIRES_REASON = /\/\/\s*guard:allow-env-credential\s*[—-]\s*\S/;
82
106
  const ENV_READ_REGEX = /process\.env(?:\.([A-Z][A-Z0-9_]*)|\[\s*["']([A-Z][A-Z0-9_]*)["']\s*\])/g;
@@ -126,6 +150,7 @@ function optOutOnLineIsValid(lines, lineIdx, key, rel) {
126
150
  }
127
151
  export function scanEnvCredentials(options) {
128
152
  const { root } = options;
153
+ const testEnvKeys = new Set(options.testEnvKeys ?? []);
129
154
  const findings = [];
130
155
  for (const file of walk(root)) {
131
156
  if (!/\.(ts|tsx|mts|cts|js|mjs|cjs)$/.test(file))
@@ -154,6 +179,8 @@ export function scanEnvCredentials(options) {
154
179
  }
155
180
  if (isAllowlistedKey(key))
156
181
  continue;
182
+ if (testEnvKeys.has(key) && TEST_PATH.test(rel))
183
+ continue;
157
184
  if (hasOptOutOnLine(lines, lineIdx)) {
158
185
  const verdict = optOutOnLineIsValid(lines, lineIdx, key, rel);
159
186
  if (verdict.ok)
@@ -1,5 +1,20 @@
1
1
  export declare function signInternalToken(taskId: string): string;
2
2
  export declare function verifyInternalToken(taskId: string, token: string): boolean;
3
+ /** What a durable chat run carries to prove its turn was started interactively. */
4
+ export interface DurableTurnGrantClaim {
5
+ /** The dispatched run; a recovery successor run never inherits the grant. */
6
+ runId: string;
7
+ turnId: string;
8
+ initiator: {
9
+ email: string;
10
+ authUserId?: string | null;
11
+ orgId?: string | null;
12
+ orgScope?: "personal" | null;
13
+ };
14
+ expiresAt: number;
15
+ }
16
+ export declare function signDurableTurnGrant(claim: DurableTurnGrantClaim): string;
17
+ export declare function verifyDurableTurnGrant(claim: DurableTurnGrantClaim, signature: unknown): boolean;
3
18
  /** Signs an MCP chat-turn claim; throws when A2A_SECRET is not set. */
4
19
  export declare function signMcpChatTurnProof(payload: readonly unknown[]): string;
5
20
  /** Throws when A2A_SECRET is not set, so a missing secret is not a forgery. */
@@ -66,6 +66,25 @@ export function verifyInternalToken(taskId, token) {
66
66
  }
67
67
  return safeEqual(sig, expected);
68
68
  }
69
+ function durableTurnGrantHex(claim) {
70
+ return hmacHex(getSecret(), `agent-native:durable-turn-grant:${JSON.stringify([
71
+ claim.runId,
72
+ claim.turnId,
73
+ claim.initiator.email,
74
+ claim.initiator.authUserId ?? null,
75
+ claim.initiator.orgId ?? null,
76
+ claim.initiator.orgScope ?? null,
77
+ claim.expiresAt,
78
+ ])}`);
79
+ }
80
+ export function signDurableTurnGrant(claim) {
81
+ return durableTurnGrantHex(claim);
82
+ }
83
+ export function verifyDurableTurnGrant(claim, signature) {
84
+ if (typeof signature !== "string")
85
+ return false;
86
+ return safeEqual(signature, durableTurnGrantHex(claim));
87
+ }
69
88
  // The prefix keeps a chat-turn proof from ever verifying as another token.
70
89
  function mcpChatTurnProofHex(payload) {
71
90
  return hmacHex(getSecret(), `agent-native:mcp-chat-turn:${JSON.stringify(payload)}`);
@@ -28,9 +28,10 @@ import { mcpApprovalPrompt, mcpApprovalRelativeLinkNote, mcpApprovalReviewUrl, }
28
28
  import { mcpApprovalAppId } from "./approval-store.js";
29
29
  import { runWithMcpChatTurnCall } from "./chat-turn-scope.js";
30
30
  import { isFrameworkMcpTool } from "./framework-tools.js";
31
+ import { admitWithMcpTurnGrantAdmitters, } from "./turn-grant-admitters.js";
31
32
  import { recordTurnGrantConnectCredential } from "./turn-grant-identity.js";
32
33
  import { actionUserTurn, isAgentTurnGrantContext, MCP_USER_TURN_META_KEY, requiresTurnGrantPageApproval, runWithMcpTurnGrantScope, runWithoutMcpTurnGrantScope, } from "./turn-grant-scope.js";
33
- import { admitMcpTurnGrant, } from "./turn-grant-store.js";
34
+ import { admitMcpTurnGrant, turnGrantCallerRefusal, } from "./turn-grant-store.js";
34
35
  export { isAutoReadExcludedActionName } from "./action-eligibility.js";
35
36
  import { isMcpAppsInlineEnabled } from "./app-cards-lab.js";
36
37
  import { createBrowserTabTargetSlot, withBrowserTabTargetNote, } from "./browser-tab-target.js";
@@ -3212,11 +3213,26 @@ export async function createMCPServerForRequest(config, identity, requestMeta) {
3212
3213
  if (userTurn === undefined && turnGrant === undefined) {
3213
3214
  return runWithoutMcpTurnGrantScope(call);
3214
3215
  }
3215
- const admission = turnGrantExcluded
3216
+ let admission = turnGrantExcluded
3216
3217
  ? { status: "refused", reason: "agent-context" }
3217
3218
  : userTurn === undefined
3218
3219
  ? { status: "refused", reason: "action-not-allowlisted" }
3219
3220
  : await admitMcpTurnGrant(turnGrant, config.appId ?? "", effectiveIdentity);
3221
+ if (admission.status === "refused" &&
3222
+ admission.reason === "unknown" &&
3223
+ turnGrant !== undefined &&
3224
+ userTurn !== undefined) {
3225
+ const callerRefusal = await turnGrantCallerRefusal(effectiveIdentity);
3226
+ admission = callerRefusal
3227
+ ? { status: "refused", reason: callerRefusal }
3228
+ : ((await admitWithMcpTurnGrantAdmitters({
3229
+ grant: turnGrant,
3230
+ appId: config.appId ?? "",
3231
+ actionName: name,
3232
+ userTurn,
3233
+ identity: effectiveIdentity,
3234
+ })) ?? admission);
3235
+ }
3220
3236
  if (admission.status === "refused") {
3221
3237
  console.info("[mcp-turn-grant] refused", {
3222
3238
  reason: admission.reason,
@@ -13,6 +13,7 @@ export { getBuiltinCrossAppTools } from "./builtin-tools.js";
13
13
  export { mcpChatTurnOwner } from "./chat-turn-scope.js";
14
14
  export { MCP_CHAT_TURN_FIELD, mintMcpChatTurn, registerMcpChatTurnApps, type McpChatTurnBinding, } from "./chat-turn-store.js";
15
15
  export { isMcpTurnGrantAction, MCP_TURN_GRANT_HEADER, MCP_USER_TURN_META_KEY, } from "./turn-grant-scope.js";
16
+ export { listMcpTurnGrantAdmitters, registerMcpTurnGrantAdmitter, type McpTurnGrantAdmitter, type McpTurnGrantAdmitterDecision, type McpTurnGrantPresentation, } from "./turn-grant-admitters.js";
16
17
  export { embedApp, MCP_APP_REQUEST_ORIGIN_CSP_SOURCE, type EmbedAppOptions, } from "./embed-app.js";
17
18
  export { embedRoute, type EmbedRouteContext, type EmbedRouteOptions, type EmbedRoutePathBuilder, type EmbedRouteResult, } from "./embed-route.js";
18
19
  export { resolveWorkspace, resolveLocalAppOrigin, findWorkspaceRoot, } from "./workspace-resolve.js";
package/dist/mcp/index.js CHANGED
@@ -7,6 +7,7 @@ export { getBuiltinCrossAppTools } from "./builtin-tools.js";
7
7
  export { mcpChatTurnOwner } from "./chat-turn-scope.js";
8
8
  export { MCP_CHAT_TURN_FIELD, mintMcpChatTurn, registerMcpChatTurnApps, } from "./chat-turn-store.js";
9
9
  export { isMcpTurnGrantAction, MCP_TURN_GRANT_HEADER, MCP_USER_TURN_META_KEY, } from "./turn-grant-scope.js";
10
+ export { listMcpTurnGrantAdmitters, registerMcpTurnGrantAdmitter, } from "./turn-grant-admitters.js";
10
11
  export { embedApp, MCP_APP_REQUEST_ORIGIN_CSP_SOURCE, } from "./embed-app.js";
11
12
  export { embedRoute, } from "./embed-route.js";
12
13
  export { resolveWorkspace, resolveLocalAppOrigin, findWorkspaceRoot, } from "./workspace-resolve.js";
@@ -0,0 +1,61 @@
1
+ import type { ActionUserTurn } from "../action.js";
2
+ import type { MCPCallerIdentity } from "./build-server.js";
3
+ /**
4
+ * MCP turn grant admitters: deployment-owned admission for turn grants the
5
+ * framework's own store does not recognize, such as a grant another
6
+ * deployment-owned service minted for the user's current turn.
7
+ *
8
+ * An admitter is asked only after the framework has looked the presented
9
+ * grant up and found nothing, and only for an action that declares
10
+ * `userTurn`, from a device-connected user caller outside an agent run. An admitted grant runs the
11
+ * call exactly like a framework grant: as the user's turn until `expiresAt`,
12
+ * and only for the owner and app the decision names.
13
+ * With no admitter registered the MCP action path behaves exactly as without
14
+ * this module.
15
+ */
16
+ /** A turn grant presented with one MCP action call. */
17
+ export interface McpTurnGrantPresentation {
18
+ /** The raw grant the caller presented (the turn-grant header value). */
19
+ grant: string;
20
+ appId: string;
21
+ actionName: string;
22
+ userTurn: ActionUserTurn;
23
+ identity: MCPCallerIdentity | undefined;
24
+ }
25
+ export type McpTurnGrantAdmitterDecision = {
26
+ status: "admitted";
27
+ expiresAt: number;
28
+ /** The user the grant was issued to; must be the calling user. */
29
+ ownerEmail: string;
30
+ /** The app the grant was issued for; must be this app. */
31
+ appId: string;
32
+ } | {
33
+ status: "refused";
34
+ reason: string;
35
+ };
36
+ export interface McpTurnGrantAdmitter {
37
+ /** Stable id; registering a different admitter under the same id throws. */
38
+ id: string;
39
+ /**
40
+ * Admit or refuse a grant this admitter recognizes. Return undefined for a
41
+ * grant it does not own, so the next admitter is asked. A throw refuses the
42
+ * grant as `admitter-failed`, and no answer within
43
+ * `MCP_TURN_GRANT_ADMITTER_TIMEOUT_MS` as `admitter-timeout`.
44
+ */
45
+ admit(presentation: McpTurnGrantPresentation): McpTurnGrantAdmitterDecision | undefined | Promise<McpTurnGrantAdmitterDecision | undefined>;
46
+ }
47
+ /**
48
+ * Register an MCP turn grant admitter. Admitters are asked in registration
49
+ * order and the first that returns a decision owns the grant. Registering the
50
+ * same admitter object again is a no-op. Returns a function that removes it.
51
+ */
52
+ export declare function registerMcpTurnGrantAdmitter(admitter: McpTurnGrantAdmitter): () => void;
53
+ export declare function listMcpTurnGrantAdmitters(): readonly McpTurnGrantAdmitter[];
54
+ export declare function clearMcpTurnGrantAdmittersForTests(): void;
55
+ /**
56
+ * Ask the registered admitters about a grant the framework did not recognize.
57
+ * Undefined when none claims it.
58
+ */
59
+ /** How long one admitter may take before its grant is refused. */
60
+ export declare const MCP_TURN_GRANT_ADMITTER_TIMEOUT_MS = 5000;
61
+ export declare function admitWithMcpTurnGrantAdmitters(presentation: McpTurnGrantPresentation): Promise<McpTurnGrantAdmitterDecision | undefined>;
@@ -0,0 +1,83 @@
1
+ const globals = globalThis;
2
+ const registry = (globals.__agentNativeMcpTurnGrantAdmitters ??= { admitters: [] });
3
+ /**
4
+ * Register an MCP turn grant admitter. Admitters are asked in registration
5
+ * order and the first that returns a decision owns the grant. Registering the
6
+ * same admitter object again is a no-op. Returns a function that removes it.
7
+ */
8
+ export function registerMcpTurnGrantAdmitter(admitter) {
9
+ if (!admitter.id)
10
+ throw new Error("An MCP turn grant admitter needs an id.");
11
+ const existing = registry.admitters.find((entry) => entry.id === admitter.id);
12
+ if (existing && existing !== admitter) {
13
+ throw new Error(`MCP turn grant admitter "${admitter.id}" is already registered by another module.`);
14
+ }
15
+ if (!existing)
16
+ registry.admitters.push(admitter);
17
+ return () => {
18
+ const index = registry.admitters.indexOf(admitter);
19
+ if (index >= 0)
20
+ registry.admitters.splice(index, 1);
21
+ };
22
+ }
23
+ export function listMcpTurnGrantAdmitters() {
24
+ return [...registry.admitters];
25
+ }
26
+ export function clearMcpTurnGrantAdmittersForTests() {
27
+ registry.admitters.length = 0;
28
+ }
29
+ /**
30
+ * Ask the registered admitters about a grant the framework did not recognize.
31
+ * Undefined when none claims it.
32
+ */
33
+ /** How long one admitter may take before its grant is refused. */
34
+ export const MCP_TURN_GRANT_ADMITTER_TIMEOUT_MS = 5_000;
35
+ const ADMITTER_TIMED_OUT = Symbol("admitter-timed-out");
36
+ export async function admitWithMcpTurnGrantAdmitters(presentation) {
37
+ for (const admitter of listMcpTurnGrantAdmitters()) {
38
+ let decision;
39
+ let timer;
40
+ try {
41
+ const settled = await Promise.race([
42
+ Promise.resolve(admitter.admit(presentation)),
43
+ new Promise((resolve) => {
44
+ timer = setTimeout(() => resolve(ADMITTER_TIMED_OUT), MCP_TURN_GRANT_ADMITTER_TIMEOUT_MS);
45
+ }),
46
+ ]);
47
+ if (settled === ADMITTER_TIMED_OUT) {
48
+ console.error(`[mcp-turn-grant] admitter "${admitter.id}" timed out`);
49
+ return { status: "refused", reason: "admitter-timeout" };
50
+ }
51
+ decision = settled;
52
+ }
53
+ catch (error) {
54
+ console.error(`[mcp-turn-grant] admitter "${admitter.id}" failed`, error);
55
+ return { status: "refused", reason: "admitter-failed" };
56
+ }
57
+ finally {
58
+ clearTimeout(timer);
59
+ }
60
+ if (decision === undefined)
61
+ continue;
62
+ if (decision.status === "refused")
63
+ return decision;
64
+ // Admitters are deployment code that may not be type-checked against this union.
65
+ const status = decision.status;
66
+ if (status !== "admitted" ||
67
+ !Number.isSafeInteger(decision.expiresAt) ||
68
+ typeof decision.ownerEmail !== "string" ||
69
+ typeof decision.appId !== "string") {
70
+ console.error(`[mcp-turn-grant] admitter "${admitter.id}" returned an invalid decision`);
71
+ return { status: "refused", reason: "admitter-failed" };
72
+ }
73
+ const caller = presentation.identity?.userEmail?.trim().toLowerCase();
74
+ if (!caller || decision.ownerEmail.trim().toLowerCase() !== caller)
75
+ return { status: "refused", reason: "owner-mismatch" };
76
+ if (decision.appId !== presentation.appId)
77
+ return { status: "refused", reason: "app-mismatch" };
78
+ if (decision.expiresAt <= Date.now())
79
+ return { status: "refused", reason: "expired" };
80
+ return decision;
81
+ }
82
+ return undefined;
83
+ }
@@ -24,4 +24,9 @@ export type TurnGrantAdmission = {
24
24
  status: "refused";
25
25
  reason: TurnGrantRefusalReason;
26
26
  };
27
+ /**
28
+ * Why a caller cannot hold a user turn grant, or undefined when it can: a
29
+ * device-connected user, the bar the framework's own grants are held to.
30
+ */
31
+ export declare function turnGrantCallerRefusal(identity: MCPCallerIdentity | undefined): Promise<"not-device" | "unavailable" | undefined>;
27
32
  export declare function admitMcpTurnGrant(id: string | undefined, appId: string, identity: MCPCallerIdentity | undefined): Promise<TurnGrantAdmission>;
@@ -108,6 +108,25 @@ export async function mintMcpTurnGrant(ownerEmail, appId) {
108
108
  await pruneExpiredTurnGrants(createdAt);
109
109
  return { grantId };
110
110
  }
111
+ /**
112
+ * Why a caller cannot hold a user turn grant, or undefined when it can: a
113
+ * device-connected user, the bar the framework's own grants are held to.
114
+ */
115
+ export async function turnGrantCallerRefusal(identity) {
116
+ if (identity?.identityAssurance !== "user" || !identity.userEmail)
117
+ return "not-device";
118
+ const connectJti = turnGrantConnectCredential(identity);
119
+ if (!connectJti)
120
+ return "not-device";
121
+ try {
122
+ return (await isDeviceConnectToken(connectJti, identity.userEmail))
123
+ ? undefined
124
+ : "not-device";
125
+ }
126
+ catch {
127
+ return "unavailable";
128
+ }
129
+ }
111
130
  export async function admitMcpTurnGrant(id, appId, identity) {
112
131
  if (id === undefined)
113
132
  return { status: "refused", reason: "missing" };
@@ -183,10 +183,10 @@ export declare const getMyOrgHandler: import("h3").EventHandlerWithFetch<import(
183
183
  soloDeploymentAdmin: boolean | undefined;
184
184
  }>>;
185
185
  export declare const createOrgHandler: import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<{
186
- id?: undefined;
187
- name?: undefined;
188
186
  role?: undefined;
189
187
  success: boolean;
188
+ name?: undefined;
189
+ id?: undefined;
190
190
  } | {
191
191
  success?: undefined;
192
192
  id: string;
@@ -637,10 +637,7 @@ async function isActiveWorkspaceOrgMember(member, orgId, email) {
637
637
  });
638
638
  return membership.active;
639
639
  }
640
- async function claimWorkspaceAppOrganization(db, appId, orgId, member) {
641
- if (member.role !== "owner" && member.role !== "admin") {
642
- return false;
643
- }
640
+ async function registerConfiguredWorkspaceApp(db, appId) {
644
641
  const configuredApp = configuredWorkspaceApp(appId);
645
642
  if (configuredApp) {
646
643
  const now = Date.now();
@@ -658,7 +655,16 @@ async function claimWorkspaceAppOrganization(db, appId, orgId, member) {
658
655
  now,
659
656
  ],
660
657
  });
658
+ invalidateMemberOrgCaches();
659
+ return true;
660
+ }
661
+ return false;
662
+ }
663
+ async function claimWorkspaceAppOrganization(db, appId, orgId, member) {
664
+ if (member.role !== "owner" && member.role !== "admin") {
665
+ return false;
661
666
  }
667
+ await registerConfiguredWorkspaceApp(db, appId);
662
668
  const claim = await db.execute({
663
669
  sql: `UPDATE workspace_apps SET org_id = ?
664
670
  WHERE id = ? AND org_id IS NULL
@@ -761,7 +767,7 @@ export async function checkWorkspaceAppAccess(appId, context) {
761
767
  };
762
768
  try {
763
769
  const db = getDbExec();
764
- const app = await cachedWorkspaceAppRow(db, normalizedAppId);
770
+ let app = await cachedWorkspaceAppRow(db, normalizedAppId);
765
771
  if (!app) {
766
772
  const orgId = context.orgId?.trim() || null;
767
773
  if (!orgId)
@@ -772,12 +778,21 @@ export async function checkWorkspaceAppAccess(appId, context) {
772
778
  return deny("no-row-not-a-member", { row: false, org: true });
773
779
  }
774
780
  const role = effectiveOrgMemberRole(member.role, orgId, email);
775
- return role
776
- ? claimWorkspaceAppOrganization(db, normalizedAppId, orgId, {
777
- ...member,
778
- role,
779
- })
780
- : false;
781
+ if (role === "member" &&
782
+ (await registerConfiguredWorkspaceApp(db, normalizedAppId))) {
783
+ // A concurrent insert may have won with a private or owned row.
784
+ app = await cachedWorkspaceAppRow(db, normalizedAppId);
785
+ if (!app)
786
+ return deny("no-row-after-registration", { row: false, org: true });
787
+ }
788
+ else {
789
+ return role
790
+ ? claimWorkspaceAppOrganization(db, normalizedAppId, orgId, {
791
+ ...member,
792
+ role,
793
+ })
794
+ : false;
795
+ }
781
796
  }
782
797
  const ownerEmail = normalizedEmail(typeof app.owner_email === "string" ? app.owner_email : "");
783
798
  const resourceOrgId = (typeof app.org_id === "string" ? app.org_id : "").trim() || null;
@@ -827,6 +842,10 @@ export async function checkWorkspaceAppAccess(appId, context) {
827
842
  if (!memberRole)
828
843
  return false;
829
844
  if (canClaimCallerOrg) {
845
+ if (memberRole === "member" &&
846
+ configuredWorkspaceApp(normalizedAppId) !== null) {
847
+ return true;
848
+ }
830
849
  if (!(await claimWorkspaceAppOrganization(db, normalizedAppId, orgId, {
831
850
  ...member,
832
851
  role: memberRole,
@@ -75,8 +75,9 @@ export declare function createCustomProviderRegistrationAction<TSchema extends Z
75
75
  user: "user";
76
76
  }>>;
77
77
  }, z.core.$strip>>, {
78
- message?: undefined;
79
78
  id?: undefined;
79
+ provider?: undefined;
80
+ deleted?: undefined;
80
81
  providers: {
81
82
  id: string;
82
83
  label: string;
@@ -87,47 +88,46 @@ export declare function createCustomProviderRegistrationAction<TSchema extends Z
87
88
  updatedAt: number;
88
89
  }[];
89
90
  count: number;
90
- provider?: undefined;
91
91
  found?: undefined;
92
- deleted?: undefined;
93
92
  registered?: undefined;
94
93
  label?: undefined;
95
- } | {
96
94
  message?: undefined;
97
- count?: undefined;
95
+ } | {
98
96
  id?: undefined;
97
+ deleted?: undefined;
99
98
  providers?: undefined;
99
+ count?: undefined;
100
100
  found: boolean;
101
101
  provider: import("../custom-registry.js").CustomProviderConfig;
102
- deleted?: undefined;
103
102
  registered?: undefined;
104
103
  label?: undefined;
105
- } | {
106
104
  message?: undefined;
107
- count?: undefined;
108
- providers?: undefined;
105
+ } | {
109
106
  provider?: undefined;
107
+ deleted?: undefined;
108
+ providers?: undefined;
109
+ count?: undefined;
110
110
  found: boolean;
111
111
  id: string;
112
- deleted?: undefined;
113
112
  registered?: undefined;
114
113
  label?: undefined;
115
- } | {
116
114
  message?: undefined;
117
- count?: undefined;
118
- providers?: undefined;
115
+ } | {
119
116
  provider?: undefined;
117
+ providers?: undefined;
118
+ count?: undefined;
120
119
  found?: undefined;
121
120
  deleted: boolean;
122
121
  id: string;
123
122
  registered?: undefined;
124
123
  label?: undefined;
124
+ message?: undefined;
125
125
  } | {
126
- count?: undefined;
127
- providers?: undefined;
128
126
  provider?: undefined;
129
- found?: undefined;
130
127
  deleted?: undefined;
128
+ providers?: undefined;
129
+ count?: undefined;
130
+ found?: undefined;
131
131
  registered: boolean;
132
132
  id: string;
133
133
  label: string;
@@ -320,9 +320,10 @@ export declare function createProviderApiActions(runtime: Pick<ProviderApiRuntim
320
320
  notes?: string | undefined;
321
321
  scope?: "org" | "user" | undefined;
322
322
  }, {
323
+ provider?: undefined;
324
+ deleted?: undefined;
323
325
  id?: undefined;
324
326
  message?: undefined;
325
- deleted?: undefined;
326
327
  providers: {
327
328
  id: string;
328
329
  label: string;
@@ -333,45 +334,44 @@ export declare function createProviderApiActions(runtime: Pick<ProviderApiRuntim
333
334
  updatedAt: number;
334
335
  }[];
335
336
  count: number;
336
- provider?: undefined;
337
337
  found?: undefined;
338
338
  registered?: undefined;
339
339
  label?: undefined;
340
340
  } | {
341
+ deleted?: undefined;
341
342
  id?: undefined;
342
343
  message?: undefined;
343
344
  count?: undefined;
344
- deleted?: undefined;
345
345
  providers?: undefined;
346
346
  found: boolean;
347
347
  provider: import("../custom-registry.js").CustomProviderConfig;
348
348
  registered?: undefined;
349
349
  label?: undefined;
350
350
  } | {
351
+ provider?: undefined;
352
+ deleted?: undefined;
351
353
  message?: undefined;
352
354
  count?: undefined;
353
- deleted?: undefined;
354
355
  providers?: undefined;
355
- provider?: undefined;
356
356
  found: boolean;
357
357
  id: string;
358
358
  registered?: undefined;
359
359
  label?: undefined;
360
360
  } | {
361
+ provider?: undefined;
361
362
  message?: undefined;
362
363
  count?: undefined;
363
364
  providers?: undefined;
364
- provider?: undefined;
365
365
  found?: undefined;
366
366
  deleted: boolean;
367
367
  id: string;
368
368
  registered?: undefined;
369
369
  label?: undefined;
370
370
  } | {
371
- count?: undefined;
371
+ provider?: undefined;
372
372
  deleted?: undefined;
373
+ count?: undefined;
373
374
  providers?: undefined;
374
- provider?: undefined;
375
375
  found?: undefined;
376
376
  registered: boolean;
377
377
  id: string;
@@ -27,6 +27,12 @@ export interface ProviderCallGateRequest {
27
27
  /** The app the request is attributed to. */
28
28
  appId: string;
29
29
  accountId: string | undefined;
30
+ /**
31
+ * Why the caller could not read the account identity. Set only when that
32
+ * read failed; `accountId` is then undefined but the account is unknown, not
33
+ * absent.
34
+ */
35
+ accountIdError?: unknown;
30
36
  connectionId: string | null;
31
37
  /** The provider runtime options of the request, when it came through one. */
32
38
  runtime: ProviderApiRuntimeOptions | undefined;
@@ -97,11 +103,74 @@ export declare function registerProviderCallGate(gate: ProviderCallGate): () =>
97
103
  export declare function listProviderCallGates(): readonly ProviderCallGate[];
98
104
  export declare function clearProviderCallGatesForTests(): void;
99
105
  export declare function findProviderCallGate(target: ProviderCallGateTarget): ProviderCallGate | undefined;
100
- /** Run the precheck of the gate that owns a request naming `providerId`. */
101
- export declare function precheckProviderCall(providerId: string): Promise<void>;
106
+ /**
107
+ * Run the precheck of the gate that owns a request naming `providerId`, and
108
+ * `url` when the caller already knows it, so a gate that claims requests by
109
+ * URL is asked too.
110
+ */
111
+ export declare function precheckProviderCall(providerId: string, url?: string): Promise<void>;
102
112
  export declare function prepareProviderCallGate(request: ProviderCallGateRequest): PreparedProviderCallGate | undefined;
103
113
  /** Remember an error as a gate's own refusal, so callers pass it through unwrapped. */
104
114
  export declare function markProviderCallGateRefusal(error: unknown): void;
105
115
  export declare function isProviderCallGateRefusal(error: unknown): boolean;
106
116
  /** Run a gate hook, marking anything it throws as the gate's refusal. */
107
117
  export declare function runProviderCallGateHook<T>(hook: () => T | Promise<T>): Promise<T>;
118
+ /** A provider request sent outside the provider-api request path. */
119
+ export interface ProviderCallGateFetchInput {
120
+ /** The provider id gates match on, e.g. "google_calendar". */
121
+ providerId: string;
122
+ /** The app the request is attributed to. */
123
+ appId: string;
124
+ url: string;
125
+ init?: RequestInit;
126
+ /** The connection or credential row the request is sent with. */
127
+ connectionId?: string | null;
128
+ /**
129
+ * The receipt {@link precheckGatedProviderCall} returned for this provider
130
+ * and URL, so the precheck is not run again. Any other value runs it here.
131
+ */
132
+ prechecked?: ProviderCallPrecheckReceipt;
133
+ /**
134
+ * Reads the provider account the credential belongs to. Called only when a
135
+ * gate owns the request; `null`/`undefined` means the credential has no
136
+ * recorded account, and a throw reaches the gate as `accountIdError`. The
137
+ * lookup shares the request's admission deadline; one that does not answer
138
+ * by then reaches the gate as a {@link ProviderAccountLookupTimeoutError}.
139
+ */
140
+ resolveAccountId?: () => Promise<string | null | undefined>;
141
+ }
142
+ /** The account lookup did not answer before the request's admission deadline. */
143
+ export declare class ProviderAccountLookupTimeoutError extends Error {
144
+ constructor();
145
+ }
146
+ /** A gate's precheck or admission did not settle before the admission deadline. */
147
+ export declare class ProviderCallGateAdmissionTimeoutError extends Error {
148
+ constructor();
149
+ }
150
+ /** Proof that a request's gate precheck settled within its admission deadline. */
151
+ export interface ProviderCallPrecheckReceipt {
152
+ readonly providerId: string;
153
+ readonly url: string;
154
+ }
155
+ /**
156
+ * Run a gated request's precheck ahead of {@link fetchWithProviderCallGate},
157
+ * for a caller that must refuse before work such as a token refresh. The
158
+ * precheck gets the same admission deadline that call enforces, so a hanging
159
+ * gate refuses with {@link ProviderCallGateAdmissionTimeoutError}. Pass the
160
+ * receipt as `prechecked` so the precheck does not run twice. A receipt
161
+ * admits one fetch, sent before its precheck's admission deadline; a later
162
+ * fetch runs the precheck again.
163
+ */
164
+ export declare function precheckGatedProviderCall(providerId: string, url: string): Promise<ProviderCallPrecheckReceipt>;
165
+ /**
166
+ * Send a provider request through the registered call gates, for packages that
167
+ * talk to a provider with their own client instead of the provider-api request
168
+ * path. The gate sees the request exactly as it would there: `precheck` for
169
+ * the provider id, `prepare`, `admit` (or `recheck` for "attempt" gates), and
170
+ * the synchronous final check right before `transport` runs. A refusal a
171
+ * "transport" gate turns into a response comes back as a `Response` that
172
+ * {@link isProviderCallGateRefusal} recognizes; any other refusal throws,
173
+ * marked the same way. With no gate owning the request this is
174
+ * `transport(url, init)`.
175
+ */
176
+ export declare function fetchWithProviderCallGate(input: ProviderCallGateFetchInput, transport?: typeof fetch): Promise<Response>;