@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,19 +3,23 @@ import { setResponseHeader, setResponseStatus } from "h3";
3
3
  import { AGENT_BACKGROUND_PROCESSOR_A2A, AGENT_BACKGROUND_PROCESSOR_FIELD, dispatchPathTargetsNetlifyBackgroundFunction, isAgentChatDurableBackgroundEnabled, resolveAgentChatProcessRunDispatchPath, } from "../agent/durable-background.js";
4
4
  import { StaleExecutionFenceError, withExecutionFence, } from "../agent/execution-fence.js";
5
5
  import { claimTaskExecutionLease, releaseTurnExecutionLease, renewTaskExecutionLease, TURN_EXECUTION_LEASE_MS, } from "../agent/run-store.js";
6
+ import { normalizeBrowserTabId } from "../application-state/script-helpers.js";
6
7
  import { uploadFile } from "../file-upload/registry.js";
8
+ import { createBrowserTabTargetSlot } from "../mcp/browser-tab-target.js";
7
9
  import { MCP_CHAT_TURN_FIELD, admitMcpChatTurn, readMcpChatTurn, } from "../mcp/chat-turn-store.js";
8
10
  import { trackingIdentityProperties } from "../observability/tracking-identity.js";
9
11
  import { parseServiceIdentityEmail } from "../org/service-identity.js";
10
12
  import { assertServicePrincipalMayRun, recordServicePrincipalDenial, ServicePrincipalRefusedError, } from "../org/service-principal-guard.js";
11
13
  import { runWithProviderInteractiveScope } from "../provider-api/interactive-scope.js";
12
14
  import { findWorkspaceDispatchAgent } from "../server/agent-discovery.js";
15
+ import { readBrowserTabIdHeader, readViewportModeHeader, } from "../server/agent-run-context.js";
13
16
  import { withConfiguredAppBasePath } from "../server/app-base-path.js";
14
17
  import { getOrigin, isConfiguredAppOrigin } from "../server/google-oauth.js";
15
18
  import { DEFAULT_UPLOAD_MAX_FILE_BYTES, isAllowedUploadMimeType, } from "../server/h3-helpers.js";
16
- import { markExplicitPersonalOrgScope } from "../server/request-context.js";
19
+ import { markExplicitPersonalOrgScope, } from "../server/request-context.js";
17
20
  import { fireInternalDispatch } from "../server/self-dispatch.js";
18
21
  import { agentChat } from "../shared/agent-chat.js";
22
+ import { normalizeViewportMode, } from "../shared/viewport-mode.js";
19
23
  import { track } from "../tracking/registry.js";
20
24
  import { hasConfiguredA2ASecret, isA2AProductionRuntime, } from "./auth-policy.js";
21
25
  import { A2A_CALL_REFUSED_KIND, decideIncomingA2AActionCall, hasA2AActionCallHooks, } from "./call-hooks.js";
@@ -155,6 +159,39 @@ function requestOriginForContext(metadata, event) {
155
159
  }
156
160
  return receiverOrigin;
157
161
  }
162
+ function eventContextRecord(event) {
163
+ if (!event)
164
+ return undefined;
165
+ return event.context;
166
+ }
167
+ function resolveA2ABrowserTabId(metadata, event) {
168
+ const fromContext = normalizeBrowserTabId(eventContextRecord(event)?.__a2aBrowserTabId);
169
+ if (fromContext)
170
+ return fromContext;
171
+ const fromHeader = event ? readBrowserTabIdHeader(event) : undefined;
172
+ if (fromHeader)
173
+ return fromHeader;
174
+ return normalizeBrowserTabId(metadata?.browserTabId) ?? undefined;
175
+ }
176
+ function resolveA2AViewportMode(metadata, event) {
177
+ return (normalizeViewportMode(eventContextRecord(event)?.__a2aViewportMode) ??
178
+ (event ? readViewportModeHeader(event) : undefined) ??
179
+ normalizeViewportMode(metadata?.viewportMode));
180
+ }
181
+ function buildA2ARunContext(input) {
182
+ const canTargetUserTab = Boolean(input.verifiedEmail) &&
183
+ input.identityAssurance !== "organization" &&
184
+ !parseServiceIdentityEmail(input.verifiedEmail);
185
+ const browserTabTarget = canTargetUserTab && input.browserTabId
186
+ ? createBrowserTabTargetSlot(input.browserTabId)
187
+ : undefined;
188
+ if (!browserTabTarget && !input.viewportMode)
189
+ return undefined;
190
+ return {
191
+ ...(browserTabTarget ? { browserTabTarget } : {}),
192
+ ...(input.viewportMode ? { viewportMode: input.viewportMode } : {}),
193
+ };
194
+ }
158
195
  function trustedA2AMetadata(metadata, event) {
159
196
  if (!metadata)
160
197
  return undefined;
@@ -349,6 +386,8 @@ async function processClaimedA2ATask(taskId, claimed, config, signal, event, pro
349
386
  return;
350
387
  }
351
388
  const requestOrigin = requestOriginFromMetadata(processorMeta) ?? requestOriginFromEvent(event);
389
+ const browserTabId = normalizeBrowserTabId(processorMeta.browserTabId) ?? undefined;
390
+ const viewportMode = normalizeViewportMode(processorMeta.viewportMode);
352
391
  const contextId = processorMeta.contextId ?? undefined;
353
392
  const callerMetadata = processorMeta.callerMetadata ?? undefined;
354
393
  const sourceContext = processorMeta.sourceContext;
@@ -372,6 +411,12 @@ async function processClaimedA2ATask(taskId, claimed, config, signal, event, pro
372
411
  }
373
412
  try {
374
413
  const { runWithRequestContext } = await import("../server/request-context.js");
414
+ const run = buildA2ARunContext({
415
+ verifiedEmail,
416
+ identityAssurance,
417
+ browserTabId,
418
+ viewportMode,
419
+ });
375
420
  await runWithRequestContext({
376
421
  userEmail: verifiedEmail,
377
422
  ...(identityAssurance
@@ -383,6 +428,7 @@ async function processClaimedA2ATask(taskId, claimed, config, signal, event, pro
383
428
  ? { orgScope: "personal" }
384
429
  : {}),
385
430
  ...(requestOrigin ? { requestOrigin } : {}),
431
+ ...(run ? { run } : {}),
386
432
  }, () => runHandlerAndPersist(taskId, message, config, contextId, callerMetadata, event, sourceContext, verifiedEmail, signal, processingAttemptId));
387
433
  }
388
434
  catch (err) {
@@ -581,6 +627,14 @@ async function withA2ARequestContext(metadata, event, fn) {
581
627
  ? rawIdentityAssurance
582
628
  : undefined;
583
629
  const requestOrigin = requestOriginForContext(metadata, event);
630
+ const browserTabId = resolveA2ABrowserTabId(metadata, event);
631
+ const viewportMode = resolveA2AViewportMode(metadata, event);
632
+ const run = buildA2ARunContext({
633
+ verifiedEmail,
634
+ identityAssurance,
635
+ browserTabId,
636
+ viewportMode,
637
+ });
584
638
  if (event?.context && verifiedEmail && !verifiedOrgId) {
585
639
  markExplicitPersonalOrgScope(event);
586
640
  }
@@ -593,6 +647,7 @@ async function withA2ARequestContext(metadata, event, fn) {
593
647
  ? { orgScope: "personal" }
594
648
  : {}),
595
649
  ...(requestOrigin ? { requestOrigin } : {}),
650
+ ...(run ? { run } : {}),
596
651
  }, fn);
597
652
  }
598
653
  function chatTurnBinding(config, taskId, event) {
@@ -815,6 +870,8 @@ async function handleSend(params, config, event) {
815
870
  const verifiedEmail = event?.context?.__a2aVerifiedEmail ?? undefined;
816
871
  const orgDomainHint = event?.context?.__a2aOrgDomain ?? undefined;
817
872
  const requestOrigin = requestOriginForContext(metadata, event);
873
+ const browserTabId = resolveA2ABrowserTabId(metadata, event);
874
+ const viewportMode = resolveA2AViewportMode(metadata, event);
818
875
  const safeMetadata = trustedA2AMetadata(metadata, event);
819
876
  const taskMetadata = {
820
877
  ...(safeMetadata ?? {}),
@@ -828,6 +885,8 @@ async function handleSend(params, config, event) {
828
885
  ? { verifiedOrgId: event.context.__a2aVerifiedOrgId }
829
886
  : {}),
830
887
  ...(requestOrigin ? { requestOrigin } : {}),
888
+ ...(browserTabId ? { browserTabId } : {}),
889
+ ...(viewportMode ? { viewportMode } : {}),
831
890
  contextId: contextId ?? null,
832
891
  callerMetadata: safeMetadata ?? null,
833
892
  sourceContext: sourceContext ?? null,
@@ -8,6 +8,7 @@ import { redactArgsToJson } from "../audit/redact.js";
8
8
  import { extractBearerToken, verifyInternalToken, } from "../integrations/internal-token.js";
9
9
  import { parseServiceIdentityEmail } from "../org/service-identity.js";
10
10
  import { assertServicePrincipalMayRun, recordServicePrincipalDenial, ServicePrincipalRefusedError, } from "../org/service-principal-guard.js";
11
+ import { readBrowserTabIdHeader, readViewportModeHeader, } from "../server/agent-run-context.js";
11
12
  import { getConfiguredAppBasePath } from "../server/app-base-path.js";
12
13
  import { readDeployCredentialEnv } from "../server/credential-provider.js";
13
14
  import { getH3App } from "../server/framework-request-handler.js";
@@ -946,6 +947,14 @@ export function mountA2A(nitroApp, config, routePrefix = "/_agent-native") {
946
947
  event.context.__a2aServicePrincipalAllowedActions =
947
948
  servicePrincipalAllowedActions;
948
949
  }
950
+ const browserTabId = readBrowserTabIdHeader(event);
951
+ if (browserTabId) {
952
+ event.context.__a2aBrowserTabId = browserTabId;
953
+ }
954
+ const viewportMode = readViewportModeHeader(event);
955
+ if (viewportMode) {
956
+ event.context.__a2aViewportMode = viewportMode;
957
+ }
949
958
  const body = await readBody(event);
950
959
  return handleJsonRpcH3(body, event, config);
951
960
  }));
@@ -77,6 +77,15 @@ export declare function actionCallIsRetrySafe(entry: {
77
77
  parameters?: ActionTool["parameters"];
78
78
  };
79
79
  }, params: unknown): boolean;
80
+ /**
81
+ * Whether one call is a write the app made on its own, as the action's
82
+ * `automatic` declaration says for these arguments. The predicate sees the
83
+ * validated arguments and the call's context. One that throws declares
84
+ * nothing, so the call counts as one someone asked for.
85
+ */
86
+ export declare function actionCallIsAutomatic<TInput, TContext>(entry: {
87
+ automatic?: boolean | ((input: TInput, ctx: TContext) => boolean);
88
+ }, params: TInput, ctx: TContext): boolean;
80
89
  /**
81
90
  * Whether a successful call should publish an `action` change event.
82
91
  *
@@ -97,6 +97,24 @@ export function actionCallIsRetrySafe(entry, params) {
97
97
  return false;
98
98
  }
99
99
  }
100
+ /**
101
+ * Whether one call is a write the app made on its own, as the action's
102
+ * `automatic` declaration says for these arguments. The predicate sees the
103
+ * validated arguments and the call's context. One that throws declares
104
+ * nothing, so the call counts as one someone asked for.
105
+ */
106
+ export function actionCallIsAutomatic(entry, params, ctx) {
107
+ const { automatic } = entry;
108
+ if (typeof automatic !== "function")
109
+ return automatic === true;
110
+ try {
111
+ return automatic(params, ctx) === true;
112
+ }
113
+ catch {
114
+ // coercion-ok: an analytics label must not fail the call; unlabeled still counts.
115
+ return false;
116
+ }
117
+ }
100
118
  /**
101
119
  * Whether a successful call should publish an `action` change event.
102
120
  *
@@ -0,0 +1,81 @@
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+ import type { ActionLinkBuilder } from "./action.js";
3
+ /** Keep inline work below the hosted-client budget; durable work is polled. */
4
+ export declare const ACTION_CONFORMANCE_TIMEOUT_MS = 25000;
5
+ export declare const ACTION_CONFORMANCE_RUN_TIMEOUT_MS = 150000;
6
+ export declare const ACTION_CONFORMANCE_SURFACES: readonly ["ui", "mcp", "a2a", "chatgpt", "claude"];
7
+ export type ActionConformanceSurface = (typeof ACTION_CONFORMANCE_SURFACES)[number];
8
+ export interface ConformanceAction {
9
+ schema?: unknown;
10
+ agentInputSchema?: unknown;
11
+ outputSchema?: StandardSchemaV1;
12
+ readOnly?: boolean;
13
+ link?: ActionLinkBuilder;
14
+ }
15
+ export interface ConformanceTool {
16
+ name: string;
17
+ /** Semantic schemas, before transport-specific envelope fields. */
18
+ inputSchema: unknown;
19
+ outputSchema: unknown;
20
+ }
21
+ export interface ConformanceResponse {
22
+ result: unknown;
23
+ openUrl?: string;
24
+ pending?: {
25
+ handle: string;
26
+ /** Poll through the same authenticated client, never re-run the action. */
27
+ poll: (signal: AbortSignal) => Promise<ConformanceResponse>;
28
+ /** Cancel through the authenticated task runner and return a terminal receipt. */
29
+ cancelAndWait?: (signal: AbortSignal) => Promise<ConformanceResponse>;
30
+ };
31
+ }
32
+ export interface ConformanceAdapter {
33
+ list: () => Promise<readonly ConformanceTool[]>;
34
+ call: (name: string, args: unknown, signal: AbortSignal) => Promise<ConformanceResponse>;
35
+ }
36
+ export interface ConformanceFocus {
37
+ route: string;
38
+ pane: string;
39
+ applicationState: unknown;
40
+ }
41
+ export interface ActionConformanceFixture {
42
+ args: Record<string, unknown>;
43
+ /** Create a new owned fixture before each transport calls a write. */
44
+ setup?: (surface: ActionConformanceSurface, signal: AbortSignal) => Promise<void>;
45
+ /** Idempotent: may also compensate setup that settles after its deadline. */
46
+ cleanup?: (surface: ActionConformanceSurface, signal: AbortSignal) => Promise<void>;
47
+ /** Independent UI read, including the displayed content rather than only ids. */
48
+ visibleContent?: (signal: AbortSignal) => Promise<unknown>;
49
+ resultContent?: (result: unknown) => unknown;
50
+ focus?: ConformanceFocus;
51
+ /** Follow the actual link in the app and read the mounted pane and persisted state. */
52
+ open?: (url: string, signal: AbortSignal) => Promise<ConformanceFocus>;
53
+ /** An intentional access boundary must be named; absence means parity is required. */
54
+ excluded?: Partial<Record<ActionConformanceSurface, string>>;
55
+ }
56
+ export interface ActionConformanceFinding {
57
+ app: string;
58
+ action: string;
59
+ surface?: ActionConformanceSurface;
60
+ check: "input-schema" | "output-schema" | "fixture" | "catalog" | "exposure" | "schema-parity" | "result" | "content" | "latency" | "link";
61
+ message: string;
62
+ }
63
+ export interface ActionConformanceReport {
64
+ app: string;
65
+ actions: number;
66
+ calls: number;
67
+ exemptions: number;
68
+ failures: ActionConformanceFinding[];
69
+ }
70
+ export declare function actionContractFindings(app: string, actions: Readonly<Record<string, ConformanceAction>>): ActionConformanceFinding[];
71
+ /** Runs owned fixtures through real client adapters; never executes an un-fixtured action. */
72
+ export declare function checkActionConformance(options: {
73
+ app: string;
74
+ actions: Readonly<Record<string, ConformanceAction>>;
75
+ adapters: Record<ActionConformanceSurface, ConformanceAdapter>;
76
+ fixtures: Readonly<Record<string, ActionConformanceFixture | undefined>>;
77
+ timeoutMs?: number;
78
+ runTimeoutMs?: number;
79
+ maxPolls?: number;
80
+ }): Promise<ActionConformanceReport>;
81
+ export declare function assertActionConformance(report: ActionConformanceReport): void;
@@ -0,0 +1,392 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { inputSchemaToJsonSchema, outputSchemaToJsonSchema, } from "./action-output-contract.js";
3
+ /** Keep inline work below the hosted-client budget; durable work is polled. */
4
+ export const ACTION_CONFORMANCE_TIMEOUT_MS = 25_000;
5
+ export const ACTION_CONFORMANCE_RUN_TIMEOUT_MS = 150_000;
6
+ const POLL_INTERVAL_MS = 250;
7
+ export const ACTION_CONFORMANCE_SURFACES = [
8
+ "ui",
9
+ "mcp",
10
+ "a2a",
11
+ "chatgpt",
12
+ "claude",
13
+ ];
14
+ export function actionContractFindings(app, actions) {
15
+ return Object.entries(actions).flatMap(([action, entry]) => {
16
+ const failures = [];
17
+ if (!isStandardSchema(entry.schema))
18
+ failures.push({
19
+ app,
20
+ action,
21
+ check: "input-schema",
22
+ message: "Missing input schema",
23
+ });
24
+ if (!isStandardSchema(entry.outputSchema))
25
+ failures.push({
26
+ app,
27
+ action,
28
+ check: "output-schema",
29
+ message: "Missing output schema",
30
+ });
31
+ return failures;
32
+ });
33
+ }
34
+ function isStandardSchema(value) {
35
+ return (!!value &&
36
+ typeof value === "object" &&
37
+ "~standard" in value &&
38
+ typeof value["~standard"]?.validate === "function");
39
+ }
40
+ function hasContent(value) {
41
+ if (typeof value === "number")
42
+ return Number.isFinite(value);
43
+ if (typeof value === "boolean")
44
+ return true;
45
+ if (typeof value === "string")
46
+ return value.trim().length > 0;
47
+ if (Array.isArray(value))
48
+ return value.some(hasContent);
49
+ if (!value || typeof value !== "object")
50
+ return false;
51
+ return Object.entries(value).some(([key, item]) => !/^(id|.*Id|.*Ids|url|href|type|kind)$/.test(key) && hasContent(item));
52
+ }
53
+ class DeadlineError extends Error {
54
+ }
55
+ class FixtureCleanupError extends Error {
56
+ }
57
+ async function bounded(work, timeoutMs) {
58
+ if (timeoutMs <= 0)
59
+ throw new DeadlineError("Conformance run budget exceeded");
60
+ const controller = new AbortController();
61
+ let timer;
62
+ try {
63
+ return await Promise.race([
64
+ Promise.resolve().then(() => work(controller.signal)),
65
+ new Promise((_, reject) => {
66
+ timer = setTimeout(() => {
67
+ reject(new DeadlineError("Client response budget exceeded"));
68
+ controller.abort();
69
+ }, timeoutMs);
70
+ }),
71
+ ]);
72
+ }
73
+ finally {
74
+ clearTimeout(timer);
75
+ }
76
+ }
77
+ function waitForPoll(delayMs, signal) {
78
+ return new Promise((resolve, reject) => {
79
+ let timer;
80
+ const onAbort = () => {
81
+ clearTimeout(timer);
82
+ signal.removeEventListener("abort", onAbort);
83
+ reject(new DeadlineError("Client response budget exceeded"));
84
+ };
85
+ if (signal.aborted) {
86
+ onAbort();
87
+ return;
88
+ }
89
+ timer = setTimeout(() => {
90
+ signal.removeEventListener("abort", onAbort);
91
+ resolve();
92
+ }, delayMs);
93
+ signal.addEventListener("abort", onAbort, { once: true });
94
+ });
95
+ }
96
+ /** Runs owned fixtures through real client adapters; never executes an un-fixtured action. */
97
+ export async function checkActionConformance(options) {
98
+ const timeoutMs = options.timeoutMs ?? ACTION_CONFORMANCE_TIMEOUT_MS;
99
+ if (!Number.isFinite(timeoutMs) ||
100
+ timeoutMs <= 0 ||
101
+ timeoutMs > ACTION_CONFORMANCE_TIMEOUT_MS) {
102
+ throw new RangeError("Conformance timeout must be between 0 and 25000 ms");
103
+ }
104
+ const maxPolls = options.maxPolls;
105
+ if (maxPolls !== undefined && (!Number.isInteger(maxPolls) || maxPolls < 1))
106
+ throw new RangeError("maxPolls must be positive");
107
+ const runTimeoutMs = options.runTimeoutMs ?? ACTION_CONFORMANCE_RUN_TIMEOUT_MS;
108
+ if (!Number.isFinite(runTimeoutMs) ||
109
+ runTimeoutMs <= 0 ||
110
+ runTimeoutMs > ACTION_CONFORMANCE_RUN_TIMEOUT_MS) {
111
+ throw new RangeError("Conformance run budget must be between 0 and 150000 ms");
112
+ }
113
+ const runDeadline = performance.now() + runTimeoutMs;
114
+ const workDeadline = runDeadline - Math.min(timeoutMs, runTimeoutMs / 4);
115
+ const runBounded = (work, perOperationMs) => bounded(work, Math.min(perOperationMs, Math.max(0, workDeadline - performance.now())));
116
+ const waitForCleanup = (work) => bounded(work, Math.min(timeoutMs, Math.max(0, runDeadline - performance.now())));
117
+ const report = {
118
+ app: options.app,
119
+ actions: Object.keys(options.actions).length,
120
+ calls: 0,
121
+ exemptions: 0,
122
+ failures: actionContractFindings(options.app, options.actions),
123
+ };
124
+ if (!report.actions)
125
+ report.failures.push({
126
+ app: options.app,
127
+ action: "*",
128
+ check: "fixture",
129
+ message: "No actions registered",
130
+ });
131
+ const catalogs = new Map();
132
+ for (const surface of ACTION_CONFORMANCE_SURFACES) {
133
+ try {
134
+ catalogs.set(surface, await runBounded(() => options.adapters[surface].list(), timeoutMs));
135
+ }
136
+ catch {
137
+ report.failures.push({
138
+ app: options.app,
139
+ action: "*",
140
+ surface,
141
+ check: "catalog",
142
+ message: "Catalog could not be measured",
143
+ });
144
+ }
145
+ }
146
+ for (const [action, entry] of Object.entries(options.actions)) {
147
+ if (performance.now() >= workDeadline)
148
+ break;
149
+ const fixture = options.fixtures[action];
150
+ const fail = (check, message, surface) => {
151
+ report.failures.push({
152
+ app: options.app,
153
+ action,
154
+ ...(surface ? { surface } : {}),
155
+ check,
156
+ message,
157
+ });
158
+ };
159
+ if (!fixture) {
160
+ fail("fixture", "Missing owned fixture; behavior is unmeasured");
161
+ continue;
162
+ }
163
+ if (isStandardSchema(entry.schema)) {
164
+ try {
165
+ const fullInput = entry.schema;
166
+ const validation = await runBounded(async () => fullInput["~standard"].validate(fixture.args), timeoutMs);
167
+ if (validation.issues) {
168
+ fail("input-schema", "Fixture arguments violate the full action schema");
169
+ continue;
170
+ }
171
+ }
172
+ catch {
173
+ fail("input-schema", "Full action input validation failed or exceeded its budget");
174
+ continue;
175
+ }
176
+ }
177
+ let declaredInput;
178
+ let declaredAgentInput;
179
+ let declaredOutput;
180
+ try {
181
+ if (isStandardSchema(entry.schema))
182
+ declaredInput = inputSchemaToJsonSchema(entry.schema);
183
+ const agentInput = entry.agentInputSchema ?? entry.schema;
184
+ if (isStandardSchema(agentInput))
185
+ declaredAgentInput = inputSchemaToJsonSchema(agentInput);
186
+ if (entry.outputSchema)
187
+ declaredOutput = outputSchemaToJsonSchema(entry.outputSchema);
188
+ }
189
+ catch {
190
+ fail("schema-parity", "Declared action schema could not be emitted");
191
+ }
192
+ const semantic = (schema) => {
193
+ if (!schema || typeof schema !== "object" || Array.isArray(schema))
194
+ return schema;
195
+ const { $schema: _dialect, ...contract } = schema;
196
+ return contract;
197
+ };
198
+ for (const surface of ACTION_CONFORMANCE_SURFACES) {
199
+ if (performance.now() >= workDeadline)
200
+ break;
201
+ const catalog = catalogs.get(surface);
202
+ if (!catalog)
203
+ continue;
204
+ const tools = catalog.filter((tool) => tool.name === action);
205
+ const exclusion = fixture.excluded?.[surface];
206
+ if (exclusion !== undefined) {
207
+ if (!exclusion.trim())
208
+ fail("exposure", "Exclusion needs an access-boundary reason", surface);
209
+ else
210
+ report.exemptions++;
211
+ if (tools.length)
212
+ fail("exposure", "Excluded action is exposed", surface);
213
+ continue;
214
+ }
215
+ if (tools.length !== 1) {
216
+ fail("exposure", "Action must be exposed exactly once", surface);
217
+ continue;
218
+ }
219
+ const tool = tools.at(0);
220
+ if (!tool)
221
+ continue;
222
+ const expectedInput = surface === "ui" ? declaredInput : declaredAgentInput;
223
+ if (!tool.inputSchema ||
224
+ !tool.outputSchema ||
225
+ !expectedInput ||
226
+ !declaredOutput ||
227
+ !isDeepStrictEqual(semantic(tool.inputSchema), semantic(expectedInput)) ||
228
+ !isDeepStrictEqual(semantic(tool.outputSchema), semantic(declaredOutput))) {
229
+ fail("schema-parity", "Semantic schemas differ from the declared action contract", surface);
230
+ }
231
+ const agentInput = entry.agentInputSchema ?? entry.schema;
232
+ if (surface !== "ui" && isStandardSchema(agentInput)) {
233
+ try {
234
+ const validated = await runBounded(async () => agentInput["~standard"].validate(fixture.args), timeoutMs);
235
+ if (validated.issues) {
236
+ fail("input-schema", "Fixture arguments violate the agent input schema", surface);
237
+ continue;
238
+ }
239
+ }
240
+ catch {
241
+ fail("input-schema", "Agent input validation failed or exceeded its budget", surface);
242
+ continue;
243
+ }
244
+ }
245
+ let phase = "fixture";
246
+ const pendingOwnedWork = new Set();
247
+ const pendingTasks = new Map();
248
+ const observeResponse = (response, previousHandle) => {
249
+ if (previousHandle)
250
+ pendingTasks.delete(previousHandle);
251
+ if (response.pending)
252
+ pendingTasks.set(response.pending.handle, response.pending);
253
+ return response;
254
+ };
255
+ const trackOwnedWork = (work) => {
256
+ pendingOwnedWork.add(work);
257
+ const settled = () => {
258
+ pendingOwnedWork.delete(work);
259
+ };
260
+ void work.then(settled, settled);
261
+ return work;
262
+ };
263
+ const finalizeFixture = async () => {
264
+ const attempted = new Set();
265
+ const cancelKnownTasks = async () => {
266
+ await Promise.allSettled([...pendingTasks].map(async ([handle, task]) => {
267
+ if (attempted.has(task))
268
+ return;
269
+ attempted.add(task);
270
+ const cancel = task.cancelAndWait;
271
+ if (!cancel)
272
+ throw new FixtureCleanupError("Missing durable cancellation");
273
+ const terminal = await bounded((signal) => cancel.call(task, signal), timeoutMs);
274
+ if (terminal.pending)
275
+ throw new FixtureCleanupError("Cancellation is not terminal");
276
+ if (pendingTasks.get(handle) === task)
277
+ pendingTasks.delete(handle);
278
+ }));
279
+ };
280
+ await cancelKnownTasks();
281
+ await Promise.allSettled([...pendingOwnedWork]);
282
+ await cancelKnownTasks();
283
+ if (pendingTasks.size)
284
+ throw new FixtureCleanupError("Durable task remains live; fixture cleanup is unconfirmed");
285
+ await bounded(async (signal) => fixture.cleanup?.(surface, signal), timeoutMs);
286
+ };
287
+ try {
288
+ await runBounded((signal) => trackOwnedWork(Promise.resolve().then(() => fixture.setup?.(surface, signal))), timeoutMs);
289
+ phase = "result";
290
+ report.calls++;
291
+ let response = await runBounded((signal) => trackOwnedWork(options.adapters[surface]
292
+ .call(action, fixture.args, signal)
293
+ .then((response) => observeResponse(response))), timeoutMs);
294
+ let nextPollAt = performance.now();
295
+ for (let poll = 0; response.pending && (maxPolls === undefined || poll < maxPolls); poll++) {
296
+ const pending = response.pending;
297
+ if (!pending.handle.trim())
298
+ throw new Error("Missing pending handle");
299
+ const delayMs = nextPollAt - performance.now();
300
+ if (delayMs > 0)
301
+ await runBounded((signal) => waitForPoll(Math.ceil(delayMs), signal), workDeadline - performance.now());
302
+ response = await runBounded((signal) => {
303
+ nextPollAt = performance.now() + POLL_INTERVAL_MS;
304
+ return trackOwnedWork(pending
305
+ .poll(signal)
306
+ .then((response) => observeResponse(response, pending.handle)));
307
+ }, timeoutMs);
308
+ }
309
+ if (response.pending) {
310
+ fail("latency", "Durable task did not reach a terminal result", surface);
311
+ continue;
312
+ }
313
+ const outputSchema = entry.outputSchema;
314
+ if (outputSchema) {
315
+ const validated = await runBounded(async () => outputSchema["~standard"].validate(response.result), timeoutMs);
316
+ if (validated.issues)
317
+ fail("result", "Result violates output schema", surface);
318
+ }
319
+ if (entry.readOnly) {
320
+ const visibleContent = fixture.visibleContent;
321
+ if (!visibleContent || !fixture.resultContent)
322
+ fail("fixture", "Read needs an independent visible-content oracle", surface);
323
+ else {
324
+ phase = "content";
325
+ const visible = await runBounded((signal) => visibleContent(signal), timeoutMs);
326
+ if (!hasContent(visible))
327
+ fail("content", "Visible-content fixture is empty or id-only", surface);
328
+ else if (!isDeepStrictEqual(fixture.resultContent(response.result), visible))
329
+ fail("content", "Read result omits or changes UI content", surface);
330
+ }
331
+ }
332
+ phase = "link";
333
+ const link = entry.link?.({
334
+ args: fixture.args,
335
+ result: response.result,
336
+ });
337
+ const url = response.openUrl ?? link?.url;
338
+ if (entry.link || url || fixture.focus) {
339
+ if (!url || !fixture.open || !fixture.focus)
340
+ fail("link", "Link needs a route, pane and application-state oracle", surface);
341
+ else if (!isDeepStrictEqual(await runBounded((signal) => fixture.open
342
+ ? fixture.open(url, signal)
343
+ : Promise.reject(new Error("Missing route adapter")), timeoutMs), fixture.focus)) {
344
+ fail("link", "Link opens the wrong route, pane or application state", surface);
345
+ }
346
+ }
347
+ }
348
+ catch (error) {
349
+ fail(error instanceof DeadlineError && phase === "result"
350
+ ? "latency"
351
+ : phase, error instanceof DeadlineError
352
+ ? "Client response budget exceeded"
353
+ : "Fixture call failed; inspect the adapter's diagnostics", surface);
354
+ }
355
+ finally {
356
+ const finalization = finalizeFixture();
357
+ try {
358
+ await waitForCleanup(() => finalization);
359
+ }
360
+ catch (error) {
361
+ fail("fixture", error instanceof DeadlineError
362
+ ? "Owned work did not settle; cleanup remains unconfirmed"
363
+ : error instanceof FixtureCleanupError
364
+ ? error.message
365
+ : "Owned fixture cleanup failed", surface);
366
+ if (error instanceof DeadlineError)
367
+ void finalization.catch(() => {
368
+ console.error("Late owned-fixture cleanup failed", {
369
+ app: options.app,
370
+ action,
371
+ surface,
372
+ });
373
+ });
374
+ }
375
+ }
376
+ }
377
+ }
378
+ if (performance.now() >= workDeadline)
379
+ report.failures.push({
380
+ app: options.app,
381
+ action: "*",
382
+ check: "latency",
383
+ message: "Conformance run budget exceeded; remaining behavior is unmeasured",
384
+ });
385
+ return report;
386
+ }
387
+ export function assertActionConformance(report) {
388
+ if (report.failures.length)
389
+ throw new Error(report.failures
390
+ .map((failure) => `${failure.app}/${failure.action}${failure.surface ? ` [${failure.surface}]` : ""} ${failure.check}: ${failure.message}`)
391
+ .join("\n"));
392
+ }