@agent-native/core 0.233.0 → 0.234.0-nightly-20261125004429

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 (70) hide show
  1. package/dist/agent/engine/ai-sdk-engine.d.ts +1 -0
  2. package/dist/agent/engine/ai-sdk-engine.js +36 -1
  3. package/dist/agent/engine/anthropic-engine.js +12 -1
  4. package/dist/agent/production-agent.d.ts +7 -0
  5. package/dist/agent/tool-search.js +34 -4
  6. package/dist/application-state/handlers.d.ts +3 -3
  7. package/dist/cli/skills-content/an-skill.d.ts +1 -1
  8. package/dist/cli/skills-content/an-skill.js +30 -13
  9. package/dist/client/action-get-batch.d.ts +1 -0
  10. package/dist/client/action-get-batch.js +5 -1
  11. package/dist/client/application-state.js +65 -7
  12. package/dist/client/chat/agentkit-protocol.js +15 -3
  13. package/dist/client/feature-flags/use-feature-flag.js +3 -0
  14. package/dist/client/labs/use-lab.js +2 -0
  15. package/dist/client/session-identity.d.ts +1 -0
  16. package/dist/client/session-identity.js +7 -0
  17. package/dist/client/use-action.d.ts +1 -0
  18. package/dist/client/use-action.js +19 -6
  19. package/dist/collab/struct-routes.d.ts +1 -1
  20. package/dist/framework-package-versions.json +8 -8
  21. package/dist/identity/rekey.js +55 -2
  22. package/dist/jobs/background-automation-runner.d.ts +7 -1
  23. package/dist/jobs/background-automation-runner.js +18 -2
  24. package/dist/mcp/build-server.d.ts +2 -0
  25. package/dist/mcp/build-server.js +45 -4
  26. package/dist/mcp/embed-app.js +52 -1
  27. package/dist/mcp/skills-extension.d.ts +42 -0
  28. package/dist/mcp/skills-extension.js +61 -0
  29. package/dist/org/migrations.d.ts +1 -1
  30. package/dist/org/workspace-app-access.js +2 -1
  31. package/dist/provider-api/actions/custom-provider-registration.d.ts +12 -12
  32. package/dist/provider-api/actions/provider-api.d.ts +8 -8
  33. package/dist/resources/handlers.d.ts +2 -2
  34. package/dist/server/action-discovery.js +7 -37
  35. package/dist/server/action-files.d.ts +15 -0
  36. package/dist/server/action-files.js +71 -0
  37. package/dist/server/agent-chat/mcp-options.d.ts +3 -0
  38. package/dist/server/agent-chat/mcp-options.js +1 -0
  39. package/dist/server/agent-chat/plugin-options.d.ts +27 -3
  40. package/dist/server/agent-chat-plugin.d.ts +4 -5
  41. package/dist/server/agent-chat-plugin.js +34 -3
  42. package/dist/server/agent-teams.d.ts +15 -3
  43. package/dist/server/agent-teams.js +26 -4
  44. package/dist/server/dev-database-lifecycle.d.ts +11 -0
  45. package/dist/server/dev-database-lifecycle.js +11 -5
  46. package/dist/server/first-touch-route.d.ts +1 -1
  47. package/dist/server/index.d.ts +1 -0
  48. package/dist/shared/analytics-panel-capture.d.ts +2 -1
  49. package/dist/shared/analytics-panel-capture.js +1 -0
  50. package/dist/shared/reasoning-effort.d.ts +9 -0
  51. package/dist/shared/reasoning-effort.js +19 -0
  52. package/dist/templates/chat/.agents/skills/actions/SKILL.md +2 -0
  53. package/dist/templates/default/.agents/skills/actions/SKILL.md +2 -0
  54. package/dist/templates/headless/.agents/skills/actions/SKILL.md +2 -0
  55. package/dist/templates/workspace-core/.agents/skills/actions/SKILL.md +2 -0
  56. package/dist/templates/workspace-core/.agents/skills/composable-mini-apps/SKILL.md +7 -2
  57. package/dist/templates/workspace-core/.agents/skills/external-agents/SKILL.md +8 -8
  58. package/dist/templates/workspace-root/AGENTS.md +3 -0
  59. package/dist/templates/workspace-root/README.md +7 -2
  60. package/dist/vite/action-types-plugin.js +13 -42
  61. package/dist/vite/client.js +28 -17
  62. package/package.json +3 -3
  63. package/src/templates/chat/.agents/skills/actions/SKILL.md +2 -0
  64. package/src/templates/default/.agents/skills/actions/SKILL.md +2 -0
  65. package/src/templates/headless/.agents/skills/actions/SKILL.md +2 -0
  66. package/src/templates/workspace-core/.agents/skills/actions/SKILL.md +2 -0
  67. package/src/templates/workspace-core/.agents/skills/composable-mini-apps/SKILL.md +7 -2
  68. package/src/templates/workspace-core/.agents/skills/external-agents/SKILL.md +8 -8
  69. package/src/templates/workspace-root/AGENTS.md +3 -0
  70. package/src/templates/workspace-root/README.md +7 -2
@@ -24,5 +24,6 @@ export interface AISDKEngineConfig {
24
24
  appUrl?: string;
25
25
  }
26
26
  export declare function createProviderEndpointFetch(endpoint: string, allowedPrivateOrigins?: readonly string[]): typeof fetch;
27
+ export declare function withAnthropicThinkingBlockBinding(baseFetch?: typeof fetch): typeof fetch;
27
28
  export declare function createAISDKEngine(provider: AISDKProvider, config?: Record<string, unknown>): AgentEngine;
28
29
  export { PROVIDER_CAPABILITIES, PROVIDER_DEFAULT_MODELS, PROVIDER_SUPPORTED_MODELS, PROVIDER_ENV_VARS, PROVIDER_PACKAGES, };
@@ -1,6 +1,6 @@
1
1
  import { ssrfSafeFetch } from "../../extensions/url-safety.js";
2
2
  import { clearProviderCredentialAuthFailure, readDeployCredentialEnv, recordProviderCredentialAuthFailure, } from "../../server/credential-provider.js";
3
- import { allowsSamplingParams, anthropicManualThinkingBudget, claudeAdaptiveThinking, isGPTReasoningModel, isUnsetReasoningEffort, normalizeReasoningEffortForModel, supportsClaudeAdaptiveThinking, } from "../../shared/reasoning-effort.js";
3
+ import { allowsSamplingParams, ANTHROPIC_THINKING_BINDING_BETA, anthropicManualThinkingBudget, claudeAdaptiveThinking, isGPTReasoningModel, isUnsetReasoningEffort, normalizeReasoningEffortForModel, supportsAnthropicThinkingBlockBinding, supportsClaudeAdaptiveThinking, } from "../../shared/reasoning-effort.js";
4
4
  import { isNodeRuntime } from "../../shared/runtime.js";
5
5
  import { AI_SDK_MODEL_CONFIG } from "../model-config.js";
6
6
  import { LLM_MISSING_CREDENTIALS_ERROR_CODE, LLM_MISSING_CREDENTIALS_MESSAGE, } from "./credential-errors.js";
@@ -650,6 +650,9 @@ class AISDKEngine {
650
650
  config.baseURL = this.baseUrl;
651
651
  if (this.requestFetch)
652
652
  config.fetch = this.requestFetch;
653
+ if (this.provider === "anthropic") {
654
+ config.fetch = withAnthropicThinkingBlockBinding(this.requestFetch);
655
+ }
653
656
  if (this.provider === "openrouter") {
654
657
  config.fetch = createOpenRouterToolFetch(this.requestFetch);
655
658
  if (this.appName)
@@ -663,6 +666,38 @@ class AISDKEngine {
663
666
  : provider(model);
664
667
  }
665
668
  }
669
+ export function withAnthropicThinkingBlockBinding(baseFetch = globalThis.fetch) {
670
+ return (async (input, init) => {
671
+ if (typeof init?.body !== "string")
672
+ return baseFetch(input, init);
673
+ let body;
674
+ try {
675
+ body = JSON.parse(init.body);
676
+ }
677
+ catch {
678
+ return baseFetch(input, init);
679
+ }
680
+ const thinking = body?.thinking;
681
+ if (thinking?.type !== "adaptive" ||
682
+ thinking.block_binding !== undefined ||
683
+ !supportsAnthropicThinkingBlockBinding(body?.model)) {
684
+ return baseFetch(input, init);
685
+ }
686
+ thinking.block_binding = { prefix_mismatch_behavior: "drop_block" };
687
+ const headers = new Headers(init.headers);
688
+ const beta = headers.get("anthropic-beta");
689
+ const betas = beta ? beta.split(",").map((b) => b.trim()) : [];
690
+ if (!betas.includes(ANTHROPIC_THINKING_BINDING_BETA)) {
691
+ betas.push(ANTHROPIC_THINKING_BINDING_BETA);
692
+ }
693
+ headers.set("anthropic-beta", betas.join(","));
694
+ return baseFetch(input, {
695
+ ...init,
696
+ headers,
697
+ body: JSON.stringify(body),
698
+ });
699
+ });
700
+ }
666
701
  export function createAISDKEngine(provider, config = {}) {
667
702
  return new AISDKEngine(provider, config);
668
703
  }
@@ -1,5 +1,5 @@
1
1
  import { clearProviderCredentialAuthFailure, readDeployCredentialEnv, recordProviderCredentialAuthFailure, } from "../../server/credential-provider.js";
2
- import { allowsSamplingParams, anthropicManualThinkingBudget, claudeAdaptiveThinking, isUnsetReasoningEffort, normalizeReasoningEffortForModel, supportsClaudeAdaptiveThinking, } from "../../shared/reasoning-effort.js";
2
+ import { allowsSamplingParams, ANTHROPIC_THINKING_BINDING_BETA, anthropicManualThinkingBudget, claudeAdaptiveThinking, isUnsetReasoningEffort, normalizeReasoningEffortForModel, supportsAnthropicThinkingBlockBinding, supportsClaudeAdaptiveThinking, } from "../../shared/reasoning-effort.js";
3
3
  import { ANTHROPIC_MODEL_CONFIG } from "../model-config.js";
4
4
  import { LLM_MISSING_CREDENTIALS_ERROR_CODE, LLM_MISSING_CREDENTIALS_MESSAGE, } from "./credential-errors.js";
5
5
  import { describeErrorWithCauses, isBareProviderRejectionMessage, PROVIDER_TRANSIENT_REJECTION_ERROR_CODE, } from "./error-detail.js";
@@ -156,6 +156,14 @@ class AnthropicEngine {
156
156
  }
157
157
  }
158
158
  }
159
+ const bindThinking = extra.thinking?.type === "adaptive" &&
160
+ supportsAnthropicThinkingBlockBinding(opts.model);
161
+ if (bindThinking) {
162
+ extra.thinking = {
163
+ ...extra.thinking,
164
+ block_binding: { prefix_mismatch_behavior: "drop_block" },
165
+ };
166
+ }
159
167
  const samplingAllowed = allowsSamplingParams({
160
168
  model: opts.model,
161
169
  thinkingEnabled: Boolean(extra.thinking),
@@ -223,6 +231,9 @@ class AnthropicEngine {
223
231
  providerDispatched = true;
224
232
  return client.messages.stream(requestParams, {
225
233
  signal: firstEventAbort.signal,
234
+ ...(bindThinking
235
+ ? { headers: { "anthropic-beta": ANTHROPIC_THINKING_BINDING_BETA } }
236
+ : {}),
226
237
  });
227
238
  });
228
239
  if (!dispatch.started)
@@ -283,6 +283,13 @@ export interface AgentActionSurfaceDetails {
283
283
  requestedTurnId?: string;
284
284
  queuedMessageId?: string;
285
285
  actionScope?: Readonly<AgentActionScope>;
286
+ /**
287
+ * Set for a saved automation run, which has no request: `event` is
288
+ * `undefined` and `threadId` is unset.
289
+ */
290
+ automation?: {
291
+ name: string;
292
+ };
286
293
  availableActionNames: readonly string[];
287
294
  }
288
295
  export declare function readPersistedAllowedActionNames(value: unknown): string[] | undefined;
@@ -24,7 +24,7 @@ export function createToolSearchEntry(getRegistry, options = {}) {
24
24
  const defaultLimit = Math.max(1, Math.min(options.defaultLimit ?? DEFAULT_LIMIT, maxLimit));
25
25
  return frameworkMcpTool({
26
26
  tool: {
27
- description: "Find actions and connected MCP tools by what they do or by exact name. The system prompt's Tool index lists every deferred tool name grouped by topic; loading several exact names in one call is the fastest path. A targeted search returns concise details and adds matches allowed in the current mode, with their full schemas, to the NEXT model step, not this one, so request every tool you need in one call (`queries` and/or `names`) and call them on the next step. If every match is already callable, call it directly instead of searching again. Results rank by words, not intent: before calling one marked `destructive`, confirm the user wants that change. Omit query for a bounded alphabetical menu; menu entries are informational until you search for a capability or name.",
27
+ description: "Find actions and connected MCP tools by what they do or by exact name. The system prompt's Tool index lists every deferred tool name grouped by topic; loading several exact names in one call is the fastest path. A query makes the matching tools callable, with their full schemas, on the NEXT model step, not this one, so request every tool you need in one call (`queries` and/or `names`) and call them on the next step. When you already know the names, pass them as one comma-separated query (`list-projects, get-project`) and only those tools load. If every match is already callable, call it directly instead of searching again. Results rank by words, not intent: before calling one marked `destructive`, confirm the user wants that change. Omit query for a bounded alphabetical menu; menu entries are informational until you search for a capability or name.",
28
28
  parameters: {
29
29
  type: "object",
30
30
  properties: {
@@ -55,7 +55,7 @@ export function createToolSearchEntry(getRegistry, options = {}) {
55
55
  },
56
56
  includeSchemas: {
57
57
  type: "boolean",
58
- description: "Accepted for compatibility. Full schemas are supplied automatically for tools returned by a targeted search.",
58
+ description: "Only set this when you need the schema JSON in the result text. Matching tools already load with their full schemas for your next call.",
59
59
  },
60
60
  readOnlyOnly: {
61
61
  type: "boolean",
@@ -122,9 +122,20 @@ export function searchToolRegistry(registry, args = {}, options = {}) {
122
122
  message: [output.message, truncationNote].filter(Boolean).join(" "),
123
123
  }
124
124
  : output;
125
+ const exactNames = [...names];
126
+ const fuzzyQueries = [];
127
+ for (const query of queries) {
128
+ const queryNames = knownActionNames(registry, query);
129
+ if (queryNames)
130
+ exactNames.push(...queryNames);
131
+ else
132
+ fuzzyQueries.push(query);
133
+ }
125
134
  const targets = [
126
- ...queries.map((query) => ({ query })),
127
- ...(names.length > 0 ? [{ names }] : []),
135
+ ...fuzzyQueries.map((query) => ({ query })),
136
+ ...(exactNames.length > 0
137
+ ? [{ names: [...new Set(exactNames)].slice(0, MAX_NAMES) }]
138
+ : []),
128
139
  ];
129
140
  if (targets.length <= 1) {
130
141
  return withTruncationNote(searchOnce(registry, targets[0] ?? { query: "" }, args, options));
@@ -156,6 +167,25 @@ export function searchToolRegistry(registry, args = {}, options = {}) {
156
167
  results,
157
168
  });
158
169
  }
170
+ function knownActionNames(registry, query) {
171
+ const words = query.split(/[\s,]+/).filter(Boolean);
172
+ if (words.length === 0)
173
+ return undefined;
174
+ const byLowerName = new Map();
175
+ for (const name of Object.keys(registry)) {
176
+ if (name !== TOOL_SEARCH_ACTION_NAME) {
177
+ byLowerName.set(name.toLowerCase(), name);
178
+ }
179
+ }
180
+ const resolved = [];
181
+ for (const word of words) {
182
+ const name = byLowerName.get(word.toLowerCase());
183
+ if (!name)
184
+ return undefined;
185
+ resolved.push(name);
186
+ }
187
+ return resolved;
188
+ }
159
189
  function searchOnce(registry, target, args, options) {
160
190
  const names = "names" in target ? target.names : undefined;
161
191
  const exactNames = names
@@ -36,18 +36,18 @@ export declare const listComposeDrafts: import("h3").EventHandlerWithFetch<impor
36
36
  export declare const getComposeDraft: import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<Record<string, unknown> | null>>;
37
37
  export declare const putComposeDraft: import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<any>>;
38
38
  export declare const saveComposeDraft: import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<{
39
- errorCode?: undefined;
40
39
  error: string;
41
40
  value?: undefined;
42
41
  revision?: undefined;
42
+ errorCode?: undefined;
43
43
  details?: undefined;
44
44
  } | {
45
- errorCode?: undefined;
45
+ error?: undefined;
46
46
  value: {
47
47
  id: string;
48
48
  };
49
49
  revision: string;
50
- error?: undefined;
50
+ errorCode?: undefined;
51
51
  details?: undefined;
52
52
  } | {
53
53
  value?: undefined;
@@ -1,2 +1,2 @@
1
- export declare const AN_SKILL_MD = "---\nname: an\ndescription: >-\n Open and operate Agent-Native workspace apps through Dispatch MCP, with\n inline app surfaces, browser-session authentication, and current screen state.\nmetadata:\n visibility: exported\n---\n\n# Agent-Native Apps\n\nUse `/an <app>` to open an Agent-Native app beside the conversation and keep\nthe app's live UI and the agent's actions in the same workflow. The first\nargument is the Dispatch app id. For example, `/an slides` opens the Slides\neditor. After it opens, the user can sign in in that browser surface and ask\nfor new decks or focused edits in ordinary language.\n\n## Open the app\n\nFor a known app, call Dispatch's `open_app` with an inline surface:\n\n```json\n{\n \"app\": \"slides\",\n \"path\": \"/\",\n \"embed\": true,\n \"chrome\": \"full\"\n}\n```\n\nThe MCP App response is the preferred handoff for Claude, Claude Desktop,\nClaude Cowork, ChatGPT, ChatGPT desktop, Codex, and other compatible hosts. Keep\nthe returned open link as the fallback for a host that cannot render MCP Apps\ninline. Do not claim that a browser opened unless the host rendered the inline\nsurface or its browser tool confirmed the returned URL.\n\nIf the app name is missing or uncertain, call `list_apps` first and use the\nexact granted app id. If the requested app is not listed, explain that it must\nbe granted in Dispatch's Agents access settings. Do not invent a URL, use a\nlocalhost URL, or route around the Dispatch grant.\n\n## Work in the opened app\n\nPrefer direct app tools when the host exposes them. After opening an app, call\n`list-host-webmcp-tools` when available, then use `run-host-webmcp-tool`\nwith the exact listed name and origin. Page-local tools reflect current app\nstate and selection, so use `view-screen` before selection-dependent edits\nand read back writes.\n\nYou are the model doing the work: when the user asks for new content \u2014 a\ndesign, a deck, a form, a document \u2014 author it yourself and save it with the\napp's create/update tools. Never hand off authoring to the app's own agent\nwhen those tools exist, and never wait on an in-app question form; it answers\nback through that app's own chat, not to you.\n\nUse `ask_app` only when the host has no direct page tools, the requested\ncapability is not exposed, the task needs the app agent's interpretation or\nmulti-step specialist reasoning, or a direct call fails and needs recovery.\nDispatch's unified `/mcp` endpoint still exposes generic cross-app verbs; a\ndirect app MCP connection or page WebMCP surface is where named app actions\nappear.\n\nThe app's MCP `instructions` name its key tools (generated from the app's own\nlist); follow those names verbatim and use `tool-search` for anything else \u2014\nnever guess a tool name.\n\n1. Call `view-screen` before any selection-dependent edit and use the ids it\n returns; never guess an id from a title, index, or stale context.\n2. If `view-screen` returns a `selection` and `nextRequiredAction`, make\n that call directly with the smallest atomic change; do not regenerate a\n whole artifact for a focused edit.\n3. Read the result back with the app's matching read action and report what\n changed. A queued `ask_app_status` task is not proof an edit completed.\n\n## Keep the open app in step with the chat\n\nClaude opens an embedded app in its side panel. The panel is one live app: an\nedit made through a tool shows there, and an edit the user makes by hand is in\nthe app's data the next time you read it.\n\n- To change what the open panel shows (filter a list, open a record, switch a\n week), call the view tools `read_view` and `navigate_view` on the open app\n instead of calling `open_app` again. Each new `open_app` call opens a new\n view and replaces the panel.\n- Before acting on \"this\", \"it\" or \"the one I opened\", call `read_view`;\n the user may have clicked or typed in the panel since your last turn.\n- Draft and edit with the app's own actions (create or update a draft, an\n event, a task), then read it back. Send, delete or move only when the user\n asks.\n\n## Authentication and host behavior\n\nThe Dispatch MCP connector identifies the calling agent, while the embedded app\nuses the user's browser session. Let the user complete sign-in in the rendered\nAgent-Native browser surface. Never request, copy, or store passwords, OAuth\ncodes, cookies, or access tokens.\n\nThe generic Agent-Native plugin registers Dispatch at\n`https://dispatch.agent-native.com/mcp` for hosts that support plugin MCP\nconfiguration. ChatGPT custom connectors use the same URL with OAuth. After\ninstalling or changing a connector, reload Claude/Cowork/ChatGPT or reconnect\nand rescan the MCP server if the new tools or inline surface are not visible.\n\n## Failure handling\n\n- If `open_app` succeeds but no inline surface appears, show its returned\n link and say that this host does not expose an embedded browser here.\n- After an app loads, check for `list-host-webmcp-tools` before delegating. If\n it is available, use the exact returned tool name and origin for direct work.\n- If `ask_app` cannot reach Slides, check that Slides is granted in\n Dispatch and that the connector is authenticated, then retry once with the\n exact app id `slides`.\n- If screen state has no deck or selection, describe that state instead of\n fabricating context. Ask the user to open a deck or select an element when\n the requested edit depends on it.\n- Treat a successful open link, a queued task, or a tool acknowledgment as\n navigation/task setup only. Confirm a write with the app's readback action.\n";
1
+ export declare const AN_SKILL_MD = "---\nname: an\ndescription: >-\n Open and operate Agent-Native workspace apps through Dispatch MCP, with\n inline app surfaces, browser-session authentication, and current screen state.\nmetadata:\n visibility: exported\n---\n\n# Agent-Native Apps\n\nUse `/an <app>` to open an Agent-Native app beside the conversation and keep\nthe app's live UI and the agent's actions in the same workflow. The first\nargument is the Dispatch app id. For example, `/an slides` opens the Slides\neditor. After it opens, the user can sign in in that browser surface and ask\nfor new decks or focused edits in ordinary language.\n\n## Open the app\n\nFor a known app, call Dispatch's `open_app` with an inline surface:\n\n```json\n{\n \"app\": \"slides\",\n \"path\": \"/\",\n \"embed\": true,\n \"chrome\": \"full\"\n}\n```\n\nThe MCP App response is the preferred handoff for Claude, Claude Desktop,\nClaude Cowork, ChatGPT, ChatGPT desktop, Codex, and other compatible hosts. Keep\nthe returned open link as the fallback for a host that cannot render MCP Apps\ninline. Do not claim that a browser opened unless the host rendered the inline\nsurface or its browser tool confirmed the returned URL.\n\nIf the app name is missing or uncertain, call `list_apps` first and use the\nexact granted app id. If the requested app is not listed, explain that it must\nbe granted in Dispatch's Agents access settings. Do not invent a URL, use a\nlocalhost URL, or route around the Dispatch grant.\n\n## Work in the opened app\n\nPrefer direct app tools when the host exposes them. After opening an app, call\n`list-host-webmcp-tools` when available, then use `run-host-webmcp-tool`\nwith the exact listed name and origin. Page-local tools reflect current app\nstate and selection, so use `view-screen` before selection-dependent edits\nand read back writes.\n\nYou are the model doing the work: when the user asks for new content \u2014 a\ndesign, a deck, a form, a document \u2014 author it yourself and save it with the\napp's create/update tools. Never hand off authoring to the app's own agent\nwhen those tools exist, and never wait on an in-app question form; it answers\nback through that app's own chat, not to you.\n\nUse `ask_app` only when the host has no direct page tools, the requested\ncapability is not exposed, the task needs the app agent's interpretation or\nmulti-step specialist reasoning, or a direct call fails and needs recovery.\nDispatch's unified `/mcp` endpoint still exposes generic cross-app verbs; a\ndirect app MCP connection or page WebMCP surface is where named app actions\nappear.\n\nThe app's MCP `instructions` name its key tools (generated from the app's own\nlist); follow those names verbatim and use `tool-search` for anything else \u2014\nnever guess a tool name.\n\n1. Call `view-screen` before any selection-dependent edit and use the ids it\n returns; never guess an id from a title, index, or stale context.\n2. If `view-screen` returns a `selection` and `nextRequiredAction`, make\n that call directly with the smallest atomic change; do not regenerate a\n whole artifact for a focused edit.\n3. Read the result back with the app's matching read action and report what\n changed. A queued `ask_app_status` task is not proof an edit completed.\n\n## Keep the open app in step with the chat\n\nAn opened app is one live view beside the chat, in Claude's side panel, a\nChatGPT inline card, or the Agent-Native desktop and Dispatch panes. An edit\nmade through a tool shows there, and an edit the user makes by hand is in the\napp's data the next time it is read.\n\n- **When a view helps.** Mail, events, tasks, decks and records are easier to\n check and change on screen than in a paragraph. When the answer is a set of\n those things, opening the app at that list or record is often the most useful\n reply, and the earlier it appears the sooner the user can act on it. Where a\n host shows only a small inline card, it should show the answer itself, with\n the full view one tap away.\n- **What the user is pointing at.** \"This\", \"that one\", a dragged chip, or \"the\n one I opened\" means the item selected in the open view, or the item the last\n turn showed. `read_view` returns the view's path, selection and visible text,\n and it is current: the user may have clicked or typed since the last turn. Ids\n come from it, not from a title or position.\n- **The same view, updated.** `navigate_view` changes the open view in place\n (a filtered list, one record, another week), so the user keeps their place.\n A new `open_app` replaces the panel with a new view. After a change, the\n useful result is the same view showing the changed item, with the app's own\n read action confirming what was saved; a tool's acknowledgment or a queued\n task is not that confirmation.\n- **Short answers when the view answers.** When the view already shows the\n result, a sentence naming what changed is enough. A table or list repeating\n what is on screen adds nothing.\n- **Unrelated turns leave the view alone.** A question that needs no app is\n answered in chat, and the open view stays where the user left it.\n- **Approvals stay as they are.** Drafts and edits go through the app's own\n actions. Sending, deleting or moving happens only when the user asks, and an\n approval the host or app asks for is the user's to give.\n\n## Authentication and host behavior\n\nThe Dispatch MCP connector identifies the calling agent, while the embedded app\nuses the user's browser session. Let the user complete sign-in in the rendered\nAgent-Native browser surface. Never request, copy, or store passwords, OAuth\ncodes, cookies, or access tokens.\n\nThe generic Agent-Native plugin registers Dispatch at\n`https://dispatch.agent-native.com/mcp` for hosts that support plugin MCP\nconfiguration. ChatGPT custom connectors use the same URL with OAuth. After\ninstalling or changing a connector, reload Claude/Cowork/ChatGPT or reconnect\nand rescan the MCP server if the new tools or inline surface are not visible.\n\n## Failure handling\n\n- If `open_app` succeeds but no inline surface appears, show its returned\n link and say that this host does not expose an embedded browser here.\n- After an app loads, check for `list-host-webmcp-tools` before delegating. If\n it is available, use the exact returned tool name and origin for direct work.\n- If `ask_app` cannot reach Slides, check that Slides is granted in\n Dispatch and that the connector is authenticated, then retry once with the\n exact app id `slides`.\n- If screen state has no deck or selection, describe that state instead of\n fabricating context. Ask the user to open a deck or select an element when\n the requested edit depends on it.\n- Treat a successful open link, a queued task, or a tool acknowledgment as\n navigation/task setup only. Confirm a write with the app's readback action.\n";
2
2
  export declare const AN_COMMAND_MD = "---\ndescription: Open and operate a granted Agent-Native app through Dispatch MCP.\nargument-hint: <app> [request]\n---\n\nUse the an skill. Treat the first argument as the Agent-Native Dispatch app id.\nFor `/an slides`, call `open_app` with app `slides`, path \"/\", embed\ntrue, and chrome `full`. Keep the returned link if the host cannot render\nthe inline MCP App. Any remaining arguments are the user's request after the\napp opens:\n\n$ARGUMENTS\n";
@@ -75,19 +75,36 @@ never guess a tool name.
75
75
 
76
76
  ## Keep the open app in step with the chat
77
77
 
78
- Claude opens an embedded app in its side panel. The panel is one live app: an
79
- edit made through a tool shows there, and an edit the user makes by hand is in
80
- the app's data the next time you read it.
81
-
82
- - To change what the open panel shows (filter a list, open a record, switch a
83
- week), call the view tools \`read_view\` and \`navigate_view\` on the open app
84
- instead of calling \`open_app\` again. Each new \`open_app\` call opens a new
85
- view and replaces the panel.
86
- - Before acting on "this", "it" or "the one I opened", call \`read_view\`;
87
- the user may have clicked or typed in the panel since your last turn.
88
- - Draft and edit with the app's own actions (create or update a draft, an
89
- event, a task), then read it back. Send, delete or move only when the user
90
- asks.
78
+ An opened app is one live view beside the chat, in Claude's side panel, a
79
+ ChatGPT inline card, or the Agent-Native desktop and Dispatch panes. An edit
80
+ made through a tool shows there, and an edit the user makes by hand is in the
81
+ app's data the next time it is read.
82
+
83
+ - **When a view helps.** Mail, events, tasks, decks and records are easier to
84
+ check and change on screen than in a paragraph. When the answer is a set of
85
+ those things, opening the app at that list or record is often the most useful
86
+ reply, and the earlier it appears the sooner the user can act on it. Where a
87
+ host shows only a small inline card, it should show the answer itself, with
88
+ the full view one tap away.
89
+ - **What the user is pointing at.** "This", "that one", a dragged chip, or "the
90
+ one I opened" means the item selected in the open view, or the item the last
91
+ turn showed. \`read_view\` returns the view's path, selection and visible text,
92
+ and it is current: the user may have clicked or typed since the last turn. Ids
93
+ come from it, not from a title or position.
94
+ - **The same view, updated.** \`navigate_view\` changes the open view in place
95
+ (a filtered list, one record, another week), so the user keeps their place.
96
+ A new \`open_app\` replaces the panel with a new view. After a change, the
97
+ useful result is the same view showing the changed item, with the app's own
98
+ read action confirming what was saved; a tool's acknowledgment or a queued
99
+ task is not that confirmation.
100
+ - **Short answers when the view answers.** When the view already shows the
101
+ result, a sentence naming what changed is enough. A table or list repeating
102
+ what is on screen adds nothing.
103
+ - **Unrelated turns leave the view alone.** A question that needs no app is
104
+ answered in chat, and the open view stays where the user left it.
105
+ - **Approvals stay as they are.** Drafts and edits go through the app's own
106
+ actions. Sending, deleting or moving happens only when the user asks, and an
107
+ approval the host or app asks for is the user's to give.
91
108
 
92
109
  ## Authentication and host behavior
93
110
 
@@ -12,6 +12,7 @@ export interface ActionGetRequest {
12
12
  init: RequestInit;
13
13
  headers: Record<string, string>;
14
14
  batchUrl: string;
15
+ batchGroup?: string;
15
16
  }
16
17
  export declare function fetchActionGet(request: ActionGetRequest): Promise<Response>;
17
18
  /** @internal exported for tests */
@@ -45,7 +45,11 @@ function flush() {
45
45
  // (for example X-Request-Source) go out as separate batches.
46
46
  const groups = new Map();
47
47
  for (const item of items) {
48
- const key = JSON.stringify(item.request.headers);
48
+ const key = JSON.stringify([
49
+ item.request.batchUrl,
50
+ item.request.headers,
51
+ item.request.batchGroup ?? "",
52
+ ]);
49
53
  const group = groups.get(key);
50
54
  if (group)
51
55
  group.push(item);
@@ -1,10 +1,11 @@
1
1
  import { APP_STATE_BATCH_ROUTE_HEADER, APP_STATE_SEQ_HEADER, APP_STATE_WRITER_HEADER, TAB_SCOPED_APP_STATE_KEYS, } from "../shared/app-state-routes.js";
2
+ import { readSessionInvalidationMarker, SESSION_BOOTSTRAP_INVALIDATION_GLOBAL, } from "../shared/ssr-session-bootstrap.js";
2
3
  import { agentNativePath } from "./api-path.js";
3
4
  import { assertAgentNativeApiEnabled } from "./api-surface.js";
4
5
  import { getBrowserTabId, isBrowserTabIdForCurrentDocument, } from "./browser-tab-id.js";
5
6
  import { availableKeepaliveBytes, reserveKeepaliveBytes, } from "./keepalive-budget.js";
6
7
  import { recordStateWrite } from "./recorder.js";
7
- import { currentSessionIdentity, currentSessionScope, subscribeSessionScope, } from "./session-identity.js";
8
+ import { currentSessionIdentity, currentSessionScope, subscribeSessionIdentityPublished, subscribeSessionInvalidation, subscribeSessionScope, } from "./session-identity.js";
8
9
  const APP_STATE_KEY_PATTERN = /^[a-zA-Z0-9_:-]+$/;
9
10
  const CORE_BEFORE_TURN_STATE_KEYS = [
10
11
  "navigation",
@@ -18,6 +19,53 @@ const beforeTurnContexts = new WeakMap();
18
19
  const mutationRevisions = new Map();
19
20
  const requestSessionIds = new WeakMap();
20
21
  let nextRequestSessionId = 0;
22
+ let appStateSessionScope = currentSessionScope();
23
+ let awaitingInitialSession = currentSessionIdentity() === undefined;
24
+ let invalidatedSession;
25
+ const initialInvalidationMarker = typeof window === "undefined"
26
+ ? undefined
27
+ : (window[SESSION_BOOTSTRAP_INVALIDATION_GLOBAL] ??
28
+ readSessionInvalidationMarker());
29
+ if (typeof window === "undefined" ||
30
+ typeof window.addEventListener === "function") {
31
+ subscribeSessionInvalidation(() => {
32
+ const session = currentSessionScope();
33
+ if (!invalidatedSession || invalidatedSession.session !== session) {
34
+ invalidatedSession = { session, appState: appStateSessionScope };
35
+ }
36
+ awaitingInitialSession = false;
37
+ appStateSessionScope = {};
38
+ });
39
+ }
40
+ subscribeSessionScope(() => {
41
+ const identity = currentSessionIdentity();
42
+ if (invalidatedSession &&
43
+ identity !== undefined &&
44
+ invalidatedSession.session !== currentSessionScope()) {
45
+ invalidatedSession = undefined;
46
+ }
47
+ if (!awaitingInitialSession ||
48
+ identity === undefined ||
49
+ (initialInvalidationMarker !== undefined &&
50
+ initialInvalidationMarker !== readSessionInvalidationMarker())) {
51
+ appStateSessionScope = currentSessionScope();
52
+ }
53
+ if (identity !== undefined)
54
+ awaitingInitialSession = false;
55
+ });
56
+ subscribeSessionIdentityPublished(() => {
57
+ if (currentSessionIdentity() === undefined)
58
+ return;
59
+ if (invalidatedSession?.session === currentSessionScope()) {
60
+ appStateSessionScope = invalidatedSession.appState;
61
+ }
62
+ invalidatedSession = undefined;
63
+ });
64
+ function assertAppStateSessionReady() {
65
+ if (invalidatedSession) {
66
+ throw new Error("Application state session is being verified");
67
+ }
68
+ }
21
69
  function appStateUrl(key) {
22
70
  if (!APP_STATE_KEY_PATTERN.test(key)) {
23
71
  throw new TypeError("Application state keys may only contain letters, numbers, underscores, hyphens, and colons.");
@@ -69,7 +117,7 @@ function browserTabHeaders() {
69
117
  // Identifies the server row a key reaches, so writes and reads through
70
118
  // `navigation` and through `navigation:<this tab>` wait on each other.
71
119
  function requestKey(key) {
72
- const session = currentSessionScope();
120
+ const session = appStateSessionScope;
73
121
  let sessionId = requestSessionIds.get(session);
74
122
  if (sessionId === undefined) {
75
123
  sessionId = ++nextRequestSessionId;
@@ -91,7 +139,7 @@ function appStateTurnScope() {
91
139
  ]);
92
140
  }
93
141
  function currentBeforeTurnContext() {
94
- const session = currentSessionScope();
142
+ const session = appStateSessionScope;
95
143
  let contexts = beforeTurnContexts.get(session);
96
144
  if (!contexts) {
97
145
  contexts = new Map();
@@ -154,6 +202,7 @@ export function registerBeforeAgentTurnFlush(flush) {
154
202
  * Failed writes are never replayed without their owner's intent and fencing.
155
203
  */
156
204
  export async function flushClientAppStateBeforeAgentTurn(signal) {
205
+ assertAppStateSessionReady();
157
206
  const context = currentBeforeTurnContext();
158
207
  const pendingInScope = () => [...pendingTurnMutations]
159
208
  .filter(([, mutationContext]) => mutationContext === context)
@@ -729,10 +778,13 @@ class AppStateScopeChangedError extends Error {
729
778
  }
730
779
  const MAX_BATCH_KEYS = 100;
731
780
  export async function readClientAppStateMany(keys, options = {}) {
781
+ assertAppStateSessionReady();
732
782
  assertAgentNativeApiEnabled(`read application state [${keys.join(", ")}]`);
733
783
  const context = currentBeforeTurnContext();
784
+ const session = currentSessionScope();
734
785
  const assertScope = () => {
735
- if (currentBeforeTurnContext() !== context) {
786
+ if (currentBeforeTurnContext() !== context ||
787
+ currentSessionScope() !== session) {
736
788
  throw new AppStateScopeChangedError();
737
789
  }
738
790
  };
@@ -790,7 +842,8 @@ export async function readClientAppStateMany(keys, options = {}) {
790
842
  let pendingBatch;
791
843
  function scheduleBatchedRead(key) {
792
844
  const context = currentBeforeTurnContext();
793
- if (pendingBatch?.context === context) {
845
+ const session = currentSessionScope();
846
+ if (pendingBatch?.context === context && pendingBatch.session === session) {
794
847
  pendingBatch.keys.add(key);
795
848
  return pendingBatch.promise;
796
849
  }
@@ -799,14 +852,15 @@ function scheduleBatchedRead(key) {
799
852
  setTimeout(() => {
800
853
  if (pendingBatch?.promise === promise)
801
854
  pendingBatch = undefined;
802
- if (currentBeforeTurnContext() !== context) {
855
+ if (currentBeforeTurnContext() !== context ||
856
+ currentSessionScope() !== session) {
803
857
  reject(new AppStateScopeChangedError());
804
858
  return;
805
859
  }
806
860
  readClientAppStateMany([...keys]).then(resolve, reject);
807
861
  }, 0);
808
862
  });
809
- pendingBatch = { keys, promise, context };
863
+ pendingBatch = { keys, promise, context, session };
810
864
  return promise;
811
865
  }
812
866
  function awaitWithAbort(promise, signal) {
@@ -835,6 +889,7 @@ function awaitWithAbort(promise, signal) {
835
889
  });
836
890
  }
837
891
  export async function readClientAppState(key, options = {}) {
892
+ assertAppStateSessionReady();
838
893
  appStateUrl(key);
839
894
  if (options.signal?.aborted) {
840
895
  throw options.signal.reason ?? new Error("Aborted");
@@ -868,6 +923,7 @@ export async function readClientAppState(key, options = {}) {
868
923
  }
869
924
  }
870
925
  export async function writeClientAppState(key, value, options = {}) {
926
+ assertAppStateSessionReady();
871
927
  assertAgentNativeApiEnabled(`write application state "${key}"`);
872
928
  const ownRequest = !!options.signal || options.ownRequest === true;
873
929
  // Numbered now, in the order it was made, like a queued write.
@@ -907,6 +963,7 @@ export async function writeClientAppState(key, value, options = {}) {
907
963
  return write;
908
964
  }
909
965
  export async function compareAndSetClientAppState(key, expected, next, options = {}) {
966
+ assertAppStateSessionReady();
910
967
  assertAgentNativeApiEnabled(`compare application state \"${key}\"`);
911
968
  return runBarrierMutation(key, async () => {
912
969
  const body = jsonBody({ expected, next });
@@ -932,6 +989,7 @@ export async function compareAndSetClientAppState(key, expected, next, options =
932
989
  }, (changed) => changed);
933
990
  }
934
991
  export async function deleteClientAppState(key, options = {}) {
992
+ assertAppStateSessionReady();
935
993
  assertAgentNativeApiEnabled(`delete application state "${key}"`);
936
994
  const seq = options.signal ? nextWriteSeq() : 0;
937
995
  const deletion = options.signal
@@ -26,6 +26,7 @@ const RUNTIME_EVENT_TYPE = "x-core.runtime-event";
26
26
  const RUNTIME_USAGE_EVENT_TYPE = "x-core.usage";
27
27
  const DEFAULT_MAX_RETAINED_EVENTS = 1_000;
28
28
  const DEFAULT_MAX_RETAINED_RUNS = 100;
29
+ const MAX_OMISSION_RANGE = 256;
29
30
  const DEFAULT_RETAINED_RUN_TTL_MS = 30 * 60 * 1_000;
30
31
  const MAX_DURABLE_RESUME_ATTEMPTS = 3;
31
32
  const MAX_TIMER_DELAY_MS = 2_147_483_647;
@@ -3289,10 +3290,21 @@ export function createAgentKitProtocolAdapter(runtime, options = {}) {
3289
3290
  };
3290
3291
  try {
3291
3292
  while (!signal?.aborted) {
3292
- if (nextSequence < run.firstRetainedSequence) {
3293
- throw new Error(`AgentKit run ${run.runId} no longer retains sequence ${nextSequence}; the earliest available sequence is ${run.firstRetainedSequence}.`);
3294
- }
3295
3293
  while (nextSequence <= run.sequence) {
3294
+ if (nextSequence < run.firstRetainedSequence) {
3295
+ const lastSequence = Math.min(run.firstRetainedSequence - 1, nextSequence + MAX_OMISSION_RANGE - 1);
3296
+ yield {
3297
+ id: `retention-pruned:${run.runId}:${nextSequence}`,
3298
+ threadId: run.threadId,
3299
+ runId: run.runId,
3300
+ sequence: nextSequence,
3301
+ occurredAt: run.events[0]?.occurredAt ?? now(),
3302
+ type: "x-agent-native.persisted-event-omission-range",
3303
+ payload: { lastSequence, sourceType: "retention_pruned" },
3304
+ };
3305
+ nextSequence = lastSequence + 1;
3306
+ continue;
3307
+ }
3296
3308
  const event = run.events[nextSequence - run.firstRetainedSequence];
3297
3309
  nextSequence += 1;
3298
3310
  if (!event) {
@@ -8,6 +8,7 @@ export function useFeatureFlag(key) {
8
8
  const { status } = useSession();
9
9
  const query = useActionQuery("get-feature-flags", undefined, {
10
10
  enabled: status === "authenticated",
11
+ batchInitial: true,
11
12
  refetchInterval: retryUnavailableFlags,
12
13
  });
13
14
  if (RETIRED_ENABLED_FLAG_KEYS.has(key))
@@ -30,6 +31,7 @@ export function useFeatureFlagState(key, options) {
30
31
  ]);
31
32
  const query = useActionQuery("get-feature-flags", undefined, {
32
33
  enabled: status === "authenticated",
34
+ batchInitial: true,
33
35
  refetchInterval: retryUnavailableFlags,
34
36
  ...(options?.freshOnMount
35
37
  ? {
@@ -65,6 +67,7 @@ export function useFeatureFlags() {
65
67
  const { status } = useSession();
66
68
  const query = useActionQuery("get-feature-flags", undefined, {
67
69
  enabled: status === "authenticated",
70
+ batchInitial: true,
68
71
  refetchInterval: retryUnavailableFlags,
69
72
  });
70
73
  return query.isError ? {} : evaluatedFeatureFlagValues(query.data);
@@ -12,6 +12,7 @@ export function useLabState(lab) {
12
12
  const { status } = useSession();
13
13
  const query = useActionQuery("get-lab-states", undefined, {
14
14
  enabled: status === "authenticated",
15
+ batchInitial: true,
15
16
  });
16
17
  const state = query.data?.[key];
17
18
  const stateFailed = state !== undefined && "error" in state;
@@ -56,6 +57,7 @@ export function useLabStates() {
56
57
  const { status } = useSession();
57
58
  const query = useActionQuery("get-lab-states", undefined, {
58
59
  enabled: status === "authenticated",
60
+ batchInitial: true,
59
61
  });
60
62
  return query.data ?? {};
61
63
  }
@@ -37,4 +37,5 @@ export type SessionScope = string | null;
37
37
  * a sign-out, or a switch to another account or org.
38
38
  */
39
39
  export declare function onSessionIdentityPublished(listener: (scope: SessionScope) => void): void;
40
+ export declare function subscribeSessionIdentityPublished(listener: () => void): () => void;
40
41
  export declare function notifySessionIdentityPublished(scope: SessionScope): void;
@@ -105,6 +105,7 @@ export function subscribeSessionInvalidation(listener) {
105
105
  };
106
106
  }
107
107
  let publishedListener;
108
+ const publishedListeners = new Set();
108
109
  /**
109
110
  * Runs after the session resolver publishes a session it read, so a module the
110
111
  * resolver can't import (it imports the resolver) can act on a known sign-in,
@@ -113,6 +114,12 @@ let publishedListener;
113
114
  export function onSessionIdentityPublished(listener) {
114
115
  publishedListener = listener;
115
116
  }
117
+ export function subscribeSessionIdentityPublished(listener) {
118
+ publishedListeners.add(listener);
119
+ return () => publishedListeners.delete(listener);
120
+ }
116
121
  export function notifySessionIdentityPublished(scope) {
117
122
  publishedListener?.(scope);
123
+ for (const listener of [...publishedListeners])
124
+ listener();
118
125
  }
@@ -226,6 +226,7 @@ export declare function useActionQuery<TResult = undefined, TName extends Action
226
226
  * than waiting on the other reads in their batch.
227
227
  */
228
228
  batchRefetches?: boolean;
229
+ batchInitial?: boolean;
229
230
  /** Captures a local projection fence before the authorized read starts. */
230
231
  onRequestStart?: () => unknown;
231
232
  /** Receives canonical responses only, never optimistic query-cache writes. */