@agent-native/core 0.211.0 → 0.212.0-nightly-20261021010049

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 (91) hide show
  1. package/README.md +1 -1
  2. package/dist/app-config/analytics.d.ts +1 -0
  3. package/dist/app-config/analytics.js +7 -0
  4. package/dist/app-config/schema.d.ts +1 -0
  5. package/dist/chat-threads/store.d.ts +28 -2
  6. package/dist/chat-threads/store.js +75 -13
  7. package/dist/cli/template-baseline.js +18 -5
  8. package/dist/cli/template-sync.js +100 -19
  9. package/dist/client/agent-chat/index.d.ts +2 -1
  10. package/dist/client/agent-chat/index.js +2 -1
  11. package/dist/client/chat/agentkit-protocol.js +21 -1
  12. package/dist/client/chat/run-outcome.d.ts +1 -0
  13. package/dist/client/chat/runtime.js +6 -0
  14. package/dist/client/sharing/index.d.ts +2 -1
  15. package/dist/client/sharing/index.js +2 -1
  16. package/dist/client/sharing/share-controller-helpers.d.ts +14 -1
  17. package/dist/client/sharing/share-controller-helpers.js +46 -1
  18. package/dist/client/sharing/useShareButtonController.d.ts +12 -0
  19. package/dist/client/sharing/useShareButtonController.js +76 -57
  20. package/dist/client/sharing/useShareDialogController.d.ts +3 -0
  21. package/dist/client/sharing/useShareDialogController.js +77 -49
  22. package/dist/client/sharing/useShareVisibilityTransition.d.ts +68 -0
  23. package/dist/client/sharing/useShareVisibilityTransition.js +224 -0
  24. package/dist/client/use-chat-thread-list.d.ts +40 -0
  25. package/dist/client/use-chat-thread-list.js +210 -0
  26. package/dist/client/use-chat-threads.d.ts +67 -0
  27. package/dist/client/use-chat-threads.js +141 -23
  28. package/dist/client/use-db-sync.d.ts +1 -0
  29. package/dist/client/use-db-sync.js +13 -1
  30. package/dist/collab/__fixtures__/live-copy-tasks.d.ts +1 -0
  31. package/dist/collab/__fixtures__/live-copy-tasks.js +92 -0
  32. package/dist/collab/awareness.d.ts +2 -2
  33. package/dist/collab/bounded-task-bundle.d.ts +17 -0
  34. package/dist/collab/bounded-task-bundle.js +39 -0
  35. package/dist/collab/bounded-task-source.d.ts +14 -0
  36. package/dist/collab/bounded-task-source.js +8 -0
  37. package/dist/collab/bounded-tasks.d.ts +67 -0
  38. package/dist/collab/bounded-tasks.js +439 -0
  39. package/dist/collab/client.js +2 -1
  40. package/dist/collab/index.d.ts +5 -2
  41. package/dist/collab/index.js +5 -2
  42. package/dist/collab/live-copy-tasks.d.ts +80 -0
  43. package/dist/collab/live-copy-tasks.js +330 -0
  44. package/dist/collab/live-copy.d.ts +188 -0
  45. package/dist/collab/live-copy.js +415 -0
  46. package/dist/collab/routes.d.ts +5 -0
  47. package/dist/collab/routes.js +24 -8
  48. package/dist/collab/storage.d.ts +53 -1
  49. package/dist/collab/storage.js +93 -5
  50. package/dist/collab/struct-routes.d.ts +1 -1
  51. package/dist/collab/ydoc-manager.d.ts +92 -3
  52. package/dist/collab/ydoc-manager.js +447 -38
  53. package/dist/db/client.d.ts +6 -0
  54. package/dist/db/client.js +25 -5
  55. package/dist/deploy/build.js +2 -0
  56. package/dist/extensions/actions.js +1 -0
  57. package/dist/jobs/actions/manage-recurring-job.d.ts +1 -1
  58. package/dist/mcp/agent-connected.js +5 -1
  59. package/dist/mcp/build-server.js +39 -10
  60. package/dist/notifications/routes.d.ts +1 -1
  61. package/dist/observability/routes.d.ts +1 -1
  62. package/dist/org/index.d.ts +2 -2
  63. package/dist/progress/routes.d.ts +1 -1
  64. package/dist/provider-api/actions/custom-provider-registration.d.ts +16 -16
  65. package/dist/provider-api/actions/provider-api.d.ts +10 -10
  66. package/dist/server/agent-chat-plugin.js +80 -17
  67. package/dist/server/agent-engine-api-key-route.d.ts +1 -1
  68. package/dist/server/agent-engine-default-model-route.d.ts +1 -1
  69. package/dist/server/analytics.d.ts +1 -0
  70. package/dist/server/analytics.js +18 -1
  71. package/dist/server/collab-plugin.d.ts +10 -1
  72. package/dist/server/collab-plugin.js +89 -20
  73. package/dist/server/index.d.ts +1 -1
  74. package/dist/server/realtime-token.d.ts +1 -1
  75. package/dist/shared/optional-node-builtins.d.ts +1 -0
  76. package/dist/shared/optional-node-builtins.js +3 -0
  77. package/dist/sharing/access.d.ts +1 -0
  78. package/dist/sharing/access.js +113 -95
  79. package/dist/tracking/providers.d.ts +1 -0
  80. package/dist/tracking/providers.js +2 -1
  81. package/dist/triggers/actions/manage-automation.d.ts +2 -2
  82. package/dist/vite/bounded-task-plugin.d.ts +22 -0
  83. package/dist/vite/bounded-task-plugin.js +44 -0
  84. package/dist/vite/client.js +2 -0
  85. package/dist/vitest-config.js +3 -0
  86. package/dist/workspace-connections/actions/list-workspace-user-groups.d.ts +1 -1
  87. package/docs/content/deployment-environment-variables.mdx +1 -0
  88. package/docs/content/environment-variables.mdx +1 -0
  89. package/docs/content/sharing.mdx +36 -0
  90. package/docs/content/toolkit-sharing.mdx +98 -12
  91. package/package.json +5 -3
package/dist/db/client.js CHANGED
@@ -1720,12 +1720,32 @@ export function annotateMissingTable(err, sql) {
1720
1720
  return err;
1721
1721
  }
1722
1722
  const scopedDbExec = new AsyncLocalStorage();
1723
+ const transactionCallbacks = new AsyncLocalStorage();
1723
1724
  export function withDbExec(exec, run) {
1724
1725
  return scopedDbExec.run(guardSchemaMutations(exec), run);
1725
1726
  }
1726
1727
  export function getScopedDbExec() {
1727
1728
  return scopedDbExec.getStore();
1728
1729
  }
1730
+ /**
1731
+ * True while a `getDbExec().transaction()` callback runs. That callback leaves
1732
+ * `getScopedDbExec()` unset, so code that must not run inside a caller's
1733
+ * transaction asks this as well.
1734
+ */
1735
+ export function insideDbTransactionCallback() {
1736
+ return transactionCallbacks.getStore()?.active === true;
1737
+ }
1738
+ async function inTransactionCallback(run) {
1739
+ const callback = { active: true };
1740
+ try {
1741
+ return await transactionCallbacks.run(callback, run);
1742
+ }
1743
+ finally {
1744
+ // Work the callback started and left running inherits this store; once
1745
+ // the callback settles, that work is no longer inside the transaction.
1746
+ callback.active = false;
1747
+ }
1748
+ }
1729
1749
  export function getDbExec() {
1730
1750
  const scoped = scopedDbExec.getStore();
1731
1751
  if (scoped)
@@ -1784,13 +1804,13 @@ export function getDbExec() {
1784
1804
  if (!currentExec.transaction) {
1785
1805
  throw new Error("This database does not support transactions.");
1786
1806
  }
1787
- return currentExec.transaction((tx) => fn({
1807
+ return currentExec.transaction((tx) => inTransactionCallback(() => fn({
1788
1808
  execute: (s) => {
1789
1809
  assertSchemaMutationAllowed(s);
1790
1810
  return tx.execute(sanitize(s));
1791
1811
  },
1792
1812
  transaction: tx.transaction?.bind(tx),
1793
- }));
1813
+ })));
1794
1814
  }
1795
1815
  : undefined,
1796
1816
  };
@@ -1806,19 +1826,19 @@ export function getDbExec() {
1806
1826
  const exec = await initializeProxy();
1807
1827
  Object.assign(proxy, createInitializedProxy(exec));
1808
1828
  if (exec.transaction) {
1809
- return exec.transaction((tx) => fn({
1829
+ return exec.transaction((tx) => inTransactionCallback(() => fn({
1810
1830
  execute: (s) => {
1811
1831
  assertSchemaMutationAllowed(s);
1812
1832
  return tx.execute(sanitize(s));
1813
1833
  },
1814
1834
  transaction: tx.transaction?.bind(tx),
1815
- }));
1835
+ })));
1816
1836
  }
1817
1837
  if (exec.atomicBatch) {
1818
1838
  throw new Error("This database supports atomic batches, not interactive transactions.");
1819
1839
  }
1820
1840
  const wrapper = createInitializedProxy(exec);
1821
- return explicitTransaction(wrapper.execute.bind(wrapper))(fn);
1841
+ return explicitTransaction(wrapper.execute.bind(wrapper))((tx) => inTransactionCallback(() => fn(tx)));
1822
1842
  },
1823
1843
  async atomicBatch(statements) {
1824
1844
  for (const statement of statements) {
@@ -28,6 +28,7 @@ import { AGENT_NATIVE_SOCIAL_IMAGE_ALT, AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER,
28
28
  import { workspaceAppAudienceFromEnv, workspaceAppAudienceFromPackageJson, workspaceAppRouteAccessFromEnv, workspaceAppRouteAccessFromPackageJson, } from "../shared/workspace-app-audience.js";
29
29
  import { generateActionRegistryForProject } from "../vite/action-types-plugin.js";
30
30
  import { createAgentNativeConfigContext, loadResolvedAgentNativeConfig, readAgentNativeBuildConfigMarker, resolveFirstRunOnboardingBuildReplacement, resolveHarnessBuildReplacement, } from "../vite/agent-native-config-loader.js";
31
+ import { boundedTaskSourcePlugin } from "../vite/bounded-task-plugin.js";
31
32
  import { createSentryServerSourceMapUploadPlugins } from "../vite/sentry-source-maps.js";
32
33
  import { cloneServerBundleForFunction, copyDir, pruneSsrIslandFromRewritingClone, readPackageManifest, SERVERLESS_BROWSER_RUNTIME_PACKAGES, } from "./function-bundle.js";
33
34
  import { collectImmutableAssetPaths, IMMUTABLE_ASSET_CACHE_CONTROL, IMMUTABLE_ASSET_CACHE_HEADERS, prefixAssetPath, } from "./immutable-assets.js";
@@ -4863,6 +4864,7 @@ export default bundle;
4863
4864
  ? [createCloudflareModuleStubPlugin()]
4864
4865
  : []),
4865
4866
  createBrowserOnlyServerStubPlugin(),
4867
+ boundedTaskSourcePlugin(),
4866
4868
  ...sentryServerSourceMapPlugins,
4867
4869
  ...(enterpriseAuthAdaptersEnabled
4868
4870
  ? []
@@ -905,6 +905,7 @@ export function createExtensionActionEntries() {
905
905
  items: result.rows ?? [],
906
906
  };
907
907
  },
908
+ readOnly: true,
908
909
  },
909
910
  "delete-extension": {
910
911
  tool: {
@@ -11,9 +11,9 @@ declare const _default: import("../../action.js").ActionDefinition<{
11
11
  enabled?: undefined;
12
12
  nextRun?: undefined;
13
13
  } | {
14
- deleted?: undefined;
15
14
  name: string;
16
15
  enabled: boolean;
17
16
  nextRun: string;
17
+ deleted?: undefined;
18
18
  }>;
19
19
  export default _default;
@@ -3,6 +3,7 @@ import { CLIENTS } from "../cli/mcp-config-writers.js";
3
3
  import { mutateSetting } from "../settings/store.js";
4
4
  import { normalizeTrackingDimension } from "../shared/analytics-events.js";
5
5
  import { resolveMcpConnectHostId } from "../shared/mcp-connect-content.js";
6
+ import { AGENT_NATIVE_ANALYTICS_PROVIDER } from "../tracking/providers.js";
6
7
  import { isTrackingSuppressed, listTrackingProviders, track, } from "../tracking/registry.js";
7
8
  import { detectVendorClient } from "./analytics.js";
8
9
  import { connectAppLabel, connectEnvironment } from "./connect-app-label.js";
@@ -21,7 +22,10 @@ export async function trackAgentConnected(input) {
21
22
  // Everything runs inside the try: the connection is already committed, so a
22
23
  // tracking or configuration failure must not turn it into a failed response.
23
24
  try {
24
- if (listTrackingProviders().length === 0 ||
25
+ // The claim is permanent, so take it only when first-party analytics will
26
+ // receive the event; a vendor-only claim would hide every later reconnect
27
+ // from first-party analytics once it is enabled.
28
+ if (!listTrackingProviders().includes(AGENT_NATIVE_ANALYTICS_PROVIDER) ||
25
29
  isTrackingSuppressed(input.email))
26
30
  return "disabled";
27
31
  const app = connectionApp(input.origin, input.appId);
@@ -132,8 +132,11 @@ function scopeToolSearchToAdvertised(advertised, advertisable) {
132
132
  },
133
133
  };
134
134
  }
135
- function withoutExternalOptOuts(actions) {
136
- return Object.fromEntries(Object.entries(actions).filter(([, entry]) => isActionExposedToExternalAgents(entry)));
135
+ // The operator's `denyActions` veto lives here with the action's own opt-out,
136
+ // so no catalog branch, `tool-search` or `tools/call` path has to remember it.
137
+ function withoutExternalOptOuts(config, actions) {
138
+ const denyNames = externalAgentDenySet(config);
139
+ return Object.fromEntries(Object.entries(actions).filter(([name, entry]) => !denyNames.has(name) && isActionExposedToExternalAgents(entry)));
137
140
  }
138
141
  /**
139
142
  * Converts an action's input schema the first time a request needs it, and
@@ -211,7 +214,7 @@ export function validateMcpDirectoryProfile(config, sourceActions = config.produ
211
214
  if (new Set(names).size !== names.length) {
212
215
  throw new McpDirectoryProfileValidationError("[agent-native] MCP directory catalog cannot contain duplicate tool names.");
213
216
  }
214
- const actions = withoutExternalOptOuts(withoutToolSearch(sourceActions));
217
+ const actions = withoutExternalOptOuts(config, withoutToolSearch(sourceActions));
215
218
  const reserved = new Set([
216
219
  ...COMPACT_MCP_APP_CATALOG_BUILTINS,
217
220
  "ask-agent",
@@ -249,6 +252,20 @@ export function validateMcpDirectoryProfile(config, sourceActions = config.produ
249
252
  }
250
253
  }
251
254
  const profile = config.directoryProfile;
255
+ // Widget grants can name actions hidden from the agent surface, which the
256
+ // filter above never sees.
257
+ const denyNames = externalAgentDenySet(config);
258
+ const deniedWidgetAction = [
259
+ ...(profile?.widgetReadOnlyActions ?? []),
260
+ ...(profile?.widgetReadPublicActions ?? []),
261
+ ...(profile?.widgetReadPrivateActions ?? []),
262
+ ...(profile?.widgetReadAuthenticatedActions ?? []),
263
+ ...Object.keys(profile?.widgetReadActionArguments ?? {}),
264
+ ...Object.keys(profile?.widgetWriteActionArguments ?? {}),
265
+ ].find((name) => denyNames.has(name));
266
+ if (deniedWidgetAction) {
267
+ throw new McpDirectoryProfileValidationError(`[agent-native] MCP directory widget action "${deniedWidgetAction}" is listed in externalAgents.denyActions.`);
268
+ }
252
269
  const widgetActionNames = names.filter((name) => Boolean(actions[name]?.mcpApp?.resource));
253
270
  const widgetReadOnlyActions = new Set(profile?.widgetReadOnlyActions ?? []);
254
271
  const widgetReadPublicActions = new Set(profile?.widgetReadPublicActions ?? []);
@@ -1962,7 +1979,13 @@ export async function createMCPServerForRequest(config, identity, requestMeta) {
1962
1979
  const mergedActions = appCatalog || directoryCatalog
1963
1980
  ? baseActions
1964
1981
  : mergeBuiltinTools(config, baseActions, requestMeta);
1965
- const actions = withoutExternalOptOuts(flatCatalog ? withoutToolSearch(mergedActions) : mergedActions);
1982
+ const actions = withoutExternalOptOuts(config, flatCatalog ? withoutToolSearch(mergedActions) : mergedActions);
1983
+ // Tools built outside the action map (`ask-agent`, `create_embed_session`)
1984
+ // never pass through the filter above, so tools/list and tools/call refuse a
1985
+ // denied name too. `ask-agent` runs `ask_app`, so denying either removes it.
1986
+ const deniedToolNames = externalAgentDenySet(config);
1987
+ if (deniedToolNames.has("ask_app"))
1988
+ deniedToolNames.add("ask-agent");
1966
1989
  const { isAdvertisable, advertisable, inputSchema: advertisedInputSchema, } = advertisedInputSchemas(actions);
1967
1990
  const scopeVisibleActions = Object.fromEntries(Object.entries(actions).filter(([, entry]) => isActionVisibleForOAuthScope(entry, effectiveIdentity?.oauthScopes)));
1968
1991
  const orgIdPromise = resolveMcpIdentityOrgId(effectiveIdentity);
@@ -1996,7 +2019,6 @@ export async function createMCPServerForRequest(config, identity, requestMeta) {
1996
2019
  ...declaredMcpToolNames(visibleActions),
1997
2020
  ...autoReadNames,
1998
2021
  ]);
1999
- const denyNames = externalAgentDenySet(config);
2000
2022
  const automaticConnectorPolicyActive = config.externalAgents?.authenticatedReads === "auto";
2001
2023
  const connectorCatalogActive = !appCatalog &&
2002
2024
  !fullCatalogRequested &&
@@ -2006,15 +2028,12 @@ export async function createMCPServerForRequest(config, identity, requestMeta) {
2006
2028
  const writesAreAskAppOnly = externalAgentWritesAreAskAppOnly(config);
2007
2029
  const preserveCompactActions = config.connectorCatalog === undefined && !automaticConnectorPolicyActive;
2008
2030
  const advertisedActionsBeforeToolSearchScope = appCatalog
2009
- ? Object.fromEntries(Object.entries(visibleActions).filter(([name]) => !denyNames.has(name)))
2031
+ ? visibleActions
2010
2032
  : directoryCatalog
2011
2033
  ? Object.fromEntries(Object.entries(visibleActions).filter(([name, entry]) => connectorNames.has(name) &&
2012
- !denyNames.has(name) &&
2013
2034
  (!writesAreAskAppOnly || isMcpReadOnlyTool(entry))))
2014
2035
  : connectorCatalogActive
2015
2036
  ? Object.fromEntries(Object.entries(visibleActions).filter(([name, entry]) => {
2016
- if (denyNames.has(name))
2017
- return false;
2018
2037
  if (COMPACT_MCP_APP_CATALOG_BUILTINS.has(name))
2019
2038
  return true;
2020
2039
  if (!connectorNames.has(name) &&
@@ -2326,7 +2345,7 @@ export async function createMCPServerForRequest(config, identity, requestMeta) {
2326
2345
  });
2327
2346
  }
2328
2347
  tools.sort((a, b) => compareMcpCatalogValues(a.name, b.name));
2329
- return { tools };
2348
+ return { tools: tools.filter((tool) => !deniedToolNames.has(tool.name)) };
2330
2349
  });
2331
2350
  trackMcpToolsList(analyticsContext(request, ctx), {
2332
2351
  toolNames: result.tools.map((tool) => tool.name),
@@ -2368,6 +2387,16 @@ export async function createMCPServerForRequest(config, identity, requestMeta) {
2368
2387
  : undefined;
2369
2388
  const result = await withToolCallContext(async () => {
2370
2389
  const { name, arguments: args } = request.params;
2390
+ if (deniedToolNames.has(name)) {
2391
+ failure = {
2392
+ errorType: "unknown_tool",
2393
+ errorMessage: `Unknown tool: ${name}`,
2394
+ };
2395
+ return {
2396
+ content: [{ type: "text", text: `Unknown tool: ${name}` }],
2397
+ isError: true,
2398
+ };
2399
+ }
2371
2400
  try {
2372
2401
  const { allowedActions } = await resolveServiceGrant();
2373
2402
  assertServicePrincipalMayCall(allowedActions, name);
@@ -16,6 +16,6 @@ export declare function createNotificationsHandler(): import("h3").EventHandlerW
16
16
  } | {
17
17
  count?: undefined;
18
18
  updated?: undefined;
19
- error?: undefined;
20
19
  ok: boolean;
20
+ error?: undefined;
21
21
  }>>;
@@ -64,6 +64,6 @@ export declare function createObservabilityHandler(): import("h3").EventHandlerW
64
64
  message?: undefined;
65
65
  summary?: undefined;
66
66
  spans?: undefined;
67
- ok: boolean;
68
67
  error?: undefined;
68
+ ok: boolean;
69
69
  }>>;
@@ -162,10 +162,10 @@ export declare const getMyOrgHandler: import("h3").EventHandlerWithFetch<import(
162
162
  soloDeploymentAdmin: boolean;
163
163
  }>>;
164
164
  export declare const createOrgHandler: import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<{
165
- success: boolean;
166
165
  name?: undefined;
167
- role?: undefined;
166
+ success: boolean;
168
167
  id?: undefined;
168
+ role?: undefined;
169
169
  } | {
170
170
  success?: undefined;
171
171
  id: string;
@@ -2,6 +2,6 @@ export declare function createProgressHandler(): import("h3").EventHandlerWithFe
2
2
  error: string;
3
3
  ok?: undefined;
4
4
  } | {
5
- ok: boolean;
6
5
  error?: undefined;
6
+ ok: boolean;
7
7
  }>>;
@@ -75,8 +75,11 @@ export declare function createCustomProviderRegistrationAction<TSchema extends Z
75
75
  user: "user";
76
76
  }>>;
77
77
  }, z.core.$strip>>, {
78
- message?: undefined;
79
78
  id?: undefined;
79
+ provider?: undefined;
80
+ message?: undefined;
81
+ deleted?: undefined;
82
+ found?: undefined;
80
83
  providers: {
81
84
  id: string;
82
85
  label: string;
@@ -87,47 +90,44 @@ export declare function createCustomProviderRegistrationAction<TSchema extends Z
87
90
  updatedAt: number;
88
91
  }[];
89
92
  count: number;
90
- provider?: undefined;
91
- found?: undefined;
92
- deleted?: undefined;
93
93
  registered?: undefined;
94
94
  label?: undefined;
95
95
  } | {
96
- message?: undefined;
97
96
  id?: undefined;
98
- providers?: undefined;
99
97
  count?: undefined;
98
+ message?: undefined;
99
+ deleted?: undefined;
100
+ providers?: undefined;
100
101
  found: boolean;
101
102
  provider: import("../custom-registry.js").CustomProviderConfig;
102
- deleted?: undefined;
103
103
  registered?: undefined;
104
104
  label?: undefined;
105
105
  } | {
106
+ provider?: undefined;
107
+ count?: undefined;
106
108
  message?: undefined;
109
+ deleted?: undefined;
107
110
  providers?: undefined;
108
- count?: undefined;
109
- provider?: undefined;
110
111
  found: boolean;
111
112
  id: string;
112
- deleted?: undefined;
113
113
  registered?: undefined;
114
114
  label?: undefined;
115
115
  } | {
116
- message?: undefined;
117
- providers?: undefined;
118
- count?: undefined;
119
116
  provider?: undefined;
117
+ count?: undefined;
118
+ message?: undefined;
120
119
  found?: undefined;
120
+ providers?: undefined;
121
121
  deleted: boolean;
122
122
  id: string;
123
123
  registered?: undefined;
124
124
  label?: undefined;
125
125
  } | {
126
- providers?: undefined;
127
- count?: undefined;
128
126
  provider?: undefined;
129
- found?: undefined;
127
+ count?: undefined;
130
128
  deleted?: undefined;
129
+ found?: undefined;
130
+ providers?: undefined;
131
131
  registered: boolean;
132
132
  id: string;
133
133
  label: string;
@@ -316,9 +316,9 @@ export declare function createProviderApiActions(runtime: Pick<ProviderApiRuntim
316
316
  notes?: string | undefined;
317
317
  scope?: "org" | "user" | undefined;
318
318
  }, {
319
- provider?: undefined;
320
319
  id?: undefined;
321
320
  deleted?: undefined;
321
+ found?: undefined;
322
322
  providers: {
323
323
  id: string;
324
324
  label: string;
@@ -329,46 +329,46 @@ export declare function createProviderApiActions(runtime: Pick<ProviderApiRuntim
329
329
  updatedAt: number;
330
330
  }[];
331
331
  count: number;
332
- found?: undefined;
332
+ provider?: undefined;
333
333
  registered?: undefined;
334
334
  label?: undefined;
335
335
  message?: undefined;
336
336
  } | {
337
337
  id?: undefined;
338
+ count?: undefined;
338
339
  deleted?: undefined;
339
340
  providers?: undefined;
340
- count?: undefined;
341
341
  found: boolean;
342
342
  provider: import("../custom-registry.js").CustomProviderConfig;
343
343
  registered?: undefined;
344
344
  label?: undefined;
345
345
  message?: undefined;
346
346
  } | {
347
- provider?: undefined;
347
+ count?: undefined;
348
348
  deleted?: undefined;
349
349
  providers?: undefined;
350
- count?: undefined;
350
+ provider?: undefined;
351
351
  found: boolean;
352
352
  id: string;
353
353
  registered?: undefined;
354
354
  label?: undefined;
355
355
  message?: undefined;
356
356
  } | {
357
- provider?: undefined;
358
- providers?: undefined;
359
357
  count?: undefined;
360
358
  found?: undefined;
359
+ providers?: undefined;
360
+ provider?: undefined;
361
361
  deleted: boolean;
362
362
  id: string;
363
363
  registered?: undefined;
364
364
  label?: undefined;
365
365
  message?: undefined;
366
366
  } | {
367
- provider?: undefined;
368
- deleted?: undefined;
369
- providers?: undefined;
370
367
  count?: undefined;
368
+ deleted?: undefined;
371
369
  found?: undefined;
370
+ providers?: undefined;
371
+ provider?: undefined;
372
372
  registered: boolean;
373
373
  id: string;
374
374
  label: string;
@@ -33,7 +33,7 @@ import { attachToolSearch } from "../agent/tool-search.js";
33
33
  import { getAppConfig } from "../app-config/index.js";
34
34
  import { readAppStateForCurrentTab } from "../application-state/script-helpers.js";
35
35
  import { runChatThreadDataMigrations } from "../chat-threads/migrations.js";
36
- import { InlineAttachmentDataNotPersistableError, QueuedSubmissionAdmissionError, adoptThreadScopeIfUnscoped, blockQueuedSubmissionReceipt, clearQueuedSubmissionInterruptRun, createThread, forkThread, getThread, getQueuedSubmissionReceipt, listQueuedSubmissionReceipts, markQueuedSubmissionSubmitted, queuedSubmissionBehaviorMatches, recordQueuedSubmissionInterruptRun, renewQueuedSubmissionInterruptClaim, registerChatThreadsShareable, retryQueuedSubmissionReceipt, resolveRunThreadScope, resolveThreadAccess, listThreads, searchThreads, renameThread, createThreadShareLink, getThreadByShareToken, getThreadShareState, revokeThreadShareLink, setThreadArchived, setThreadPinned, setThreadScope, updateThreadData, withThreadDataLock, deleteThread, mutateThreadQueuedMessages, setThreadSourceIfMissing, isAppOwnedChatScope, threadScopeMismatch, } from "../chat-threads/store.js";
36
+ import { InlineAttachmentDataNotPersistableError, QueuedSubmissionAdmissionError, adoptThreadScopeIfUnscoped, blockQueuedSubmissionReceipt, clearQueuedSubmissionInterruptRun, createThread, forkThread, getThread, getQueuedSubmissionReceipt, listQueuedSubmissionReceipts, markQueuedSubmissionSubmitted, queuedSubmissionBehaviorMatches, recordQueuedSubmissionInterruptRun, renewQueuedSubmissionInterruptClaim, registerChatThreadsShareable, retryQueuedSubmissionReceipt, resolveRunThreadScope, resolveThreadAccess, listThreads, searchThreads, renameThread, createThreadShareLink, getThreadByShareToken, getThreadShareState, revokeThreadShareLink, setThreadArchived, setThreadPinned, setThreadScope, updateThreadData, withThreadDataLock, deleteThread, mutateThreadQueuedMessages, setThreadSourceIfMissing, isAppOwnedChatScope, isChatThreadOwnership, threadScopeMismatch, } from "../chat-threads/store.js";
37
37
  import { isCheckpointRestorePath } from "../checkpoints/route-match.js";
38
38
  import { createDbAdminAgentTools } from "../db-admin/agent-tools.js";
39
39
  import { isTransientDatabaseError } from "../db/client.js";
@@ -5396,10 +5396,41 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
5396
5396
  const pendingConnectionRequestId = includePendingConnectionRequest
5397
5397
  ? await getRunPendingConnectionRequestId(run.id)
5398
5398
  : undefined;
5399
+ const record = (value) => value && typeof value === "object" && !Array.isArray(value)
5400
+ ? value
5401
+ : undefined;
5402
+ const customMetadata = (message) => record(record(record(message)?.metadata)?.custom);
5403
+ const thread = await getThread(threadId);
5404
+ const threadData = record(JSON.parse(thread?.threadData || "{}"));
5405
+ const messages = Array.isArray(threadData?.messages)
5406
+ ? threadData.messages
5407
+ : [];
5408
+ const matchingTurnMessages = run.turnId
5409
+ ? messages.filter((message) => {
5410
+ const messageRecord = record(message);
5411
+ const custom = customMetadata(message);
5412
+ return (messageRecord?.role === "user" &&
5413
+ custom?.submittedTurnId === run.turnId);
5414
+ })
5415
+ : [];
5416
+ const matchingMessages = matchingTurnMessages.length > 0
5417
+ ? matchingTurnMessages
5418
+ : messages.filter((message) => {
5419
+ const messageRecord = record(message);
5420
+ const custom = customMetadata(message);
5421
+ return (messageRecord?.role === "user" &&
5422
+ custom?.submittedRunId === run.id);
5423
+ });
5424
+ const startMessageId = matchingMessages.length === 1
5425
+ ? customMetadata(matchingMessages[0])?.agentKitMessageId
5426
+ : undefined;
5399
5427
  return {
5400
5428
  runId: run.id,
5401
5429
  threadId: run.threadId,
5402
5430
  turnId: run.turnId ?? null,
5431
+ ...(typeof startMessageId === "string" && startMessageId.trim()
5432
+ ? { startMessageId }
5433
+ : {}),
5403
5434
  startedAt: run.startedAt,
5404
5435
  status: run.status,
5405
5436
  heartbeatAt: run.heartbeatAt,
@@ -5630,6 +5661,19 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
5630
5661
  const label = q.scopeLabel ? String(q.scopeLabel) : undefined;
5631
5662
  return label ? { type, id, label } : { type, id };
5632
5663
  };
5664
+ // Absent -> the default; present but not a whole number -> null, so the
5665
+ // caller can answer 400 instead of silently paging from somewhere else.
5666
+ const parseNonNegativeInteger = (raw, fallback) => {
5667
+ if (raw === undefined)
5668
+ return fallback;
5669
+ if (typeof raw !== "string")
5670
+ return null;
5671
+ const text = raw.trim();
5672
+ if (!/^\d+$/.test(text))
5673
+ return null;
5674
+ const value = Number(text);
5675
+ return Number.isSafeInteger(value) ? value : null;
5676
+ };
5633
5677
  const parseScopeFromBody = (raw) => {
5634
5678
  if (raw == null)
5635
5679
  return null;
@@ -6303,31 +6347,50 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
6303
6347
  // ── Thread list: GET/POST /threads ──
6304
6348
  if (method === "GET") {
6305
6349
  const query = getQuery(event);
6306
- const limit = Math.min(parseInt(String(query.limit ?? "50"), 10) || 50, 200);
6350
+ const requestedLimit = parseNonNegativeInteger(query.limit, 50);
6351
+ const requestedOffset = parseNonNegativeInteger(query.offset, 0);
6352
+ if (requestedLimit === null ||
6353
+ requestedLimit < 1 ||
6354
+ requestedOffset === null) {
6355
+ setResponseStatus(event, 400);
6356
+ return { error: "Invalid limit or offset" };
6357
+ }
6358
+ const limit = Math.min(requestedLimit, 200);
6307
6359
  const q = query.q ? String(query.q).trim() : "";
6308
6360
  const scope = parseScopeFromQuery(query);
6309
6361
  const unscopedOnly = String(query.unscoped ?? "") === "1";
6310
6362
  const includeExternal = String(query.includeExternal ?? "") === "1";
6311
- if (q) {
6312
- const threads = await searchThreads(owner, q, limit, {
6363
+ const ownership = query.ownership === undefined ? "all" : query.ownership;
6364
+ if (!isChatThreadOwnership(ownership)) {
6365
+ setResponseStatus(event, 400);
6366
+ return { error: "Invalid ownership filter" };
6367
+ }
6368
+ const offset = requestedOffset;
6369
+ // Fetch one extra row so the page can say whether another exists
6370
+ // without a count query.
6371
+ const fetched = q
6372
+ ? await searchThreads(owner, q, limit + 1, {
6313
6373
  scope: scope ?? undefined,
6314
6374
  orgId,
6315
6375
  includeExternal,
6316
6376
  sourceAppId: options?.appId ?? null,
6377
+ ownership,
6378
+ offset,
6379
+ })
6380
+ : await listThreads(owner, {
6381
+ limit: limit + 1,
6382
+ offset,
6383
+ scope: scope ?? undefined,
6384
+ unscopedOnly,
6385
+ orgId,
6386
+ includeExternal,
6387
+ sourceAppId: options?.appId ?? null,
6388
+ ownership,
6317
6389
  });
6318
- return { threads };
6319
- }
6320
- const offset = parseInt(String(query.offset ?? "0"), 10) || 0;
6321
- const threads = await listThreads(owner, {
6322
- limit,
6323
- offset,
6324
- scope: scope ?? undefined,
6325
- unscopedOnly,
6326
- orgId,
6327
- includeExternal,
6328
- sourceAppId: options?.appId ?? null,
6329
- });
6330
- return { threads };
6390
+ return {
6391
+ threads: fetched.slice(0, limit),
6392
+ hasMore: fetched.length > limit,
6393
+ };
6331
6394
  }
6332
6395
  if (method === "POST") {
6333
6396
  const body = await readBody(event);
@@ -66,6 +66,7 @@ export declare function createAgentEngineApiKeyHandler(): import("h3").EventHand
66
66
  error: any;
67
67
  code: any;
68
68
  } | {
69
+ error?: undefined;
69
70
  errorCode?: undefined;
70
71
  code?: undefined;
71
72
  ok: boolean;
@@ -73,6 +74,5 @@ export declare function createAgentEngineApiKeyHandler(): import("h3").EventHand
73
74
  baseUrlKey?: string;
74
75
  scope: AgentEngineApiKeyScope;
75
76
  defaultModel?: import("./agent-engine-default-model-route.js").SavedKeyDefaultModelOutcome;
76
- error?: undefined;
77
77
  }>>;
78
78
  export {};
@@ -8,8 +8,8 @@ export declare const AGENT_ENGINE_API_KEY_ACTION_NAME = "agent-engine-api-key";
8
8
  * resolveEngine's credential detection.
9
9
  */
10
10
  export declare function createAgentEngineDisconnectHandler(): import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<{
11
- ok?: undefined;
12
11
  error: string;
12
+ ok?: undefined;
13
13
  scope?: undefined;
14
14
  } | {
15
15
  ok: boolean;
@@ -1,4 +1,5 @@
1
1
  export declare function getAgentNativeAnalyticsConfigScript(): string | null;
2
+ export declare function getHeadScriptTag(): string | null;
2
3
  export declare function getGaInlineConfigScriptBody(options?: {
3
4
  dataLayerName?: string;
4
5
  sendPageView?: boolean;
@@ -54,6 +54,19 @@ export function getAgentNativeAnalyticsConfigScript() {
54
54
  ");</script>",
55
55
  ].join("");
56
56
  }
57
+ function escapeHtmlAttribute(value) {
58
+ return value
59
+ .replace(/&/g, "&amp;")
60
+ .replace(/"/g, "&quot;")
61
+ .replace(/</g, "&lt;")
62
+ .replace(/>/g, "&gt;");
63
+ }
64
+ export function getHeadScriptTag() {
65
+ const src = getAppConfig().analytics.headScriptSrc;
66
+ if (!src)
67
+ return null;
68
+ return `<script src="${escapeHtmlAttribute(src)}" defer data-agent-native-head-script></script>`;
69
+ }
57
70
  export function getGaInlineConfigScriptBody(options) {
58
71
  const id = getGaMeasurementId();
59
72
  if (!id)
@@ -111,6 +124,7 @@ function getGtmBodyFallback(containerId) {
111
124
  }
112
125
  function getAnalyticsInjection() {
113
126
  const agentNativeAnalytics = getAgentNativeAnalyticsConfigScript();
127
+ const headScript = getHeadScriptTag();
114
128
  const containerId = getGtmContainerId();
115
129
  if (containerId) {
116
130
  return {
@@ -118,6 +132,7 @@ function getAnalyticsInjection() {
118
132
  agentNativeAnalytics,
119
133
  getGtmHeadScript(containerId),
120
134
  getGtmGaFallbackScript(),
135
+ headScript,
121
136
  ]
122
137
  .filter(Boolean)
123
138
  .join(""),
@@ -125,7 +140,9 @@ function getAnalyticsInjection() {
125
140
  };
126
141
  }
127
142
  const gaScript = getGaScript();
128
- const head = [agentNativeAnalytics, gaScript].filter(Boolean).join("");
143
+ const head = [agentNativeAnalytics, gaScript, headScript]
144
+ .filter(Boolean)
145
+ .join("");
129
146
  return head ? { head, body: "" } : null;
130
147
  }
131
148
  const HEAD_CLOSE_PATTERN = /<\/head>/i;