@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
@@ -29,9 +29,13 @@ export function clearProviderCallGatesForTests() {
29
29
  export function findProviderCallGate(target) {
30
30
  return registry.gates.find((gate) => gate.matches(target));
31
31
  }
32
- /** Run the precheck of the gate that owns a request naming `providerId`. */
33
- export async function precheckProviderCall(providerId) {
34
- await findProviderCallGate({ providerId })?.precheck?.(providerId);
32
+ /**
33
+ * Run the precheck of the gate that owns a request naming `providerId`, and
34
+ * `url` when the caller already knows it, so a gate that claims requests by
35
+ * URL is asked too.
36
+ */
37
+ export async function precheckProviderCall(providerId, url) {
38
+ await findProviderCallGate({ providerId, url })?.precheck?.(providerId);
35
39
  }
36
40
  export function prepareProviderCallGate(request) {
37
41
  const gate = findProviderCallGate({
@@ -61,3 +65,153 @@ export async function runProviderCallGateHook(hook) {
61
65
  throw error;
62
66
  }
63
67
  }
68
+ /** How long a gate may hold a {@link fetchWithProviderCallGate} request before refusing it. */
69
+ const GATED_FETCH_ADMISSION_WAIT_MS = 2_000;
70
+ /** The account lookup did not answer before the request's admission deadline. */
71
+ export class ProviderAccountLookupTimeoutError extends Error {
72
+ constructor() {
73
+ super("The provider account lookup did not answer before the admission deadline.");
74
+ this.name = "ProviderAccountLookupTimeoutError";
75
+ }
76
+ }
77
+ /** A gate's precheck or admission did not settle before the admission deadline. */
78
+ export class ProviderCallGateAdmissionTimeoutError extends Error {
79
+ constructor() {
80
+ super("The provider call gate did not admit the request before its deadline.");
81
+ this.name = "ProviderCallGateAdmissionTimeoutError";
82
+ }
83
+ }
84
+ async function settleBefore(deadline, work, timeoutError) {
85
+ let timer;
86
+ try {
87
+ return await Promise.race([
88
+ Promise.resolve().then(work),
89
+ new Promise((_, reject) => {
90
+ timer = setTimeout(() => reject(timeoutError()), Math.max(0, deadline - Date.now()));
91
+ }),
92
+ ]);
93
+ }
94
+ finally {
95
+ clearTimeout(timer);
96
+ }
97
+ }
98
+ function readAccountIdBefore(deadline, resolve) {
99
+ return settleBefore(deadline, resolve, () => new ProviderAccountLookupTimeoutError());
100
+ }
101
+ const admissionTimeout = () => new ProviderCallGateAdmissionTimeoutError();
102
+ function precheckBefore(deadline, providerId, url) {
103
+ return runProviderCallGateHook(() => settleBefore(deadline, () => precheckProviderCall(providerId, url), admissionTimeout));
104
+ }
105
+ /** Each live receipt, with the admission deadline of the precheck that issued it. */
106
+ const precheckReceipts = new WeakMap();
107
+ /**
108
+ * Run a gated request's precheck ahead of {@link fetchWithProviderCallGate},
109
+ * for a caller that must refuse before work such as a token refresh. The
110
+ * precheck gets the same admission deadline that call enforces, so a hanging
111
+ * gate refuses with {@link ProviderCallGateAdmissionTimeoutError}. Pass the
112
+ * receipt as `prechecked` so the precheck does not run twice. A receipt
113
+ * admits one fetch, sent before its precheck's admission deadline; a later
114
+ * fetch runs the precheck again.
115
+ */
116
+ export async function precheckGatedProviderCall(providerId, url) {
117
+ const deadline = Date.now() + GATED_FETCH_ADMISSION_WAIT_MS;
118
+ await precheckBefore(deadline, providerId, url);
119
+ const receipt = Object.freeze({ providerId, url });
120
+ precheckReceipts.set(receipt, deadline);
121
+ return receipt;
122
+ }
123
+ function consumePrecheckReceiptFor(receipt, providerId, url) {
124
+ if (receipt?.providerId !== providerId || receipt.url !== url)
125
+ return false;
126
+ const deadline = precheckReceipts.get(receipt);
127
+ precheckReceipts.delete(receipt);
128
+ return deadline !== undefined && Date.now() <= deadline;
129
+ }
130
+ function syntheticRefusalResponse(refusal) {
131
+ const headers = new Headers(refusal.headers);
132
+ if (refusal.json !== undefined && !headers.has("content-type"))
133
+ headers.set("content-type", "application/json");
134
+ const response = new Response(refusal.json === undefined ? null : JSON.stringify(refusal.json), { status: refusal.status, statusText: refusal.statusText, headers });
135
+ gateRefusals.add(response);
136
+ return response;
137
+ }
138
+ /**
139
+ * Send a provider request through the registered call gates, for packages that
140
+ * talk to a provider with their own client instead of the provider-api request
141
+ * path. The gate sees the request exactly as it would there: `precheck` for
142
+ * the provider id, `prepare`, `admit` (or `recheck` for "attempt" gates), and
143
+ * the synchronous final check right before `transport` runs. A refusal a
144
+ * "transport" gate turns into a response comes back as a `Response` that
145
+ * {@link isProviderCallGateRefusal} recognizes; any other refusal throws,
146
+ * marked the same way. With no gate owning the request this is
147
+ * `transport(url, init)`.
148
+ */
149
+ export async function fetchWithProviderCallGate(input, transport = globalThis.fetch) {
150
+ // One admission window covers the precheck, the account lookup and the gate.
151
+ const deadline = Date.now() + GATED_FETCH_ADMISSION_WAIT_MS;
152
+ if (!consumePrecheckReceiptFor(input.prechecked, input.providerId, input.url)) {
153
+ await precheckBefore(deadline, input.providerId, input.url);
154
+ }
155
+ const gate = findProviderCallGate({
156
+ providerId: input.providerId,
157
+ url: input.url,
158
+ });
159
+ if (!gate)
160
+ return transport(input.url, input.init);
161
+ let accountId;
162
+ let accountIdError;
163
+ if (input.resolveAccountId) {
164
+ try {
165
+ accountId =
166
+ (await readAccountIdBefore(deadline, input.resolveAccountId))?.trim() ||
167
+ undefined;
168
+ }
169
+ catch (error) {
170
+ accountIdError = error;
171
+ }
172
+ }
173
+ const request = {
174
+ providerId: input.providerId,
175
+ url: input.url,
176
+ method: (input.init?.method ?? "GET").toUpperCase(),
177
+ path: input.url,
178
+ body: input.init?.body ?? undefined,
179
+ appId: input.appId,
180
+ accountId,
181
+ ...(accountIdError === undefined ? {} : { accountIdError }),
182
+ connectionId: input.connectionId ?? null,
183
+ runtime: undefined,
184
+ deadline,
185
+ signal: input.init?.signal ?? undefined,
186
+ };
187
+ let finalCheck;
188
+ if (gate.admission === "attempt") {
189
+ finalCheck = await runProviderCallGateHook(() => settleBefore(deadline, async () => {
190
+ const check = await gate.prepare(request)();
191
+ await gate.recheck?.(request);
192
+ return check;
193
+ }, admissionTimeout));
194
+ }
195
+ else {
196
+ try {
197
+ finalCheck = await settleBefore(deadline, () => gate.prepare(request)(), admissionTimeout);
198
+ }
199
+ catch (error) {
200
+ const refusal = gate.refusalResponse?.(error);
201
+ if (refusal)
202
+ return syntheticRefusalResponse(refusal);
203
+ markProviderCallGateRefusal(error);
204
+ throw error;
205
+ }
206
+ }
207
+ if (typeof finalCheck === "function") {
208
+ try {
209
+ finalCheck();
210
+ }
211
+ catch (error) {
212
+ markProviderCallGateRefusal(error);
213
+ throw error;
214
+ }
215
+ }
216
+ return transport(input.url, input.init);
217
+ }
@@ -73,7 +73,6 @@ export declare function createProviderCorpusJobAction(options: CreateProviderCor
73
73
  offset?: unknown;
74
74
  limit?: unknown;
75
75
  }, {
76
- deleted?: undefined;
77
76
  jobs: {
78
77
  id: string;
79
78
  name: string;
@@ -84,6 +83,7 @@ export declare function createProviderCorpusJobAction(options: CreateProviderCor
84
83
  updatedAt: string;
85
84
  }[];
86
85
  total: number;
86
+ deleted?: undefined;
87
87
  jobId?: undefined;
88
88
  } | {
89
89
  jobs?: undefined;
@@ -91,9 +91,9 @@ export declare function createProviderCorpusJobAction(options: CreateProviderCor
91
91
  deleted: boolean;
92
92
  jobId: string;
93
93
  } | {
94
- deleted?: undefined;
95
94
  jobs?: undefined;
96
95
  total?: undefined;
96
+ deleted?: undefined;
97
97
  jobId?: undefined;
98
98
  hits: Record<string, unknown>[];
99
99
  offset: number;
@@ -2,7 +2,7 @@ import { type WorkspaceConnectionTemplateUse } from "../connections/catalog.js";
2
2
  import { type CredentialContext } from "../credentials/index.js";
3
3
  import { type WebContentSearchOptions, type WebExtractMode, type WebResponseMode } from "../extensions/web-content.js";
4
4
  import type { CustomProviderConfig } from "./custom-registry.js";
5
- export { registerProviderCallGate, listProviderCallGates, type ProviderCallAdmission, type ProviderCallGate, type ProviderCallGateRefusal, type ProviderCallGateRequest, type ProviderCallGateTarget, } from "./call-gates.js";
5
+ export { registerProviderCallGate, listProviderCallGates, fetchWithProviderCallGate, precheckGatedProviderCall, ProviderAccountLookupTimeoutError, ProviderCallGateAdmissionTimeoutError, isProviderCallGateRefusal, type ProviderCallAdmission, type ProviderCallGateFetchInput, type ProviderCallPrecheckReceipt, type ProviderCallGate, type ProviderCallGateRefusal, type ProviderCallGateRequest, type ProviderCallGateTarget, } from "./call-gates.js";
6
6
  export { isChatTurnInteractiveScope, isDurableProviderInteractiveScope, isProviderInteractiveScope, runWithDurableTurnToolScope, runWithProviderInteractiveScope, type ProviderTurnGrant, } from "./interactive-scope.js";
7
7
  export type { CustomProviderConfig, CustomProviderScope, CustomProviderAuthKind, UpsertCustomProviderArgs, } from "./custom-registry.js";
8
8
  export { upsertCustomProvider, deleteCustomProvider, listCustomProviders, getCustomProvider, validateCustomBaseUrl, assertCanMutateCustomProviderScope, CustomProviderAuthError, } from "./custom-registry.js";
@@ -16,7 +16,7 @@ import { resolveWorkspaceConnectionForApp, } from "../workspace-connections/stor
16
16
  import { recordProviderCall, } from "./call-census.js";
17
17
  import { isProviderCallGateRefusal, markProviderCallGateRefusal, precheckProviderCall, prepareProviderCallGate, runProviderCallGateHook, } from "./call-gates.js";
18
18
  import { createProviderQuotaIdentity, createProviderRequestDedupeKey, executeWithProviderQuota, } from "./quota-governor.js";
19
- export { registerProviderCallGate, listProviderCallGates, } from "./call-gates.js";
19
+ export { registerProviderCallGate, listProviderCallGates, fetchWithProviderCallGate, precheckGatedProviderCall, ProviderAccountLookupTimeoutError, ProviderCallGateAdmissionTimeoutError, isProviderCallGateRefusal, } from "./call-gates.js";
20
20
  export { isChatTurnInteractiveScope, isDurableProviderInteractiveScope, isProviderInteractiveScope, runWithDurableTurnToolScope, runWithProviderInteractiveScope, } from "./interactive-scope.js";
21
21
  export { upsertCustomProvider, deleteCustomProvider, listCustomProviders, getCustomProvider, validateCustomBaseUrl, assertCanMutateCustomProviderScope, CustomProviderAuthError, } from "./custom-registry.js";
22
22
  import { setBodyValueAtPath } from "./request-body.js";
@@ -18,7 +18,8 @@ export declare function isChatTurnInteractiveScope(): boolean;
18
18
  /**
19
19
  * True while a person is waiting on this work through a scope: an MCP/tool call
20
20
  * made for a live chat turn. A background worker counts only with a chat-turn
21
- * grant. A browser request is not marked here; a gate recognises it from the
21
+ * grant, or inside a durable run's own tool call for the turn its verified
22
+ * grant names (`runWithDurableTurnToolScope`). A browser request is not marked here; a gate recognises it from the
22
23
  * request itself. `actionOnly` also requires the innermost scope to be an
23
24
  * action run.
24
25
  */
@@ -17,9 +17,7 @@ function grantExpired(grant) {
17
17
  return grant !== undefined && Date.now() >= grant.expiresAt;
18
18
  }
19
19
  function hasInteractiveScope(actionOnly, allowBackground) {
20
- if (!allowBackground &&
21
- isBackgroundWorkerRun() &&
22
- !isChatTurnInteractiveScope())
20
+ if (!allowBackground && isBackgroundWorkerRun() && !hasProvenTurn())
23
21
  return false;
24
22
  let scope = interactiveScope?.getStore();
25
23
  if (!scope || (actionOnly && !scope.action))
@@ -34,6 +32,19 @@ function hasInteractiveScope(actionOnly, allowBackground) {
34
32
  }
35
33
  return true;
36
34
  }
35
+ // A background worker's action counts only for a turn proven on its chain:
36
+ // a chat-turn grant, or a durable tool call matched to its run's turn grant.
37
+ function hasProvenTurn() {
38
+ let scope = interactiveScope?.getStore();
39
+ if (!scope?.action)
40
+ return false;
41
+ while (scope) {
42
+ if (scope.chatTurnGrant || scope.durableTurnCall)
43
+ return true;
44
+ scope = scope.parent;
45
+ }
46
+ return false;
47
+ }
37
48
  /** True inside an action whose chain carries a live, unexpired chat-turn grant. */
38
49
  export function isChatTurnInteractiveScope() {
39
50
  let scope = interactiveScope?.getStore();
@@ -55,7 +66,8 @@ export function isChatTurnInteractiveScope() {
55
66
  /**
56
67
  * True while a person is waiting on this work through a scope: an MCP/tool call
57
68
  * made for a live chat turn. A background worker counts only with a chat-turn
58
- * grant. A browser request is not marked here; a gate recognises it from the
69
+ * grant, or inside a durable run's own tool call for the turn its verified
70
+ * grant names (`runWithDurableTurnToolScope`). A browser request is not marked here; a gate recognises it from the
59
71
  * request itself. `actionOnly` also requires the innermost scope to be an
60
72
  * action run.
61
73
  */
@@ -93,6 +105,7 @@ export async function runWithDurableTurnToolScope(work, signal, binding) {
93
105
  const scope = {
94
106
  active: true,
95
107
  action: true,
108
+ durableTurnCall: true,
96
109
  ...(parent ? { parent } : {}),
97
110
  signal,
98
111
  };
@@ -15,7 +15,8 @@ import { approvalKeyWithArguments } from "../agent/approval-key.js";
15
15
  import { CHATGPT_SUBSCRIPTION_ENGINE_NAME } from "../agent/chatgpt-subscription-contract.js";
16
16
  import { readDefaultAgentEngineSetting } from "../agent/default-agent-engine.js";
17
17
  import { DEFAULT_ANTHROPIC_MODEL } from "../agent/default-model.js";
18
- import { AGENT_CHAT_BACKGROUND_RUN_FIELD, AGENT_CHAT_BACKGROUND_SETUP_CLEANUP_FIELD, AGENT_CHAT_PROCESS_RUN_PATH, backgroundRunMarkerExpectsBackgroundRuntime, isAgentChatDurableBackgroundEnabled, isInBackgroundFunctionRuntime, prepareProcessRunRequest, } from "../agent/durable-background.js";
18
+ import { AGENT_CHAT_BACKGROUND_RUN_FIELD, AGENT_CHAT_TURN_GRANT_FIELD, AGENT_CHAT_BACKGROUND_SETUP_CLEANUP_FIELD, AGENT_CHAT_PROCESS_RUN_PATH, backgroundRunMarkerExpectsBackgroundRuntime, isAgentChatDurableBackgroundEnabled, isInBackgroundFunctionRuntime, prepareProcessRunRequest, } from "../agent/durable-background.js";
19
+ import { verifyDispatchedTurnGrant } from "../agent/durable-turn-grant.js";
19
20
  import { listChatGPTSubscriptionModels } from "../agent/engine/chatgpt-subscription-engine.js";
20
21
  import { getEngineLlmConnectionSource } from "../agent/engine/credential-owner.js";
21
22
  import { resolveEngine, createAnthropicEngine, getStoredModelForEngine, normalizeModelForEngine, resolveDelegatedRunModel, getAgentEngineEntry, isAgentEnginePackageInstalled, isStoredEngineUsableForRequest, listAgentEngines, registerBuiltinEngines, } from "../agent/engine/index.js";
@@ -74,7 +75,7 @@ import { handleSharedThreadRequest, } from "./agent-chat/shared-thread.js";
74
75
  import { sortResourceSkills } from "./agent-chat/skill-frontmatter.js";
75
76
  import { discoverAgentContextAgents } from "./agent-context-agents.js";
76
77
  import { getWorkspaceAppProfile } from "./agent-discovery.js";
77
- import { resolveAgentRunOrgId, resolveAgentRunOrgScope, resolveAgentRunOwnerContext, runWithAgentRunContext, seedAgentRunOwnerContext, seedBackgroundAgentRunOwnerContext, } from "./agent-run-context.js";
78
+ import { resolveAgentRunOrgId, resolveAgentRunOrgScope, resolveAgentRunOwnerContext, runWithAgentRunContext, seedAgentRunOwnerContext, seedBackgroundAgentRunOwnerContext, VERIFIED_TURN_GRANT_CONTEXT_KEY, } from "./agent-run-context.js";
78
79
  import { AGENT_TEAM_PROCESS_RUN_PATH, getCurrentDelegationDepth, processAgentTeamRun, reconcileStaleAgentTeamRuns, reconcileAgentTeamRunsForOwner, } from "./agent-teams.js";
79
80
  import { getSession, isLoopbackRequest, registerAuthPublicPaths, } from "./auth.js";
80
81
  import { captureError } from "./capture-error.js";
@@ -8189,6 +8190,12 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
8189
8190
  // per-turn initiator captured before dispatch; the shared thread
8190
8191
  // owner is not necessarily the member who submitted this turn.
8191
8192
  await seedBackgroundAgentRunOwnerContext(event, prepared.runId);
8193
+ if (preparedMarkerRecord?.payloadRef === true &&
8194
+ getAppConfig().agent.interactiveChatTurns) {
8195
+ const turnGrant = await verifyDispatchedTurnGrant(workerBody[AGENT_CHAT_TURN_GRANT_FIELD], prepared.runId, await import("../agent/run-store.js"));
8196
+ if (turnGrant)
8197
+ event.context[VERIFIED_TURN_GRANT_CONTEXT_KEY] = turnGrant;
8198
+ }
8192
8199
  const result = await invokeAgentChatHandler(event);
8193
8200
  const responseStatus = getResponseStatus(event);
8194
8201
  if (responseStatus >= 400) {
@@ -48,4 +48,4 @@ export declare function runWithAgentRunContext<T>(options: {
48
48
  resolveOrgId?: OrgIdResolver;
49
49
  isBackgroundWorker?: boolean;
50
50
  }, fn: () => T | Promise<T>): Promise<T>;
51
- export {};
51
+ export { VERIFIED_TURN_GRANT_CONTEXT_KEY } from "../agent/durable-turn-grant.js";
@@ -1,12 +1,15 @@
1
- import { createError, getHeader } from "h3";
1
+ import { createError, getHeader, getMethod } from "h3";
2
2
  import { AGENT_CHAT_BROWSER_SESSION_ID_FIELD, AGENT_CHAT_REQUEST_CONTEXT_FIELD, } from "../agent/durable-background.js";
3
+ import { VERIFIED_TURN_GRANT_CONTEXT_KEY } from "../agent/durable-turn-grant.js";
4
+ import { getAppConfig } from "../app-config/index.js";
5
+ import { runWithProviderInteractiveScope, } from "../provider-api/interactive-scope.js";
3
6
  import { ANALYTICS_CLIENT_PLATFORM_BODY_FIELD, ANALYTICS_CLIENT_PLATFORM_HEADER, normalizeAnalyticsClientPlatform, } from "../shared/analytics-platform.js";
4
7
  import { SYNTHETIC_TRAFFIC_HEADER, isSyntheticTrafficValue, } from "../shared/test-traffic.js";
5
8
  import { ForbiddenError } from "../sharing/errors.js";
6
9
  import { CREDENTIAL_MEMBERSHIP_UNAVAILABLE_MESSAGE, isCredentialMembershipUnavailable, } from "./credential-membership-unavailable.js";
7
10
  import { isDirectLoopbackRequest, isLoopbackRequest } from "./loopback.js";
8
11
  import { getRequestContext, getRequestIdentityAuthenticatedAtMs, getRequestIdentitySessionToken, hasExplicitPersonalOrgScope, runWithRequestContext, } from "./request-context.js";
9
- import { getForwardedRequestOrigin } from "./request-origin.js";
12
+ import { getForwardedRequestOrigin, hasSameOriginBrowserEvidence, } from "./request-origin.js";
10
13
  import { SessionResolutionUnavailableError, sessionResolutionFailure, } from "./session-resolution-errors.js";
11
14
  import { isSessionResolutionUnavailable, sessionResolutionUnavailableError, } from "./session-resolution-unavailable.js";
12
15
  const resolveOrgScopeForEmail = (...args) => import("../org/context.js").then(({ resolveOrgScopeForEmail }) => resolveOrgScopeForEmail(...args));
@@ -358,5 +361,33 @@ export async function resolveAgentRunRequestContext(options) {
358
361
  }
359
362
  export async function runWithAgentRunContext(options, fn) {
360
363
  const requestContext = await resolveAgentRunRequestContext(options);
361
- return await runWithRequestContext(requestContext, fn);
364
+ if (!getAppConfig().agent.interactiveChatTurns)
365
+ return await runWithRequestContext(requestContext, fn);
366
+ const turnGrant = options.isBackgroundWorker
367
+ ? options.event.context[VERIFIED_TURN_GRANT_CONTEXT_KEY]
368
+ : undefined;
369
+ const interactive = !options.isBackgroundWorker &&
370
+ (await isOwnerBrowserTurn(options.event, options.ownerContext));
371
+ return await runWithRequestContext(requestContext, () => runWithProviderInteractiveScope(interactive, fn, {
372
+ action: false,
373
+ ...(turnGrant ? { turnGrant } : {}),
374
+ }));
375
+ }
376
+ export { VERIFIED_TURN_GRANT_CONTEXT_KEY } from "../agent/durable-turn-grant.js";
377
+ /**
378
+ * A chat turn counts as interactive only when the signed-in owner sent it from
379
+ * this app's own page: a cookie session (no bearer token), same-origin browser
380
+ * evidence, and not a speculative prefetch.
381
+ */
382
+ async function isOwnerBrowserTurn(event, ownerContext) {
383
+ if (ownerContext.anonymous ||
384
+ getHeader(event, "authorization") ||
385
+ getMethod(event) !== "POST" ||
386
+ !hasSameOriginBrowserEvidence(event) ||
387
+ /prefetch/i.test(`${getHeader(event, "purpose") ?? ""} ${getHeader(event, "sec-purpose") ?? ""}`))
388
+ return false;
389
+ const { getBrowserCookieSession } = await import("./auth.js");
390
+ const session = await getBrowserCookieSession(event);
391
+ return (session?.email.trim().toLowerCase() ===
392
+ ownerContext.owner.trim().toLowerCase());
362
393
  }
@@ -20,6 +20,7 @@ function buildIdStampScriptTag() {
20
20
  ? `<script data-agent-native-build-id>globalThis.__AGENT_NATIVE_BUILD_ID__=${JSON.stringify(value)};</script>`
21
21
  : "";
22
22
  }
23
+ const HAS_OWN_BOOTSTRAP_TAG = `<script data-agent-native-has-own-bootstrap>if(typeof Object.hasOwn!=="function"){Object.defineProperty(Object,"hasOwn",{configurable:true,writable:true,value:{hasOwn(object,key){if(object==null)throw new TypeError("Cannot convert nullish value to object");return Object.prototype.hasOwnProperty.call(object,key)}}.hasOwn})}</script>`;
23
24
  const CHUNK_RECOVERY_BOOTSTRAP_TAG = `<script data-agent-native-chunk-recovery-bootstrap>${ROUTE_CHUNK_RECOVERY_BOOTSTRAP_SCRIPT}</script>`;
24
25
  // Inline scripts placed first in <head> run before any stylesheet or module
25
26
  // preload is requested; anywhere after a stylesheet they wait for it to load.
@@ -98,7 +99,8 @@ export function createDocumentRequestHandler(ServerRouter) {
98
99
  await body.allReady;
99
100
  }
100
101
  responseHeaders.set("Content-Type", "text/html; charset=utf-8");
101
- const headScripts = CHUNK_RECOVERY_BOOTSTRAP_TAG +
102
+ const headScripts = HAS_OWN_BOOTSTRAP_TAG +
103
+ CHUNK_RECOVERY_BOOTSTRAP_TAG +
102
104
  buildIdStampScriptTag() +
103
105
  documentBuildIdMetaTag() +
104
106
  (sessionPath ? getSsrSessionBootstrapScriptTag(sessionPath) : "");
@@ -17,8 +17,8 @@
17
17
  * typed JSON-in / JSON-out).
18
18
  */
19
19
  export declare function createTranscribeVoiceHandler(): import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<{
20
- error: string;
21
20
  text?: undefined;
21
+ error: string;
22
22
  } | {
23
23
  error?: undefined;
24
24
  text: string;
@@ -5,3 +5,17 @@ export declare function resolveAgentNativeBuildId(env: Record<string, string | u
5
5
  * can hold a deploy ID, so only a full SHA counts as a commit.
6
6
  */
7
7
  export declare function resolveAgentNativeCommitSha(env: Record<string, string | undefined>): string;
8
+ /** A build identity an app sets for itself instead of reading the build environment. */
9
+ export interface AgentNativeBuildIdentityOverride {
10
+ buildId?: string | undefined;
11
+ commitSha?: string | undefined;
12
+ }
13
+ /**
14
+ * The build id and commit an app's bundles carry. Each value the app sets wins
15
+ * over the build environment; a set value that is blank, or a commit that is
16
+ * not a full SHA, throws instead of silently falling back to the environment.
17
+ */
18
+ export declare function resolveAgentNativeBuildIdentity(env: Record<string, string | undefined>, override?: AgentNativeBuildIdentityOverride): {
19
+ buildId: string;
20
+ commitSha: string;
21
+ };
@@ -37,3 +37,24 @@ export function resolveAgentNativeCommitSha(env) {
37
37
  }
38
38
  return "";
39
39
  }
40
+ /**
41
+ * The build id and commit an app's bundles carry. Each value the app sets wins
42
+ * over the build environment; a set value that is blank, or a commit that is
43
+ * not a full SHA, throws instead of silently falling back to the environment.
44
+ */
45
+ export function resolveAgentNativeBuildIdentity(env, override = {}) {
46
+ let buildId = resolveAgentNativeBuildId(env, "development");
47
+ if (override.buildId !== undefined) {
48
+ buildId = override.buildId.trim();
49
+ if (!buildId)
50
+ throw new Error("The app's buildId override is empty.");
51
+ }
52
+ let commitSha = resolveAgentNativeCommitSha(env);
53
+ if (override.commitSha !== undefined) {
54
+ commitSha = override.commitSha.trim().toLowerCase();
55
+ if (!FULL_COMMIT_SHA.test(commitSha)) {
56
+ throw new Error(`The app's commitSha override "${override.commitSha}" is not a full 40-character commit SHA.`);
57
+ }
58
+ }
59
+ return { buildId, commitSha };
60
+ }
@@ -37,6 +37,22 @@ export interface ClientConfigOptions {
37
37
  define?: UserConfig["define"];
38
38
  agentNativeConfig?: AgentNativeConfigInput;
39
39
  clientCompatibilityVersion?: string;
40
+ /**
41
+ * The build id this app's client and server bundles carry, which the served
42
+ * document stamps and the client compares with the server's. Defaults to the
43
+ * build environment's id (`DEPLOY_ID`, `AGENT_NATIVE_BUILD_ID`, ...). Set it
44
+ * when one build process compiles several apps that must report different
45
+ * builds, such as a mount pinned to an earlier release. Workspace deploy's
46
+ * served-build manifest records the build environment's id, so an app it
47
+ * builds leaves this unset; a pipeline that sets it records its own ids.
48
+ */
49
+ buildId?: string;
50
+ /**
51
+ * The full commit SHA this app was built from, named by the served
52
+ * document's `agent-native-build-sha` meta. Defaults to the commit the build
53
+ * environment names.
54
+ */
55
+ commitSha?: string;
40
56
  routeWarmup?: AgentNativeRouteWarmupConfigInput;
41
57
  mcpIntegrations?: McpIntegrationsConfigInput;
42
58
  tailwind?: boolean;
@@ -18,7 +18,7 @@ import { hashDatabaseKey, removeDevActionDiscoveryFile, writeDevActionDiscoveryF
18
18
  import { validateEmbedRequestOrigin } from "../server/embed-request-origin.js";
19
19
  import { resolveEmbedSessionTokenForOrigin } from "../server/embed-session.js";
20
20
  import { getForwardedRequestOriginFromHeaders } from "../server/request-origin.js";
21
- import { resolveAgentNativeBuildId, resolveAgentNativeCommitSha, } from "../shared/build-id.js";
21
+ import { resolveAgentNativeBuildIdentity } from "../shared/build-id.js";
22
22
  import { EMBED_SESSION_COOKIE, EMBED_TOKEN_QUERY_PARAM, MCP_APP_CHAT_BRIDGE_QUERY_PARAM, } from "../shared/embed-auth.js";
23
23
  import { FRAMEWORK_INTERNAL_ROUTE_PREFIX, matchesPathPrefix, normalizeFrameworkRoutePrefix, } from "../shared/framework-route-prefix.js";
24
24
  import { isMcpEmbedCorsOrigin, MCP_EMBED_CORS_ALLOW_HEADERS, MCP_EMBED_STATIC_ASSET_HEADERS, mcpEmbedStaticAssetRouteRules, shouldAllowMcpEmbedCredentials, } from "../shared/mcp-embed-headers.js";
@@ -3987,7 +3987,10 @@ function createAgentNativeConfig(options = {}, command, userConfig = {}, mode =
3987
3987
  const firstRunOnboardingBuildMode = JSON.stringify(firstRunOnboardingMode);
3988
3988
  const harnessBuildMode = JSON.stringify(harnessMode);
3989
3989
  const requiredEnvBuildValue = JSON.stringify(requiredEnv);
3990
- const buildId = resolveAgentNativeBuildId(process.env, "development");
3990
+ const { buildId, commitSha } = resolveAgentNativeBuildIdentity(process.env, {
3991
+ buildId: options.buildId,
3992
+ commitSha: options.commitSha,
3993
+ });
3991
3994
  const packageVersions = resolveAgentNativePackageVersions(cwd);
3992
3995
  const frameworkRoutePrefix = resolvedAppConfig.runtime?.frameworkRoutePrefix ?? "";
3993
3996
  // guard:allow-env-mutation — Vite config phase, set once before the in-process Nitro dev server accepts a request
@@ -4064,7 +4067,7 @@ function createAgentNativeConfig(options = {}, command, userConfig = {}, mode =
4064
4067
  ...(userConfig.define ?? {}),
4065
4068
  ...(options.define ?? {}),
4066
4069
  __AGENT_NATIVE_BUILD_ID__: JSON.stringify(buildId),
4067
- __AGENT_NATIVE_COMMIT_SHA__: JSON.stringify(resolveAgentNativeCommitSha(process.env)),
4070
+ __AGENT_NATIVE_COMMIT_SHA__: JSON.stringify(commitSha),
4068
4071
  __AGENT_NATIVE_LAZY_TOOLKIT_LOCALES__: JSON.stringify(process.env.AGENT_NATIVE_LAZY_TOOLKIT_LOCALES === "1"),
4069
4072
  __AGENT_NATIVE_PACKAGE_VERSIONS__: JSON.stringify(packageVersions),
4070
4073
  __AGENT_NATIVE_CLIENT_COMPATIBILITY_VERSION__: JSON.stringify(options.clientCompatibilityVersion?.trim() || ""),
@@ -41,6 +41,7 @@ const vitestBaseConfig = {
41
41
  // bundle inside a test takes several times longer, and which test crosses
42
42
  // the limit changes from run to run.
43
43
  testTimeout: 30_000,
44
+ hookTimeout: 30_000,
44
45
  },
45
46
  };
46
47
  export default vitestBaseConfig;
@@ -17,6 +17,7 @@ export declare function createWorkspaceCredentialActions(options: WorkspaceCrede
17
17
  update: import("../action.js").ActionDefinition<{
18
18
  connectionId: string;
19
19
  revision: string;
20
+ draft?: boolean | undefined;
20
21
  name?: string | undefined;
21
22
  config?: Record<string, string | number | boolean> | undefined;
22
23
  secretValues?: {
@@ -84,6 +84,7 @@ export function createWorkspaceCredentialActions(options) {
84
84
  schema: identity
85
85
  .extend({
86
86
  revision: z.string().min(1).max(200),
87
+ draft: z.boolean().optional(),
87
88
  name: z.string().trim().min(1).max(200).optional(),
88
89
  config: z
89
90
  .record(z.string(), z.union([
@@ -30,6 +30,9 @@ export interface WorkspaceCredentialServiceOptions {
30
30
  validateCredentials(input: WorkspaceCredentialValidationInput): Promise<void>;
31
31
  /** Trusted server limit, 1..30000 milliseconds. Defaults to 15000. */
32
32
  validationTimeoutMs?: number;
33
+ /** Allow private edits to disable a profile as a draft until validation succeeds.
34
+ * See packages/core/docs/workspace-credential-drafts.md for lifecycle details. */
35
+ allowDraftEdits?: boolean;
33
36
  /** Trusted server integration only. Runs inside native update publication,
34
37
  * before row locks and writes; throwing rolls back the whole update.
35
38
  * Never receives credentials or browser-provided callbacks. */
@@ -68,6 +71,7 @@ export declare function createWorkspaceCredentialService(rawOptions: WorkspaceCr
68
71
  update(raw: {
69
72
  connectionId: string;
70
73
  revision: string;
74
+ draft?: boolean | undefined;
71
75
  name?: string | undefined;
72
76
  config?: Record<string, WorkspaceCredentialConfigValue> | undefined;
73
77
  secretValues?: ReadonlyArray<{