@agent-native/core 0.206.0 → 0.206.1-nightly-20261009213000

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 (93) hide show
  1. package/dist/action.d.ts +2 -0
  2. package/dist/agent/default-agent-engine.js +25 -0
  3. package/dist/agent/durable-background.d.ts +2 -0
  4. package/dist/agent/durable-background.js +2 -0
  5. package/dist/agent/engine/error-detail.d.ts +1 -0
  6. package/dist/agent/engine/error-detail.js +6 -1
  7. package/dist/agent/engine/tool-call-journal-seed.d.ts +1 -1
  8. package/dist/agent/engine/tool-call-journal-seed.js +47 -11
  9. package/dist/agent/engine/translate-anthropic.d.ts +9 -0
  10. package/dist/agent/engine/translate-anthropic.js +18 -3
  11. package/dist/agent/production-agent.d.ts +6 -4
  12. package/dist/agent/production-agent.js +126 -85
  13. package/dist/agent/run-store.js +15 -3
  14. package/dist/agent/thread-data-builder.js +1 -2
  15. package/dist/agent/types.d.ts +1 -0
  16. package/dist/automation/index.d.ts +1 -1
  17. package/dist/chat-threads/store.js +6 -2
  18. package/dist/cli/design-connect.d.ts +1 -0
  19. package/dist/cli/design-connect.js +72 -19
  20. package/dist/client/analytics.js +48 -58
  21. package/dist/client/chat/agentkit-agent-native.js +11 -10
  22. package/dist/client/chat/agentkit-protocol.js +5 -1
  23. package/dist/client/chat/runtime.d.ts +4 -1
  24. package/dist/client/chat/runtime.js +135 -43
  25. package/dist/client/session-replay-endpoint.d.ts +1 -0
  26. package/dist/client/session-replay-endpoint.js +35 -0
  27. package/dist/client/session-replay.js +2 -24
  28. package/dist/client/sharing/share-controller-helpers.d.ts +1 -1
  29. package/dist/client/sharing/share-controller-helpers.js +2 -1
  30. package/dist/client/sharing/useShareButtonController.js +2 -9
  31. package/dist/client/use-action.d.ts +1 -0
  32. package/dist/client/use-action.js +2 -1
  33. package/dist/deploy/build.js +1 -1
  34. package/dist/deploy/workspace-deploy.js +65 -6
  35. package/dist/file-upload/actions/upload-image.d.ts +2 -2
  36. package/dist/file-upload/registry.d.ts +7 -1
  37. package/dist/file-upload/registry.js +25 -7
  38. package/dist/mcp/build-server.d.ts +6 -0
  39. package/dist/mcp/build-server.js +97 -28
  40. package/dist/mcp/embed-app.js +9 -8
  41. package/dist/mcp/screen-memory-stdio.d.ts +7 -7
  42. package/dist/notifications/routes.d.ts +3 -3
  43. package/dist/observability/metrics.d.ts +5 -0
  44. package/dist/observability/metrics.js +62 -7
  45. package/dist/observability/routes.d.ts +4 -4
  46. package/dist/org/handlers.d.ts +1 -1
  47. package/dist/org/index.d.ts +1 -1
  48. package/dist/provider-api/actions/custom-provider-registration.d.ts +13 -13
  49. package/dist/provider-api/actions/provider-api.d.ts +5 -5
  50. package/dist/scripts/docs/search.d.ts +1 -0
  51. package/dist/scripts/docs/search.js +17 -4
  52. package/dist/secrets/index.d.ts +1 -1
  53. package/dist/secrets/index.js +1 -1
  54. package/dist/secrets/storage.d.ts +1 -0
  55. package/dist/secrets/storage.js +8 -0
  56. package/dist/server/action-routes.js +62 -29
  57. package/dist/server/agent-chat/mcp-options.d.ts +2 -0
  58. package/dist/server/agent-chat/prompt-resources.js +2 -2
  59. package/dist/server/agent-engine-api-key-route.d.ts +2 -1
  60. package/dist/server/agent-engine-api-key-route.js +66 -2
  61. package/dist/server/agent-engine-default-model-route.d.ts +1 -1
  62. package/dist/server/agent-engine-ollama-models-route.d.ts +2 -2
  63. package/dist/server/agent-run-context.js +21 -1
  64. package/dist/server/agent-teams-run-queue.js +2 -1
  65. package/dist/server/agents-bundle.js +1 -1
  66. package/dist/server/auth.js +1 -0
  67. package/dist/server/core-routes-plugin.js +12 -0
  68. package/dist/server/embed-session.js +15 -1
  69. package/dist/server/http-response-telemetry.js +37 -8
  70. package/dist/server/realtime-token.d.ts +1 -1
  71. package/dist/shared/embed-auth.d.ts +4 -0
  72. package/dist/shared/embed-auth.js +156 -23
  73. package/dist/shared/inline-bytes.d.ts +29 -0
  74. package/dist/shared/inline-bytes.js +170 -0
  75. package/dist/shared/mcp-embed-headers.d.ts +1 -1
  76. package/dist/shared/mcp-embed-headers.js +1 -1
  77. package/dist/sharing/actions/list-resource-shares.d.ts +1 -1
  78. package/dist/sharing/actions/list-resource-shares.js +10 -4
  79. package/dist/sharing/actions/set-resource-visibility.js +3 -1
  80. package/dist/sharing/actions/share-resource.js +4 -2
  81. package/dist/sharing/actions/unshare-resource.js +3 -1
  82. package/dist/sharing/widget-grant.d.ts +19 -0
  83. package/dist/sharing/widget-grant.js +55 -0
  84. package/dist/templates/factory/.agents/skills/review-latest-feedback/SKILL.md +20 -21
  85. package/dist/testing.d.ts +1 -0
  86. package/dist/testing.js +1 -0
  87. package/dist/tracking/registry.d.ts +3 -2
  88. package/dist/tracking/registry.js +12 -3
  89. package/dist/vite/client.js +6 -1
  90. package/docs/content/observability.mdx +15 -10
  91. package/docs/content/tracking.mdx +1 -1
  92. package/package.json +4 -4
  93. package/src/templates/factory/.agents/skills/review-latest-feedback/SKILL.md +20 -21
@@ -13,7 +13,7 @@ import { checkWorkspaceAppAccessForRequest } from "../org/workspace-app-access-r
13
13
  import { WORKSPACE_APP_ACCESS_UNAVAILABLE, WORKSPACE_APP_ACCESS_UNAVAILABLE_MESSAGE, } from "../org/workspace-app-access.js";
14
14
  import { LLM_PROVIDER_MISSING_ERROR_CODE, LLM_PROVIDER_MISSING_STATUS, } from "../shared/action-error-codes.js";
15
15
  import { agentNativeMcpInstructions, agentNativeToolTitle, } from "../shared/agent-mcp-metadata.js";
16
- import { EMBED_TARGET_HEADER, EMBED_TARGET_QUERY_PARAM, EMBED_TOKEN_QUERY_PARAM, MCP_DIRECTORY_WIDGET_SESSION_EXPIRED_HEADER, allowsMcpDirectoryWidgetReadAction, getMcpDirectoryWidgetWriteCapabilityGrant, isExpiredMcpDirectoryWidgetWriteCapability, isMcpDirectoryWidgetCapabilityScope, isMcpDirectoryWidgetReadCapabilityScope, isMcpDirectoryWidgetWriteCapabilityScope, normalizeMcpDirectoryWidgetReadActionArguments, normalizeMcpDirectoryWidgetWriteActionArguments, } from "../shared/embed-auth.js";
16
+ import { EMBED_TARGET_HEADER, EMBED_TARGET_QUERY_PARAM, EMBED_TOKEN_QUERY_PARAM, MCP_DIRECTORY_WIDGET_SESSION_EXPIRED_HEADER, allowsMcpDirectoryWidgetReadAction, getMcpDirectoryWidgetReadCapabilityResourceIds, getMcpDirectoryWidgetWriteCapabilityGrant, isExpiredMcpDirectoryWidgetWriteCapability, isMcpDirectoryWidgetCapabilityScope, isMcpDirectoryWidgetReadCapabilityScope, isMcpDirectoryWidgetWriteCapabilityScope, normalizeMcpDirectoryWidgetReadActionArguments, normalizeMcpDirectoryWidgetWriteActionArguments, } from "../shared/embed-auth.js";
17
17
  import { isMcpEmbedCorsOrigin, MCP_EMBED_CORS_ALLOW_HEADERS, shouldAllowMcpEmbedCredentials, } from "../shared/mcp-embed-headers.js";
18
18
  import { countActionFailure, countCredentialState, } from "../tracking/failure-counters.js";
19
19
  import { redact, redactErrorStack } from "../tracking/redaction.js";
@@ -181,7 +181,7 @@ function handleOptionsRequest(event) {
181
181
  }
182
182
  setResponseHeader(event, "Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS");
183
183
  setResponseHeader(event, "Access-Control-Allow-Headers", cors.credentials
184
- ? `Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-Browser-Tab,X-Agent-Native-CSRF,X-User-Timezone,X-Agent-Native-Session-Id,X-Agent-Native-Client-Platform,X-Agent-Native-Tool-Bridge,X-Agent-Native-Tool-Id,X-Agent-Native-Frontend,X-Agent-Native-Client-Compatibility,X-Agent-Native-Build-Id,${EMBED_TARGET_HEADER}`
184
+ ? `Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Content-Save-Origin,X-Agent-Native-Browser-Tab,X-Agent-Native-CSRF,X-User-Timezone,X-Agent-Native-Session-Id,X-Agent-Native-Client-Platform,X-Agent-Native-Tool-Bridge,X-Agent-Native-Tool-Id,X-Agent-Native-Frontend,X-Agent-Native-Client-Compatibility,X-Agent-Native-Build-Id,${EMBED_TARGET_HEADER}`
185
185
  : `${MCP_EMBED_CORS_ALLOW_HEADERS},X-Agent-Native-Tool-Bridge,X-Agent-Native-Tool-Id,X-Agent-Native-Frontend,X-Agent-Native-Client-Compatibility,X-Agent-Native-Build-Id`);
186
186
  }
187
187
  setResponseStatus(event, 204);
@@ -322,6 +322,37 @@ async function resolveRequestAuthCapability(event) {
322
322
  function resolveRequestEmbedSession(event) {
323
323
  return resolveEmbedSessionFromRequest(event);
324
324
  }
325
+ /**
326
+ * Widget-scoped action routes are auth-public, so the global guard never runs
327
+ * the workspace app access check for them; the handler runs it for the
328
+ * session-authenticated callers it resolves itself.
329
+ */
330
+ async function denyWithoutWorkspaceAppAccess(event, name, ownerContext, resolvedCaller, resolveOrgId) {
331
+ const workspaceOrgId = resolvedCaller
332
+ ? resolvedCaller.orgId === null
333
+ ? undefined
334
+ : (normalizeOrgId(resolvedCaller.orgId) ??
335
+ (resolvedCaller.owner && !resolvedCaller.anonymous
336
+ ? await storedActiveOrgId(resolvedCaller.owner)
337
+ : undefined))
338
+ : await resolveAgentRunOrgId({ event, ownerContext, resolveOrgId });
339
+ const workspaceAppAccess = await checkWorkspaceAppAccessForRequest({
340
+ path: `/_agent-native/actions/${name}`,
341
+ method: getMethod(event),
342
+ email: ownerContext.owner,
343
+ orgId: workspaceOrgId,
344
+ });
345
+ if (workspaceAppAccess === WORKSPACE_APP_ACCESS_UNAVAILABLE) {
346
+ return { status: 503, error: WORKSPACE_APP_ACCESS_UNAVAILABLE_MESSAGE };
347
+ }
348
+ if (workspaceAppAccess === false) {
349
+ return {
350
+ status: 403,
351
+ error: "You do not have access to this workspace app.",
352
+ };
353
+ }
354
+ return null;
355
+ }
325
356
  function mountActionRoutesInternal(nitroApp, actions, options) {
326
357
  const mounted = [];
327
358
  const app = getH3App(nitroApp);
@@ -406,6 +437,13 @@ function mountActionRoutesInternal(nitroApp, actions, options) {
406
437
  orgId: embedSession.orgId,
407
438
  })
408
439
  : undefined;
440
+ const directoryWidgetResourceIds = directoryWidgetWriteGrant?.resourceIds ??
441
+ (directoryWidgetCapability && embedSession
442
+ ? getMcpDirectoryWidgetReadCapabilityResourceIds(authCapability, {
443
+ appId: options?.mcpDirectoryWidgetAppId ?? options?.appId ?? "",
444
+ resourceUri: options?.mcpDirectoryWidgetResourceUri ?? "",
445
+ })
446
+ : undefined);
409
447
  const directoryWidgetReadRequest = isFrontendActionRequest(event) ||
410
448
  (options?.caller === "webmcp" &&
411
449
  options.routePrefix === WEBMCP_ACTION_ROUTE_PREFIX);
@@ -535,6 +573,11 @@ function mountActionRoutesInternal(nitroApp, actions, options) {
535
573
  authUserId = ownerContext.authUserId;
536
574
  ownerContextResolved = true;
537
575
  directoryWidgetReadAuthenticatedFallback = true;
576
+ const denied = await denyWithoutWorkspaceAppAccess(event, name, ownerContext, null, options?.resolveOrgId);
577
+ if (denied) {
578
+ setResponseStatus(event, denied.status);
579
+ return { error: denied.error };
580
+ }
538
581
  }
539
582
  catch (error) {
540
583
  if (!isAuthResolutionFailure(error))
@@ -543,6 +586,13 @@ function mountActionRoutesInternal(nitroApp, actions, options) {
543
586
  return { error: "Unauthorized" };
544
587
  }
545
588
  }
589
+ else {
590
+ const denied = await denyWithoutWorkspaceAppAccess(event, name, resolvedCaller, resolvedCaller, options?.resolveOrgId);
591
+ if (denied) {
592
+ setResponseStatus(event, denied.status);
593
+ return { error: denied.error };
594
+ }
595
+ }
546
596
  }
547
597
  if (directoryWidgetWriteRoute && !directoryWidgetWriteAllowed) {
548
598
  let ownerContext;
@@ -576,33 +626,10 @@ function mountActionRoutesInternal(nitroApp, actions, options) {
576
626
  authUserId = ownerContext.authUserId;
577
627
  ownerContextResolved = true;
578
628
  }
579
- const workspaceOrgId = resolvedCaller
580
- ? resolvedCaller.orgId === null
581
- ? undefined
582
- : (normalizeOrgId(resolvedCaller.orgId) ??
583
- (resolvedCaller.owner && !resolvedCaller.anonymous
584
- ? await storedActiveOrgId(resolvedCaller.owner)
585
- : undefined))
586
- : await resolveAgentRunOrgId({
587
- event,
588
- ownerContext,
589
- resolveOrgId: options?.resolveOrgId,
590
- });
591
- const workspaceAppAccess = await checkWorkspaceAppAccessForRequest({
592
- path: `/_agent-native/actions/${name}`,
593
- method: getMethod(event),
594
- email: ownerContext.owner,
595
- orgId: workspaceOrgId,
596
- });
597
- if (workspaceAppAccess === WORKSPACE_APP_ACCESS_UNAVAILABLE) {
598
- setResponseStatus(event, 503);
599
- return { error: WORKSPACE_APP_ACCESS_UNAVAILABLE_MESSAGE };
600
- }
601
- if (workspaceAppAccess === false) {
602
- setResponseStatus(event, 403);
603
- return {
604
- error: "You do not have access to this workspace app.",
605
- };
629
+ const denied = await denyWithoutWorkspaceAppAccess(event, name, ownerContext, resolvedCaller, options?.resolveOrgId);
630
+ if (denied) {
631
+ setResponseStatus(event, denied.status);
632
+ return { error: denied.error };
606
633
  }
607
634
  }
608
635
  if (!resolvedCaller &&
@@ -918,6 +945,12 @@ function mountActionRoutesInternal(nitroApp, actions, options) {
918
945
  ...(directoryWidgetReadAllowed
919
946
  ? { mcpDirectoryWidgetReadOnly: true }
920
947
  : {}),
948
+ ...(directoryWidgetResourceIds &&
949
+ (directoryWidgetWriteAllowed || directoryWidgetReadAllowed)
950
+ ? {
951
+ mcpDirectoryWidgetResourceIds: directoryWidgetResourceIds,
952
+ }
953
+ : {}),
921
954
  ...(directoryWidgetWriteGrant &&
922
955
  (directoryWidgetWriteAllowed || directoryWidgetReadAllowed)
923
956
  ? {
@@ -27,6 +27,8 @@ export interface AgentChatMcpOptions {
27
27
  widgetReadPrivateActions?: readonly string[];
28
28
  /** Authenticated reads surfaced on other agent profiles, but only scoped here. */
29
29
  widgetReadAuthenticatedActions?: readonly string[];
30
+ /** Scoped reads minted only into a write capability that lists the mapped write action. */
31
+ widgetReadActionWriteGates?: Record<string, string>;
30
32
  /** Omit the one shared resource title when tools have distinct invocation labels. */
31
33
  widgetResourceTitle?: string | false;
32
34
  keyToolNames?: readonly string[];
@@ -286,12 +286,12 @@ export function buildCompactSkillsSummary(skills, skillReadTool) {
286
286
  const description = s.meta.description?.trim()
287
287
  ? ` - ${ensureSentence(compactPromptLine(s.meta.description, PROMPT_SUMMARY_DESCRIPTION_MAX_CHARS))}`
288
288
  : "";
289
- return `- \`${s.meta.name}\`${description} Read with \`${skillReadTool} --slug "${skillDocsSlug(s.meta.name)}"\` before starting a task it applies to; reuse that page for subsequent steps in this turn.`;
289
+ return `- \`${s.meta.name}\`${description} Read with \`${skillReadTool} --slug "${skillDocsSlug(s.meta.name)}"\` before starting a task it applies to; reuse that page for the rest of the conversation.`;
290
290
  });
291
291
  if (skills.length > listedSkills.length) {
292
292
  lines.push(`- ...${skills.length - listedSkills.length} more codebase skills. Use \`${skillReadTool} --query "<topic>"\` to discover the relevant one.`);
293
293
  }
294
- return `<skills-summary>\nCodebase skills bundled from \`.agents/skills/\` (or legacy \`.agent/skills/\`) are available as ${skillReadTool} pages. Do not use MCP resource reads for these skills. Read each relevant page once per turn and reuse it; do not repeat an equivalent ${skillReadTool} lookup unless the page or question is different.\n\n${lines.join("\n")}\n</skills-summary>`;
294
+ return `<skills-summary>\nCodebase skills bundled from \`.agents/skills/\` (or legacy \`.agent/skills/\`) are available as ${skillReadTool} pages. Do not use MCP resource reads for these skills. Read each relevant page once per conversation and reuse it; do not repeat an equivalent ${skillReadTool} lookup unless the page or question is different.\n\n${lines.join("\n")}\n</skills-summary>`;
295
295
  }
296
296
  function escapeXmlAttribute(value) {
297
297
  return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
@@ -29,6 +29,7 @@ export declare function normalizeAgentEngineApiKeyPayload(body: unknown): {
29
29
  baseUrl?: string;
30
30
  clearBaseUrl: boolean;
31
31
  scope: AgentEngineApiKeyScope;
32
+ surface?: "settings" | "onboarding" | "setup_card";
32
33
  } | {
33
34
  ok: false;
34
35
  statusCode: number;
@@ -66,12 +67,12 @@ export declare function createAgentEngineApiKeyHandler(): import("h3").EventHand
66
67
  code: any;
67
68
  } | {
68
69
  errorCode?: undefined;
70
+ error?: undefined;
69
71
  code?: undefined;
70
72
  ok: boolean;
71
73
  key: string;
72
74
  baseUrlKey?: string;
73
75
  scope: AgentEngineApiKeyScope;
74
76
  defaultModel?: import("./agent-engine-default-model-route.js").SavedKeyDefaultModelOutcome;
75
- error?: undefined;
76
77
  }>>;
77
78
  export {};
@@ -4,7 +4,9 @@ import { validateProviderBaseUrl } from "../agent/engine/provider-endpoint-valid
4
4
  import { OLLAMA_BASE_URL_ENV_VAR, OPENAI_BASE_URL_ENV_VAR, PROVIDER_ENV_META, } from "../agent/engine/provider-env-vars.js";
5
5
  import { getOrgContext } from "../org/context.js";
6
6
  import { secretKeyNames } from "../secrets/key-aliases.js";
7
- import { deleteAppSecret, writeAppSecret } from "../secrets/storage.js";
7
+ import { deleteAppSecret, hasAppSecret, writeAppSecret, } from "../secrets/storage.js";
8
+ import { normalizeLlmConnection } from "../shared/llm-connection.js";
9
+ import { track } from "../tracking/registry.js";
8
10
  import { readDefaultModelSelectionRequest, selectDefaultModelForSavedKey, } from "./agent-engine-default-model-route.js";
9
11
  import { checkProviderKeyForSave, providerForKeyEnvVar, } from "./agent-engine-provider-models-route.js";
10
12
  import { getSession } from "./auth.js";
@@ -22,6 +24,10 @@ const BASE_URL_KEYS = new Set([
22
24
  OLLAMA_BASE_URL_ENV_VAR,
23
25
  ]);
24
26
  const OPENAI_PROVIDER_KEY = PROVIDER_TO_ENV_VAR.get("openai") ?? "";
27
+ function credentialProviderForKey(key) {
28
+ return normalizeLlmConnection(providerForKeyEnvVar(key) ??
29
+ (key === OLLAMA_BASE_URL_ENV_VAR ? "ollama" : "openai"));
30
+ }
25
31
  /**
26
32
  * Check a provider key before it is stored, by listing the models it
27
33
  * reaches. `baseUrl` is OpenAI's gateway: a string checks that endpoint,
@@ -119,6 +125,11 @@ export function normalizeAgentEngineApiKeyPayload(body) {
119
125
  ...(baseUrl ? { baseUrl } : {}),
120
126
  clearBaseUrl,
121
127
  scope: raw.scope === "org" ? "org" : "user",
128
+ ...(raw.surface === "settings" ||
129
+ raw.surface === "onboarding" ||
130
+ raw.surface === "setup_card"
131
+ ? { surface: raw.surface }
132
+ : {}),
122
133
  };
123
134
  }
124
135
  export function normalizeAgentEngineApiKeyDeletePayload(body) {
@@ -191,6 +202,31 @@ function legacyWorkspaceRowFor(target) {
191
202
  scopeId: target.scope === "org" ? target.scopeId : `solo:${target.scopeId}`,
192
203
  };
193
204
  }
205
+ function baseUrlKeyFor(key) {
206
+ if (key === OLLAMA_BASE_URL_ENV_VAR)
207
+ return OLLAMA_BASE_URL_ENV_VAR;
208
+ return key === OPENAI_PROVIDER_KEY ? OPENAI_BASE_URL_ENV_VAR : undefined;
209
+ }
210
+ function credentialKindFor(state) {
211
+ if (state.hasApiKey && state.hasBaseUrl)
212
+ return "api_key_and_base_url";
213
+ return state.hasBaseUrl ? "base_url" : "api_key";
214
+ }
215
+ async function readCredentialState(key, target) {
216
+ const targets = [target, legacyWorkspaceRowFor(target)];
217
+ const apiKeyNames = key === OLLAMA_BASE_URL_ENV_VAR ? [] : secretKeyNames(key);
218
+ const baseUrlKey = baseUrlKeyFor(key);
219
+ const [apiKeyMatches, baseUrlMatches] = await Promise.all([
220
+ Promise.all(targets.flatMap((scope) => apiKeyNames.map((key) => hasAppSecret({ key, ...scope })))),
221
+ baseUrlKey
222
+ ? Promise.all(targets.map((scope) => hasAppSecret({ key: baseUrlKey, ...scope })))
223
+ : [],
224
+ ]);
225
+ return {
226
+ hasApiKey: apiKeyMatches.some(Boolean),
227
+ hasBaseUrl: baseUrlMatches.some(Boolean),
228
+ };
229
+ }
194
230
  export function createAgentEngineApiKeyHandler() {
195
231
  return defineEventHandler(async (event) => {
196
232
  if (getMethod(event) === "DELETE") {
@@ -212,6 +248,7 @@ export function createAgentEngineApiKeyHandler() {
212
248
  setResponseStatus(event, resolved.statusCode);
213
249
  return { error: resolved.error };
214
250
  }
251
+ const session = await getSession(event);
215
252
  // A row saved under an older name of the same key, or in the legacy
216
253
  // workspace row the resolver reads after this scope, would otherwise
217
254
  // keep the provider working after it was removed.
@@ -219,6 +256,7 @@ export function createAgentEngineApiKeyHandler() {
219
256
  ...secretKeyNames(payload.key),
220
257
  ...(payload.endpointKey ? [payload.endpointKey] : []),
221
258
  ];
259
+ const credentialState = await readCredentialState(payload.key, resolved.target);
222
260
  for (const target of [
223
261
  resolved.target,
224
262
  legacyWorkspaceRowFor(resolved.target),
@@ -227,6 +265,14 @@ export function createAgentEngineApiKeyHandler() {
227
265
  await deleteAppSecret({ key, ...target });
228
266
  }
229
267
  }
268
+ if (credentialState.hasApiKey || credentialState.hasBaseUrl) {
269
+ track("llm_credential_changed", {
270
+ change_type: "disconnected",
271
+ provider: credentialProviderForKey(payload.key),
272
+ scope: resolved.target.scope,
273
+ credential_kind: credentialKindFor(credentialState),
274
+ }, { userId: session?.email });
275
+ }
230
276
  return { ok: true, key: payload.key, scope: resolved.target.scope };
231
277
  }
232
278
  if (getMethod(event) !== "POST") {
@@ -251,6 +297,7 @@ export function createAgentEngineApiKeyHandler() {
251
297
  return { error: resolved.error };
252
298
  }
253
299
  // Removing a personal key stays allowed; only new personal saves stop.
300
+ const session = await getSession(event);
254
301
  if (resolved.target.scope === "user" &&
255
302
  (payload.value || payload.baseUrl)) {
256
303
  const denial = await resolvePersonalProviderKeySaveDenial(event, resolved.target.scopeId, payload.key);
@@ -287,7 +334,6 @@ export function createAgentEngineApiKeyHandler() {
287
334
  // A key saved without an endpoint keeps the saved one, which the
288
335
  // runtime resolves across the caller's personal and org rows.
289
336
  const needsSavedEndpoint = payload.key === OPENAI_PROVIDER_KEY && baseUrl === undefined;
290
- const session = await getSession(event);
291
337
  const orgId = resolved.target.scope === "org"
292
338
  ? resolved.target.scopeId
293
339
  : needsSavedEndpoint
@@ -299,6 +345,7 @@ export function createAgentEngineApiKeyHandler() {
299
345
  return { error: keyValidation.error, code: keyValidation.code };
300
346
  }
301
347
  }
348
+ const credentialState = await readCredentialState(payload.key, resolved.target);
302
349
  if (payload.value) {
303
350
  await writeAppSecret({
304
351
  key: payload.key,
@@ -330,6 +377,23 @@ export function createAgentEngineApiKeyHandler() {
330
377
  scopeId: resolved.target.scopeId,
331
378
  });
332
379
  }
380
+ const credentialStateAfter = {
381
+ hasApiKey: Boolean(payload.value) || credentialState.hasApiKey,
382
+ hasBaseUrl: payload.baseUrl
383
+ ? true
384
+ : payload.clearBaseUrl
385
+ ? false
386
+ : credentialState.hasBaseUrl,
387
+ };
388
+ track("llm_credential_changed", {
389
+ change_type: credentialState.hasApiKey || credentialState.hasBaseUrl
390
+ ? "key_updated"
391
+ : "connected",
392
+ provider: credentialProviderForKey(payload.key),
393
+ scope: resolved.target.scope,
394
+ ...(payload.surface ? { surface: payload.surface } : {}),
395
+ credential_kind: credentialKindFor(credentialStateAfter),
396
+ }, { userId: session?.email });
333
397
  // Personal and organization rows for one provider coexist: an org save
334
398
  // never touches the caller's personal row, which the resolver keeps using
335
399
  // for them alone (user before org).
@@ -16,9 +16,9 @@ export declare function createAgentEngineDisconnectHandler(): import("h3").Event
16
16
  error: any;
17
17
  scope?: undefined;
18
18
  } | {
19
- error?: undefined;
20
19
  ok: boolean;
21
20
  scope: "org" | "user";
21
+ error?: undefined;
22
22
  }>>;
23
23
  export interface DefaultModelSelectionRequest {
24
24
  engine: string;
@@ -1,9 +1,9 @@
1
1
  export declare function createAgentEngineOllamaModelsHandler(): import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<{
2
2
  error: string;
3
- ok?: undefined;
4
3
  models?: undefined;
4
+ ok?: undefined;
5
5
  } | {
6
- error?: undefined;
7
6
  ok: boolean;
8
7
  models: string[];
8
+ error?: undefined;
9
9
  }>>;
@@ -1,4 +1,5 @@
1
1
  import { createError, getHeader } from "h3";
2
+ import { AGENT_CHAT_BROWSER_SESSION_ID_FIELD } from "../agent/durable-background.js";
2
3
  import { ANALYTICS_CLIENT_PLATFORM_BODY_FIELD, ANALYTICS_CLIENT_PLATFORM_HEADER, normalizeAnalyticsClientPlatform, } from "../shared/analytics-platform.js";
3
4
  import { SYNTHETIC_TRAFFIC_HEADER, isSyntheticTrafficValue, } from "../shared/test-traffic.js";
4
5
  import { CREDENTIAL_MEMBERSHIP_UNAVAILABLE_MESSAGE, isCredentialMembershipUnavailable, } from "./credential-membership-unavailable.js";
@@ -53,6 +54,23 @@ export function readBrowserSessionIdHeader(event) {
53
54
  const trimmed = typeof value === "string" ? value.trim() : "";
54
55
  return /^[!-~]{1,127}$/.test(trimmed) ? trimmed : undefined;
55
56
  }
57
+ function readDurableBrowserSessionId(event) {
58
+ const body = event.context?.["__agentChatBackgroundBody"];
59
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
60
+ return undefined;
61
+ }
62
+ const record = body;
63
+ if (!Object.prototype.hasOwnProperty.call(record, AGENT_CHAT_BROWSER_SESSION_ID_FIELD)) {
64
+ return undefined;
65
+ }
66
+ const value = record[AGENT_CHAT_BROWSER_SESSION_ID_FIELD];
67
+ if (value === null)
68
+ return undefined;
69
+ if (typeof value === "string" && /^[!-~]{1,127}$/.test(value)) {
70
+ return value;
71
+ }
72
+ throw new Error("Malformed browser session id in durable agent run payload.");
73
+ }
56
74
  const SAFE_BROWSER_TAB_ID_RE = /^[A-Za-z0-9_-]{1,96}$/;
57
75
  export function readBrowserTabIdHeader(event) {
58
76
  const raw = readHeaderValue(event, "x-agent-native-browser-tab");
@@ -176,7 +194,9 @@ export async function resolveAgentRunOrgId(options) {
176
194
  export async function resolveAgentRunRequestContext(options) {
177
195
  const orgId = await resolveAgentRunOrgId(options);
178
196
  const timezone = readAgentRunTimezone(options.event);
179
- const browserSessionId = readBrowserSessionIdHeader(options.event);
197
+ const browserSessionId = options.isBackgroundWorker
198
+ ? readDurableBrowserSessionId(options.event)
199
+ : readBrowserSessionIdHeader(options.event);
180
200
  const browserTabId = readBrowserTabIdHeader(options.event);
181
201
  const identitySessionToken = getRequestIdentitySessionToken(options.event, options.ownerContext.owner);
182
202
  const clientPlatform = readAnalyticsClientPlatformHeader(options.event);
@@ -1,6 +1,7 @@
1
1
  import { ensureRunTables } from "../agent/run-store.js";
2
2
  import { getDbExec, withDbExec } from "../db/client.js";
3
3
  import { ensureColumnExists, ensureIndexExists, ensureTableExists, } from "../db/ddl-guard.js";
4
+ import { stripInlineBytesFromJson } from "../shared/inline-bytes.js";
4
5
  export const MAX_AGENT_TEAM_CONTINUATIONS = 60;
5
6
  export const MAX_AGENT_TEAM_NO_PROGRESS_CONTINUATIONS = 3;
6
7
  export const RUN_DISPATCH_STUCK_AFTER_MS = 15_000;
@@ -221,7 +222,7 @@ export async function persistAgentTeamRunEventIfCurrent(input) {
221
222
  input.runId,
222
223
  input.seq,
223
224
  Date.now(),
224
- input.eventData,
225
+ stripInlineBytesFromJson(input.eventData, "placeholder"),
225
226
  input.runId,
226
227
  ],
227
228
  });
@@ -354,7 +354,7 @@ function generateSkillsPromptBlockForEntries(entries, mode) {
354
354
  ? `To read a skill in the in-app runtime agent, before starting a task it applies to:
355
355
  \`docs-search --slug "<slug>"\` — each skill's slug is the [bracketed] token ending its line
356
356
  \`docs-search --query "<topic>"\` to discover matching docs/skills
357
- Read each relevant page once per turn and reuse it for subsequent steps. Do not repeat an equivalent lookup unless you need a different page or question.`
357
+ Read each relevant page once per conversation and reuse it. Do not repeat an equivalent lookup unless you need a different page or question.`
358
358
  : `To read a skill in dev mode (when you have bash access):
359
359
  \`bash(command="cat <skill-dir>/SKILL.md")\`
360
360
  \`bash(command="ls <skill-dir>/")\` to see all files in the folder`;
@@ -2180,6 +2180,7 @@ function applyCorsHeaders(event, publicCorsPaths = [], requestPath) {
2180
2180
  "Authorization",
2181
2181
  "X-Requested-With",
2182
2182
  "X-Request-Source",
2183
+ "X-Content-Save-Origin",
2183
2184
  "X-Agent-Native-CSRF",
2184
2185
  "X-User-Timezone",
2185
2186
  "X-Agent-Native-Desktop-Verifier",
@@ -1537,6 +1537,12 @@ export async function activateBuilderAccount(event, input) {
1537
1537
  credential_scope: written.scope,
1538
1538
  account_provisioned: true,
1539
1539
  });
1540
+ track("llm_credential_changed", {
1541
+ change_type: "connected",
1542
+ provider: "builder",
1543
+ scope: written.scope,
1544
+ credential_kind: "builder",
1545
+ }, { userId: ownerEmail });
1540
1546
  await recordBuilderConnectionAudit({
1541
1547
  connected: true,
1542
1548
  ownerEmail,
@@ -3638,6 +3644,12 @@ export function createCoreRoutesPlugin(options = {}) {
3638
3644
  stage: "callback",
3639
3645
  credential_scope: credentialScope,
3640
3646
  });
3647
+ track("llm_credential_changed", {
3648
+ change_type: "connected",
3649
+ provider: "builder",
3650
+ scope: credentialScope,
3651
+ credential_kind: "builder",
3652
+ }, { userId: ownerEmail });
3641
3653
  await recordBuilderConnectionAudit({
3642
3654
  connected: true,
3643
3655
  ownerEmail,
@@ -1225,12 +1225,26 @@ function crossSiteCookieAttrs(event) {
1225
1225
  ? { sameSite: "none", secure: true, partitioned: true }
1226
1226
  : { sameSite: "lax", secure: false };
1227
1227
  }
1228
+ // A browser drops a cookie whose name and value exceed 4096 bytes, and the
1229
+ // widest directory widget grants sign a larger token than that.
1230
+ const EMBED_SESSION_COOKIE_MAX_BYTES = 4096;
1228
1231
  export function setEmbedSessionCookie(event, token) {
1229
- setCookie(event, EMBED_SESSION_COOKIE, token, {
1232
+ const attrs = {
1230
1233
  httpOnly: true,
1231
1234
  ...crossSiteCookieAttrs(event),
1232
1235
  ...cookieDomainAttrs(event),
1233
1236
  path: "/",
1237
+ };
1238
+ if (Buffer.byteLength(`${EMBED_SESSION_COOKIE}=${token}`) >
1239
+ EMBED_SESSION_COOKIE_MAX_BYTES) {
1240
+ // The page keeps the token it was handed (query or bearer), which resolves
1241
+ // ahead of the cookie. Expire any earlier cookie so it cannot stand in for
1242
+ // this session on requests that carry no token.
1243
+ setCookie(event, EMBED_SESSION_COOKIE, "", { ...attrs, maxAge: 0 });
1244
+ return;
1245
+ }
1246
+ setCookie(event, EMBED_SESSION_COOKIE, token, {
1247
+ ...attrs,
1234
1248
  maxAge: DEFAULT_TOKEN_TTL_SECONDS,
1235
1249
  });
1236
1250
  }
@@ -3,7 +3,7 @@ import { getHeader, getMethod, getResponseStatus, setResponseHeader, setServerTi
3
3
  import { claimStartupDatabaseTelemetry, createDatabaseRequestTelemetry, enterDatabaseRequestTelemetry, } from "../db/request-telemetry.js";
4
4
  import { getDatabaseRuntimeFingerprint } from "../db/runtime-diagnostics.js";
5
5
  import { isMcpPublicPath } from "../mcp/route-paths.js";
6
- import { flushObservability, recordHttpServerRequest, } from "../observability/metrics.js";
6
+ import { flushObservability, recordHttpServerHandoff, recordHttpServerRequest, } from "../observability/metrics.js";
7
7
  import { createTrackingEventScope, flushTrackingEvents, } from "../observability/tracing.js";
8
8
  import { trackingIdentityProperties } from "../observability/tracking-identity.js";
9
9
  import { track } from "../tracking/index.js";
@@ -359,14 +359,43 @@ async function emitTelemetry(event, state, response, durationMs) {
359
359
  // Response telemetry is best-effort. Never perturb request handling.
360
360
  }
361
361
  }
362
- recordHttpServerRequest({
363
- method: getMethod(event),
364
- statusCode,
365
- durationMs,
366
- route,
362
+ const metric = { method: getMethod(event), statusCode, durationMs, route };
363
+ recordHttpServerRequest(metric);
364
+ const recordHandoff = () => recordHttpServerHandoff({
365
+ ...metric,
366
+ durationMs: Date.now() - state.startedAt,
367
367
  });
368
- await flushTrackingEvents(state.trackingScope);
369
- await flushObservability();
368
+ const flush = async () => {
369
+ await flushTrackingEvents(state.trackingScope);
370
+ await flushObservability();
371
+ };
372
+ const waitUntil = responseWaitUntil(event);
373
+ if (waitUntil) {
374
+ recordHandoff();
375
+ waitUntil(flush());
376
+ return;
377
+ }
378
+ await flush();
379
+ // Recorded after the export it measures, so the next flush carries it.
380
+ recordHandoff();
381
+ }
382
+ const NETLIFY_CONTEXT_STORE_KEY = Symbol.for("@netlify/functions/request-context-store");
383
+ // h3 holds the Response until the response hook settles, so awaiting the
384
+ // export here delays every reply by up to the flush timeout.
385
+ function responseWaitUntil(event) {
386
+ const req = event.req;
387
+ if (typeof req?.waitUntil === "function") {
388
+ return req.waitUntil.bind(req);
389
+ }
390
+ // Nitro's Netlify entry drops the function context. The Netlify runtime
391
+ // still keeps it in the AsyncLocalStorage that `getContext()` from
392
+ // `@netlify/functions` reads, registered under this global symbol.
393
+ const store = globalThis[NETLIFY_CONTEXT_STORE_KEY];
394
+ const netlifyContext = store?.getStore?.()?.context;
395
+ if (typeof netlifyContext?.waitUntil === "function") {
396
+ return netlifyContext.waitUntil.bind(netlifyContext);
397
+ }
398
+ return undefined;
370
399
  }
371
400
  function requestTelemetryState(event) {
372
401
  return event.context?.[REQUEST_TELEMETRY_KEY];
@@ -54,8 +54,8 @@ export declare function createRealtimeTokenHandler(): import("h3").EventHandlerW
54
54
  expiresAt?: undefined;
55
55
  ttlSeconds?: undefined;
56
56
  } | {
57
+ error?: undefined;
57
58
  token: string;
58
59
  expiresAt: string;
59
60
  ttlSeconds: number;
60
- error?: undefined;
61
61
  }>>;
@@ -72,6 +72,10 @@ export declare function isExpiredMcpDirectoryWidgetWriteCapability(scope: string
72
72
  userEmail: string;
73
73
  orgId?: string | null;
74
74
  }): boolean;
75
+ export declare function getMcpDirectoryWidgetReadCapabilityResourceIds(scope: string | undefined, input: {
76
+ appId: string;
77
+ resourceUri: string;
78
+ }): Record<string, string> | undefined;
75
79
  export declare function getMcpDirectoryWidgetWriteCapabilityGrant(scope: string | undefined, input: {
76
80
  appId: string;
77
81
  resourceUri: string;