@agent-native/core 0.232.0 → 0.233.0-nightly-20261124004026

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 (119) hide show
  1. package/dist/a2a/handlers.js +60 -1
  2. package/dist/a2a/server.js +9 -0
  3. package/dist/action-call-classification.d.ts +9 -0
  4. package/dist/action-call-classification.js +18 -0
  5. package/dist/action-conformance.d.ts +81 -0
  6. package/dist/action-conformance.js +392 -0
  7. package/dist/action.d.ts +18 -0
  8. package/dist/action.js +68 -5
  9. package/dist/agent/execution-fence.d.ts +3 -1
  10. package/dist/agent/execution-fence.js +13 -2
  11. package/dist/agent/production-agent.d.ts +3 -0
  12. package/dist/agent/production-agent.js +301 -145
  13. package/dist/agent/run-store.js +11 -0
  14. package/dist/agent/thread-data-builder.d.ts +2 -0
  15. package/dist/agent/thread-data-builder.js +5 -1
  16. package/dist/app-config/schema.d.ts +24 -1
  17. package/dist/application-state/handlers.d.ts +1 -1
  18. package/dist/application-state/navigate-write-guard.d.ts +4 -1
  19. package/dist/application-state/navigate-write-guard.js +15 -1
  20. package/dist/cli/design-connect.js +5 -1
  21. package/dist/cli/matched-check.d.ts +1 -0
  22. package/dist/cli/matched-check.js +76 -0
  23. package/dist/client/agent-chat/index.d.ts +1 -1
  24. package/dist/client/agent-chat/index.js +1 -1
  25. package/dist/client/analytics/index.d.ts +1 -1
  26. package/dist/client/analytics.d.ts +13 -1
  27. package/dist/client/analytics.js +5 -2
  28. package/dist/client/application-state.d.ts +11 -0
  29. package/dist/client/application-state.js +219 -23
  30. package/dist/client/chat/agentkit-agent-native.js +52 -11
  31. package/dist/client/chat/agentkit-protocol.js +23 -2
  32. package/dist/client/chat-first-state.d.ts +6 -0
  33. package/dist/client/chat-first-state.js +36 -1
  34. package/dist/client/feature-flags/use-feature-flag.js +14 -6
  35. package/dist/client/navigation/index.d.ts +2 -0
  36. package/dist/client/navigation/index.js +2 -0
  37. package/dist/client/route-state.js +60 -18
  38. package/dist/client/screen-settled.d.ts +71 -1
  39. package/dist/client/screen-settled.js +221 -3
  40. package/dist/client/sse-event-processor.d.ts +1 -0
  41. package/dist/client/sse-event-processor.js +89 -10
  42. package/dist/client/theme.d.ts +6 -0
  43. package/dist/client/theme.js +7 -1
  44. package/dist/client/use-action.js +32 -10
  45. package/dist/client/use-session.js +36 -18
  46. package/dist/collab/struct-routes.d.ts +1 -1
  47. package/dist/db/client.js +2 -2
  48. package/dist/db/errors.d.ts +2 -0
  49. package/dist/db/errors.js +38 -6
  50. package/dist/feature-flags/actions/get-feature-flags.js +9 -2
  51. package/dist/file-upload/actions/upload-image.d.ts +2 -2
  52. package/dist/framework-package-versions.json +8 -8
  53. package/dist/ingestion/index.d.ts +1 -0
  54. package/dist/ingestion/index.js +1 -0
  55. package/dist/ingestion/matched-capture.d.ts +173 -0
  56. package/dist/ingestion/matched-capture.js +574 -0
  57. package/dist/ingestion/pptx.d.ts +1 -0
  58. package/dist/ingestion/pptx.js +4 -2
  59. package/dist/labs/store.d.ts +3 -1
  60. package/dist/labs/store.js +8 -4
  61. package/dist/manifest/index.d.ts +142 -3
  62. package/dist/manifest/index.js +249 -19
  63. package/dist/mcp/build-server.d.ts +2 -0
  64. package/dist/mcp/build-server.js +8 -1
  65. package/dist/mcp/server.js +3 -1
  66. package/dist/notifications/routes.d.ts +3 -3
  67. package/dist/observability/metrics.d.ts +2 -0
  68. package/dist/observability/metrics.js +7 -0
  69. package/dist/org/index.d.ts +1 -1
  70. package/dist/provider-api/actions/custom-provider-registration.d.ts +10 -10
  71. package/dist/provider-api/actions/provider-api.d.ts +14 -14
  72. package/dist/server/action-routes.js +9 -0
  73. package/dist/server/agent-chat/prompt-resources.js +107 -83
  74. package/dist/server/agent-run-context.d.ts +3 -0
  75. package/dist/server/agent-run-context.js +7 -0
  76. package/dist/server/builder-oauth.d.ts +1 -0
  77. package/dist/server/builder-oauth.js +40 -2
  78. package/dist/server/filesystem-action-entry.js +5 -0
  79. package/dist/server/first-touch-route.d.ts +2 -2
  80. package/dist/server/index.d.ts +2 -2
  81. package/dist/server/index.js +2 -2
  82. package/dist/server/open-route.js +10 -4
  83. package/dist/server/poll.d.ts +3 -0
  84. package/dist/server/poll.js +74 -14
  85. package/dist/server/request-context.d.ts +16 -6
  86. package/dist/server/request-context.js +4 -0
  87. package/dist/server/transcribe-voice.d.ts +1 -1
  88. package/dist/shared/analytics-events.d.ts +7 -0
  89. package/dist/shared/viewport-mode.d.ts +2 -0
  90. package/dist/shared/viewport-mode.js +9 -0
  91. package/dist/templates/chat/.agents/skills/actions/SKILL.md +1 -0
  92. package/dist/templates/chat/.agents/skills/build-an-app/SKILL.md +38 -17
  93. package/dist/templates/chat/.agents/skills/shadcn-ui/SKILL.md +3 -2
  94. package/dist/templates/default/.agents/skills/actions/SKILL.md +1 -0
  95. package/dist/templates/default/.agents/skills/build-an-app/SKILL.md +38 -17
  96. package/dist/templates/default/.agents/skills/shadcn-ui/SKILL.md +3 -2
  97. package/dist/templates/factory/.agents/skills/review-latest-feedback/SKILL.md +3 -2
  98. package/dist/templates/headless/.agents/skills/actions/SKILL.md +1 -0
  99. package/dist/templates/workspace-core/.agents/skills/actions/SKILL.md +1 -0
  100. package/dist/templates/workspace-core/.agents/skills/build-an-app/SKILL.md +38 -17
  101. package/dist/templates/workspace-core/.agents/skills/shadcn-ui/SKILL.md +3 -2
  102. package/dist/testing.d.ts +1 -0
  103. package/dist/testing.js +1 -0
  104. package/dist/tracking/action-lifecycle.d.ts +2 -0
  105. package/dist/tracking/action-lifecycle.js +16 -5
  106. package/docs/content/actions-defining.mdx +7 -0
  107. package/docs/content/custom-design-system.mdx +4 -2
  108. package/package.json +3 -3
  109. package/src/templates/chat/.agents/skills/actions/SKILL.md +1 -0
  110. package/src/templates/chat/.agents/skills/build-an-app/SKILL.md +38 -17
  111. package/src/templates/chat/.agents/skills/shadcn-ui/SKILL.md +3 -2
  112. package/src/templates/default/.agents/skills/actions/SKILL.md +1 -0
  113. package/src/templates/default/.agents/skills/build-an-app/SKILL.md +38 -17
  114. package/src/templates/default/.agents/skills/shadcn-ui/SKILL.md +3 -2
  115. package/src/templates/factory/.agents/skills/review-latest-feedback/SKILL.md +3 -2
  116. package/src/templates/headless/.agents/skills/actions/SKILL.md +1 -0
  117. package/src/templates/workspace-core/.agents/skills/actions/SKILL.md +1 -0
  118. package/src/templates/workspace-core/.agents/skills/build-an-app/SKILL.md +38 -17
  119. package/src/templates/workspace-core/.agents/skills/shadcn-ui/SKILL.md +3 -2
@@ -3,11 +3,17 @@ import { agentNativeApiDisabledReason } from "../api-surface.js";
3
3
  import { useActionQuery } from "../use-action.js";
4
4
  import { useSession } from "../use-session.js";
5
5
  import { evaluatedFeatureFlagValues, featureFlagValue, } from "./helpers.js";
6
+ const retryUnavailableFlags = (query) => query.state.status === "error" ? 60_000 : false;
6
7
  export function useFeatureFlag(key) {
7
8
  const { status } = useSession();
8
- const query = useActionQuery("get-feature-flags", undefined, { enabled: status === "authenticated" });
9
+ const query = useActionQuery("get-feature-flags", undefined, {
10
+ enabled: status === "authenticated",
11
+ refetchInterval: retryUnavailableFlags,
12
+ });
9
13
  if (RETIRED_ENABLED_FLAG_KEYS.has(key))
10
14
  return true;
15
+ if (query.isError)
16
+ return false;
11
17
  return featureFlagValue(evaluatedFeatureFlagValues(query.data), key);
12
18
  }
13
19
  /**
@@ -24,6 +30,7 @@ export function useFeatureFlagState(key, options) {
24
30
  ]);
25
31
  const query = useActionQuery("get-feature-flags", undefined, {
26
32
  enabled: status === "authenticated",
33
+ refetchInterval: retryUnavailableFlags,
27
34
  ...(options?.freshOnMount
28
35
  ? {
29
36
  staleTime: 0,
@@ -42,7 +49,7 @@ export function useFeatureFlagState(key, options) {
42
49
  if (status !== "authenticated") {
43
50
  return { status: "unavailable", enabled: false };
44
51
  }
45
- if (options?.freshOnMount && query.isError)
52
+ if (query.isError)
46
53
  return { status: "unavailable", enabled: false };
47
54
  if (options?.freshOnMount && !query.isFetchedAfterMount)
48
55
  return { status: "loading", enabled: false };
@@ -52,12 +59,13 @@ export function useFeatureFlagState(key, options) {
52
59
  enabled: featureFlagValue(evaluatedFeatureFlagValues(query.data), key),
53
60
  };
54
61
  }
55
- if (query.isError)
56
- return { status: "unavailable", enabled: false };
57
62
  return { status: "loading", enabled: false };
58
63
  }
59
64
  export function useFeatureFlags() {
60
65
  const { status } = useSession();
61
- const query = useActionQuery("get-feature-flags", undefined, { enabled: status === "authenticated" });
62
- return evaluatedFeatureFlagValues(query.data);
66
+ const query = useActionQuery("get-feature-flags", undefined, {
67
+ enabled: status === "authenticated",
68
+ refetchInterval: retryUnavailableFlags,
69
+ });
70
+ return query.isError ? {} : evaluatedFeatureFlagValues(query.data);
63
71
  }
@@ -5,3 +5,5 @@ export { AGENT_NATIVE_WORKSPACE_APP_ROUTE_MESSAGE_TYPE, postAgentNativeWorkspace
5
5
  export { buildOpenRouteLink, buildOpenRoutePath, buildLegacyAgentSettingsRoute, buildResourceRoute, buildSettingsEntryRoute, buildSettingsRedirectRoute, buildSettingsRoute, buildStandardAppRoute, buildTeamRoute, createStandardOpenPathResolver, resolveLegacySettingsId, resolveSettingsSectionRedirect, SETTINGS_PAGE_IDS, STANDARD_APP_ROUTES, STANDARD_SETTINGS_TABS, type BuildResourceRouteOptions, type BuildSettingsRouteOptions, type CoreSettingsPageId, type SettingsRedirect, type BuildStandardAppRouteOptions, type NavigationLink, type NavigationTarget, type StandardAppRouteId, type StandardOpenPathResolverOptions, type StandardOpenPathRoute, type StandardSettingsTabId, } from "../../navigation/index.js";
6
6
  export { getSettingsShortcutHint, isSettingsRoutePath, isSettingsShortcutEvent, OPEN_SETTINGS_PAGE_EVENT, openSettingsPage, SETTINGS_SHORTCUT_PAGE, settingsPagePath, useSettingsShortcut, type OpenSettingsPageDetail, } from "../use-settings-shortcut.js";
7
7
  export { postNavigate, isInAgentEmbed, AGENT_NAVIGATE_MESSAGE_TYPE, type AgentNavigateMessage, } from "../embed.js";
8
+ export { registerBeforeAgentTurnFlush, registerBeforeAgentTurnStateKeys, flushClientAppStateBeforeAgentTurn, } from "../application-state.js";
9
+ export { SCREEN_SETTLED_EVENT, UPDATE_MODEL_CONTEXT_MESSAGE_TYPE, getCurrentRenderedScreen, getLastUserInteractedEntity, getLastUserInteractedEntityId, postScreenSettled, reportRenderedScreen, reportUserInteraction, useReportRenderedScreen, verifyScreenSettledReceipt, type ExpectedRenderedScreen, type LastUserInteractedEntity, type RenderedScreenReport, type ScreenSettledReceipt, type ScreenSettledVerificationResult, type UserInteractionReport, } from "../screen-settled.js";
@@ -5,3 +5,5 @@ export { AGENT_NATIVE_WORKSPACE_APP_ROUTE_MESSAGE_TYPE, postAgentNativeWorkspace
5
5
  export { buildOpenRouteLink, buildOpenRoutePath, buildLegacyAgentSettingsRoute, buildResourceRoute, buildSettingsEntryRoute, buildSettingsRedirectRoute, buildSettingsRoute, buildStandardAppRoute, buildTeamRoute, createStandardOpenPathResolver, resolveLegacySettingsId, resolveSettingsSectionRedirect, SETTINGS_PAGE_IDS, STANDARD_APP_ROUTES, STANDARD_SETTINGS_TABS, } from "../../navigation/index.js";
6
6
  export { getSettingsShortcutHint, isSettingsRoutePath, isSettingsShortcutEvent, OPEN_SETTINGS_PAGE_EVENT, openSettingsPage, SETTINGS_SHORTCUT_PAGE, settingsPagePath, useSettingsShortcut, } from "../use-settings-shortcut.js";
7
7
  export { postNavigate, isInAgentEmbed, AGENT_NAVIGATE_MESSAGE_TYPE, } from "../embed.js";
8
+ export { registerBeforeAgentTurnFlush, registerBeforeAgentTurnStateKeys, flushClientAppStateBeforeAgentTurn, } from "../application-state.js";
9
+ export { SCREEN_SETTLED_EVENT, UPDATE_MODEL_CONTEXT_MESSAGE_TYPE, getCurrentRenderedScreen, getLastUserInteractedEntity, getLastUserInteractedEntityId, postScreenSettled, reportRenderedScreen, reportUserInteraction, useReportRenderedScreen, verifyScreenSettledReceipt, } from "../screen-settled.js";
@@ -1,12 +1,13 @@
1
1
  import { useQuery, useQueryClient } from "@tanstack/react-query";
2
- import { useCallback, useContext, useEffect, useMemo, useRef, useState, } from "react";
2
+ import { useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore, } from "react";
3
3
  import { UNSAFE_DataRouterStateContext, resolvePath, useLocation, useNavigate, } from "react-router";
4
4
  import { isWorkspaceAppPath } from "./api-path.js";
5
- import { compareAndSetClientAppState, deleteClientAppState, readClientAppState, setClientAppState, } from "./application-state.js";
5
+ import { compareAndSetClientAppState, deleteClientAppState, readClientAppState, registerBeforeAgentTurnFlush, setClientAppState, } from "./application-state.js";
6
6
  import { getBrowserTabId, isBrowserTabIdForCurrentDocument, } from "./browser-tab-id.js";
7
7
  import { useBrowserTabUse } from "./browser-tab-use.js";
8
8
  import { navigateWithAgentChatViewTransition, } from "./chat-view-transition.js";
9
9
  import { postScreenSettled } from "./screen-settled.js";
10
+ import { currentSessionScope, subscribeSessionScope, } from "./session-identity.js";
10
11
  import { postAgentNativeWorkspaceAppRoute } from "./workspace-app-navigation.js";
11
12
  const SAFE_BROWSER_TAB_ID_RE = /^[A-Za-z0-9_-]{1,96}$/;
12
13
  function normalizeBrowserTabId(browserTabId) {
@@ -96,6 +97,7 @@ function resolveAgentChatViewTransitionOption(option, command, path) {
96
97
  }
97
98
  export function useSemanticNavigationState(options) {
98
99
  const { commandRefetchInterval = 15_000, enabled = true, keepalive = true, writeDebounceMs = 0, } = options;
100
+ const sessionScope = useSyncExternalStore(subscribeSessionScope, currentSessionScope, currentSessionScope);
99
101
  const browserTabId = useMemo(() => normalizeBrowserTabId(options.browserTabId) ??
100
102
  (options.browserTabId === undefined ? defaultBrowserTabId() : undefined), [options.browserTabId]);
101
103
  const requestSource = options.requestSource ?? browserTabId;
@@ -120,33 +122,73 @@ export function useSemanticNavigationState(options) {
120
122
  // `null` is safe as "never written": a null state serializes to a string, so
121
123
  // the token itself is never null.
122
124
  const lastNavigationWriteRef = useRef(null);
125
+ const navigationWriteRef = useRef({ navigationKeys, navigationState });
126
+ navigationWriteRef.current = { navigationKeys, navigationState };
123
127
  useEffect(() => {
124
128
  if (!enabled)
125
129
  return;
126
- if (lastNavigationWriteRef.current === navigationWriteDedup)
130
+ if (lastNavigationWriteRef.current?.scope === sessionScope &&
131
+ lastNavigationWriteRef.current.token === navigationWriteDedup)
127
132
  return;
128
- lastNavigationWriteRef.current = navigationWriteDedup;
129
- const write = () => {
130
- for (const key of navigationKeys) {
131
- setClientAppState(key, navigationState, {
132
- keepalive,
133
- requestSource,
134
- }).catch((error) => onErrorRef.current?.(error));
135
- }
133
+ lastNavigationWriteRef.current = {
134
+ scope: sessionScope,
135
+ token: navigationWriteDedup,
136
+ };
137
+ const { navigationKeys, navigationState } = navigationWriteRef.current;
138
+ let active = true;
139
+ const write = () => Promise.all(navigationKeys.map((key) => setClientAppState(key, navigationState, {
140
+ keepalive,
141
+ ...(requestSource ? { requestSource } : {}),
142
+ }))).then(() => { });
143
+ const reportError = (error) => {
144
+ if (active && currentSessionScope() === sessionScope)
145
+ onErrorRef.current?.(error);
146
+ };
147
+ let pending = true;
148
+ let inFlight;
149
+ let timer;
150
+ const flush = () => {
151
+ if (!active || currentSessionScope() !== sessionScope)
152
+ return;
153
+ if (inFlight)
154
+ return inFlight;
155
+ if (!pending)
156
+ return;
157
+ pending = false;
158
+ clearTimeout(timer);
159
+ inFlight = write()
160
+ .catch((error) => {
161
+ if (active && currentSessionScope() === sessionScope)
162
+ pending = true;
163
+ throw error;
164
+ })
165
+ .finally(() => {
166
+ inFlight = undefined;
167
+ });
168
+ return inFlight;
169
+ };
170
+ const unregister = registerBeforeAgentTurnFlush(flush);
171
+ if (writeDebounceMs > 0)
172
+ timer = setTimeout(() => {
173
+ flush()?.catch(reportError);
174
+ }, writeDebounceMs);
175
+ else
176
+ flush()?.catch(reportError);
177
+ return () => {
178
+ active = false;
179
+ if (pending || inFlight)
180
+ lastNavigationWriteRef.current = null;
181
+ pending = false;
182
+ clearTimeout(timer);
183
+ unregister();
136
184
  };
137
- if (writeDebounceMs > 0) {
138
- const timer = setTimeout(write, writeDebounceMs);
139
- return () => clearTimeout(timer);
140
- }
141
- write();
142
185
  }, [
143
186
  enabled,
144
187
  keepalive,
145
- navigationKeys,
146
- navigationState,
147
188
  navigationWriteDedup,
148
189
  requestSource,
149
190
  writeDebounceMs,
191
+ sessionScope,
150
192
  ]);
151
193
  const commandQuery = useQuery({
152
194
  queryKey: commandQueryKey,
@@ -1,6 +1,76 @@
1
1
  export declare const SCREEN_SETTLED_EVENT = "agent-native:screen-settled";
2
- export declare function postScreenSettled({ writeId, url, tabId, }: {
2
+ export declare const UPDATE_MODEL_CONTEXT_MESSAGE_TYPE = "ui/update-model-context";
3
+ export interface RenderedScreenReport {
4
+ screenId: string;
5
+ entityType?: string;
6
+ entityId?: string;
7
+ objectTitle?: string;
8
+ interactiveControls: readonly string[];
9
+ isFallback?: boolean;
10
+ }
11
+ export interface UserInteractionReport {
12
+ entityId: string;
13
+ entityType?: string;
14
+ action: string;
15
+ }
16
+ export interface LastUserInteractedEntity {
17
+ entityId: string;
18
+ entityType?: string;
19
+ action: string;
20
+ updatedAt: number;
21
+ }
22
+ export interface ScreenSettledReceipt {
23
+ type: typeof SCREEN_SETTLED_EVENT;
24
+ writeId: string;
25
+ tabId: string;
26
+ appBasePath: string;
27
+ url: string;
28
+ screenSummary: {
29
+ title: string;
30
+ route: string;
31
+ };
32
+ renderedScreen?: RenderedScreenReport;
33
+ lastUserInteractedEntity?: LastUserInteractedEntity;
34
+ lastUserInteractedEntityId?: string;
35
+ }
36
+ export interface ExpectedRenderedScreen {
37
+ screenId?: string;
38
+ entityId?: string;
39
+ requiredControls?: readonly string[];
40
+ }
41
+ export type ScreenSettledVerificationResult = {
42
+ verified: true;
43
+ renderedScreen: RenderedScreenReport;
44
+ } | {
45
+ verified: false;
46
+ reason: "missing-rendered-screen" | "fallback-rendered" | "screen-mismatch" | "entity-mismatch" | "missing-controls";
47
+ renderedScreen?: RenderedScreenReport;
48
+ expectedScreenId?: string;
49
+ actualScreenId?: string;
50
+ expectedEntityId?: string;
51
+ actualEntityId?: string;
52
+ missingControls?: string[];
53
+ };
54
+ /** Returns the latest rendered-screen report recorded in this tab, if any. */
55
+ export declare function getCurrentRenderedScreen(): RenderedScreenReport | null;
56
+ /** Returns the most recent user interaction recorded in this tab, if any. */
57
+ export declare function getLastUserInteractedEntity(): LastUserInteractedEntity | null;
58
+ /** Returns the entity ID from the most recent user interaction in this tab, if any. */
59
+ export declare function getLastUserInteractedEntityId(): string | null;
60
+ /** Records the currently mounted screen/object and publishes it to the host model context. */
61
+ export declare function reportRenderedScreen(report: RenderedScreenReport | null): RenderedScreenReport | null;
62
+ /** React hook for views to report their mounted screen, entity, and interactive controls to the host. */
63
+ export declare function useReportRenderedScreen(report: RenderedScreenReport | null): void;
64
+ /** Records a user interaction (click, drag, select) so follow-up references like "that one" resolve immediately. */
65
+ export declare function reportUserInteraction(interaction: UserInteractionReport): LastUserInteractedEntity;
66
+ /** Verifies that a settled screen receipt actually mounted the requested screen, entity, and usable controls. */
67
+ export declare function verifyScreenSettledReceipt(receipt: ScreenSettledReceipt, expected?: ExpectedRenderedScreen): ScreenSettledVerificationResult;
68
+ /** Resets rendered-screen and interaction state between unit tests. */
69
+ export declare function _resetRenderedScreenStateForTests(): void;
70
+ export declare function postScreenSettled({ writeId, url, tabId, renderedScreen, lastUserInteractedEntity: explicitInteraction, }: {
3
71
  writeId: string;
4
72
  url: string;
5
73
  tabId: string;
74
+ renderedScreen?: RenderedScreenReport;
75
+ lastUserInteractedEntity?: LastUserInteractedEntity;
6
76
  }): void;
@@ -1,8 +1,211 @@
1
+ import { useEffect, useRef } from "react";
1
2
  import { resolveAppBasePath } from "./api-path.js";
2
3
  import { getFrameOrigin, isKnownFrameHostOrigin } from "./frame.js";
4
+ import { updateMcpAppModelContext } from "./mcp-app-host.js";
3
5
  export const SCREEN_SETTLED_EVENT = "agent-native:screen-settled";
6
+ export const UPDATE_MODEL_CONTEXT_MESSAGE_TYPE = "ui/update-model-context";
4
7
  const recentlySettled = new Set();
5
- export function postScreenSettled({ writeId, url, tabId, }) {
8
+ let currentRenderedScreen = null;
9
+ let lastUserInteractedEntity = null;
10
+ function normalizeRenderedScreen(report) {
11
+ const screenId = report.screenId.trim();
12
+ const controls = Array.from(new Set(report.interactiveControls
13
+ .map((control) => control.trim())
14
+ .filter(Boolean)));
15
+ return {
16
+ screenId,
17
+ ...(report.entityType?.trim()
18
+ ? { entityType: report.entityType.trim() }
19
+ : {}),
20
+ ...(report.entityId?.trim() ? { entityId: report.entityId.trim() } : {}),
21
+ ...(report.objectTitle?.trim()
22
+ ? { objectTitle: report.objectTitle.trim() }
23
+ : {}),
24
+ interactiveControls: controls,
25
+ ...(report.isFallback === true ? { isFallback: true } : {}),
26
+ };
27
+ }
28
+ function buildModelContextSnapshot(includeClearedRenderedScreen = false) {
29
+ return {
30
+ ...(currentRenderedScreen
31
+ ? { renderedScreen: currentRenderedScreen }
32
+ : includeClearedRenderedScreen
33
+ ? { renderedScreen: null }
34
+ : {}),
35
+ ...(lastUserInteractedEntity
36
+ ? {
37
+ lastUserInteractedEntity,
38
+ lastUserInteractedEntityId: lastUserInteractedEntity.entityId,
39
+ }
40
+ : {}),
41
+ };
42
+ }
43
+ function resolveParentFrameOrigin() {
44
+ const fromFrame = getFrameOrigin();
45
+ if (fromFrame)
46
+ return fromFrame;
47
+ const loc = window.location;
48
+ return loc?.origin;
49
+ }
50
+ function publishModelContextUpdate(includeClearedRenderedScreen = false) {
51
+ if (typeof window === "undefined")
52
+ return;
53
+ const snapshot = buildModelContextSnapshot(includeClearedRenderedScreen);
54
+ if (Object.keys(snapshot).length === 0)
55
+ return;
56
+ try {
57
+ const maybePromise = updateMcpAppModelContext({
58
+ structuredContent: snapshot,
59
+ });
60
+ if (maybePromise && typeof maybePromise.catch === "function") {
61
+ void maybePromise.catch(() => { });
62
+ }
63
+ }
64
+ catch {
65
+ // coercion-ok: standalone pages without an MCP host bridge skip RPC updates.
66
+ }
67
+ const parentOrigin = resolveParentFrameOrigin();
68
+ if (window.parent !== window &&
69
+ parentOrigin &&
70
+ isKnownFrameHostOrigin(parentOrigin)) {
71
+ try {
72
+ window.parent.postMessage({
73
+ type: UPDATE_MODEL_CONTEXT_MESSAGE_TYPE,
74
+ ...snapshot,
75
+ }, parentOrigin);
76
+ }
77
+ catch {
78
+ // coercion-ok: best-effort postMessage to host frame.
79
+ }
80
+ }
81
+ }
82
+ /** Returns the latest rendered-screen report recorded in this tab, if any. */
83
+ export function getCurrentRenderedScreen() {
84
+ return currentRenderedScreen;
85
+ }
86
+ /** Returns the most recent user interaction recorded in this tab, if any. */
87
+ export function getLastUserInteractedEntity() {
88
+ return lastUserInteractedEntity;
89
+ }
90
+ /** Returns the entity ID from the most recent user interaction in this tab, if any. */
91
+ export function getLastUserInteractedEntityId() {
92
+ return lastUserInteractedEntity?.entityId ?? null;
93
+ }
94
+ /** Records the currently mounted screen/object and publishes it to the host model context. */
95
+ export function reportRenderedScreen(report) {
96
+ if (report === null) {
97
+ const hadScreen = currentRenderedScreen !== null;
98
+ currentRenderedScreen = null;
99
+ if (hadScreen) {
100
+ publishModelContextUpdate(true);
101
+ }
102
+ return null;
103
+ }
104
+ const normalized = normalizeRenderedScreen(report);
105
+ currentRenderedScreen = normalized;
106
+ if (typeof window !== "undefined") {
107
+ window.dispatchEvent(new CustomEvent("agent-native:rendered-screen", { detail: normalized }));
108
+ }
109
+ publishModelContextUpdate();
110
+ return normalized;
111
+ }
112
+ /** React hook for views to report their mounted screen, entity, and interactive controls to the host. */
113
+ export function useReportRenderedScreen(report) {
114
+ const normalized = report ? normalizeRenderedScreen(report) : null;
115
+ const signature = normalized ? JSON.stringify(normalized) : null;
116
+ const latestNormalizedRef = useRef(normalized);
117
+ latestNormalizedRef.current = normalized;
118
+ const lastReportedRef = useRef(null);
119
+ useEffect(() => {
120
+ const next = latestNormalizedRef.current;
121
+ if (!signature || !next) {
122
+ if (lastReportedRef.current &&
123
+ currentRenderedScreen === lastReportedRef.current) {
124
+ currentRenderedScreen = null;
125
+ }
126
+ lastReportedRef.current = null;
127
+ return;
128
+ }
129
+ const recorded = reportRenderedScreen(next);
130
+ lastReportedRef.current = recorded;
131
+ return () => {
132
+ if (recorded && currentRenderedScreen === recorded) {
133
+ currentRenderedScreen = null;
134
+ }
135
+ };
136
+ }, [signature]);
137
+ }
138
+ /** Records a user interaction (click, drag, select) so follow-up references like "that one" resolve immediately. */
139
+ export function reportUserInteraction(interaction) {
140
+ const recorded = {
141
+ entityId: interaction.entityId.trim(),
142
+ ...(interaction.entityType?.trim()
143
+ ? { entityType: interaction.entityType.trim() }
144
+ : {}),
145
+ action: interaction.action.trim(),
146
+ updatedAt: Date.now(),
147
+ };
148
+ lastUserInteractedEntity = recorded;
149
+ if (typeof window !== "undefined") {
150
+ window.dispatchEvent(new CustomEvent("agent-native:user-interaction", { detail: recorded }));
151
+ }
152
+ publishModelContextUpdate();
153
+ return recorded;
154
+ }
155
+ /** Verifies that a settled screen receipt actually mounted the requested screen, entity, and usable controls. */
156
+ export function verifyScreenSettledReceipt(receipt, expected = {}) {
157
+ const rendered = receipt.renderedScreen;
158
+ if (!rendered) {
159
+ return { verified: false, reason: "missing-rendered-screen" };
160
+ }
161
+ if (rendered.isFallback === true) {
162
+ return {
163
+ verified: false,
164
+ reason: "fallback-rendered",
165
+ renderedScreen: rendered,
166
+ };
167
+ }
168
+ if (expected.screenId && rendered.screenId !== expected.screenId) {
169
+ return {
170
+ verified: false,
171
+ reason: "screen-mismatch",
172
+ renderedScreen: rendered,
173
+ expectedScreenId: expected.screenId,
174
+ actualScreenId: rendered.screenId,
175
+ };
176
+ }
177
+ if (expected.entityId && rendered.entityId !== expected.entityId) {
178
+ return {
179
+ verified: false,
180
+ reason: "entity-mismatch",
181
+ renderedScreen: rendered,
182
+ expectedEntityId: expected.entityId,
183
+ ...(rendered.entityId !== undefined
184
+ ? { actualEntityId: rendered.entityId }
185
+ : {}),
186
+ };
187
+ }
188
+ if (expected.requiredControls && expected.requiredControls.length > 0) {
189
+ const present = new Set(rendered.interactiveControls);
190
+ const missingControls = expected.requiredControls.filter((control) => !present.has(control));
191
+ if (missingControls.length > 0) {
192
+ return {
193
+ verified: false,
194
+ reason: "missing-controls",
195
+ renderedScreen: rendered,
196
+ missingControls,
197
+ };
198
+ }
199
+ }
200
+ return { verified: true, renderedScreen: rendered };
201
+ }
202
+ /** Resets rendered-screen and interaction state between unit tests. */
203
+ export function _resetRenderedScreenStateForTests() {
204
+ recentlySettled.clear();
205
+ currentRenderedScreen = null;
206
+ lastUserInteractedEntity = null;
207
+ }
208
+ export function postScreenSettled({ writeId, url, tabId, renderedScreen, lastUserInteractedEntity: explicitInteraction, }) {
6
209
  const key = `${tabId}:${writeId}`;
7
210
  if (recentlySettled.has(key))
8
211
  return;
@@ -15,6 +218,10 @@ export function postScreenSettled({ writeId, url, tabId, }) {
15
218
  const safeUrl = new URL(url, "https://app.invalid");
16
219
  safeUrl.searchParams.delete("__an_embed_token");
17
220
  const route = safeUrl.pathname + safeUrl.search + safeUrl.hash;
221
+ const effectiveRenderedScreen = renderedScreen
222
+ ? normalizeRenderedScreen(renderedScreen)
223
+ : (currentRenderedScreen ?? undefined);
224
+ const effectiveInteraction = explicitInteraction ?? lastUserInteractedEntity ?? undefined;
18
225
  const detail = {
19
226
  type: SCREEN_SETTLED_EVENT,
20
227
  writeId,
@@ -22,10 +229,21 @@ export function postScreenSettled({ writeId, url, tabId, }) {
22
229
  appBasePath: resolveAppBasePath(),
23
230
  url: route,
24
231
  screenSummary: { title: document.title, route },
232
+ ...(effectiveRenderedScreen
233
+ ? { renderedScreen: effectiveRenderedScreen }
234
+ : {}),
235
+ ...(effectiveInteraction
236
+ ? {
237
+ lastUserInteractedEntity: effectiveInteraction,
238
+ lastUserInteractedEntityId: effectiveInteraction.entityId,
239
+ }
240
+ : {}),
25
241
  };
26
242
  window.dispatchEvent(new CustomEvent(SCREEN_SETTLED_EVENT, { detail }));
27
- const parentOrigin = getFrameOrigin() ?? window.location.origin;
28
- if (window.parent !== window && isKnownFrameHostOrigin(parentOrigin)) {
243
+ const parentOrigin = resolveParentFrameOrigin();
244
+ if (window.parent !== window &&
245
+ parentOrigin &&
246
+ isKnownFrameHostOrigin(parentOrigin)) {
29
247
  window.parent.postMessage(detail, parentOrigin);
30
248
  }
31
249
  }
@@ -347,6 +347,7 @@ interface ProcessEventState {
347
347
  * it once. Cleared by `resetProcessEventState` on a server `clear` retry
348
348
  * so the next batch of real output re-arms it. */
349
349
  streamProgressDispatched: boolean;
350
+ optimisticOpenAppTargets?: Map<string, string>;
350
351
  }
351
352
  /**
352
353
  * Process a single SSE event and update the content accumulator.
@@ -4,7 +4,7 @@ import { normalizeConnectRequiredResult } from "../shared/connect-required.js";
4
4
  import { isNonProgressEventType } from "../shared/progress-events.js";
5
5
  import { toolInputsMatch } from "../shared/tool-inputs.js";
6
6
  import { getBrowserTabId } from "./browser-tab-id.js";
7
- import { emitChatFirstOpenApp } from "./chat-first-state.js";
7
+ import { emitChatFirstOpenApp, emitChatFirstOpenAppStart, } from "./chat-first-state.js";
8
8
  import { formatChatErrorText, normalizeChatError } from "./error-format.js";
9
9
  import { humanizeToolLabelText, humanizeToolName, isToolCallActive, runningToolLabel, } from "./tool-display.js";
10
10
  /**
@@ -1026,6 +1026,7 @@ function markCompletedToolAfterAssistantText(state, toolName) {
1026
1026
  }
1027
1027
  function resetProcessEventState(state) {
1028
1028
  state?.completedToolsAfterLastAssistantText.clear();
1029
+ state?.optimisticOpenAppTargets?.clear();
1029
1030
  if (state)
1030
1031
  state.streamProgressDispatched = false;
1031
1032
  }
@@ -1039,7 +1040,61 @@ function shouldDispatchStreamProgress(state) {
1039
1040
  state.streamProgressDispatched = true;
1040
1041
  return true;
1041
1042
  }
1042
- function emitFirstPartyOpenAppHandoff(ev) {
1043
+ function readOpenAppString(value) {
1044
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
1045
+ }
1046
+ function openAppHandoffSignature(detail) {
1047
+ return JSON.stringify([
1048
+ detail.app ?? "",
1049
+ detail.path ?? "",
1050
+ detail.url ?? "",
1051
+ detail.view ?? "",
1052
+ detail.focus === true,
1053
+ ]);
1054
+ }
1055
+ function emitOptimisticOpenAppHandoff(rawInput, toolCallId, state, context) {
1056
+ if (!rawInput || typeof rawInput !== "object" || Array.isArray(rawInput)) {
1057
+ return;
1058
+ }
1059
+ const input = rawInput;
1060
+ const app = readOpenAppString(input.app ?? input.appId ?? input.application);
1061
+ const url = readOpenAppString(input.url ?? input.href);
1062
+ if (!app && !url)
1063
+ return;
1064
+ const path = readOpenAppString(input.path ?? input.targetPath);
1065
+ const view = readOpenAppString(input.view);
1066
+ const focus = input.focus === true ? true : undefined;
1067
+ const signature = openAppHandoffSignature({ app, path, url, view, focus });
1068
+ const key = toolCallId ?? "__open_app__";
1069
+ if (state) {
1070
+ state.optimisticOpenAppTargets ??= new Map();
1071
+ if (state.optimisticOpenAppTargets.get(key) === signature)
1072
+ return;
1073
+ state.optimisticOpenAppTargets.set(key, signature);
1074
+ }
1075
+ emitChatFirstOpenAppStart({
1076
+ ...(app ? { app } : {}),
1077
+ ...(path ? { path } : {}),
1078
+ ...(url ? { url } : {}),
1079
+ ...(view ? { view } : {}),
1080
+ ...(focus ? { focus } : {}),
1081
+ optimistic: true,
1082
+ ...(context?.turnId ? { turnId: context.turnId } : {}),
1083
+ });
1084
+ }
1085
+ function tryEmitStreamingOpenAppHandoff(argsText, toolCallId, state, context) {
1086
+ const trimmed = argsText.trim();
1087
+ if (!trimmed.startsWith("{") || !trimmed.endsWith("}"))
1088
+ return;
1089
+ try {
1090
+ const parsed = JSON.parse(trimmed);
1091
+ emitOptimisticOpenAppHandoff(parsed, toolCallId, state, context);
1092
+ }
1093
+ catch {
1094
+ // coercion-ok: partial streaming tool JSON may not be complete yet.
1095
+ }
1096
+ }
1097
+ function emitFirstPartyOpenAppHandoff(ev, state, context) {
1043
1098
  if (ev.type !== "tool_done" || (ev.tool ?? "unknown") !== "open_app") {
1044
1099
  return;
1045
1100
  }
@@ -1063,13 +1118,21 @@ function emitFirstPartyOpenAppHandoff(ev) {
1063
1118
  console.warn("[chat-first] open_app completed without a readable result; no app pane opened");
1064
1119
  return;
1065
1120
  }
1066
- const readString = (value) => typeof value === "string" && value.trim() ? value : undefined;
1067
- const delivery = emitChatFirstOpenApp({
1068
- app: readString(result.app ?? result.appId ?? result.application),
1069
- path: readString(result.path ?? result.targetPath),
1070
- url: readString(result.url ?? result.href),
1071
- view: readString(result.view),
1072
- });
1121
+ const app = readOpenAppString(result.app ?? result.appId ?? result.application);
1122
+ const path = readOpenAppString(result.path ?? result.targetPath);
1123
+ const url = readOpenAppString(result.url ?? result.href);
1124
+ const view = readOpenAppString(result.view);
1125
+ const detail = {
1126
+ ...(app ? { app } : {}),
1127
+ ...(path ? { path } : {}),
1128
+ ...(url ? { url } : {}),
1129
+ ...(view ? { view } : {}),
1130
+ ...(result.focus === true ? { focus: true } : {}),
1131
+ ...(context?.turnId ? { turnId: context.turnId } : {}),
1132
+ };
1133
+ const key = ev.id ?? "__open_app__";
1134
+ state?.optimisticOpenAppTargets?.delete(key);
1135
+ const delivery = emitChatFirstOpenApp(detail);
1073
1136
  if (!delivery.delivered) {
1074
1137
  console.warn(`[chat-first] open_app was completed but not delivered (${delivery.reason ?? "unknown"})`);
1075
1138
  }
@@ -1083,6 +1146,16 @@ export function processEvent(ev, content, toolCallCounter, tabId, state, context
1083
1146
  if (state) {
1084
1147
  state.omitFromPersistedHistory = false;
1085
1148
  state.assistantTurnBoundaryPending = true;
1149
+ state.optimisticOpenAppTargets?.clear();
1150
+ }
1151
+ if (typeof window !== "undefined") {
1152
+ window.dispatchEvent(new CustomEvent("agent-native:turn-start", {
1153
+ detail: {
1154
+ tabId,
1155
+ ...(context?.runId ? { runId: context.runId } : {}),
1156
+ ...(context?.turnId ? { turnId: context.turnId } : {}),
1157
+ },
1158
+ }));
1086
1159
  }
1087
1160
  }
1088
1161
  else if (ev.omitFromPersistedHistory === true && state) {
@@ -1254,6 +1327,9 @@ export function processEvent(ev, content, toolCallCounter, tabId, state, context
1254
1327
  }
1255
1328
  if (ev.type === "tool_input_delta" && ev.text) {
1256
1329
  pending.argsText += ev.text;
1330
+ if (tool === "open_app") {
1331
+ tryEmitStreamingOpenAppHandoff(pending.argsText, ev.id ?? pending.toolCallId, state, context);
1332
+ }
1257
1333
  }
1258
1334
  if (omitFromPersistedHistory) {
1259
1335
  pending.omitFromPersistedHistory = true;
@@ -1293,6 +1369,9 @@ export function processEvent(ev, content, toolCallCounter, tabId, state, context
1293
1369
  }
1294
1370
  return { action: "continue" };
1295
1371
  }
1372
+ if (tool === "open_app") {
1373
+ emitOptimisticOpenAppHandoff(args, ev.id, state, context);
1374
+ }
1296
1375
  if (typeof window !== "undefined") {
1297
1376
  window.dispatchEvent(new CustomEvent("agent-native:tool-start", {
1298
1377
  detail: { tool, input: args },
@@ -1416,7 +1495,7 @@ export function processEvent(ev, content, toolCallCounter, tabId, state, context
1416
1495
  return { action: "continue" };
1417
1496
  }
1418
1497
  }
1419
- emitFirstPartyOpenAppHandoff(ev);
1498
+ emitFirstPartyOpenAppHandoff(ev, state, context);
1420
1499
  if (typeof window !== "undefined") {
1421
1500
  window.dispatchEvent(new CustomEvent("agent-native:tool-done", {
1422
1501
  detail: {