@agent-native/core 0.204.0 → 0.204.1-nightly-20261008065100

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 (139) hide show
  1. package/dist/action.js +5 -6
  2. package/dist/agent/auto-continue.d.ts +35 -0
  3. package/dist/agent/auto-continue.js +38 -0
  4. package/dist/agent/connection-required-note.d.ts +52 -0
  5. package/dist/agent/connection-required-note.js +187 -0
  6. package/dist/agent/jev-tool-prefetch.d.ts +5 -1
  7. package/dist/agent/jev-tool-prefetch.js +19 -6
  8. package/dist/agent/previous-turn-note.d.ts +9 -0
  9. package/dist/agent/previous-turn-note.js +48 -0
  10. package/dist/agent/production-agent.d.ts +17 -13
  11. package/dist/agent/production-agent.js +185 -43
  12. package/dist/agent/reaped-run-thread.d.ts +13 -0
  13. package/dist/agent/reaped-run-thread.js +45 -0
  14. package/dist/agent/run-store.d.ts +29 -5
  15. package/dist/agent/run-store.js +144 -30
  16. package/dist/agent/thread-data-builder.d.ts +16 -0
  17. package/dist/agent/thread-data-builder.js +30 -8
  18. package/dist/agent/thread-message-projection.js +5 -3
  19. package/dist/agent/tool-search.js +5 -1
  20. package/dist/agent/types.d.ts +3 -0
  21. package/dist/audit/config.d.ts +6 -0
  22. package/dist/audit/config.js +12 -1
  23. package/dist/audit/index.d.ts +1 -1
  24. package/dist/audit/index.js +1 -1
  25. package/dist/audit/store.js +39 -4
  26. package/dist/automation/index.d.ts +1 -1
  27. package/dist/cli/skills.d.ts +1 -0
  28. package/dist/cli/skills.js +1 -1
  29. package/dist/client/agent-chat/index.d.ts +1 -1
  30. package/dist/client/agent-chat/index.js +1 -1
  31. package/dist/client/chat/agentkit-agent-native.js +83 -7
  32. package/dist/client/chat/agentkit-protocol.js +140 -67
  33. package/dist/client/chat/runtime.js +10 -4
  34. package/dist/client/embed-auth.d.ts +15 -0
  35. package/dist/client/embed-auth.js +77 -7
  36. package/dist/client/host/index.d.ts +1 -1
  37. package/dist/client/host/index.js +1 -1
  38. package/dist/client/mcp-app-host.d.ts +19 -0
  39. package/dist/client/mcp-app-host.js +88 -2
  40. package/dist/client/use-chat-threads.d.ts +1 -1
  41. package/dist/client/use-chat-threads.js +2 -0
  42. package/dist/client/use-run-stuck-detection.d.ts +18 -1
  43. package/dist/client/use-run-stuck-detection.js +115 -75
  44. package/dist/collab/routes.d.ts +1 -1
  45. package/dist/collab/struct-routes.d.ts +1 -1
  46. package/dist/db/request-telemetry.d.ts +7 -1
  47. package/dist/db/request-telemetry.js +20 -1
  48. package/dist/deploy/build.d.ts +25 -1
  49. package/dist/deploy/build.js +176 -3
  50. package/dist/deploy/workspace-deploy.js +8 -3
  51. package/dist/extensions/fetch-tool.js +50 -14
  52. package/dist/file-upload/builder.js +1 -1
  53. package/dist/file-upload/s3.js +1 -1
  54. package/dist/file-upload/types.d.ts +1 -0
  55. package/dist/integrations/adapters/email.js +11 -3
  56. package/dist/integrations/adapters/telegram.js +4 -2
  57. package/dist/jobs/actions/automation-no-op.d.ts +12 -0
  58. package/dist/jobs/actions/automation-no-op.js +20 -0
  59. package/dist/jobs/actions/manage-recurring-job.d.ts +1 -1
  60. package/dist/jobs/background-automation-runner.d.ts +8 -1
  61. package/dist/jobs/background-automation-runner.js +102 -19
  62. package/dist/jobs/run-history.d.ts +1 -1
  63. package/dist/jobs/run-history.js +8 -4
  64. package/dist/jobs/scheduler.js +25 -12
  65. package/dist/localization/automation-outcome-messages.d.ts +22 -0
  66. package/dist/localization/automation-outcome-messages.js +90 -0
  67. package/dist/localization/default-messages.d.ts +2 -0
  68. package/dist/localization/default-messages.js +4 -2
  69. package/dist/mcp/build-server.js +22 -11
  70. package/dist/mcp/embed-app.js +143 -9
  71. package/dist/mcp/index.d.ts +1 -1
  72. package/dist/mcp/index.js +1 -1
  73. package/dist/observability/metrics.d.ts +3 -0
  74. package/dist/observability/metrics.js +10 -0
  75. package/dist/observability/migrations.js +22 -0
  76. package/dist/observability/routes.d.ts +10 -5
  77. package/dist/observability/routes.js +88 -14
  78. package/dist/observability/sentiment.d.ts +5 -0
  79. package/dist/observability/sentiment.js +75 -25
  80. package/dist/observability/store.d.ts +28 -0
  81. package/dist/observability/store.js +58 -0
  82. package/dist/observability/traces.js +37 -5
  83. package/dist/org/handlers.d.ts +1 -1
  84. package/dist/progress/actions.js +1 -0
  85. package/dist/provider-api/actions/custom-provider-registration.d.ts +13 -13
  86. package/dist/provider-api/actions/provider-api.d.ts +13 -13
  87. package/dist/provider-api/actions/provider-api.js +6 -2
  88. package/dist/provider-api/index.d.ts +1 -0
  89. package/dist/provider-api/index.js +18 -0
  90. package/dist/provider-api/result-outcome.d.ts +1 -0
  91. package/dist/provider-api/result-outcome.js +20 -0
  92. package/dist/provider-api/staging.js +10 -9
  93. package/dist/resources/handlers.d.ts +1 -1
  94. package/dist/resources/script-helpers.d.ts +1 -0
  95. package/dist/resources/script-helpers.js +1 -1
  96. package/dist/resources/store.js +81 -0
  97. package/dist/scripts/resources/save-memory.js +3 -0
  98. package/dist/server/action-routes.js +34 -6
  99. package/dist/server/agent-chat/prompt-resources.d.ts +8 -2
  100. package/dist/server/agent-chat/prompt-resources.js +31 -8
  101. package/dist/server/agent-chat/recurring-jobs-runtime.d.ts +19 -4
  102. package/dist/server/agent-chat/recurring-jobs-runtime.js +52 -16
  103. package/dist/server/agent-chat/script-entries.js +30 -3
  104. package/dist/server/agent-chat/sweep-trigger-auth.d.ts +18 -0
  105. package/dist/server/agent-chat/sweep-trigger-auth.js +36 -0
  106. package/dist/server/agent-chat-plugin.js +51 -47
  107. package/dist/server/agent-engine-default-model-route.d.ts +2 -2
  108. package/dist/server/agent-engine-ollama-models-route.d.ts +2 -2
  109. package/dist/server/auth.js +21 -6
  110. package/dist/server/embed-route.js +5 -2
  111. package/dist/server/framework-request-handler.js +19 -0
  112. package/dist/server/http-response-telemetry.js +4 -1
  113. package/dist/server/realtime-token.d.ts +1 -1
  114. package/dist/server/request-context.d.ts +6 -0
  115. package/dist/shared/context-status.d.ts +21 -0
  116. package/dist/shared/context-status.js +54 -0
  117. package/dist/shared/mcp-app-display.d.ts +20 -0
  118. package/dist/shared/mcp-app-display.js +34 -0
  119. package/dist/shared/mcp-app-widget-embed.d.ts +18 -0
  120. package/dist/shared/mcp-app-widget-embed.js +41 -0
  121. package/dist/templates/chat/app/components/chat/ChatRouteContent.tsx +9 -2
  122. package/dist/templates/factory/.agents/skills/review-latest-feedback/SKILL.md +9 -2
  123. package/dist/templates/workspace-core/.agents/skills/automations/SKILL.md +8 -1
  124. package/dist/templates/workspace-core/.agents/skills/recurring-jobs/SKILL.md +3 -1
  125. package/dist/triggers/actions/manage-automation.d.ts +5 -5
  126. package/dist/triggers/dispatcher.js +10 -7
  127. package/docs/content/audit-log.mdx +3 -3
  128. package/docs/content/cloudflare.mdx +27 -0
  129. package/docs/content/deployment-environment-variables.mdx +2 -0
  130. package/docs/content/durable-resume.mdx +3 -1
  131. package/docs/content/environment-variables.mdx +2 -0
  132. package/docs/content/mcp-apps.mdx +1 -1
  133. package/docs/content/recurring-jobs.mdx +29 -9
  134. package/docs/content/vercel.mdx +30 -0
  135. package/package.json +4 -3
  136. package/src/templates/chat/app/components/chat/ChatRouteContent.tsx +9 -2
  137. package/src/templates/factory/.agents/skills/review-latest-feedback/SKILL.md +9 -2
  138. package/src/templates/workspace-core/.agents/skills/automations/SKILL.md +8 -1
  139. package/src/templates/workspace-core/.agents/skills/recurring-jobs/SKILL.md +3 -1
@@ -1,6 +1,8 @@
1
1
  import { useSyncExternalStore } from "react";
2
2
  import { EMBED_MODE_QUERY_PARAM, EMBED_TOKEN_QUERY_PARAM, MCP_APP_CHAT_BRIDGE_QUERY_PARAM, } from "../shared/embed-auth.js";
3
- import { getEmbedAuthToken, isEmbedAuthActive, markEmbedMcpChatBridgeActive, isEmbedMcpChatBridgeActive, readEmbedMcpChatBridgeFlagFromUrl, } from "./embed-auth.js";
3
+ import { MCP_APP_HOST_FILL_ATTRIBUTE, mcpAppHostFillsContainer, } from "../shared/mcp-app-display.js";
4
+ import { MCP_APP_WIDGET_EMBED_ATTRIBUTE } from "../shared/mcp-app-widget-embed.js";
5
+ import { getEmbedAuthToken, hasMcpDirectoryWidgetCapabilityToken, isEmbedAuthActive, markEmbedMcpChatBridgeActive, isEmbedMcpChatBridgeActive, isMcpDirectoryWidgetReadOnlyEmbed, readEmbedMcpChatBridgeFlagFromUrl, } from "./embed-auth.js";
4
6
  import { getFrameOrigin } from "./frame.js";
5
7
  export const AGENT_NATIVE_MCP_APP_HOST_MESSAGE_TYPES = {
6
8
  HOST_CONTEXT: "agentNative.mcpHostContext",
@@ -113,6 +115,28 @@ function notify() {
113
115
  for (const listener of listeners)
114
116
  listener();
115
117
  }
118
+ function syncHostFillAttribute(context) {
119
+ if (!isBrowserWindow() || !document.documentElement)
120
+ return;
121
+ if (mcpAppHostFillsContainer(context)) {
122
+ document.documentElement.setAttribute(MCP_APP_HOST_FILL_ATTRIBUTE, "1");
123
+ }
124
+ else {
125
+ document.documentElement.removeAttribute(MCP_APP_HOST_FILL_ATTRIBUTE);
126
+ }
127
+ }
128
+ function mergeHostContext(previous, update) {
129
+ const merged = { ...(previous ?? {}), ...update };
130
+ if (isRecord(update.containerDimensions)) {
131
+ merged.containerDimensions = {
132
+ ...(isRecord(previous?.containerDimensions)
133
+ ? previous.containerDimensions
134
+ : {}),
135
+ ...update.containerDimensions,
136
+ };
137
+ }
138
+ return merged;
139
+ }
116
140
  function updateSnapshot(data) {
117
141
  if (!isRecord(data))
118
142
  return;
@@ -131,6 +155,7 @@ function updateSnapshot(data) {
131
155
  if (hostInfo)
132
156
  nextSnapshot.hostInfo = hostInfo;
133
157
  snapshot = nextSnapshot;
158
+ syncHostFillAttribute(nextSnapshot.context);
134
159
  notify();
135
160
  }
136
161
  function updateSnapshotFromInitialize(result) {
@@ -196,8 +221,9 @@ function resolveJsonRpc(data) {
196
221
  function handleJsonRpcNotification(message) {
197
222
  if (message.method !== "ui/notifications/host-context-changed")
198
223
  return;
224
+ const update = isRecord(message.params) ? message.params : null;
199
225
  updateSnapshot({
200
- context: isRecord(message.params) ? message.params : undefined,
226
+ context: update ? mergeHostContext(snapshot.context, update) : undefined,
201
227
  });
202
228
  }
203
229
  function onMessage(event) {
@@ -330,6 +356,60 @@ function readOpenAiBridge() {
330
356
  ? bridge
331
357
  : null;
332
358
  }
359
+ const widgetEmbedListeners = new Set();
360
+ let widgetEmbedLatched = false;
361
+ function latchWidgetEmbed() {
362
+ if (widgetEmbedLatched)
363
+ return;
364
+ widgetEmbedLatched = true;
365
+ document.documentElement?.setAttribute(MCP_APP_WIDGET_EMBED_ATTRIBUTE, "1");
366
+ // The first answer is computed during a render, and a subscriber must not be
367
+ // told to re-render from inside another component's render.
368
+ queueMicrotask(() => {
369
+ for (const listener of widgetEmbedListeners)
370
+ listener();
371
+ });
372
+ }
373
+ /**
374
+ * True when this document is an app running inside an MCP App widget (a
375
+ * ChatGPT, Codex, or Claude card or panel). The host, not the app, owns
376
+ * navigation and chat there, so apps drop their own navigation chrome.
377
+ *
378
+ * Being a widget is a property of the document, not of its current URL: the
379
+ * first positive answer is kept (and marked on `<html>`, where the first-paint
380
+ * script in `getMcpAppWidgetEmbedBootScriptBody` also marks it), so a client
381
+ * navigation that drops the embed query params, or a token swap that
382
+ * de-enrolls the chat bridge, never brings the app's own chrome back.
383
+ */
384
+ export function isMcpAppWidgetEmbed() {
385
+ if (!isBrowserWindow())
386
+ return false;
387
+ if (widgetEmbedLatched)
388
+ return true;
389
+ if (document.documentElement?.hasAttribute(MCP_APP_WIDGET_EMBED_ATTRIBUTE) ||
390
+ (isInChildFrame() &&
391
+ (isMcpAppBridgeEnabled() || hasMcpDirectoryWidgetCapabilityToken()))) {
392
+ latchWidgetEmbed();
393
+ }
394
+ return widgetEmbedLatched;
395
+ }
396
+ function subscribeToWidgetEmbed(listener) {
397
+ widgetEmbedListeners.add(listener);
398
+ return () => {
399
+ widgetEmbedListeners.delete(listener);
400
+ };
401
+ }
402
+ export function useIsMcpAppWidgetEmbed() {
403
+ return useSyncExternalStore(subscribeToWidgetEmbed, isMcpAppWidgetEmbed, () => false);
404
+ }
405
+ /**
406
+ * True for a directory widget, whose scoped session can only read its own
407
+ * resource. Apps skip application-state writes and save-failure surfaces there
408
+ * instead of showing errors for requests that can never land.
409
+ */
410
+ export function useIsMcpDirectoryWidgetReadOnlyEmbed() {
411
+ return useSyncExternalStore(() => () => { }, isMcpDirectoryWidgetReadOnlyEmbed, () => false);
412
+ }
333
413
  export function isOpenAiMcpAppHost() {
334
414
  return (isInChildFrame() && isMcpAppBridgeEnabled() && readOpenAiBridge() !== null);
335
415
  }
@@ -631,6 +711,12 @@ export function _resetMcpAppHostForTests() {
631
711
  directHostChatQueue = Promise.resolve();
632
712
  snapshot = { context: null, capabilities: null, version: null };
633
713
  listeners.clear();
714
+ widgetEmbedLatched = false;
715
+ widgetEmbedListeners.clear();
716
+ if (isBrowserWindow()) {
717
+ document.documentElement?.removeAttribute(MCP_APP_HOST_FILL_ATTRIBUTE);
718
+ document.documentElement?.removeAttribute(MCP_APP_WIDGET_EMBED_ATTRIBUTE);
719
+ }
634
720
  }
635
721
  if (isBrowserWindow()) {
636
722
  window.addEventListener("openai:set_globals", () => {
@@ -53,7 +53,7 @@ export interface ChatThreadShareLink extends ChatThreadShareState {
53
53
  token?: string;
54
54
  url: string;
55
55
  }
56
- type ThreadTitleSource = "generated" | "extracted";
56
+ type ThreadTitleSource = "fallback" | "generated" | "extracted";
57
57
  export interface UseChatThreadsOptions {
58
58
  autoCreate?: boolean;
59
59
  restoreActiveThread?: boolean;
@@ -177,6 +177,8 @@ function nextThreadTitle(currentTitle, incomingTitle, incomingPreview, source =
177
177
  return currentTitle;
178
178
  if (source === "generated")
179
179
  return incomingTitle;
180
+ if (source === "fallback")
181
+ return currentTitle || incomingTitle;
180
182
  if (!currentTitle && source === "extracted")
181
183
  return "";
182
184
  if (!currentTitle)
@@ -9,10 +9,27 @@ export interface RunStuckState {
9
9
  heartbeatSinceMs: number | null;
10
10
  dispatchMode: string | null;
11
11
  hasInFlightWork: boolean | null;
12
+ /**
13
+ * The server reported no run in flight on this thread on two polls in a row.
14
+ * A chat still showing "running" at that point has lost the run's ending and
15
+ * should reload the thread, not keep waiting.
16
+ */
17
+ serverSettled: boolean;
18
+ /**
19
+ * The last polls failed, so nothing here says whether the run is alive.
20
+ * Distinct from "no run": the other fields are the last answer, not a fresh one.
21
+ */
22
+ statusUnreadable: boolean;
12
23
  }
13
24
  export interface UseRunStuckDetectionOptions {
14
25
  threadId: string | null | undefined;
15
26
  enabled?: boolean;
27
+ /**
28
+ * Whether the chat is showing a run in progress. Each time it turns on, the
29
+ * hook starts over, so `serverSettled` only ever reflects polls taken after
30
+ * the chat began waiting, never an idle answer from before the user sent.
31
+ */
32
+ awaitingResponse?: boolean;
16
33
  stuckThresholdMs?: number;
17
34
  /**
18
35
  * Threshold for BACKGROUND-dispatched runs (dispatchMode starts with
@@ -29,5 +46,5 @@ export interface UseRunStuckDetectionOptions {
29
46
  }
30
47
  export declare const DEFAULT_BACKGROUND_STUCK_THRESHOLD_MS = 180000;
31
48
  export declare const DEFAULT_LIVE_BACKGROUND_STUCK_THRESHOLD_MS: number;
32
- export declare function useRunStuckDetection({ threadId, enabled, stuckThresholdMs, backgroundStuckThresholdMs, liveBackgroundStuckThresholdMs, pollIntervalMs, apiUrl, }: UseRunStuckDetectionOptions): RunStuckState;
49
+ export declare function useRunStuckDetection({ threadId, enabled, awaitingResponse, stuckThresholdMs, backgroundStuckThresholdMs, liveBackgroundStuckThresholdMs, pollIntervalMs, apiUrl, }: UseRunStuckDetectionOptions): RunStuckState;
33
50
  export declare function useAbortRun(apiUrl?: string): (runId: string, reason?: string) => Promise<string | null>;
@@ -9,10 +9,15 @@ const DEFAULT_POLL_INTERVAL_MS = 5_000;
9
9
  const IDLE_BACKOFF_INTERVAL_MS = 15_000;
10
10
  const MAX_POLL_ERROR_BACKOFF_MS = 30_000;
11
11
  const FRESH_BACKGROUND_HEARTBEAT_MS = 30_000;
12
+ const SETTLED_CONFIRMATIONS = 2;
13
+ const UNREADABLE_AFTER_FAILURES = 2;
12
14
  const POLL_ABORT_MIN_MS = 10_000;
13
15
  function getPollAbortMs(interval) {
14
16
  return Math.max(POLL_ABORT_MIN_MS, interval * 4);
15
17
  }
18
+ function isActiveRunResponse(body) {
19
+ return typeof body?.active === "boolean";
20
+ }
16
21
  const EMPTY_STATE = {
17
22
  isStuck: false,
18
23
  runId: null,
@@ -24,9 +29,27 @@ const EMPTY_STATE = {
24
29
  heartbeatSinceMs: null,
25
30
  dispatchMode: null,
26
31
  hasInFlightWork: null,
32
+ serverSettled: false,
33
+ statusUnreadable: false,
27
34
  };
28
- export function useRunStuckDetection({ threadId, enabled = true, stuckThresholdMs = DEFAULT_STUCK_THRESHOLD_MS, backgroundStuckThresholdMs = DEFAULT_BACKGROUND_STUCK_THRESHOLD_MS, liveBackgroundStuckThresholdMs = DEFAULT_LIVE_BACKGROUND_STUCK_THRESHOLD_MS, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, apiUrl, }) {
35
+ export function useRunStuckDetection({ threadId, enabled = true, awaitingResponse, stuckThresholdMs = DEFAULT_STUCK_THRESHOLD_MS, backgroundStuckThresholdMs = DEFAULT_BACKGROUND_STUCK_THRESHOLD_MS, liveBackgroundStuckThresholdMs = DEFAULT_LIVE_BACKGROUND_STUCK_THRESHOLD_MS, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, apiUrl, }) {
29
36
  const [state, setState] = useState(EMPTY_STATE);
37
+ // Reset in render, not in the effect: an effect-time reset still lets the
38
+ // consumer's own effects act once on the previous answer. The epoch also
39
+ // restarts polling, which drops any poll still in flight from before.
40
+ const awaiting = awaitingResponse === true;
41
+ const [scope, setScope] = useState({ threadId, awaiting, epoch: 0 });
42
+ if (scope.threadId !== threadId || scope.awaiting !== awaiting) {
43
+ const waitingStarted = awaiting && !scope.awaiting;
44
+ setScope({
45
+ threadId,
46
+ awaiting,
47
+ epoch: scope.epoch + (waitingStarted ? 1 : 0),
48
+ });
49
+ if (waitingStarted || scope.threadId !== threadId)
50
+ setState(EMPTY_STATE);
51
+ }
52
+ const awaitingEpoch = scope.epoch;
30
53
  useEffect(() => {
31
54
  setState(EMPTY_STATE);
32
55
  if (!threadId || !enabled)
@@ -38,18 +61,24 @@ export function useRunStuckDetection({ threadId, enabled = true, stuckThresholdM
38
61
  let lastObservedLocalProgressAt = null;
39
62
  let lastObservedLocalProgressSeq = null;
40
63
  let consecutivePollFailures = 0;
64
+ let consecutiveIdlePolls = 0;
41
65
  const nextDelayRef = { current: 2_000 };
42
66
  const pollFailureDelay = () => {
43
67
  consecutivePollFailures += 1;
68
+ // A poll that got no answer breaks an idle streak still being confirmed:
69
+ // a run can start and be missed between two idle answers that surround
70
+ // it. A streak that already settled stands, or the verdict would flip
71
+ // off and on again across one outage.
72
+ if (consecutiveIdlePolls < SETTLED_CONFIRMATIONS) {
73
+ consecutiveIdlePolls = 0;
74
+ }
75
+ if (!cancelled && consecutivePollFailures >= UNREADABLE_AFTER_FAILURES) {
76
+ setState((current) => current.statusUnreadable
77
+ ? current
78
+ : { ...current, statusUnreadable: true });
79
+ }
44
80
  return Math.min(Math.max(pollIntervalMs, 1) * 2 ** consecutivePollFailures, MAX_POLL_ERROR_BACKOFF_MS);
45
81
  };
46
- const clearObservedRun = () => {
47
- snapshotVersion += 1;
48
- if (snapshotTransitionTimer)
49
- clearTimeout(snapshotTransitionTimer);
50
- snapshotTransitionTimer = null;
51
- setState(EMPTY_STATE);
52
- };
53
82
  const effectiveThresholdFor = (dispatchMode, heartbeatSinceMs) => {
54
83
  const liveBackgroundWorker = dispatchMode === "background-processing" &&
55
84
  heartbeatSinceMs != null &&
@@ -180,77 +209,87 @@ export function useRunStuckDetection({ threadId, enabled = true, stuckThresholdM
180
209
  const res = await fetch(`${base}/runs/active?threadId=${encodeURIComponent(threadId)}`, { credentials: "same-origin", signal });
181
210
  if (cancelled)
182
211
  return;
183
- if (res.ok) {
184
- consecutivePollFailures = 0;
185
- const data = (await res.json());
186
- const lastProgressAt = data.lastProgressAt ?? null;
187
- const nowMs = data.serverNow ?? Date.now();
188
- const stuckSinceMs = lastProgressAt != null ? nowMs - lastProgressAt : null;
189
- const heartbeatAt = data.heartbeatAt ?? null;
190
- const heartbeatSinceMs = heartbeatAt != null ? nowMs - heartbeatAt : null;
191
- const dispatchMode = typeof data.dispatchMode === "string" ? data.dispatchMode : null;
192
- const runId = data.runId ?? null;
193
- const activeRun = getActiveRun();
194
- const localProgressObservedAt = activeRun?.threadId === threadId && activeRun.runId === runId
195
- ? (activeRun.lastProgressObservedAt ?? null)
196
- : null;
197
- const localProgressSinceMs = localProgressObservedAt == null
198
- ? null
199
- : Math.max(0, Date.now() - localProgressObservedAt);
200
- const effectiveThresholdMs = effectiveThresholdFor(dispatchMode, heartbeatSinceMs);
201
- const isStuck = Boolean(data.active &&
202
- data.status === "running" &&
203
- stuckSinceMs != null &&
204
- stuckSinceMs > effectiveThresholdMs &&
205
- (localProgressSinceMs == null ||
206
- localProgressSinceMs > effectiveThresholdMs));
207
- const observedAtMs = Date.now();
208
- const version = ++snapshotVersion;
209
- scheduleSnapshotTransition({
210
- active: data.active,
211
- runId,
212
- status: data.status ?? null,
213
- lastProgressAt,
214
- stuckSinceMs,
215
- localProgressObservedAt,
216
- lastProgressSeq: activeRun?.threadId === threadId && activeRun.runId === runId
217
- ? (activeRun.lastProgressSeq ?? null)
218
- : null,
219
- heartbeatAt,
220
- heartbeatSinceMs,
221
- dispatchMode,
222
- }, observedAtMs, version);
223
- setState({
224
- isStuck,
225
- runId,
226
- status: data.status ?? null,
227
- lastProgressAt,
228
- stuckSinceMs: localProgressSinceMs != null &&
229
- localProgressSinceMs <= effectiveThresholdMs
230
- ? null
231
- : stuckSinceMs,
232
- lastProgressSeq: activeRun?.threadId === threadId && activeRun.runId === runId
233
- ? (activeRun.lastProgressSeq ?? null)
234
- : null,
235
- heartbeatAt,
236
- heartbeatSinceMs,
237
- dispatchMode,
238
- hasInFlightWork: typeof data.hasInFlightWork === "boolean"
239
- ? data.hasInFlightWork
240
- : null,
241
- });
242
- if (!data.active || data.status !== "running") {
243
- nextDelay = IDLE_BACKOFF_INTERVAL_MS;
244
- }
212
+ // The endpoint answers "no run" with a 200 and a boolean `active`, so
213
+ // no other status or body is an idle answer: a 401/403/404 or a body
214
+ // without `active` leaves the run's state unknown, not gone.
215
+ if (!res.ok) {
216
+ nextDelay = pollFailureDelay();
217
+ return;
245
218
  }
246
- else if (res.status === 429 || res.status >= 500) {
219
+ const data = await res.json();
220
+ if (cancelled)
221
+ return;
222
+ if (!isActiveRunResponse(data)) {
247
223
  nextDelay = pollFailureDelay();
224
+ return;
248
225
  }
249
- else {
250
- consecutivePollFailures = 0;
251
- clearObservedRun();
252
- nextDelay = MAX_POLL_ERROR_BACKOFF_MS;
226
+ consecutiveIdlePolls = data.active ? 0 : consecutiveIdlePolls + 1;
227
+ const serverSettled = consecutiveIdlePolls >= SETTLED_CONFIRMATIONS;
228
+ const lastProgressAt = data.lastProgressAt ?? null;
229
+ const nowMs = data.serverNow ?? Date.now();
230
+ const stuckSinceMs = lastProgressAt != null ? nowMs - lastProgressAt : null;
231
+ const heartbeatAt = data.heartbeatAt ?? null;
232
+ const heartbeatSinceMs = heartbeatAt != null ? nowMs - heartbeatAt : null;
233
+ const dispatchMode = typeof data.dispatchMode === "string" ? data.dispatchMode : null;
234
+ const runId = data.runId ?? null;
235
+ const activeRun = getActiveRun();
236
+ const localProgressObservedAt = activeRun?.threadId === threadId && activeRun.runId === runId
237
+ ? (activeRun.lastProgressObservedAt ?? null)
238
+ : null;
239
+ const localProgressSinceMs = localProgressObservedAt == null
240
+ ? null
241
+ : Math.max(0, Date.now() - localProgressObservedAt);
242
+ const effectiveThresholdMs = effectiveThresholdFor(dispatchMode, heartbeatSinceMs);
243
+ const isStuck = Boolean(data.active &&
244
+ data.status === "running" &&
245
+ stuckSinceMs != null &&
246
+ stuckSinceMs > effectiveThresholdMs &&
247
+ (localProgressSinceMs == null ||
248
+ localProgressSinceMs > effectiveThresholdMs));
249
+ const observedAtMs = Date.now();
250
+ const version = ++snapshotVersion;
251
+ scheduleSnapshotTransition({
252
+ active: data.active,
253
+ runId,
254
+ status: data.status ?? null,
255
+ lastProgressAt,
256
+ stuckSinceMs,
257
+ localProgressObservedAt,
258
+ lastProgressSeq: activeRun?.threadId === threadId && activeRun.runId === runId
259
+ ? (activeRun.lastProgressSeq ?? null)
260
+ : null,
261
+ heartbeatAt,
262
+ heartbeatSinceMs,
263
+ dispatchMode,
264
+ }, observedAtMs, version);
265
+ setState({
266
+ isStuck,
267
+ runId,
268
+ status: data.status ?? null,
269
+ lastProgressAt,
270
+ stuckSinceMs: localProgressSinceMs != null &&
271
+ localProgressSinceMs <= effectiveThresholdMs
272
+ ? null
273
+ : stuckSinceMs,
274
+ lastProgressSeq: activeRun?.threadId === threadId && activeRun.runId === runId
275
+ ? (activeRun.lastProgressSeq ?? null)
276
+ : null,
277
+ heartbeatAt,
278
+ heartbeatSinceMs,
279
+ dispatchMode,
280
+ hasInFlightWork: typeof data.hasInFlightWork === "boolean"
281
+ ? data.hasInFlightWork
282
+ : null,
283
+ serverSettled,
284
+ statusUnreadable: false,
285
+ });
286
+ // The first idle answer is confirmed at the normal cadence, so a
287
+ // run the server has not registered yet is not called settled.
288
+ const confirmingIdle = !data.active && !serverSettled;
289
+ if (!confirmingIdle && (!data.active || data.status !== "running")) {
290
+ nextDelay = IDLE_BACKOFF_INTERVAL_MS;
253
291
  }
292
+ consecutivePollFailures = 0;
254
293
  }
255
294
  catch {
256
295
  nextDelay = pollFailureDelay();
@@ -292,6 +331,7 @@ export function useRunStuckDetection({ threadId, enabled = true, stuckThresholdM
292
331
  liveBackgroundStuckThresholdMs,
293
332
  pollIntervalMs,
294
333
  apiUrl,
334
+ awaitingEpoch,
295
335
  ]);
296
336
  return state;
297
337
  }
@@ -13,8 +13,8 @@ export declare const getCollabState: import("h3").EventHandlerWithFetch<import("
13
13
  };
14
14
  }>>;
15
15
  export declare const postCollabUpdate: import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<{
16
- ok?: undefined;
17
16
  error: string;
17
+ ok?: undefined;
18
18
  } | {
19
19
  error?: undefined;
20
20
  ok: boolean;
@@ -1,6 +1,6 @@
1
1
  export declare const postCollabJson: import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<{
2
- error: string;
3
2
  ok?: undefined;
3
+ error: string;
4
4
  } | {
5
5
  error?: undefined;
6
6
  ok: boolean;
@@ -20,7 +20,13 @@ export interface DatabaseRequestTelemetry {
20
20
  export declare function createDatabaseRequestTelemetry(): DatabaseRequestTelemetry;
21
21
  export declare function claimStartupDatabaseTelemetry(): DatabaseRequestTelemetry | undefined;
22
22
  export declare function runWithDatabaseRequestTelemetry<T>(telemetry: DatabaseRequestTelemetry, fn: () => T): T;
23
- export declare function enterDatabaseRequestTelemetry(telemetry: DatabaseRequestTelemetry): void;
23
+ /**
24
+ * Returns false when the runtime cannot scope telemetry to the rest of the
25
+ * request. workerd's AsyncLocalStorage implements `run()` but throws from
26
+ * `enterWith()`, and a throw here escapes the Nitro request hook and skips
27
+ * every hook after it, including the framework route readiness gate.
28
+ */
29
+ export declare function enterDatabaseRequestTelemetry(telemetry: DatabaseRequestTelemetry): boolean;
24
30
  export declare function beginDatabaseOperation(operation: DatabaseOperationKind): (outcome: "success" | "error" | "timeout") => void;
25
31
  export declare function recordDatabaseRetry(): void;
26
32
  export declare function recordDatabaseQueryResult(sql: string, rowsReturned: number): void;
@@ -62,8 +62,27 @@ export function claimStartupDatabaseTelemetry() {
62
62
  export function runWithDatabaseRequestTelemetry(telemetry, fn) {
63
63
  return getStorage().run(telemetry, fn);
64
64
  }
65
+ const storagesWithoutEnterWith = new WeakSet();
66
+ /**
67
+ * Returns false when the runtime cannot scope telemetry to the rest of the
68
+ * request. workerd's AsyncLocalStorage implements `run()` but throws from
69
+ * `enterWith()`, and a throw here escapes the Nitro request hook and skips
70
+ * every hook after it, including the framework route readiness gate.
71
+ */
65
72
  export function enterDatabaseRequestTelemetry(telemetry) {
66
- getStorage().enterWith(telemetry);
73
+ const storage = getStorage();
74
+ if (storage === NOOP_STORAGE || storagesWithoutEnterWith.has(storage)) {
75
+ return false;
76
+ }
77
+ try {
78
+ storage.enterWith(telemetry);
79
+ return true;
80
+ }
81
+ catch (error) {
82
+ storagesWithoutEnterWith.add(storage);
83
+ console.warn("[db] Per-request database telemetry is unavailable: AsyncLocalStorage.enterWith() failed on this runtime.", error);
84
+ return false;
85
+ }
67
86
  }
68
87
  export function beginDatabaseOperation(operation) {
69
88
  const telemetry = currentDatabaseTelemetry();
@@ -15,7 +15,15 @@ export declare const CLOUDFLARE_MODULE_WORKER_ENTRY = "worker.mjs";
15
15
  export declare function configureAwsAmplifyRuntimeOutput(serverDir: string, appDir: string, env?: NodeJS.ProcessEnv): void;
16
16
  export declare function configureAwsLambdaRuntimeOutput(serverDir: string, appDir: string, env?: NodeJS.ProcessEnv): void;
17
17
  export declare function shimCloudflarePagesModuleTimers(code: string): string;
18
- export declare function generateCloudflareModuleWorkerEntry(): string;
18
+ export declare const CLOUDFLARE_SWEEP_CRON = "* * * * *";
19
+ /**
20
+ * The URL path a platform scheduler requests. Under a custom framework route
21
+ * prefix the request boundary 404s `/_agent-native/*` before any route runs,
22
+ * and the server is mounted under the app base path, so the internal sweep
23
+ * path alone never reaches the sweep.
24
+ */
25
+ export declare function publicRecurringJobsSweepPath(env?: NodeJS.ProcessEnv): string;
26
+ export declare function generateCloudflareModuleWorkerEntry(env?: NodeJS.ProcessEnv): string;
19
27
  export declare function patchCloudflareModuleNitroEntry(code: string): string;
20
28
  export declare function configureCloudflareModuleWorkerOutput(serverDir: string): void;
21
29
  export declare const NITRO_RUNTIME_IGNORE_PATTERNS: string[];
@@ -65,6 +73,22 @@ export declare function isRecurringJobsDeployEnabled(): boolean;
65
73
  export declare function isKeepWarmDeployEnabled(): boolean;
66
74
  export declare function isKeepWarmBackgroundDeployEnabled(): boolean;
67
75
  export declare function resolveKeepWarmSchedule(): string;
76
+ export declare function resolveVercelSweepCronSchedule(env?: NodeJS.ProcessEnv): string;
77
+ export declare function vercelSweepCrons(sweepPaths: readonly string[], env?: NodeJS.ProcessEnv): Array<{
78
+ path: string;
79
+ schedule: string;
80
+ }>;
81
+ export declare function addVercelSweepCron(outputDir: string, env?: NodeJS.ProcessEnv): void;
82
+ /**
83
+ * Reads back the sweep cron `addVercelSweepCron` wrote for an app mounted at
84
+ * `basePath`. A workspace deploy must reuse it rather than recompute it: the
85
+ * app's build resolved its framework route prefix from config files the
86
+ * workspace build never reads.
87
+ */
88
+ export declare function readVercelSweepCron(outputDir: string, basePath: string): {
89
+ path: string;
90
+ schedule: string;
91
+ };
68
92
  export declare function emitSingleTemplateNetlifyKeepWarmFunction(projectCwd: string): void;
69
93
  export declare function emitSingleTemplateNetlifyRecurringJobsFunction(projectCwd: string): void;
70
94
  /**