@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
@@ -10440,7 +10440,7 @@ export function createProductionAgentHandler(options) {
10440
10440
  return filterActionsByExcludedNames(filtered, getRequestRunContext()?.excludedActionNames ?? []);
10441
10441
  };
10442
10442
  const getEngineTools = (actions) => actionsToEngineTools(getRequestActions(actions));
10443
- return defineEventHandler(async (event) => {
10443
+ const handleAgentChatEvent = async (event, prepCleanup) => {
10444
10444
  let completionTrackingSource = options.onRunComplete
10445
10445
  ? snapshotAgentRunTrackingSource()
10446
10446
  : undefined;
@@ -11428,6 +11428,11 @@ export function createProductionAgentHandler(options) {
11428
11428
  typeof requestedContinueOfRunId === "string",
11429
11429
  });
11430
11430
  const isQueuedPromotion = admittedQueuedMessage !== null;
11431
+ // Only an admitted promotion's claim may save a refused turn over its
11432
+ // queue entry. An unadmitted claim is refused below, so it consumes nothing.
11433
+ const admittedQueuedMessageClaimId = admittedQueuedMessage && typeof queuedMessageClaimId === "string"
11434
+ ? queuedMessageClaimId.trim()
11435
+ : "";
11431
11436
  if (admittedQueuedMessage) {
11432
11437
  // A claim admits the persisted queue payload, not extra fields in this request.
11433
11438
  const promotionOptions = admittedQueuedMessage.options ?? {};
@@ -11515,6 +11520,9 @@ export function createProductionAgentHandler(options) {
11515
11520
  ...(typeof queuedMessageId === "string" && queuedMessageId.trim()
11516
11521
  ? { queuedMessageId: queuedMessageId.trim() }
11517
11522
  : {}),
11523
+ ...(admittedQueuedMessageClaimId
11524
+ ? { queuedMessageClaimId: admittedQueuedMessageClaimId }
11525
+ : {}),
11518
11526
  ...(agentKitMessageId ? { agentKitMessageId } : {}),
11519
11527
  retryContext: retryContextFromRequest(body, (dropped) => console.warn(`[agent-chat] dropped ${dropped} invalid reference(s) from a refused turn's retry context`)),
11520
11528
  failure,
@@ -11571,7 +11579,7 @@ export function createProductionAgentHandler(options) {
11571
11579
  ? { credentialScope: integrationCredentialScope }
11572
11580
  : {}),
11573
11581
  });
11574
- const contextPrefetchDeadlineAt = Date.now() + 1_300;
11582
+ let contextPrefetchDeadlineAt = Date.now() + 1_300;
11575
11583
  const preparedRequest = await options.prepareRequest?.({
11576
11584
  event,
11577
11585
  ownerEmail,
@@ -11987,6 +11995,9 @@ export function createProductionAgentHandler(options) {
11987
11995
  ...(typeof queuedMessageId === "string" && queuedMessageId.trim()
11988
11996
  ? { queuedMessageId: queuedMessageId.trim() }
11989
11997
  : {}),
11998
+ ...(admittedQueuedMessageClaimId
11999
+ ? { queuedMessageClaimId: admittedQueuedMessageClaimId }
12000
+ : {}),
11990
12001
  ...(agentKitMessageId ? { agentKitMessageId } : {}),
11991
12002
  retryContext: retryContextFromRequest(body, (dropped) => console.warn(`[agent-chat] dropped ${dropped} invalid reference(s) from a refused turn's retry context`)),
11992
12003
  failure: {
@@ -12002,6 +12013,113 @@ export function createProductionAgentHandler(options) {
12002
12013
  },
12003
12014
  });
12004
12015
  }
12016
+ const promptRunContext = ensureRequestRunContext();
12017
+ if (promptRunContext) {
12018
+ promptRunContext.appDiscoveryQuery = requestMessage;
12019
+ if (ownerEmail && !promptRunContext.owner) {
12020
+ promptRunContext.owner = ownerEmail;
12021
+ }
12022
+ }
12023
+ const isChainedBackgroundContinuation = isBackgroundWorker && backgroundContinuationCount > 0;
12024
+ const isReaperSuccessor = isBackgroundWorker &&
12025
+ typeof mutableBody[AGENT_CHAT_RECOVERY_OF_RUN_FIELD] === "string" &&
12026
+ Boolean(mutableBody[AGENT_CHAT_RECOVERY_OF_RUN_FIELD]);
12027
+ const isClientTurnContinuation = !isBackgroundWorker &&
12028
+ internalContinuation === true &&
12029
+ !continueOf &&
12030
+ !approvedToolCallsForExecution?.length &&
12031
+ typeof message === "string" &&
12032
+ message.startsWith(AGENT_INTERNAL_CONTINUE_PROMPT) &&
12033
+ typeof threadId === "string" &&
12034
+ threadId.trim().length > 0 &&
12035
+ typeof requestTurnId === "string" &&
12036
+ requestTurnId.trim().length > 0;
12037
+ const shouldRecoverCompletedExecutionSteps = isChainedBackgroundContinuation ||
12038
+ isReaperSuccessor ||
12039
+ Boolean(continueOf) ||
12040
+ isClientTurnContinuation;
12041
+ const runId = backgroundRunMarker?.runId ?? generateRunId();
12042
+ const effectiveThreadId = threadId ?? runId;
12043
+ const effectiveTurnId = typeof backgroundRunMarker?.turnId === "string" &&
12044
+ backgroundRunMarker.turnId.trim()
12045
+ ? backgroundRunMarker.turnId.trim()
12046
+ : (resolvedApprovalTurnId ??
12047
+ (typeof requestTurnId === "string" && requestTurnId.trim()
12048
+ ? requestTurnId.trim()
12049
+ : runId));
12050
+ if (dispatchToBackground && getAppConfig().agent.interactiveChatTurns) {
12051
+ const grant = mintDurableTurnGrant({
12052
+ runId,
12053
+ turnId: effectiveTurnId,
12054
+ initiator: turnInitiator,
12055
+ interactive: isProviderInteractiveScope(),
12056
+ continuation: internalContinuation === true ||
12057
+ Boolean(continueOf) ||
12058
+ Boolean(requestedAutoContinueOfRunId) ||
12059
+ Boolean(requestedContinueOfRunId),
12060
+ lifetimeMs: MAX_TURN_WALL_CLOCK_MS,
12061
+ });
12062
+ if (grant)
12063
+ mutableBody[AGENT_CHAT_TURN_GRANT_FIELD] = grant;
12064
+ }
12065
+ let durableDispatchPayload;
12066
+ if (dispatchToBackground) {
12067
+ try {
12068
+ const dispatchBody = {
12069
+ ...body,
12070
+ ...(Array.isArray(attachments) || requestAttachments.length > 0
12071
+ ? { attachments: requestAttachments }
12072
+ : {}),
12073
+ };
12074
+ delete dispatchBody.queuedMessageClaimId;
12075
+ durableDispatchPayload = serializeDurableDispatchPayload(dispatchBody);
12076
+ }
12077
+ catch (error) {
12078
+ if (!(error instanceof DurableAttachmentReferenceRequiredError)) {
12079
+ throw error;
12080
+ }
12081
+ setResponseStatus(event, 503);
12082
+ return {
12083
+ error: error.message,
12084
+ code: error.code,
12085
+ retryable: false,
12086
+ };
12087
+ }
12088
+ }
12089
+ const foregroundSelfChainEligible = !isBackgroundWorker &&
12090
+ !dispatchToBackground &&
12091
+ typeof threadId === "string" &&
12092
+ threadId.trim().length > 0 &&
12093
+ isAgentChatForegroundSelfChainEnabled();
12094
+ const runRowState = {
12095
+ foregroundInserted: false,
12096
+ durableInserted: false,
12097
+ };
12098
+ prepCleanup.runId = runId;
12099
+ prepCleanup.runRowState = runRowState;
12100
+ let setupResumeClaim;
12101
+ const messageToPersist = typeof requestDisplayMessage === "string" &&
12102
+ requestDisplayMessage.trim().length > 0
12103
+ ? requestDisplayMessage
12104
+ : requestMessage;
12105
+ const deferExecutionContext = dispatchToBackground && !shouldRecoverCompletedExecutionSteps;
12106
+ let backgroundDispatchAttempted = false;
12107
+ if (deferExecutionContext) {
12108
+ backgroundDispatchAttempted = true;
12109
+ const slotResult = await claimForegroundRunSlot();
12110
+ if (slotResult.earlyResponse !== null) {
12111
+ return slotResult.earlyResponse;
12112
+ }
12113
+ const preparedResult = await runOnRunPreparedHook();
12114
+ if (preparedResult.earlyResponse !== null) {
12115
+ return preparedResult.earlyResponse;
12116
+ }
12117
+ const dispatchResult = await dispatchDurableBackgroundRun();
12118
+ if (dispatchResult.earlyResponse !== null) {
12119
+ return dispatchResult.earlyResponse;
12120
+ }
12121
+ contextPrefetchDeadlineAt = Date.now() + 1_300;
12122
+ }
12005
12123
  attachmentHydrationBudget ??= createOwnedAttachmentHydrationBudget();
12006
12124
  const resolvedHistoryImages = await hydrateStructuredHistoryImageReferences(requestStructuredHistory, { vision: modelSupportsVision, budget: attachmentHydrationBudget });
12007
12125
  const modelPreparedContext = await preparedRequest?.prepareAfterModel?.({
@@ -12034,9 +12152,6 @@ export function createProductionAgentHandler(options) {
12034
12152
  userEmail: ownerEmail ?? getRequestUserEmail() ?? null,
12035
12153
  orgId: getRequestOrgId() ?? null,
12036
12154
  }).catch(() => readAgentLoopSettings({}));
12037
- const promptRunContext = ensureRequestRunContext();
12038
- if (promptRunContext)
12039
- promptRunContext.appDiscoveryQuery = requestMessage;
12040
12155
  let systemPromptError = null;
12041
12156
  const systemPromptThunk = () => (async () => {
12042
12157
  const sysPromptStart = Date.now();
@@ -12212,6 +12327,30 @@ export function createProductionAgentHandler(options) {
12212
12327
  const skillLines = [];
12213
12328
  const agentLines = [];
12214
12329
  const jobLines = [];
12330
+ const detailResources = allResources.filter((r) => {
12331
+ const kind = getResourceKind(r.path);
12332
+ return (kind === "skill" ||
12333
+ kind === "agent" ||
12334
+ kind === "remote-agent");
12335
+ });
12336
+ const fullById = new Map();
12337
+ if (detailResources.length > 0) {
12338
+ const resourceOpts = {
12339
+ userEmail: ownerEmail,
12340
+ ...(orgId !== undefined ? { orgId } : {}),
12341
+ };
12342
+ const concurrency = Math.min(4, detailResources.length);
12343
+ let nextIndex = 0;
12344
+ await Promise.all(Array.from({ length: concurrency }, async () => {
12345
+ while (nextIndex < detailResources.length) {
12346
+ const item = detailResources.at(nextIndex++);
12347
+ if (!item)
12348
+ break;
12349
+ const full = await resourceGet(item.id, resourceOpts);
12350
+ fullById.set(item.id, full);
12351
+ }
12352
+ }));
12353
+ }
12215
12354
  for (const r of allResources) {
12216
12355
  const scope = isWorkspaceResourceOwner(r.owner)
12217
12356
  ? "workspace"
@@ -12230,10 +12369,7 @@ export function createProductionAgentHandler(options) {
12230
12369
  if (kind === "skill" ||
12231
12370
  kind === "agent" ||
12232
12371
  kind === "remote-agent") {
12233
- const full = await resourceGet(r.id, {
12234
- userEmail: ownerEmail,
12235
- orgId,
12236
- });
12372
+ const full = fullById.get(r.id);
12237
12373
  if (!full)
12238
12374
  continue;
12239
12375
  if (kind === "skill") {
@@ -12325,7 +12461,7 @@ export function createProductionAgentHandler(options) {
12325
12461
  presendCap("priorConnection",
12326
12462
  // The foreground of a dispatched run never prompts the model; the
12327
12463
  // worker re-reads, so reading here would pay for it twice.
12328
- () => threadId && !dispatchToBackground
12464
+ () => threadId && (!dispatchToBackground || backgroundDispatchAttempted)
12329
12465
  ? resolvePriorConnectionNote({
12330
12466
  threadId,
12331
12467
  orgId: getRequestOrgId() ?? null,
@@ -12337,12 +12473,25 @@ export function createProductionAgentHandler(options) {
12337
12473
  setupMark("ctxAll");
12338
12474
  workerStep("context_all");
12339
12475
  if (systemPromptError) {
12476
+ const err = systemPromptError;
12477
+ if (runRowState.foregroundInserted || runRowState.durableInserted) {
12478
+ try {
12479
+ const terminalized = await updateRunStatusIfRunning(runId, "errored");
12480
+ if (terminalized) {
12481
+ await setRunTerminalReason(runId, "system_prompt_failed");
12482
+ await setRunError(runId, "system_prompt_failed", err.message);
12483
+ }
12484
+ }
12485
+ catch (cleanupErr) {
12486
+ console.warn("[agent-chat] failed to mark run errored after system prompt failure:", cleanupErr);
12487
+ }
12488
+ }
12489
+ await setupResumeClaim?.release();
12340
12490
  if (isBackgroundWorker)
12341
- throw systemPromptError;
12491
+ throw err;
12342
12492
  setResponseHeader(event, "Content-Type", "text/event-stream");
12343
12493
  setResponseHeader(event, "Cache-Control", "no-cache");
12344
12494
  const encoder = new TextEncoder();
12345
- const err = systemPromptError;
12346
12495
  return new ReadableStream({
12347
12496
  start(controller) {
12348
12497
  controller.enqueue(encoder.encode(`data: ${JSON.stringify({ type: "error", error: `Failed to load system prompt: ${err.message}` })}\n\n`));
@@ -12395,10 +12544,13 @@ export function createProductionAgentHandler(options) {
12395
12544
  const jevContextMaxChars = options.jevContextCompact
12396
12545
  ? Math.max(0, COMPACT_PROMPT_RESOURCES_TOTAL_MAX_CHARS - systemPrompt.length - 2)
12397
12546
  : undefined;
12547
+ const effectiveDispatchToBackground = backgroundDispatchAttempted
12548
+ ? false
12549
+ : dispatchToBackground;
12398
12550
  const [requestTools, jevPreload] = await Promise.all([
12399
12551
  preloadJevTools({
12400
12552
  request: jevRequestContext,
12401
- skip: Boolean(internalContinuation || dispatchToBackground),
12553
+ skip: Boolean(internalContinuation || effectiveDispatchToBackground),
12402
12554
  deadlineAt: contextPrefetchDeadlineAt,
12403
12555
  apiKey: jevContextCredentials.apiKey,
12404
12556
  personalApiKey: jevContextCredentials.personalApiKey,
@@ -12424,7 +12576,7 @@ export function createProductionAgentHandler(options) {
12424
12576
  compact: options.jevContextCompact,
12425
12577
  maxChars: jevContextMaxChars,
12426
12578
  contextPrefetchDeadlineAt,
12427
- dispatchToBackground,
12579
+ dispatchToBackground: effectiveDispatchToBackground,
12428
12580
  internalContinuation: Boolean(internalContinuation),
12429
12581
  candidates: jevPromptCandidates,
12430
12582
  fallbackCandidateIds: jevFallbackCandidateIds,
@@ -12543,87 +12695,14 @@ export function createProductionAgentHandler(options) {
12543
12695
  tools: requestTools,
12544
12696
  availableToolCount: availableRequestTools.length,
12545
12697
  });
12546
- const isChainedBackgroundContinuation = isBackgroundWorker && backgroundContinuationCount > 0;
12547
- const isReaperSuccessor = isBackgroundWorker &&
12548
- typeof mutableBody[AGENT_CHAT_RECOVERY_OF_RUN_FIELD] === "string" &&
12549
- Boolean(mutableBody[AGENT_CHAT_RECOVERY_OF_RUN_FIELD]);
12550
- const isClientTurnContinuation = !isBackgroundWorker &&
12551
- internalContinuation === true &&
12552
- !continueOf &&
12553
- !approvedToolCallsForExecution?.length &&
12554
- typeof message === "string" &&
12555
- message.startsWith(AGENT_INTERNAL_CONTINUE_PROMPT) &&
12556
- typeof threadId === "string" &&
12557
- threadId.trim().length > 0 &&
12558
- typeof requestTurnId === "string" &&
12559
- requestTurnId.trim().length > 0;
12560
- const shouldRecoverCompletedExecutionSteps = isChainedBackgroundContinuation ||
12561
- isReaperSuccessor ||
12562
- Boolean(continueOf) ||
12563
- isClientTurnContinuation;
12564
- const runId = backgroundRunMarker?.runId ?? generateRunId();
12565
- const effectiveThreadId = threadId ?? runId;
12566
- const effectiveTurnId = typeof backgroundRunMarker?.turnId === "string" &&
12567
- backgroundRunMarker.turnId.trim()
12568
- ? backgroundRunMarker.turnId.trim()
12569
- : (resolvedApprovalTurnId ??
12570
- (typeof requestTurnId === "string" && requestTurnId.trim()
12571
- ? requestTurnId.trim()
12572
- : runId));
12573
- // Only a fresh turn the owner is driving from the page right now hands its
12574
- // foreground standing to the durable run; continuations never mint one.
12575
- if (dispatchToBackground && getAppConfig().agent.interactiveChatTurns) {
12576
- const grant = mintDurableTurnGrant({
12577
- runId,
12578
- turnId: effectiveTurnId,
12579
- initiator: turnInitiator,
12580
- interactive: isProviderInteractiveScope(),
12581
- continuation: internalContinuation === true ||
12582
- Boolean(continueOf) ||
12583
- Boolean(requestedAutoContinueOfRunId) ||
12584
- Boolean(requestedContinueOfRunId),
12585
- lifetimeMs: MAX_TURN_WALL_CLOCK_MS,
12586
- });
12587
- if (grant)
12588
- mutableBody[AGENT_CHAT_TURN_GRANT_FIELD] = grant;
12589
- }
12590
- let durableDispatchPayload;
12591
- if (dispatchToBackground) {
12592
- try {
12593
- const dispatchBody = {
12594
- ...body,
12595
- ...(Array.isArray(attachments) || requestAttachments.length > 0
12596
- ? { attachments: requestAttachments }
12597
- : {}),
12598
- };
12599
- // This one-time claim authorizes only the request that consumes it.
12600
- delete dispatchBody.queuedMessageClaimId;
12601
- durableDispatchPayload = serializeDurableDispatchPayload(dispatchBody);
12698
+ async function claimForegroundRunSlot() {
12699
+ if (!threadId || isBackgroundWorker) {
12700
+ return { earlyResponse: null };
12602
12701
  }
12603
- catch (error) {
12604
- if (!(error instanceof DurableAttachmentReferenceRequiredError)) {
12605
- throw error;
12606
- }
12607
- setResponseStatus(event, 503);
12608
- return {
12609
- error: error.message,
12610
- code: error.code,
12611
- retryable: false,
12612
- };
12613
- }
12614
- }
12615
- const foregroundSelfChainEligible = !isBackgroundWorker &&
12616
- !dispatchToBackground &&
12617
- typeof threadId === "string" &&
12618
- threadId.trim().length > 0 &&
12619
- isAgentChatForegroundSelfChainEnabled();
12620
- let foregroundRunRowInserted = false;
12621
- let setupResumeClaim;
12622
- if (threadId && !isBackgroundWorker) {
12623
12702
  if (typeof requestTurnId === "string" &&
12624
12703
  requestTurnId &&
12625
12704
  (await isTurnAborted(threadId, requestTurnId))) {
12626
- return { ok: true, stopped: true };
12705
+ return { earlyResponse: { ok: true, stopped: true } };
12627
12706
  }
12628
12707
  const setupResumeOfRunId = setupResumeRefusedRunId(body);
12629
12708
  setupResumeClaim =
@@ -12635,9 +12714,11 @@ export function createProductionAgentHandler(options) {
12635
12714
  turnId: effectiveTurnId,
12636
12715
  })
12637
12716
  : undefined;
12717
+ prepCleanup.setupResumeClaim = setupResumeClaim;
12638
12718
  if (setupResumeOfRunId && ownerEmail && !setupResumeClaim) {
12639
- // Another tab already sent this refused prompt again.
12640
- return { ok: true, stopped: true, resumeAlreadySent: true };
12719
+ return {
12720
+ earlyResponse: { ok: true, stopped: true, resumeAlreadySent: true },
12721
+ };
12641
12722
  }
12642
12723
  let slot;
12643
12724
  try {
@@ -12652,7 +12733,6 @@ export function createProductionAgentHandler(options) {
12652
12733
  if (ownerEmail && !isAuthorizedApprovalContinuation) {
12653
12734
  await ensureAgentToolApprovalTable();
12654
12735
  }
12655
- // The inbox read runs under the slot lock, but its schema must be ready first.
12656
12736
  await queuedSubmissionStore?.ensureChatThreadTables();
12657
12737
  slot = await tryClaimRunSlot(threadId, runId, undefined, {
12658
12738
  turnId: effectiveTurnId,
@@ -12668,7 +12748,7 @@ export function createProductionAgentHandler(options) {
12668
12748
  : foregroundSelfChainEligible
12669
12749
  ? "foreground-self-chain"
12670
12750
  : "foreground",
12671
- ...(dispatchToBackground
12751
+ ...(dispatchToBackground && durableDispatchPayload !== undefined
12672
12752
  ? { dispatchPayload: durableDispatchPayload }
12673
12753
  : {}),
12674
12754
  ...(continueOf ? { continueOf } : {}),
@@ -12691,49 +12771,60 @@ export function createProductionAgentHandler(options) {
12691
12771
  if (error instanceof AgentTurnInitiatorMismatchError ||
12692
12772
  error instanceof AgentTurnInitiatorUnavailableError) {
12693
12773
  setResponseStatus(event, 409);
12694
- return { error: "This agent turn cannot resume for this initiator" };
12774
+ return {
12775
+ earlyResponse: {
12776
+ error: "This agent turn cannot resume for this initiator",
12777
+ },
12778
+ };
12695
12779
  }
12696
12780
  throw error;
12697
12781
  }
12698
12782
  if (slot.turnAborted) {
12699
12783
  await setupResumeClaim?.release();
12700
- return { ok: true, stopped: true };
12784
+ return { earlyResponse: { ok: true, stopped: true } };
12701
12785
  }
12702
12786
  if (slot.continueRefused) {
12703
12787
  await setupResumeClaim?.release();
12704
12788
  setResponseStatus(event, 409);
12705
- return continueRefusal(slot.continueRefused);
12789
+ return { earlyResponse: continueRefusal(slot.continueRefused) };
12706
12790
  }
12707
12791
  if (slot.completedRunId) {
12708
12792
  const stream = await replayCompletedTurn(threadId, effectiveTurnId);
12709
12793
  if (!stream) {
12710
12794
  setResponseStatus(event, 500);
12711
- return { error: "Failed to replay completed agent run" };
12795
+ return {
12796
+ earlyResponse: { error: "Failed to replay completed agent run" },
12797
+ };
12712
12798
  }
12713
12799
  setResponseHeader(event, "Content-Type", "text/event-stream");
12714
12800
  setResponseHeader(event, "Cache-Control", "no-cache");
12715
12801
  setResponseHeader(event, "Connection", "keep-alive");
12716
12802
  setResponseHeader(event, "X-Run-Id", slot.completedRunId);
12717
- // The client leaves a replay's turn out unless named here, and this
12718
- // replay was found by its turn, so the stored turn is known.
12719
12803
  setRunTurnIdHeader(event, effectiveTurnId);
12720
12804
  setResponseHeader(event, "X-Dispatch-Mode", "replay");
12721
- return stream;
12805
+ return { earlyResponse: stream };
12722
12806
  }
12723
12807
  if (!slot.claimed) {
12724
12808
  await setupResumeClaim?.release();
12725
12809
  if (slot.queuedSubmissionPending) {
12726
12810
  const queued = await tryAdmitBusySubmission();
12727
12811
  if (queued !== null)
12728
- return queued;
12729
- return runSlotBusy(event, null);
12812
+ return { earlyResponse: queued };
12813
+ return { earlyResponse: runSlotBusy(event, null) };
12730
12814
  }
12731
12815
  const queued = await tryAdmitBusySubmission();
12732
12816
  if (queued !== null)
12733
- return queued;
12734
- return runSlotBusy(event, slot.activeRunId);
12817
+ return { earlyResponse: queued };
12818
+ return { earlyResponse: runSlotBusy(event, slot.activeRunId) };
12819
+ }
12820
+ runRowState.foregroundInserted = true;
12821
+ return { earlyResponse: null };
12822
+ }
12823
+ if (!backgroundDispatchAttempted) {
12824
+ const slotResult = await claimForegroundRunSlot();
12825
+ if (slotResult.earlyResponse !== null) {
12826
+ return slotResult.earlyResponse;
12735
12827
  }
12736
- foregroundRunRowInserted = true;
12737
12828
  }
12738
12829
  const approvalStoreBinding = (binding) => {
12739
12830
  if (!ownerEmail) {
@@ -12777,10 +12868,6 @@ export function createProductionAgentHandler(options) {
12777
12868
  await markRunAborted(runId, "user").catch(() => { });
12778
12869
  return { ok: true, stopped: true };
12779
12870
  }
12780
- const messageToPersist = typeof requestDisplayMessage === "string" &&
12781
- requestDisplayMessage.trim().length > 0
12782
- ? requestDisplayMessage
12783
- : requestMessage;
12784
12871
  const priorTurnInputTokensFromBody = Number(body[AGENT_CHAT_TURN_INPUT_TOKENS_FIELD]);
12785
12872
  let turnInputTokens = Number.isFinite(priorTurnInputTokensFromBody)
12786
12873
  ? Math.max(0, priorTurnInputTokensFromBody)
@@ -12897,7 +12984,10 @@ export function createProductionAgentHandler(options) {
12897
12984
  try {
12898
12985
  const { getThread } = await import("../chat-threads/store.js");
12899
12986
  const { recoverThreadHistoryForRequest } = await import("./thread-data-builder.js");
12900
- const recovered = recoverThreadHistoryForRequest((await getThread(threadId))?.threadData);
12987
+ const threadData = (await getThread(threadId))?.threadData;
12988
+ const recovered = recoverThreadHistoryForRequest(threadData, backgroundDispatchAttempted
12989
+ ? { excludeSubmittedTurnId: effectiveTurnId }
12990
+ : undefined);
12901
12991
  if (recovered.length > 0)
12902
12992
  messages.unshift(...recovered);
12903
12993
  }
@@ -12923,7 +13013,12 @@ export function createProductionAgentHandler(options) {
12923
13013
  }
12924
13014
  setupMark("depsThread");
12925
13015
  workerStep("owner_thread");
12926
- if (options.onRunPrepared && !internalContinuation && !isBackgroundWorker) {
13016
+ async function runOnRunPreparedHook() {
13017
+ if (!options.onRunPrepared ||
13018
+ internalContinuation ||
13019
+ isBackgroundWorker) {
13020
+ return { earlyResponse: null };
13021
+ }
12927
13022
  try {
12928
13023
  const prepared = await options.onRunPrepared({
12929
13024
  runId,
@@ -12948,7 +13043,7 @@ export function createProductionAgentHandler(options) {
12948
13043
  ? prepared.duplicateRunId.trim()
12949
13044
  : undefined;
12950
13045
  if (duplicateRunId) {
12951
- if (foregroundRunRowInserted) {
13046
+ if (runRowState.foregroundInserted) {
12952
13047
  await markRunAborted(runId, "duplicate_submission");
12953
13048
  }
12954
13049
  await setupResumeClaim?.release();
@@ -12956,9 +13051,11 @@ export function createProductionAgentHandler(options) {
12956
13051
  if (!stream) {
12957
13052
  setResponseStatus(event, 503);
12958
13053
  return {
12959
- error: "The accepted submission run is no longer replayable",
12960
- code: "queued_message_run_unavailable",
12961
- retryable: true,
13054
+ earlyResponse: {
13055
+ error: "The accepted submission run is no longer replayable",
13056
+ code: "queued_message_run_unavailable",
13057
+ retryable: true,
13058
+ },
12962
13059
  };
12963
13060
  }
12964
13061
  setResponseHeader(event, "Content-Type", "text/event-stream");
@@ -12967,11 +13064,11 @@ export function createProductionAgentHandler(options) {
12967
13064
  setResponseHeader(event, "X-Run-Id", duplicateRunId);
12968
13065
  setRunTurnIdHeader(event, getRun(duplicateRunId)?.turnId);
12969
13066
  setResponseHeader(event, "X-Dispatch-Mode", "replay");
12970
- return stream;
13067
+ return { earlyResponse: stream };
12971
13068
  }
12972
13069
  }
12973
13070
  catch (error) {
12974
- if (foregroundRunRowInserted) {
13071
+ if (runRowState.foregroundInserted) {
12975
13072
  const terminalized = await updateRunStatusIfRunning(runId, "errored");
12976
13073
  if (terminalized) {
12977
13074
  await setRunTerminalReason(runId, "run_preparation_failed");
@@ -12980,14 +13077,20 @@ export function createProductionAgentHandler(options) {
12980
13077
  }
12981
13078
  throw error;
12982
13079
  }
13080
+ return { earlyResponse: null };
12983
13081
  }
12984
- if (dispatchToBackground) {
12985
- let backgroundRowInserted = foregroundRunRowInserted;
13082
+ async function dispatchDurableBackgroundRun() {
13083
+ if (!dispatchToBackground) {
13084
+ return { earlyResponse: null };
13085
+ }
13086
+ let backgroundRowInserted = runRowState.foregroundInserted;
12986
13087
  if (!backgroundRowInserted) {
12987
13088
  try {
12988
13089
  await insertRun(runId, effectiveThreadId, effectiveTurnId, {
12989
13090
  dispatchMode: "background",
12990
- dispatchPayload: durableDispatchPayload,
13091
+ ...(durableDispatchPayload !== undefined
13092
+ ? { dispatchPayload: durableDispatchPayload }
13093
+ : {}),
12991
13094
  ...(turnInitiator ? { turnInitiator } : {}),
12992
13095
  });
12993
13096
  backgroundRowInserted = true;
@@ -12998,27 +13101,19 @@ export function createProductionAgentHandler(options) {
12998
13101
  console.error("[agent-chat] background insertRun failed; falling back to inline:", err instanceof Error ? err.message : err);
12999
13102
  }
13000
13103
  }
13104
+ runRowState.durableInserted = backgroundRowInserted;
13001
13105
  if (backgroundRowInserted &&
13002
13106
  (await isTurnAborted(effectiveThreadId, effectiveTurnId))) {
13003
13107
  await markRunAborted(runId, "user");
13004
- return { ok: true, stopped: true };
13108
+ return { earlyResponse: { ok: true, stopped: true } };
13005
13109
  }
13006
13110
  let dispatched = false;
13007
13111
  const backgroundDispatchPath = resolveAgentChatProcessRunDispatchPath();
13008
13112
  const expectsNetlifyBackgroundFunction = dispatchPathTargetsNetlifyBackgroundFunction(backgroundDispatchPath);
13113
+ prepCleanup.dispatchMayOwnRun = true;
13009
13114
  try {
13010
13115
  await fireInternalDispatch({
13011
13116
  event,
13012
- // On hosted Netlify this resolves to the background function's DEFAULT
13013
- // url (/.netlify/functions/<name>, or per-app <app>-agent-background for
13014
- // workspaces) — the function declares NO custom config.path, so it keeps
13015
- // its default url, and `background: true` makes that url async (202,
13016
- // 15-min budget). The `server` /* catch-all already excludes /.netlify/*
13017
- // so it never shadows it. Off-Netlify this resolves to the framework
13018
- // `_process-run` route and the same in-process catch-all handles it
13019
- // inline. `fireInternalDispatch` strips the app base path for
13020
- // /.netlify/* targets so the request reaches the host-root function url;
13021
- // the Authorization Bearer HMAC is preserved either way.
13022
13117
  path: backgroundDispatchPath,
13023
13118
  taskId: runId,
13024
13119
  ...(expectsNetlifyBackgroundFunction
@@ -13070,30 +13165,59 @@ export function createProductionAgentHandler(options) {
13070
13165
  setResponseHeader(event, "X-Run-Id", runId);
13071
13166
  setRunTurnIdHeader(event, effectiveTurnId);
13072
13167
  setResponseHeader(event, "X-Dispatch-Mode", "background");
13073
- return stream;
13168
+ return { earlyResponse: stream };
13074
13169
  }
13075
13170
  const terminalReason = backgroundOutcome.action === "stream"
13076
13171
  ? "background_subscribe_failed"
13077
13172
  : "background_dispatch_failed";
13078
- const statusUpdated = await updateRunStatusIfRunning(runId, "errored").catch(() => false);
13079
- if (statusUpdated) {
13080
- await setRunTerminalReason(runId, terminalReason).catch(() => { });
13173
+ try {
13174
+ const statusUpdated = await updateRunStatusIfRunning(runId, "errored");
13175
+ if (statusUpdated) {
13176
+ await setRunTerminalReason(runId, terminalReason);
13177
+ }
13178
+ }
13179
+ catch (cleanupErr) {
13180
+ console.warn("[agent-chat] failed to mark background run errored after subscribe failure:", cleanupErr);
13081
13181
  }
13082
13182
  setResponseStatus(event, 500);
13083
13183
  return {
13084
- error: backgroundOutcome.action === "stream"
13085
- ? "Failed to subscribe to background run"
13086
- : "Failed to dispatch background run",
13184
+ earlyResponse: {
13185
+ error: backgroundOutcome.action === "stream"
13186
+ ? "Failed to subscribe to background run"
13187
+ : "Failed to dispatch background run",
13188
+ },
13087
13189
  };
13088
13190
  }
13191
+ prepCleanup.dispatchMayOwnRun = false;
13089
13192
  if (backgroundOutcome.reason === "worker-never-claimed") {
13090
- const priorClaim = await readBackgroundRunClaim(runId).catch(() => null);
13091
- const priorDiag = priorClaim?.diagStage ?? "none";
13193
+ let priorDiag = "none";
13194
+ try {
13195
+ const priorClaim = await readBackgroundRunClaim(runId);
13196
+ priorDiag = priorClaim?.diagStage ?? "none";
13197
+ }
13198
+ catch (diagErr) {
13199
+ console.warn("[agent-chat] failed to read prior background claim diagnostic:", diagErr);
13200
+ }
13092
13201
  console.error("[agent-chat] background worker did not claim the 202-dispatched run " +
13093
13202
  `within grace; recovering inline. bgFnPriorDiag=${priorDiag}`, runId);
13094
- await recordRunDiagnostic(runId, RUN_DIAG_STAGE.foregroundInlineRecovery, `202 dispatched but no worker claimed within grace; bgFnPriorDiag=${priorDiag}`).catch(() => { });
13203
+ try {
13204
+ await recordRunDiagnostic(runId, RUN_DIAG_STAGE.foregroundInlineRecovery, `202 dispatched but no worker claimed within grace; bgFnPriorDiag=${priorDiag}`);
13205
+ }
13206
+ catch (diagErr) {
13207
+ console.warn("[agent-chat] failed to record foreground inline recovery diagnostic:", diagErr);
13208
+ }
13209
+ }
13210
+ return { earlyResponse: null };
13211
+ }
13212
+ if (!backgroundDispatchAttempted) {
13213
+ const preparedResult = await runOnRunPreparedHook();
13214
+ if (preparedResult.earlyResponse !== null) {
13215
+ return preparedResult.earlyResponse;
13216
+ }
13217
+ const dispatchResult = await dispatchDurableBackgroundRun();
13218
+ if (dispatchResult.earlyResponse !== null) {
13219
+ return dispatchResult.earlyResponse;
13095
13220
  }
13096
- // Fall through to the inline `startRun` path below.
13097
13221
  }
13098
13222
  const trackedProgressOwner = trackInRunsTray === true && ownerEmail ? ownerEmail : null;
13099
13223
  const trackedProgressRunId = trackedProgressOwner
@@ -13309,6 +13433,7 @@ export function createProductionAgentHandler(options) {
13309
13433
  return { ok: true, skipped: "setup-deadline" };
13310
13434
  }
13311
13435
  // raw-sql-ok: run callback IDs and prompts reach static queries as bound arguments.
13436
+ prepCleanup.runStarted = true;
13312
13437
  const startedRun = startRun(runId, effectiveThreadId, async (rawSend, signal, control) => {
13313
13438
  if (backgroundSetupDeadlineExceeded?.())
13314
13439
  return;
@@ -14045,7 +14170,7 @@ export function createProductionAgentHandler(options) {
14045
14170
  : foregroundSelfChainEligible
14046
14171
  ? "foreground-self-chain"
14047
14172
  : "foreground",
14048
- runRowAlreadyInserted: foregroundRunRowInserted,
14173
+ runRowAlreadyInserted: runRowState.foregroundInserted,
14049
14174
  executionLease: true,
14050
14175
  // An anonymous run is not a user; `run_started` does not name one either.
14051
14176
  userId: turnInitiator?.anonymous
@@ -14080,6 +14205,37 @@ export function createProductionAgentHandler(options) {
14080
14205
  setRunTurnIdHeader(event, effectiveTurnId);
14081
14206
  setResponseHeader(event, "X-Dispatch-Mode", foregroundSelfChainEligible ? "foreground-self-chain" : "foreground");
14082
14207
  return stream;
14208
+ };
14209
+ return defineEventHandler(async (event) => {
14210
+ const prepCleanup = { runStarted: false };
14211
+ try {
14212
+ return await handleAgentChatEvent(event, prepCleanup);
14213
+ }
14214
+ catch (error) {
14215
+ if (!prepCleanup.runStarted &&
14216
+ !prepCleanup.dispatchMayOwnRun &&
14217
+ prepCleanup.runId &&
14218
+ (prepCleanup.runRowState?.foregroundInserted ||
14219
+ prepCleanup.runRowState?.durableInserted)) {
14220
+ try {
14221
+ const terminalized = await updateRunStatusIfRunning(prepCleanup.runId, "errored");
14222
+ if (terminalized) {
14223
+ await setRunTerminalReason(prepCleanup.runId, "run_preparation_failed");
14224
+ await setRunError(prepCleanup.runId, "run_preparation_failed", error instanceof Error ? error.message : String(error));
14225
+ }
14226
+ }
14227
+ catch (cleanupErr) {
14228
+ console.warn("[agent-chat] failed to mark run errored after preparation failure:", cleanupErr);
14229
+ }
14230
+ }
14231
+ try {
14232
+ await prepCleanup.setupResumeClaim?.release();
14233
+ }
14234
+ catch (releaseErr) {
14235
+ console.warn("[agent-chat] failed to release setup resume claim:", releaseErr);
14236
+ }
14237
+ throw error;
14238
+ }
14083
14239
  });
14084
14240
  }
14085
14241
  export { getActiveRunForThread, getActiveRunForThreadAsync, getRun, abortRun, abortRunDurably, abortRunAndTurnDurably, abortRunAtSafeBoundaryDurably, abortTurnByRefDurably, abortTurnDurably, subscribeToRun, };