@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
@@ -4,9 +4,20 @@ import { assertAgentNativeApiEnabled } from "./api-surface.js";
4
4
  import { getBrowserTabId, isBrowserTabIdForCurrentDocument, } from "./browser-tab-id.js";
5
5
  import { availableKeepaliveBytes, reserveKeepaliveBytes, } from "./keepalive-budget.js";
6
6
  import { recordStateWrite } from "./recorder.js";
7
+ import { currentSessionScope } from "./session-identity.js";
7
8
  const APP_STATE_KEY_PATTERN = /^[a-zA-Z0-9_:-]+$/;
9
+ const CORE_BEFORE_TURN_STATE_KEYS = [
10
+ "navigation",
11
+ "__url__",
12
+ "pending-selection-context",
13
+ "selection",
14
+ ];
8
15
  const pendingMutations = new Map();
16
+ const pendingTurnMutations = new Map();
17
+ const beforeTurnContexts = new WeakMap();
9
18
  const mutationRevisions = new Map();
19
+ const requestSessionIds = new WeakMap();
20
+ let nextRequestSessionId = 0;
10
21
  function appStateUrl(key) {
11
22
  if (!APP_STATE_KEY_PATTERN.test(key)) {
12
23
  throw new TypeError("Application state keys may only contain letters, numbers, underscores, hyphens, and colons.");
@@ -58,43 +69,190 @@ function browserTabHeaders() {
58
69
  // Identifies the server row a key reaches, so writes and reads through
59
70
  // `navigation` and through `navigation:<this tab>` wait on each other.
60
71
  function requestKey(key) {
61
- if (typeof window === "undefined")
62
- return `:${key}`;
63
- const tab = getBrowserTabId();
64
- return `${tab}:${TAB_SCOPED_APP_STATE_KEYS.has(key) ? `${key}:${tab}` : key}`;
72
+ const session = currentSessionScope();
73
+ let sessionId = requestSessionIds.get(session);
74
+ if (sessionId === undefined) {
75
+ sessionId = ++nextRequestSessionId;
76
+ requestSessionIds.set(session, sessionId);
77
+ }
78
+ const tab = typeof window === "undefined" ? null : getBrowserTabId();
79
+ const storageKey = tab && TAB_SCOPED_APP_STATE_KEYS.has(key) ? `${key}:${tab}` : key;
80
+ return JSON.stringify([
81
+ sessionId,
82
+ agentNativePath("/_agent-native/application-state"),
83
+ tab,
84
+ storageKey,
85
+ ]);
86
+ }
87
+ function appStateTurnScope() {
88
+ return JSON.stringify([
89
+ agentNativePath("/_agent-native/application-state"),
90
+ typeof window === "undefined" ? null : getBrowserTabId(),
91
+ ]);
92
+ }
93
+ function currentBeforeTurnContext() {
94
+ const session = currentSessionScope();
95
+ let contexts = beforeTurnContexts.get(session);
96
+ if (!contexts) {
97
+ contexts = new Map();
98
+ beforeTurnContexts.set(session, contexts);
99
+ }
100
+ const scope = appStateTurnScope();
101
+ let context = contexts.get(scope);
102
+ if (!context) {
103
+ const coreKeys = new Set();
104
+ const tab = typeof window === "undefined" ? undefined : getBrowserTabId();
105
+ for (const key of CORE_BEFORE_TURN_STATE_KEYS) {
106
+ coreKeys.add(requestKey(key));
107
+ if (tab)
108
+ coreKeys.add(requestKey(`${key}:${tab}`));
109
+ }
110
+ context = {
111
+ states: new Map(),
112
+ coreKeys,
113
+ requiredKeys: new Map(),
114
+ flushers: new Set(),
115
+ };
116
+ contexts.set(scope, context);
117
+ }
118
+ return context;
119
+ }
120
+ /** Keep app-owned context required while its editor or view is mounted. */
121
+ export function registerBeforeAgentTurnStateKeys(keys) {
122
+ for (const key of keys)
123
+ appStateUrl(key);
124
+ const context = currentBeforeTurnContext();
125
+ const ids = [...new Set(keys.map(requestKey))];
126
+ for (const id of ids)
127
+ context.requiredKeys.set(id, (context.requiredKeys.get(id) ?? 0) + 1);
128
+ let registered = true;
129
+ return () => {
130
+ if (!registered)
131
+ return;
132
+ registered = false;
133
+ for (const id of ids) {
134
+ const count = context.requiredKeys.get(id) ?? 0;
135
+ if (count <= 1)
136
+ context.requiredKeys.delete(id);
137
+ else
138
+ context.requiredKeys.set(id, count - 1);
139
+ }
140
+ };
141
+ }
142
+ /** Register deferred UI state or editor saves that must precede a new turn. */
143
+ export function registerBeforeAgentTurnFlush(flush) {
144
+ const context = currentBeforeTurnContext();
145
+ context.flushers.add(flush);
146
+ return () => {
147
+ context.flushers.delete(flush);
148
+ };
149
+ }
150
+ /**
151
+ * Await all in-flight writes. Retained failures gate core context and keys
152
+ * registered by a mounted owner. Custom keys opt in with
153
+ * registerBeforeAgentTurnStateKeys; owner flushers perform recovery.
154
+ * Failed writes are never replayed without their owner's intent and fencing.
155
+ */
156
+ export async function flushClientAppStateBeforeAgentTurn(signal) {
157
+ const context = currentBeforeTurnContext();
158
+ const pendingInScope = () => [...pendingTurnMutations]
159
+ .filter(([, mutationContext]) => mutationContext === context)
160
+ .map(([mutation]) => mutation);
161
+ const deadline = new AbortController();
162
+ const timer = setTimeout(() => deadline.abort(new Error("Application state save timed out")), 25_000);
163
+ const boundedSignal = signal
164
+ ? AbortSignal.any([signal, deadline.signal])
165
+ : deadline.signal;
166
+ try {
167
+ boundedSignal.throwIfAborted();
168
+ const inFlight = pendingInScope();
169
+ await awaitWithAbort(Promise.all([
170
+ ...inFlight,
171
+ ...[...context.flushers].map((flush) => Promise.resolve().then(() => {
172
+ if (currentBeforeTurnContext() !== context) {
173
+ throw new Error("Application state scope changed before the agent turn");
174
+ }
175
+ if (context.flushers.has(flush))
176
+ return flush();
177
+ })),
178
+ ]), boundedSignal);
179
+ while (pendingInScope().length > 0) {
180
+ await awaitWithAbort(Promise.all(pendingInScope()), boundedSignal);
181
+ }
182
+ if (currentBeforeTurnContext() !== context) {
183
+ throw new Error("Application state scope changed before the agent turn");
184
+ }
185
+ for (const [id, state] of context.states) {
186
+ if (state.failure &&
187
+ (context.coreKeys.has(id) || context.requiredKeys.has(id))) {
188
+ throw state.failure.error;
189
+ }
190
+ }
191
+ }
192
+ finally {
193
+ clearTimeout(timer);
194
+ }
65
195
  }
66
196
  export function isClientAppStateMutationPending(key) {
67
197
  return pendingMutations.has(requestKey(key));
68
198
  }
69
- function runClientAppStateMutation(key, operation) {
199
+ function runClientAppStateMutation(key, operation, saved = () => true, startedOperation) {
70
200
  const id = requestKey(key);
201
+ const context = currentBeforeTurnContext();
202
+ const state = context.states.get(id) ?? {
203
+ savedRevision: 0,
204
+ };
205
+ context.states.set(id, state);
71
206
  const previous = pendingMutations.get(id);
72
207
  // A later write must not fold into one queued before this mutation.
73
208
  queuedReplacements.delete(id);
74
- mutationRevisions.set(id, (mutationRevisions.get(id) ?? 0) + 1);
209
+ const revision = (mutationRevisions.get(id) ?? 0) + 1;
210
+ mutationRevisions.set(id, revision);
75
211
  const mutation = (async () => {
76
212
  if (previous)
77
213
  await previous;
214
+ const underway = startedOperation?.();
215
+ if (underway)
216
+ return underway;
217
+ if (currentBeforeTurnContext() !== context) {
218
+ throw new Error("Application state scope changed before saving");
219
+ }
78
220
  return operation();
79
221
  })();
222
+ pendingTurnMutations.set(mutation, context);
80
223
  let pending;
81
224
  const clearPending = () => {
225
+ pendingTurnMutations.delete(mutation);
82
226
  if (pendingMutations.get(id) === pending) {
83
227
  pendingMutations.delete(id);
84
228
  }
85
229
  };
86
- pending = mutation.then(clearPending, clearPending);
230
+ pending = mutation.then((result) => {
231
+ clearPending();
232
+ if (saved(result)) {
233
+ state.savedRevision = Math.max(state.savedRevision, revision);
234
+ if (state.failure && state.failure.revision <= state.savedRevision) {
235
+ delete state.failure;
236
+ }
237
+ }
238
+ }, (error) => {
239
+ clearPending();
240
+ if (revision > state.savedRevision &&
241
+ revision >= (state.failure?.revision ?? 0)) {
242
+ state.failure = { revision, error };
243
+ }
244
+ });
87
245
  pendingMutations.set(id, pending);
88
246
  return mutation;
89
247
  }
90
248
  const unsettledBarriers = new Map();
91
- function runBarrierMutation(key, operation) {
249
+ function runBarrierMutation(key, operation, saved) {
92
250
  const id = requestKey(key);
93
251
  const barrier = { settled: false };
94
252
  const barriers = unsettledBarriers.get(id) ?? new Set();
95
253
  barriers.add(barrier);
96
254
  unsettledBarriers.set(id, barriers);
97
- const mutation = runClientAppStateMutation(key, operation);
255
+ const mutation = runClientAppStateMutation(key, operation, saved);
98
256
  const settle = () => {
99
257
  barrier.settled = true;
100
258
  barriers.delete(barrier);
@@ -107,18 +265,26 @@ function runBarrierMutation(key, operation) {
107
265
  }
108
266
  const waitingOwnRequests = new Set();
109
267
  function runOwnRequestMutation(key, keepalive, operation) {
268
+ const context = currentBeforeTurnContext();
110
269
  let started;
111
270
  const waiting = {
112
271
  keepalive,
113
272
  barriersAhead: [...(unsettledBarriers.get(requestKey(key)) ?? [])],
114
273
  start: () => {
115
274
  waitingOwnRequests.delete(waiting);
116
- return (started ??= operation());
275
+ return (started ??=
276
+ currentBeforeTurnContext() === context
277
+ ? operation()
278
+ : Promise.reject(new Error("Application state scope changed before saving")));
117
279
  },
118
280
  };
119
281
  waitingOwnRequests.add(waiting);
120
282
  watchPageHide();
121
- const mutation = runClientAppStateMutation(key, () => waiting.start());
283
+ const mutation = runClientAppStateMutation(key, () => waiting.start(), undefined, () => started);
284
+ const forget = () => {
285
+ waitingOwnRequests.delete(waiting);
286
+ };
287
+ mutation.then(forget, forget);
122
288
  if (pageIsHiding())
123
289
  startWaitingOwnRequest(waiting);
124
290
  return mutation;
@@ -191,11 +357,13 @@ function mergeReplacement(id, target, replacement) {
191
357
  function replaceClientAppState(key, replacement) {
192
358
  appStateUrl(key);
193
359
  const id = requestKey(key);
360
+ const context = currentBeforeTurnContext();
194
361
  const queued = queuedReplacements.get(id);
195
- if (queued)
362
+ if (queued?.context === context)
196
363
  return mergeReplacement(id, queued, replacement);
197
364
  const inFlight = inFlightReplacements.get(id);
198
- if (inFlight && inFlight.pending === pendingMutations.get(id)) {
365
+ if (inFlight?.context === context &&
366
+ inFlight.pending === pendingMutations.get(id)) {
199
367
  // Not sent yet: it can still carry this value instead.
200
368
  if (!inFlight.sent)
201
369
  return mergeReplacement(id, inFlight, replacement);
@@ -208,6 +376,8 @@ function replaceClientAppState(key, replacement) {
208
376
  }
209
377
  const entry = {
210
378
  key,
379
+ id,
380
+ context,
211
381
  replacement,
212
382
  started: false,
213
383
  sent: false,
@@ -225,7 +395,7 @@ function replaceClientAppState(key, replacement) {
225
395
  function startReplacement(entry) {
226
396
  if (entry.running)
227
397
  return entry.running;
228
- const id = requestKey(entry.key);
398
+ const id = entry.id;
229
399
  entry.started = true;
230
400
  if (queuedReplacements.get(id) === entry)
231
401
  queuedReplacements.delete(id);
@@ -295,7 +465,7 @@ function flushOnPageHide() {
295
465
  startWaitingOwnRequest(waiting);
296
466
  }
297
467
  for (const entry of [...queuedReplacements.values()]) {
298
- if (unsettledBarriers.has(requestKey(entry.key)))
468
+ if (unsettledBarriers.has(entry.id))
299
469
  continue;
300
470
  if (entry.replacement.keepalive) {
301
471
  // Its caller hears how it went through entry.result, once the earlier
@@ -340,14 +510,23 @@ function flushReplacements() {
340
510
  sendChunk(chunk, true);
341
511
  }
342
512
  function sendChunk(chunk, keepalive) {
343
- if (chunk.length === 1 ||
513
+ const context = currentBeforeTurnContext();
514
+ const eligible = chunk.filter((entry) => {
515
+ if (entry.context === context)
516
+ return true;
517
+ entry.settle?.reject(new Error("Application state scope changed before saving"));
518
+ return false;
519
+ });
520
+ if (eligible.length === 0)
521
+ return;
522
+ if (eligible.length === 1 ||
344
523
  batchWritesUnsupported ||
345
524
  (pageIsHiding() && !batchRouteConfirmed)) {
346
- for (const entry of chunk)
525
+ for (const entry of eligible)
347
526
  sendEach(entry, keepalive);
348
527
  }
349
528
  else {
350
- void sendBatch(chunk, keepalive);
529
+ void sendBatch(eligible, keepalive);
351
530
  }
352
531
  }
353
532
  function sendEach(entry, keepalive) {
@@ -466,6 +645,9 @@ function isBatchWriteResult(value) {
466
645
  typeof result.error === "string"));
467
646
  }
468
647
  async function sendReplacement(entry, wantKeepalive) {
648
+ if (entry.context !== currentBeforeTurnContext()) {
649
+ throw new Error("Application state scope changed before saving");
650
+ }
469
651
  const { key } = entry;
470
652
  const { method, body, requestSource, keepalive: asked } = entry.replacement;
471
653
  const order = writeOrderHeaders(entry.seq);
@@ -543,6 +725,12 @@ function jsonBody(value) {
543
725
  const MAX_BATCH_KEYS = 100;
544
726
  export async function readClientAppStateMany(keys, options = {}) {
545
727
  assertAgentNativeApiEnabled(`read application state [${keys.join(", ")}]`);
728
+ const context = currentBeforeTurnContext();
729
+ const assertScope = () => {
730
+ if (currentBeforeTurnContext() !== context) {
731
+ throw new Error("Application state scope changed before reading");
732
+ }
733
+ };
546
734
  const unique = [...new Set(keys)];
547
735
  for (const key of unique)
548
736
  appStateUrl(key);
@@ -558,6 +746,7 @@ export async function readClientAppStateMany(keys, options = {}) {
558
746
  return mutation ? [mutation] : [];
559
747
  });
560
748
  await awaitWithAbort(Promise.all(pending), options.signal);
749
+ assertScope();
561
750
  if (unique.some((key) => {
562
751
  const id = requestKey(key);
563
752
  return revisions.get(id) !== (mutationRevisions.get(id) ?? 0);
@@ -581,6 +770,7 @@ export async function readClientAppStateMany(keys, options = {}) {
581
770
  if (!batch || typeof batch !== "object" || !batch.values) {
582
771
  throw new Error(`Read application state [${chunk.join(", ")}] returned an unexpected payload.`);
583
772
  }
773
+ assertScope();
584
774
  Object.assign(merged.values, batch.values);
585
775
  merged.missing.push(...(batch.missing ?? []));
586
776
  }
@@ -594,18 +784,24 @@ export async function readClientAppStateMany(keys, options = {}) {
594
784
  }
595
785
  let pendingBatch;
596
786
  function scheduleBatchedRead(key) {
597
- if (pendingBatch) {
787
+ const context = currentBeforeTurnContext();
788
+ if (pendingBatch?.context === context) {
598
789
  pendingBatch.keys.add(key);
599
790
  return pendingBatch.promise;
600
791
  }
601
792
  const keys = new Set([key]);
602
793
  const promise = new Promise((resolve, reject) => {
603
794
  setTimeout(() => {
604
- pendingBatch = undefined;
795
+ if (pendingBatch?.promise === promise)
796
+ pendingBatch = undefined;
797
+ if (currentBeforeTurnContext() !== context) {
798
+ reject(new Error("Application state scope changed before reading"));
799
+ return;
800
+ }
605
801
  readClientAppStateMany([...keys]).then(resolve, reject);
606
802
  }, 0);
607
803
  });
608
- pendingBatch = { keys, promise };
804
+ pendingBatch = { keys, promise, context };
609
805
  return promise;
610
806
  }
611
807
  function awaitWithAbort(promise, signal) {
@@ -699,11 +895,11 @@ export async function compareAndSetClientAppState(key, expected, next, options =
699
895
  keepalive.release();
700
896
  }
701
897
  const result = await parseAppStateResponse(response, `Compare application state \"${key}\"`);
702
- if (typeof result?.changed !== "boolean") {
898
+ if (typeof result.changed !== "boolean") {
703
899
  throw new Error(`Compare application state \"${key}\" returned an unexpected payload.`);
704
900
  }
705
901
  return result.changed;
706
- });
902
+ }, (changed) => changed);
707
903
  }
708
904
  export async function deleteClientAppState(key, options = {}) {
709
905
  assertAgentNativeApiEnabled(`delete application state "${key}"`);
@@ -1,5 +1,5 @@
1
1
  import { AgentKitRunSlotBusyError, createAgentThreadState, reduceAgentEvent, } from "@agent-native/agentkit/client";
2
- import { AGENT_NATIVE_SUBMISSION_DEADLINES_CAPABILITY_ID, createCapabilityUnavailableError, createCapabilityUnsupportedError, agentEventSequenceEnd, isAgentKitProtocolVersion, negotiateAgentKitProtocolVersion, parseAgentQueuedMessage, parseForkThreadInput, parseNullableAgentQueuedSubmissionStatus, parseAgentRunOptions, parseAgentThreadSnapshot, persistableFilePart, } from "@agent-native/agentkit/protocol";
2
+ import { AGENT_NATIVE_SUBMISSION_DEADLINES_CAPABILITY_ID, createCapabilityUnavailableError, createCapabilityUnsupportedError, agentEventSequenceEnd, isAgentKitProtocolVersion, negotiateAgentKitProtocolVersion, parseAgentQueuedMessage, parseForkThreadInput, parseNullableAgentQueuedSubmissionStatus, parseAgentRunOptions, parseAgentThreadSnapshot, parseAgentToolCall, persistableFilePart, } from "@agent-native/agentkit/protocol";
3
3
  import { failedRunIdsWithError, isRenderedRunNotStartedNotice, projectRootAssistantMessages, } from "../../agent/thread-message-projection.js";
4
4
  import { RUN_NOT_STARTED_METADATA_KEY, retryContextFromRequest, } from "../../shared/agent-chat-run-not-started.js";
5
5
  import { AGENT_CHAT_THREAD_ABSENCE_HEADER } from "../../shared/agent-chat.js";
@@ -7,6 +7,7 @@ import { assertNoInlineImageBytes, stripInlineBytes, } from "../../shared/inline
7
7
  import { toolInputFingerprint } from "../../shared/tool-inputs.js";
8
8
  import { agentEngineStatusUrlForChatApi, requireAgentEngineConfiguredForDispatch, } from "../agent-engine-readiness.js";
9
9
  import { agentNativePath } from "../api-path.js";
10
+ import { flushClientAppStateBeforeAgentTurn } from "../application-state.js";
10
11
  import { CHAT_CAPABILITY_UNAVAILABLE_MESSAGE, CHAT_CAPABILITY_UNSUPPORTED_MESSAGE, CHAT_REQUEST_TOO_LARGE_MESSAGE, formatChatErrorText, } from "../error-format.js";
11
12
  import { dispatchAgentChatRunning } from "../use-agent-chat-running-threads.js";
12
13
  import { appendChatThreadScopeParams, } from "../use-chat-threads.js";
@@ -2651,11 +2652,48 @@ export function createAgentNativeAgentKitTransport(options = {}) {
2651
2652
  ? mergeStoredAndIncomingMessages(storedMessageProjection, agentKitMessages)
2652
2653
  : (messagesWithLegacyRoot ?? agentKitMessages)
2653
2654
  : storedMessageProjection,
2654
- events: agentKit.events,
2655
+ events: Array.isArray(agentKit.events)
2656
+ ? agentKit.events.map((value) => {
2657
+ const event = asRecord(value);
2658
+ if (event?.omitFromPersistedHistory === true &&
2659
+ (((event.type === "activity.started" ||
2660
+ event.type === "activity.updated" ||
2661
+ event.type === "activity.completed") &&
2662
+ !Object.hasOwn(event, "activity")) ||
2663
+ (event.type === "message.completed" &&
2664
+ !Object.hasOwn(event, "message")) ||
2665
+ (event.type === "x-agent-native.persisted-event-omission" &&
2666
+ !Object.hasOwn(event, "payload")))) {
2667
+ return {
2668
+ id: event.id,
2669
+ threadId: event.threadId,
2670
+ runId: event.runId,
2671
+ sequence: event.sequence,
2672
+ occurredAt: event.occurredAt,
2673
+ ...(Object.hasOwn(event, "metadata")
2674
+ ? { metadata: event.metadata }
2675
+ : {}),
2676
+ type: "x-agent-native.persisted-event-omission",
2677
+ payload: { sourceType: event.type },
2678
+ };
2679
+ }
2680
+ return value;
2681
+ })
2682
+ : agentKit.events,
2655
2683
  runs: agentKit.runs,
2656
2684
  activeRunIds: agentKit.activeRunIds,
2657
2685
  suggestions: agentKit.suggestions,
2658
- toolCalls: agentKit.toolCalls,
2686
+ toolCalls: Array.isArray(agentKit.toolCalls)
2687
+ ? agentKit.toolCalls.filter((value, index) => {
2688
+ const toolCall = asRecord(value);
2689
+ if (toolCall?.omitFromPersistedHistory === true &&
2690
+ !Object.hasOwn(toolCall, "name")) {
2691
+ parseAgentToolCall({ ...toolCall, name: "redacted" }, `threadSnapshot.toolCalls[${index}]`);
2692
+ return false;
2693
+ }
2694
+ return true;
2695
+ })
2696
+ : agentKit.toolCalls,
2659
2697
  activities: agentKit.activities,
2660
2698
  widgets: agentKit.widgets,
2661
2699
  annotations: agentKit.annotations,
@@ -3697,7 +3735,7 @@ export function createAgentNativeAgentKitTransport(options = {}) {
3697
3735
  : null;
3698
3736
  throw new AgentKitRunSlotBusyError(localRun?.id ?? activeRunId);
3699
3737
  }
3700
- async function startRunTrackingRunningState(input, context) {
3738
+ async function startRunTrackingRunningState(input, context, beforeSubmit) {
3701
3739
  dispatchAgentChatRunning({
3702
3740
  isRunning: true,
3703
3741
  phase: "working",
@@ -3705,7 +3743,7 @@ export function createAgentNativeAgentKitTransport(options = {}) {
3705
3743
  tabId: input.threadId,
3706
3744
  });
3707
3745
  try {
3708
- const run = await startRun(input, context);
3746
+ const run = await startRun(input, context, beforeSubmit);
3709
3747
  if (!run.runId) {
3710
3748
  dispatchAgentChatRunning({
3711
3749
  isRunning: false,
@@ -3823,10 +3861,6 @@ export function createAgentNativeAgentKitTransport(options = {}) {
3823
3861
  const waitedTooLong = Date.now() - firstSeen >= RECEIPT_QUEUED_TAKEOVER_MS;
3824
3862
  if (seen < RECEIPT_QUEUED_TAKEOVER_ATTEMPTS && !waitedTooLong)
3825
3863
  throw busy();
3826
- await persistQueueMutation(threadId, { type: "remove", messageId });
3827
- receiptQueuedWaits.delete(seenKey);
3828
- receiptQueuedFirstSeen.delete(seenKey);
3829
- clearPromotionClaimId(threadId, messageId);
3830
3864
  const latest = (await snapshot(threadId)) ?? thread;
3831
3865
  const run = await startRunTrackingRunningState({
3832
3866
  threadId,
@@ -3853,7 +3887,12 @@ export function createAgentNativeAgentKitTransport(options = {}) {
3853
3887
  : { references: queued.references }),
3854
3888
  ...(queued.options === undefined ? {} : { options: queued.options }),
3855
3889
  ...(queued.metadata === undefined ? {} : { metadata: queued.metadata }),
3856
- }, undefined);
3890
+ }, undefined, async () => {
3891
+ await persistQueueMutation(threadId, { type: "remove", messageId });
3892
+ receiptQueuedWaits.delete(seenKey);
3893
+ receiptQueuedFirstSeen.delete(seenKey);
3894
+ clearPromotionClaimId(threadId, messageId);
3895
+ });
3857
3896
  if (!run.runId) {
3858
3897
  throw new TypeError("A queue promotion cannot be acknowledged as a new queued submission.");
3859
3898
  }
@@ -4465,8 +4504,10 @@ export function createAgentNativeAgentKitTransport(options = {}) {
4465
4504
  // coercion-ok: telemetry must never change how a start fails.
4466
4505
  }
4467
4506
  };
4468
- const startRun = async (input, context) => {
4507
+ const startRun = async (input, context, beforeSubmit) => {
4469
4508
  try {
4509
+ await flushClientAppStateBeforeAgentTurn(context?.signal);
4510
+ await beforeSubmit?.();
4470
4511
  return await protocolStartRun(input, context);
4471
4512
  }
4472
4513
  catch (error) {
@@ -4,7 +4,7 @@ import { AUTO_CONTINUE_OF_RUN_METADATA_KEY, AUTO_CONTINUE_PROMPT, AUTO_CONTINUE_
4
4
  import { RUN_CODE_TOOL_NAME, runCodeResultFailure, } from "../../coding-tools/run-code-result.js";
5
5
  import { isPersistableAttachmentUrl } from "../../shared/attachments.js";
6
6
  import { parseBase64DataUrl } from "../../shared/data-url.js";
7
- import { emitChatFirstOpenApp, emitChatFirstOpenBrowser, } from "../chat-first-state.js";
7
+ import { emitChatFirstOpenApp, emitChatFirstOpenAppStart, emitChatFirstOpenBrowser, } from "../chat-first-state.js";
8
8
  import { toolDisplayName } from "../tool-display.js";
9
9
  import { decideAfterStreamClosed, runOutcomeForCode, transition, } from "./run-outcome.js";
10
10
  function isRunTerminal(run) {
@@ -2711,6 +2711,27 @@ export function createAgentKitProtocolAdapter(runtime, options = {}) {
2711
2711
  }
2712
2712
  }
2713
2713
  function dispatchChatFirstOpenFromRuntimeEvent(event) {
2714
+ const readString = (value) => typeof value === "string" && value.trim() ? value.trim() : undefined;
2715
+ if (event.type === "tool-start" && event.toolCall.name === "open_app") {
2716
+ const input = asRecord(event.toolCall.input);
2717
+ if (!input)
2718
+ return;
2719
+ const app = readString(input.app ?? input.appId ?? input.application);
2720
+ const url = readString(input.url ?? input.href);
2721
+ if (!app && !url)
2722
+ return;
2723
+ const path = readString(input.path ?? input.targetPath);
2724
+ const view = readString(input.view);
2725
+ emitChatFirstOpenAppStart({
2726
+ ...(app ? { app } : {}),
2727
+ ...(path ? { path } : {}),
2728
+ ...(url ? { url } : {}),
2729
+ ...(view ? { view } : {}),
2730
+ ...(input.focus === true ? { focus: true } : {}),
2731
+ optimistic: true,
2732
+ });
2733
+ return;
2734
+ }
2714
2735
  if (event.type !== "tool-done" ||
2715
2736
  event.status !== "completed" ||
2716
2737
  (event.toolName !== "open_app" && event.toolName !== "open_browser")) {
@@ -2729,7 +2750,6 @@ export function createAgentKitProtocolAdapter(runtime, options = {}) {
2729
2750
  console.warn(`[chat-first] ${event.toolName} completed without a readable result`);
2730
2751
  return;
2731
2752
  }
2732
- const readString = (value) => typeof value === "string" && value.trim() ? value : undefined;
2733
2753
  const delivery = event.toolName === "open_browser"
2734
2754
  ? emitChatFirstOpenBrowser({
2735
2755
  url: readString(result.url ?? result.href),
@@ -2740,6 +2760,7 @@ export function createAgentKitProtocolAdapter(runtime, options = {}) {
2740
2760
  path: readString(result.path ?? result.targetPath),
2741
2761
  url: readString(result.url ?? result.href),
2742
2762
  view: readString(result.view),
2763
+ ...(result.focus === true ? { focus: true } : {}),
2743
2764
  });
2744
2765
  if (!delivery.delivered) {
2745
2766
  console.warn(`[chat-first] ${event.toolName} was completed but not delivered (${delivery.reason ?? "unknown"})`);
@@ -5,6 +5,7 @@ export declare const CHAT_FIRST_SURFACE_WIDTH_STORAGE_KEY = "agent-native:chat-f
5
5
  export declare const CHAT_FIRST_SURFACE_PANEL_STORAGE_KEY = "agent-native:chat-first-surface-panel:v1";
6
6
  export declare const CHAT_FIRST_MODE_CHANGED_EVENT = "agentNative:chatFirstModeChanged";
7
7
  export declare const CHAT_FIRST_OPEN_APP_EVENT = "agentNative:openApp";
8
+ export declare const CHAT_FIRST_OPEN_APP_START_EVENT = "agentNative:openAppStart";
8
9
  export declare const CHAT_FIRST_OPEN_BROWSER_EVENT = "agentNative:openBrowser";
9
10
  export declare const CHAT_FIRST_WATCH_SESSION_EVENT = "agentNative:watchSession";
10
11
  export type ChatFirstOpenAppDetail = {
@@ -12,6 +13,9 @@ export type ChatFirstOpenAppDetail = {
12
13
  path?: string;
13
14
  url?: string;
14
15
  view?: string;
16
+ focus?: boolean;
17
+ optimistic?: boolean;
18
+ turnId?: string;
15
19
  };
16
20
  export type ChatFirstOpenBrowserDetail = {
17
21
  url?: string;
@@ -197,6 +201,8 @@ export declare function getChatFirstSurfaceTabsStore(scope?: string): ChatFirstS
197
201
  export declare function useChatFirstSurfaceTabs(scope?: string): ChatFirstSurfaceTabsState;
198
202
  export declare function subscribeChatFirstOpenApp(listener: ChatFirstOpenAppListener): () => void;
199
203
  export declare function emitChatFirstOpenApp(detail: ChatFirstOpenAppDetail): ChatFirstOpenAppDelivery;
204
+ export declare function subscribeChatFirstOpenAppStart(listener: ChatFirstOpenAppListener): () => void;
205
+ export declare function emitChatFirstOpenAppStart(detail: ChatFirstOpenAppDetail): ChatFirstOpenAppDelivery;
200
206
  export declare function subscribeChatFirstOpenBrowser(listener: ChatFirstOpenBrowserListener): () => void;
201
207
  export declare function emitChatFirstOpenBrowser(detail: ChatFirstOpenBrowserDetail): ChatFirstOpenAppDelivery;
202
208
  export declare function shouldOpenChatFirstBrowserExternally(value: string): boolean;
@@ -8,6 +8,7 @@ export const CHAT_FIRST_SURFACE_WIDTH_STORAGE_KEY = "agent-native:chat-first-sur
8
8
  export const CHAT_FIRST_SURFACE_PANEL_STORAGE_KEY = "agent-native:chat-first-surface-panel:v1";
9
9
  export const CHAT_FIRST_MODE_CHANGED_EVENT = "agentNative:chatFirstModeChanged";
10
10
  export const CHAT_FIRST_OPEN_APP_EVENT = "agentNative:openApp";
11
+ export const CHAT_FIRST_OPEN_APP_START_EVENT = "agentNative:openAppStart";
11
12
  export const CHAT_FIRST_OPEN_BROWSER_EVENT = "agentNative:openBrowser";
12
13
  export const CHAT_FIRST_WATCH_SESSION_EVENT = "agentNative:watchSession";
13
14
  export const CHAT_FIRST_SURFACE_CATALOG = [
@@ -345,6 +346,7 @@ export function resolveChatFirstBrowserTarget(detail) {
345
346
  };
346
347
  }
347
348
  const chatFirstOpenAppListeners = new Set();
349
+ const chatFirstOpenAppStartListeners = new Set();
348
350
  const chatFirstOpenBrowserListeners = new Set();
349
351
  function normalizeSessionId(value) {
350
352
  if (typeof value !== "string")
@@ -650,7 +652,8 @@ export function subscribeChatFirstOpenApp(listener) {
650
652
  return () => undefined;
651
653
  const subscription = Symbol("chat-first-open-app");
652
654
  const handleEvent = (event) => {
653
- const detail = event.detail;
655
+ const detail = event
656
+ .detail;
654
657
  if (detail && typeof detail === "object")
655
658
  listener(detail);
656
659
  };
@@ -676,6 +679,38 @@ export function emitChatFirstOpenApp(detail) {
676
679
  ? { delivered: true }
677
680
  : { delivered: false, reason: "no-listener" };
678
681
  }
682
+ export function subscribeChatFirstOpenAppStart(listener) {
683
+ if (typeof window === "undefined")
684
+ return () => undefined;
685
+ const subscription = Symbol("chat-first-open-app-start");
686
+ const handleEvent = (event) => {
687
+ const detail = event
688
+ .detail;
689
+ if (detail && typeof detail === "object")
690
+ listener(detail);
691
+ };
692
+ chatFirstOpenAppStartListeners.add(subscription);
693
+ window.addEventListener(CHAT_FIRST_OPEN_APP_START_EVENT, handleEvent);
694
+ return () => {
695
+ chatFirstOpenAppStartListeners.delete(subscription);
696
+ window.removeEventListener(CHAT_FIRST_OPEN_APP_START_EVENT, handleEvent);
697
+ };
698
+ }
699
+ export function emitChatFirstOpenAppStart(detail) {
700
+ if (!detail.app && !detail.url && !detail.path && !detail.view) {
701
+ return { delivered: false, reason: "empty-detail" };
702
+ }
703
+ if (typeof window === "undefined") {
704
+ return { delivered: false, reason: "no-listener" };
705
+ }
706
+ const delivered = chatFirstOpenAppStartListeners.size > 0;
707
+ window.dispatchEvent(new CustomEvent(CHAT_FIRST_OPEN_APP_START_EVENT, {
708
+ detail,
709
+ }));
710
+ return delivered
711
+ ? { delivered: true }
712
+ : { delivered: false, reason: "no-listener" };
713
+ }
679
714
  export function subscribeChatFirstOpenBrowser(listener) {
680
715
  if (typeof window === "undefined")
681
716
  return () => undefined;