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

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 (75) 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/cli/skills-content/design-visual-edit-skill.d.ts +1 -1
  24. package/dist/cli/skills-content/design-visual-edit-skill.js +9 -15
  25. package/dist/client/sharing/useShareButtonController.d.ts +5 -0
  26. package/dist/client/sharing/useShareButtonController.js +2 -1
  27. package/dist/client/use-chat-threads.js +3 -0
  28. package/dist/client/use-db-sync.js +22 -0
  29. package/dist/collab/routes.d.ts +1 -1
  30. package/dist/deploy/build.d.ts +4 -1
  31. package/dist/deploy/build.js +25 -15
  32. package/dist/file-upload/actions/upload-image.d.ts +2 -2
  33. package/dist/framework-package-versions.json +7 -7
  34. package/dist/guards/index.d.ts +1 -1
  35. package/dist/guards/index.js +1 -1
  36. package/dist/guards/no-env-credentials.d.ts +15 -1
  37. package/dist/guards/no-env-credentials.js +27 -0
  38. package/dist/integrations/internal-token.d.ts +15 -0
  39. package/dist/integrations/internal-token.js +19 -0
  40. package/dist/mcp/build-server.js +18 -2
  41. package/dist/mcp/index.d.ts +1 -0
  42. package/dist/mcp/index.js +1 -0
  43. package/dist/mcp/turn-grant-admitters.d.ts +61 -0
  44. package/dist/mcp/turn-grant-admitters.js +83 -0
  45. package/dist/mcp/turn-grant-store.d.ts +5 -0
  46. package/dist/mcp/turn-grant-store.js +19 -0
  47. package/dist/org/index.d.ts +2 -2
  48. package/dist/org/workspace-app-access.js +30 -11
  49. package/dist/provider-api/actions/custom-provider-registration.d.ts +16 -16
  50. package/dist/provider-api/actions/provider-api.d.ts +8 -8
  51. package/dist/provider-api/call-gates.d.ts +71 -2
  52. package/dist/provider-api/call-gates.js +157 -3
  53. package/dist/provider-api/corpus-jobs.d.ts +2 -2
  54. package/dist/provider-api/index.d.ts +1 -1
  55. package/dist/provider-api/index.js +1 -1
  56. package/dist/provider-api/interactive-scope.d.ts +2 -1
  57. package/dist/provider-api/interactive-scope.js +17 -4
  58. package/dist/server/agent-chat-plugin.js +9 -2
  59. package/dist/server/agent-run-context.d.ts +1 -1
  60. package/dist/server/agent-run-context.js +34 -3
  61. package/dist/server/entry-server.js +3 -1
  62. package/dist/server/transcribe-voice.d.ts +1 -1
  63. package/dist/shared/build-id.d.ts +14 -0
  64. package/dist/shared/build-id.js +21 -0
  65. package/dist/vite/client.d.ts +16 -0
  66. package/dist/vite/client.js +6 -3
  67. package/dist/vitest-config.js +1 -0
  68. package/dist/workspace-connections/workspace-credential-actions.d.ts +1 -0
  69. package/dist/workspace-connections/workspace-credential-actions.js +1 -0
  70. package/dist/workspace-connections/workspace-credentials.d.ts +4 -0
  71. package/dist/workspace-connections/workspace-credentials.js +40 -4
  72. package/docs/content/template-design-agent.mdx +0 -1
  73. package/docs/content/template-design-developers.mdx +6 -9
  74. package/docs/workspace-credential-drafts.md +28 -0
  75. package/package.json +5 -4
@@ -59,7 +59,10 @@ export declare function shouldBundleFfmpegStaticForServerless(hostPlatform?: Nod
59
59
  export declare function findServerlessBrowserRuntimeConsumer(projectCwd?: string): string | null;
60
60
  export declare function findInstalledPackageRoot(packageName: string, nodeModulesRoots: string[], fromPackageDir?: string): string | null;
61
61
  export declare function copyInstalledBrowserRuntimePackages(serverDir: string | undefined, projectCwd?: string): number;
62
- export declare function copyInstalledExternalSsrPackages(serverDir: string | undefined, projectCwd?: string): number;
62
+ export declare function copyInstalledExternalSsrPackages(serverDir: string | undefined, projectCwd?: string, options?: {
63
+ includeSsrPackages?: boolean;
64
+ }): number;
65
+ export declare function copyPresetRuntimePackages(targetPreset: string, serverDir: string | undefined, projectCwd?: string): void;
63
66
  export declare function findInstalledFfmpegStaticPackage(nodeModulesRoots: string[]): string | null;
64
67
  export declare function findInstalledResvgPackages(nodeModulesRoots: string[]): Array<{
65
68
  packageName: string;
@@ -2942,7 +2942,7 @@ export function copyInstalledBrowserRuntimePackages(serverDir, projectCwd = cwd)
2942
2942
  console.log(`[deploy] Copied ${copiedCount} serverless browser runtime package(s) into the server bundle (required by ${consumer}).`);
2943
2943
  return copiedCount;
2944
2944
  }
2945
- export function copyInstalledExternalSsrPackages(serverDir, projectCwd = cwd) {
2945
+ export function copyInstalledExternalSsrPackages(serverDir, projectCwd = cwd, options = {}) {
2946
2946
  if (!serverDir || !fs.existsSync(serverDir))
2947
2947
  return 0;
2948
2948
  const packagesToCopy = new Set();
@@ -2951,9 +2951,11 @@ export function copyInstalledExternalSsrPackages(serverDir, projectCwd = cwd) {
2951
2951
  // Keep undici opaque to client bundlers, but copy it into the server runtime.
2952
2952
  if (/(\"|'|\x60)undici\1/.test(source))
2953
2953
  packagesToCopy.add("undici");
2954
- for (const packageName of SERVERLESS_EXTERNAL_SSR_PACKAGES) {
2955
- if (hasExternalSsrRuntimeReference(source, packageName)) {
2956
- packagesToCopy.add(packageName);
2954
+ if (options.includeSsrPackages !== false) {
2955
+ for (const packageName of SERVERLESS_EXTERNAL_SSR_PACKAGES) {
2956
+ if (hasExternalSsrRuntimeReference(source, packageName)) {
2957
+ packagesToCopy.add(packageName);
2958
+ }
2957
2959
  }
2958
2960
  }
2959
2961
  });
@@ -2994,6 +2996,24 @@ export function copyInstalledExternalSsrPackages(serverDir, projectCwd = cwd) {
2994
2996
  console.log(`[deploy] Copied ${copiedCount} external SSR runtime package(s) into the server bundle.`);
2995
2997
  return copiedCount;
2996
2998
  }
2999
+ export function copyPresetRuntimePackages(targetPreset, serverDir, projectCwd = cwd) {
3000
+ if (targetPreset === "netlify" ||
3001
+ targetPreset === "vercel" ||
3002
+ isAwsLambdaPreset(targetPreset) ||
3003
+ isAwsAmplifyPreset(targetPreset)) {
3004
+ copyInstalledResvgPackages(serverDir);
3005
+ copyInstalledFfmpegStaticPackage(serverDir);
3006
+ copyInstalledBrowserRuntimePackages(serverDir);
3007
+ copyInstalledExternalSsrPackages(serverDir, projectCwd);
3008
+ sanitizeServerlessFunctionPackageManifest(serverDir);
3009
+ pruneServerlessFunctionDeadWeight(serverDir);
3010
+ }
3011
+ else if (targetPreset === "node" || targetPreset === "node-server") {
3012
+ copyInstalledExternalSsrPackages(serverDir, projectCwd, {
3013
+ includeSsrPackages: false,
3014
+ });
3015
+ }
3016
+ }
2997
3017
  function hasFfmpegStaticBinary(packageDir) {
2998
3018
  return FFMPEG_STATIC_BINARY_NAMES.some((binaryName) => fs.existsSync(path.join(packageDir, binaryName)));
2999
3019
  }
@@ -5269,17 +5289,7 @@ export default bundle;
5269
5289
  if (preset === "vercel") {
5270
5290
  addVercelSweepCron(nitro.options.output.dir);
5271
5291
  }
5272
- if (preset === "netlify" ||
5273
- preset === "vercel" ||
5274
- isAwsLambdaPreset(preset) ||
5275
- isAwsAmplifyPreset(preset)) {
5276
- copyInstalledResvgPackages(nitro.options.output.serverDir);
5277
- copyInstalledFfmpegStaticPackage(nitro.options.output.serverDir);
5278
- copyInstalledBrowserRuntimePackages(nitro.options.output.serverDir);
5279
- copyInstalledExternalSsrPackages(nitro.options.output.serverDir);
5280
- sanitizeServerlessFunctionPackageManifest(nitro.options.output.serverDir);
5281
- pruneServerlessFunctionDeadWeight(nitro.options.output.serverDir);
5282
- }
5292
+ copyPresetRuntimePackages(preset, nitro.options.output.serverDir);
5283
5293
  if (preset === "vercel") {
5284
5294
  prepareVercelFunctionOutputs(nitro.options.output.dir, cwd);
5285
5295
  }
@@ -33,9 +33,9 @@ declare const _default: import("../../action.js").ActionDefinition<{
33
33
  idempotencyKey: string;
34
34
  deleted: boolean;
35
35
  } | {
36
- id?: undefined;
37
36
  error: string;
38
37
  url?: undefined;
38
+ id?: undefined;
39
39
  provider?: undefined;
40
40
  configured?: undefined;
41
41
  } | {
@@ -45,8 +45,8 @@ declare const _default: import("../../action.js").ActionDefinition<{
45
45
  provider: string;
46
46
  configured?: undefined;
47
47
  } | {
48
- id?: undefined;
49
48
  url?: undefined;
49
+ id?: undefined;
50
50
  provider?: undefined;
51
51
  error: string;
52
52
  configured: boolean;
@@ -1,17 +1,17 @@
1
1
  {
2
- "@agent-native/agentkit": "0.231.0",
2
+ "@agent-native/agentkit": "0.232.0-nightly-20261118182504",
3
3
  "@agent-native/code-agents-ui": "0.1.75",
4
- "@agent-native/core": "0.231.0",
5
- "@agent-native/core-corpus": "0.231.0",
4
+ "@agent-native/core": "0.232.0-nightly-20261118182504",
5
+ "@agent-native/core-corpus": "0.232.0-nightly-20261118182504",
6
6
  "@agent-native/creative-context": "0.8.75",
7
- "@agent-native/dispatch": "0.42.10",
7
+ "@agent-native/dispatch": "0.42.11-nightly-20261118182504",
8
8
  "@agent-native/embedding": "0.2.0",
9
9
  "@agent-native/migrate": "0.0.7",
10
10
  "@agent-native/otel": "0.1.42",
11
11
  "@agent-native/pinpoint": "0.1.118",
12
12
  "@agent-native/recap-cli": "0.5.106",
13
- "@agent-native/scheduling": "0.3.2",
13
+ "@agent-native/scheduling": "0.4.0-nightly-20261118182504",
14
14
  "@agent-native/shared-app-config": "0.1.2",
15
- "@agent-native/skills": "0.4.10",
16
- "@agent-native/toolkit": "0.231.0"
15
+ "@agent-native/skills": "0.4.11-nightly-20261118182504",
16
+ "@agent-native/toolkit": "0.232.0-nightly-20261118182504"
17
17
  }
@@ -6,7 +6,7 @@ export { scanEmptyMigrations } from "./no-empty-migrations.js";
6
6
  export { scanReleaseSchemaCoverage } from "./release-schema-complete.js";
7
7
  export type { EmptyMigrationsSourceOptions } from "./no-empty-migrations.js";
8
8
  export { analyzeEmptyMigrationsSource, shouldScanEmptyMigrationsFile, } from "./no-empty-migrations.js";
9
- export { scanEnvCredentials } from "./no-env-credentials.js";
9
+ export { parseTestEnvKeys, scanEnvCredentials, type EnvCredentialsScanOptions, } from "./no-env-credentials.js";
10
10
  export { scanEnvMutation } from "./no-env-mutation.js";
11
11
  export { scanIdentityColumnsRegistered } from "./identity-columns-registered.js";
12
12
  export { scanLocalhostFallback } from "./no-localhost-fallback.js";
@@ -4,7 +4,7 @@ export { scanDrizzlePush } from "./no-drizzle-push.js";
4
4
  export { scanEmptyMigrations } from "./no-empty-migrations.js";
5
5
  export { scanReleaseSchemaCoverage } from "./release-schema-complete.js";
6
6
  export { analyzeEmptyMigrationsSource, shouldScanEmptyMigrationsFile, } from "./no-empty-migrations.js";
7
- export { scanEnvCredentials } from "./no-env-credentials.js";
7
+ export { parseTestEnvKeys, scanEnvCredentials, } from "./no-env-credentials.js";
8
8
  export { scanEnvMutation } from "./no-env-mutation.js";
9
9
  export { scanIdentityColumnsRegistered } from "./identity-columns-registered.js";
10
10
  export { scanLocalhostFallback } from "./no-localhost-fallback.js";
@@ -32,4 +32,18 @@
32
32
  * process.env.SOMETHING // guard:allow-env-credential — short reason
33
33
  */
34
34
  import type { GuardResult, GuardScanOptions } from "./types.js";
35
- export declare function scanEnvCredentials(options: GuardScanOptions): GuardResult;
35
+ export interface EnvCredentialsScanOptions extends GuardScanOptions {
36
+ /**
37
+ * Non-secret configuration keys (a test target URL, an artifact directory)
38
+ * the app's tests may read: honored only in `tests/` and `*.spec.*` /
39
+ * `*.test.*` files. From agent-native.json `doctor.testEnvKeys`.
40
+ */
41
+ testEnvKeys?: readonly string[];
42
+ }
43
+ /**
44
+ * Validates `doctor.testEnvKeys`. Throws on anything but env key names, and on
45
+ * a credential-like name, so a bad entry fails the guard rather than reading
46
+ * as an empty list or widening it to a secret.
47
+ */
48
+ export declare function parseTestEnvKeys(value: unknown): string[];
49
+ export declare function scanEnvCredentials(options: EnvCredentialsScanOptions): GuardResult;
@@ -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,