@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,4 +1,5 @@
1
1
  import { MCP_APP_CHAT_BRIDGE_QUERY_PARAM } from "../shared/embed-auth.js";
2
+ import { MCP_APP_HOST_FILL_ATTRIBUTE, MCP_APP_PANE_FILL_MAX_HEIGHT, } from "../shared/mcp-app-display.js";
2
3
  const MCP_APP_IMPORT = "https://esm.sh/@modelcontextprotocol/ext-apps@1.7.5/app-with-deps";
3
4
  export const MCP_APP_REQUEST_ORIGIN_CSP_SOURCE = "$requestOrigin";
4
5
  const MCP_APP_WRAPPER_CHROME_HEIGHT = 44;
@@ -28,8 +29,12 @@ export function embedApp(options = {}) {
28
29
  ...(options.description ? { description: options.description } : {}),
29
30
  html: (ctx) => {
30
31
  const remoteBridgeFallbackEnabled = ctx.catalogMode !== "directory";
32
+ // A directory widget is an editor that lives in a host pane, never a
33
+ // content-sized card, so it fills the pane even when the host will not
34
+ // give it a height (see paneFillHeight).
35
+ const fillsPane = ctx.catalogMode === "directory";
31
36
  return `<!doctype html>
32
- <html lang="en">
37
+ <html lang="en"${fillsPane ? ` ${MCP_APP_HOST_FILL_ATTRIBUTE}="1"` : ""}>
33
38
  <head>
34
39
  <meta charset="utf-8">
35
40
  <meta name="viewport" content="width=device-width, initial-scale=1">
@@ -55,6 +60,11 @@ export function embedApp(options = {}) {
55
60
  .fallback-copy { max-width: 520px; color: color-mix(in srgb, CanvasText 64%, Canvas); font-size: 13px; line-height: 1.45; }
56
61
  .fallback-actions { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 8px; }
57
62
  .fallback-url { max-width: min(560px, 100%); overflow-wrap: anywhere; color: color-mix(in srgb, CanvasText 76%, Canvas); font-size: 12px; }
63
+ html[${MCP_APP_HOST_FILL_ATTRIBUTE}], html[${MCP_APP_HOST_FILL_ATTRIBUTE}] body { height: 100%; }
64
+ html[${MCP_APP_HOST_FILL_ATTRIBUTE}] .shell { display: flex; flex-direction: column; gap: 0; height: 100vh; height: 100dvh; min-height: 0; }
65
+ html[${MCP_APP_HOST_FILL_ATTRIBUTE}] .bar { display: none; }
66
+ html[${MCP_APP_HOST_FILL_ATTRIBUTE}] .stage { flex: 1 1 auto; min-height: 0; }
67
+ html[${MCP_APP_HOST_FILL_ATTRIBUTE}] iframe, html[${MCP_APP_HOST_FILL_ATTRIBUTE}] .message, html[${MCP_APP_HOST_FILL_ATTRIBUTE}] .fallback { height: 100% !important; min-height: 0; }
58
68
  </style>
59
69
  </head>
60
70
  <body
@@ -89,6 +99,9 @@ export function embedApp(options = {}) {
89
99
  const chatBridgeParam = ${JSON.stringify(MCP_APP_CHAT_BRIDGE_QUERY_PARAM)};
90
100
  const defaultIntrinsicHeight = ${height};
91
101
  const chromeHeight = ${MCP_APP_WRAPPER_CHROME_HEIGHT};
102
+ const hostFillAttribute = ${JSON.stringify(MCP_APP_HOST_FILL_ATTRIBUTE)};
103
+ const fillsPane = ${fillsPane};
104
+ const paneFillMaxHeight = ${MCP_APP_PANE_FILL_MAX_HEIGHT};
92
105
  const frameReadyMessageDelays = [0, 200, 500, 1500, 3000, 7000, 15000, 30000];
93
106
  const frameReadyTimeoutMs = 45000;
94
107
  const frameLoadTimeoutMs = 45000;
@@ -153,6 +166,76 @@ export function embedApp(options = {}) {
153
166
  finiteNumber(context.containerDimensions && context.containerDimensions.maxHeight);
154
167
  }
155
168
 
169
+ // Keep in sync with mcpAppHostFillsContainer (shared/mcp-app-display.ts);
170
+ // embed-app.spec.ts runs both over the same table.
171
+ function hostFillsContainer(context) {
172
+ const record = objectValue(context);
173
+ const dimensions = objectValue(record.containerDimensions);
174
+ const fixedHeight = dimensions.height;
175
+ if (typeof fixedHeight === "number" && Number.isFinite(fixedHeight) && fixedHeight > 0) {
176
+ return true;
177
+ }
178
+ return record.displayMode === "fullscreen" || record.displayMode === "pip";
179
+ }
180
+
181
+ // A fullscreen view or fixed-height container sizes the frame itself, so
182
+ // the shell fills it with CSS and never reports a height. An inline card is
183
+ // the opposite: the host follows the height reported here, so filling the
184
+ // frame would feed its own size back into it. Never derive the height from
185
+ // the frame's innerHeight. A directory widget fills with CSS in both cases;
186
+ // only the host-sized one still reports (see paneFillHeight).
187
+ function applyHostFillMode() {
188
+ const context = hostState().context || {};
189
+ const hostFill = hostFillsContainer(context);
190
+ const root = document.documentElement;
191
+ if (hostFill || fillsPane) {
192
+ root.setAttribute(hostFillAttribute, "1");
193
+ if (appFrame) appFrame.style.height = "";
194
+ } else {
195
+ root.removeAttribute(hostFillAttribute);
196
+ }
197
+ body.dataset.hostFill = hostFill ? "1" : "0";
198
+ body.dataset.paneFill = fillsPane && !hostFill ? "1" : "0";
199
+ body.dataset.hostDisplayMode = typeof context.displayMode === "string" ? context.displayMode : "";
200
+ return hostFill;
201
+ }
202
+
203
+ // Codex and ChatGPT side panes size the widget frame only from the height
204
+ // reported here, and their containerDimensions are a { maxHeight } hint
205
+ // (about 360 inline on Codex), not the pane's height. A content-sized
206
+ // report leaves the pane's own background showing under the frame, so a
207
+ // directory widget reports the most height the viewer's screen can show and
208
+ // lets the host clamp it to the pane. It is a constant of the viewer, never
209
+ // of the frame or the content, so it cannot feed back into itself.
210
+ function paneFillHeight(context) {
211
+ const screenHeight = finiteNumber(window.screen && window.screen.availHeight) || 0;
212
+ const hostMaxHeight = contextMaxHeight(context) || 0;
213
+ // The configured height is only a fallback: as a floor it would push the
214
+ // frame past a pane shorter than it.
215
+ const height = screenHeight
216
+ ? Math.max(screenHeight, hostMaxHeight)
217
+ : Math.max(defaultIntrinsicHeight, hostMaxHeight);
218
+ return Math.floor(Math.min(paneFillMaxHeight, height));
219
+ }
220
+
221
+ // The app document lifts its inline-card height clamp when the host owns
222
+ // the frame's height; in a pane the shell owns it, so tell the app so.
223
+ function hostStateForApp() {
224
+ const state = hostState();
225
+ if (!fillsPane || hostFillsContainer(state.context)) return state;
226
+ const context = objectValue(state.context);
227
+ return {
228
+ ...state,
229
+ context: {
230
+ ...context,
231
+ containerDimensions: {
232
+ ...objectValue(context.containerDimensions),
233
+ height: paneFillHeight(context)
234
+ }
235
+ }
236
+ };
237
+ }
238
+
156
239
  function visibleIntrinsicHeight() {
157
240
  const context = hostState().context || {};
158
241
  const hostMaxHeight = contextMaxHeight(context);
@@ -382,7 +465,7 @@ export function embedApp(options = {}) {
382
465
  }
383
466
 
384
467
  function sendHostContext() {
385
- sendToAppFrame({ type: "agentNative.mcpHostContext", data: hostState() });
468
+ sendToAppFrame({ type: "agentNative.mcpHostContext", data: hostStateForApp() });
386
469
  }
387
470
 
388
471
  function sendFrameReadyMessages(frame) {
@@ -1028,6 +1111,30 @@ export function embedApp(options = {}) {
1028
1111
  };
1029
1112
  }
1030
1113
 
1114
+ // A directory widget on a host that offers fullscreen asks for it once, on
1115
+ // the first click into the app: never on load, which would take over the
1116
+ // chat before the user touched the widget. The flag is not reset, so a host
1117
+ // that refuses is not asked again.
1118
+ let fullscreenRequested = false;
1119
+ function requestFullscreenOnFirstInteraction() {
1120
+ if (!fillsPane || fullscreenRequested) return;
1121
+ const context = hostState().context || {};
1122
+ if ((context.displayMode || "inline") !== "inline") return;
1123
+ if (!supportedDisplayMode("fullscreen")) return;
1124
+ fullscreenRequested = true;
1125
+ void requestHostDisplayMode("fullscreen").catch((err) => {
1126
+ console.warn("[agent-native] MCP host rejected display mode request", err);
1127
+ });
1128
+ }
1129
+
1130
+ // Focus moving into the cross-origin app frame is the only signal the
1131
+ // shell gets that the user clicked in it.
1132
+ window.addEventListener("blur", () => {
1133
+ if (appFrame && document.activeElement === appFrame) {
1134
+ requestFullscreenOnFirstInteraction();
1135
+ }
1136
+ });
1137
+
1031
1138
  function setMessage(message) {
1032
1139
  stage.innerHTML = '<div class="message">' + esc(message) + '</div>';
1033
1140
  }
@@ -1445,8 +1552,10 @@ export function embedApp(options = {}) {
1445
1552
  }
1446
1553
 
1447
1554
  function notifyHostHeight() {
1448
- const intrinsic = visibleIntrinsicHeight();
1449
- const height = applyIntrinsicHeight(intrinsic);
1555
+ if (applyHostFillMode()) return;
1556
+ const height = fillsPane
1557
+ ? paneFillHeight(hostState().context || {})
1558
+ : applyIntrinsicHeight(visibleIntrinsicHeight());
1450
1559
  if (!openAiBridge || typeof openAiBridge.notifyIntrinsicHeight !== "function") {
1451
1560
  if (app && typeof app.sendSizeChanged === "function") {
1452
1561
  try {
@@ -1973,8 +2082,33 @@ export function embedApp(options = {}) {
1973
2082
  let rpcId = 0;
1974
2083
  let connectPromise = null;
1975
2084
  let hostContext = {};
2085
+ let hostContextFields = {};
1976
2086
  const pendingRequests = new Map();
1977
2087
 
2088
+ // ui/initialize answers { hostContext }; host-context-changed carries a
2089
+ // partial context, so merge it instead of replacing what we know.
2090
+ function setHostContext(payload, replace) {
2091
+ const nextHostContext = objectValue(payload);
2092
+ if (replace) hostContext = nextHostContext;
2093
+ const fields = objectValue(nextHostContext.hostContext || nextHostContext.context || nextHostContext);
2094
+ if (replace) {
2095
+ hostContextFields = { ...fields };
2096
+ } else {
2097
+ const merged = { ...hostContextFields, ...fields };
2098
+ if (
2099
+ fields.containerDimensions &&
2100
+ typeof fields.containerDimensions === "object" &&
2101
+ !Array.isArray(fields.containerDimensions)
2102
+ ) {
2103
+ merged.containerDimensions = {
2104
+ ...objectValue(hostContextFields.containerDimensions),
2105
+ ...fields.containerDimensions,
2106
+ };
2107
+ }
2108
+ hostContextFields = merged;
2109
+ }
2110
+ }
2111
+
1978
2112
  function rpcNotify(method, params) {
1979
2113
  window.parent.postMessage({ jsonrpc: "2.0", method, params: params || {} }, "*");
1980
2114
  }
@@ -2031,7 +2165,7 @@ export function embedApp(options = {}) {
2031
2165
  ontoolresult: null,
2032
2166
  onhostcontextchanged: null,
2033
2167
  getHostContext() {
2034
- return hostContext.context || hostContext;
2168
+ return hostContextFields;
2035
2169
  },
2036
2170
  getHostCapabilities() {
2037
2171
  return hostContext.capabilities || { tools: true, messaging: true };
@@ -2052,10 +2186,10 @@ export function embedApp(options = {}) {
2052
2186
  },
2053
2187
  nativeBridgeInitializeTimeoutMs
2054
2188
  );
2055
- hostContext = objectValue(result);
2189
+ setHostContext(result, true);
2056
2190
  rpcNotify("ui/notifications/initialized", {});
2057
2191
  if (typeof nativeApp.onhostcontextchanged === "function") {
2058
- nativeApp.onhostcontextchanged(hostContext);
2192
+ nativeApp.onhostcontextchanged(hostContextFields);
2059
2193
  }
2060
2194
  return hostContext;
2061
2195
  })().catch((err) => {
@@ -2127,9 +2261,9 @@ export function embedApp(options = {}) {
2127
2261
  message.method === "ui/notifications/host-context" ||
2128
2262
  message.method === "ui/notifications/context"
2129
2263
  ) {
2130
- hostContext = objectValue(params);
2264
+ setHostContext(params, false);
2131
2265
  if (typeof nativeApp.onhostcontextchanged === "function") {
2132
- nativeApp.onhostcontextchanged(hostContext);
2266
+ nativeApp.onhostcontextchanged(hostContextFields);
2133
2267
  }
2134
2268
  }
2135
2269
  }
@@ -1,6 +1,6 @@
1
1
  export { mountMCP } from "./server.js";
2
2
  export type { MCPConfig } from "./server.js";
3
- export { createMCPServerForRequest, verifyAuth, getAccessTokens, resolveOrgIdFromDomain, buildLinkArtifacts, } from "./build-server.js";
3
+ export { createMCPServerForRequest, verifyAuth, getAccessTokens, resolveOrgIdFromDomain, buildLinkArtifacts, getMcpDirectoryWidgetResourceUri, } from "./build-server.js";
4
4
  export type { MCPCallerIdentity, MCPRequestMeta } from "./build-server.js";
5
5
  export type { ExternalAgentPolicy } from "./external-agent-policy.js";
6
6
  export { runMCPStdio } from "./stdio.js";
package/dist/mcp/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { mountMCP } from "./server.js";
2
- export { createMCPServerForRequest, verifyAuth, getAccessTokens, resolveOrgIdFromDomain, buildLinkArtifacts, } from "./build-server.js";
2
+ export { createMCPServerForRequest, verifyAuth, getAccessTokens, resolveOrgIdFromDomain, buildLinkArtifacts, getMcpDirectoryWidgetResourceUri, } from "./build-server.js";
3
3
  export { runMCPStdio } from "./stdio.js";
4
4
  export { runScreenMemoryMCPStdio } from "./screen-memory-stdio.js";
5
5
  export { getBuiltinCrossAppTools } from "./builtin-tools.js";
@@ -45,6 +45,9 @@ export interface AgentToolCallMetric {
45
45
  }
46
46
  /** App-defined tool names collapse to `other` so they cannot mint series. */
47
47
  export declare function recordAgentToolCall(call: AgentToolCallMetric): void;
48
+ export type TraceWriteStage = "spans" | "summary" | "thread_org" | "write";
49
+ /** Counted once per failed stage of a run, never per span. */
50
+ export declare function recordTraceWriteFailure(stage: TraceWriteStage, error: unknown): void;
48
51
  /**
49
52
  * Export buffered telemetry before a serverless function can freeze. Never
50
53
  * delays a request by more than OBSERVABILITY_FLUSH_TIMEOUT_MS; each provider
@@ -72,6 +72,9 @@ function instruments() {
72
72
  flushFailures: meter.createCounter("agent_native.telemetry.flush_failures", {
73
73
  description: "Telemetry flushes that timed out or failed; their points were dropped.",
74
74
  }),
75
+ traceWriteFailures: meter.createCounter("agent_native.observability.trace_write_failures", {
76
+ description: "Runs whose trace spans or summary could not be persisted; their trace is incomplete or missing.",
77
+ }),
75
78
  };
76
79
  return cachedInstruments;
77
80
  }
@@ -154,6 +157,13 @@ export function recordAgentToolCall(call) {
154
157
  ...(call.errorType ? { "error.type": call.errorType } : {}),
155
158
  });
156
159
  }
160
+ /** Counted once per failed stage of a run, never per span. */
161
+ export function recordTraceWriteFailure(stage, error) {
162
+ instruments()?.traceWriteFailures.add(1, {
163
+ "agent_native.observability.stage": stage,
164
+ "error.type": flushErrorType(error),
165
+ });
166
+ }
157
167
  function flushErrorType(error) {
158
168
  return error instanceof Error && error.name ? error.name : "unknown";
159
169
  }
@@ -54,4 +54,26 @@ export const OBSERVABILITY_MIGRATIONS = [
54
54
  AND summary.org_id IS NOT NULL;
55
55
  `,
56
56
  },
57
+ {
58
+ version: 3,
59
+ name: "observability-org-scope-legacy-threads",
60
+ // A thread created without a request org kept org_id NULL, so every review
61
+ // join (thread.org_id = trace org) hid it. Adopt the org only when all of
62
+ // the owner's runs on the thread name the same one.
63
+ sql: `
64
+ UPDATE chat_threads AS thread
65
+ SET org_id = trace_org.org_id
66
+ FROM (
67
+ SELECT thread_id, LOWER(user_id) AS owner_key, MIN(org_id) AS org_id
68
+ FROM agent_trace_summaries
69
+ WHERE thread_id IS NOT NULL AND user_id IS NOT NULL
70
+ AND org_id IS NOT NULL
71
+ GROUP BY thread_id, LOWER(user_id)
72
+ HAVING COUNT(DISTINCT org_id) = 1
73
+ ) AS trace_org
74
+ WHERE thread.org_id IS NULL
75
+ AND thread.id = trace_org.thread_id
76
+ AND LOWER(thread.owner_email) = trace_org.owner_key;
77
+ `,
78
+ },
57
79
  ];
@@ -31,19 +31,26 @@ export declare function createObservabilityHandler(): import("h3").EventHandlerW
31
31
  message: string;
32
32
  summary?: undefined;
33
33
  spans?: undefined;
34
- id?: undefined;
35
34
  ok?: undefined;
36
35
  } | {
37
36
  message?: undefined;
38
37
  summary: import("./types.js").TraceSummary;
39
38
  spans: import("./types.js").TraceSpan[];
40
- id?: undefined;
41
39
  error?: undefined;
42
40
  ok?: undefined;
43
41
  } | {
44
42
  message?: undefined;
45
43
  summary?: undefined;
46
44
  spans?: undefined;
45
+ traceMissing: true;
46
+ id: string;
47
+ error?: undefined;
48
+ ok?: undefined;
49
+ } | {
50
+ message?: undefined;
51
+ summary?: undefined;
52
+ spans?: undefined;
53
+ traceMissing?: undefined;
47
54
  id: string;
48
55
  error?: undefined;
49
56
  ok?: undefined;
@@ -51,14 +58,12 @@ export declare function createObservabilityHandler(): import("h3").EventHandlerW
51
58
  message?: undefined;
52
59
  summary?: undefined;
53
60
  spans?: undefined;
54
- id?: undefined;
55
61
  error: any;
56
62
  ok?: undefined;
57
63
  } | {
58
64
  message?: undefined;
59
65
  summary?: undefined;
60
66
  spans?: undefined;
61
- id?: undefined;
62
- error?: undefined;
63
67
  ok: boolean;
68
+ error?: undefined;
64
69
  }>>;
@@ -1,6 +1,8 @@
1
1
  import { defineEventHandler, getHeader, getMethod, getQuery, setResponseHeader, setResponseStatus, } from "h3";
2
2
  import { isActionContractError } from "../action.js";
3
+ import { resolveThreadAccess } from "../chat-threads/store.js";
3
4
  import { getOrgContext } from "../org/context.js";
5
+ import { isOrgMember } from "../org/membership.js";
4
6
  import { getSession } from "../server/auth.js";
5
7
  import { readBody } from "../server/h3-helpers.js";
6
8
  import { getRequestContext } from "../server/request-context.js";
@@ -15,6 +17,16 @@ const FEEDBACK_TYPES = [
15
17
  "category",
16
18
  "text",
17
19
  ];
20
+ const MAX_FEEDBACK_VALUE_CHARS = 20_000;
21
+ const MAX_ID_CHARS = 200;
22
+ // An id past the bound is recorded truncated but never looked up: no real id is
23
+ // that long, and its prefix can name a different row.
24
+ function idClaim(value) {
25
+ if (!value)
26
+ return null;
27
+ const id = String(value);
28
+ return { id: id.slice(0, MAX_ID_CHARS), overlong: id.length > MAX_ID_CHARS };
29
+ }
18
30
  function isFeedbackType(value) {
19
31
  return (typeof value === "string" &&
20
32
  FEEDBACK_TYPES.includes(value));
@@ -174,33 +186,90 @@ export function createObservabilityHandler() {
174
186
  return { error: "feedbackType is required" };
175
187
  }
176
188
  const rawValue = body.value;
177
- const value = rawValue == null
189
+ let value = rawValue == null
178
190
  ? ""
179
191
  : typeof rawValue === "object"
180
192
  ? JSON.stringify(rawValue)
181
193
  : String(rawValue);
194
+ if (value.length > MAX_FEEDBACK_VALUE_CHARS) {
195
+ setResponseStatus(event, 413);
196
+ return { error: "Feedback value is too large" };
197
+ }
182
198
  const id = nanoid();
183
199
  const idempotencyKey = feedbackType === "text"
184
200
  ? getHeader(event, "idempotency-key")?.trim() || null
185
201
  : null;
186
202
  const org = await getOrgContext(event);
187
- const runId = body.runId ? String(body.runId) : null;
188
- let threadId = body.threadId ? String(body.threadId) : null;
203
+ const runClaim = idClaim(body.runId);
204
+ const threadClaim = idClaim(body.threadId);
205
+ let runId = runClaim?.id ?? null;
206
+ let threadId = threadClaim?.id ?? null;
189
207
  let model;
190
208
  let orgId = org.orgId;
191
- if (runId) {
192
- const summary = await getTraceSummary(runId, {
193
- userId: owner,
194
- ...(org.orgId ? { orgId: org.orgId } : {}),
195
- });
196
- if (!summary || (threadId && threadId !== summary.threadId)) {
209
+ let unverifiedRunId;
210
+ let unverifiedThreadId;
211
+ // A thread id is the caller's claim until one of their own runs vouches
212
+ // for it or they are shown to have access to the thread.
213
+ let threadVouched = false;
214
+ if (runId && runClaim?.overlong) {
215
+ unverifiedRunId = runId;
216
+ runId = null;
217
+ }
218
+ else if (runId) {
219
+ // Ownership is the user, not the org: a run recorded with no org, or
220
+ // under another of the caller's orgs, is still the caller's own.
221
+ const summary = await getTraceSummary(runId, { userId: owner });
222
+ // Trace writes are fire-and-forget, so a vote can arrive for a run
223
+ // that was never persisted. That is a missing trace, not a run that
224
+ // belongs to someone else: the latter still answers 404.
225
+ const traceMissing = !summary && !(await getTraceSummary(runId));
226
+ if (traceMissing) {
227
+ unverifiedRunId = runId;
228
+ runId = null;
229
+ }
230
+ else if (!summary ||
231
+ (threadId && (threadClaim?.overlong || threadId !== summary.threadId))) {
197
232
  setResponseStatus(event, 404);
198
233
  return { error: "Trace not found" };
199
234
  }
200
- threadId = summary.threadId;
201
- model = summary.model || undefined;
202
- orgId = summary.orgId ?? org.orgId;
235
+ else {
236
+ threadId = summary.threadId;
237
+ threadVouched = true;
238
+ model = summary.model || undefined;
239
+ // The run is the caller's, but it may be recorded under an org they
240
+ // have since left; that org's review data is not theirs to write to.
241
+ if (summary.orgId && summary.orgId !== org.orgId) {
242
+ orgId = (await isOrgMember(summary.orgId, owner))
243
+ ? summary.orgId
244
+ : null;
245
+ }
246
+ }
247
+ }
248
+ if (threadId &&
249
+ !threadVouched &&
250
+ (threadClaim?.overlong ||
251
+ !(await resolveThreadAccess(owner, threadId, "viewer", {
252
+ orgId: org.orgId ?? undefined,
253
+ })))) {
254
+ // The thread may live in another app (a workspace chat rail posts
255
+ // votes to the host for a remote app's thread), so an unverifiable id
256
+ // is not an error. A missing and an inaccessible thread must answer
257
+ // alike, or the route reveals which thread ids exist.
258
+ unverifiedThreadId = threadId;
259
+ threadId = null;
260
+ }
261
+ const traceMissing = !!(unverifiedRunId || unverifiedThreadId);
262
+ if (traceMissing && rawValue && typeof rawValue === "object") {
263
+ value = JSON.stringify({
264
+ ...rawValue,
265
+ traceMissing: true,
266
+ ...(unverifiedRunId ? { unverifiedRunId } : {}),
267
+ ...(unverifiedThreadId ? { unverifiedThreadId } : {}),
268
+ });
203
269
  }
270
+ const traceMissingResult = traceMissing
271
+ ? { traceMissing: true }
272
+ : {};
204
273
  const inserted = await insertFeedback({
205
274
  id,
206
275
  runId,
@@ -215,7 +284,7 @@ export function createObservabilityHandler() {
215
284
  createdAt: Date.now(),
216
285
  });
217
286
  if (!inserted)
218
- return { id };
287
+ return { id, ...traceMissingResult };
219
288
  {
220
289
  const isThumb = feedbackType === "thumbs_up" || feedbackType === "thumbs_down";
221
290
  track("$ai_feedback", {
@@ -230,6 +299,11 @@ export function createObservabilityHandler() {
230
299
  run_id: runId,
231
300
  thread_id: threadId,
232
301
  model,
302
+ ...(traceMissing ? { trace_missing: true } : {}),
303
+ ...(unverifiedRunId ? { unverified_run_id: unverifiedRunId } : {}),
304
+ ...(unverifiedThreadId
305
+ ? { unverified_thread_id: unverifiedThreadId }
306
+ : {}),
233
307
  $ai_trace_id: runId ?? undefined,
234
308
  $ai_session_id: threadId ?? undefined,
235
309
  $ai_model: model,
@@ -255,7 +329,7 @@ export function createObservabilityHandler() {
255
329
  }).catch(() => { }))
256
330
  .catch(() => { });
257
331
  }
258
- return { id };
332
+ return { id, ...traceMissingResult };
259
333
  }
260
334
  if (method === "GET" && parts.length === 1 && parts[0] === "feedback") {
261
335
  setResponseHeader(event, "Cache-Control", "private, no-store");
@@ -15,8 +15,13 @@ export declare function shouldInferSentimentForTurn(args: {
15
15
  hasUserText: boolean;
16
16
  }): boolean;
17
17
  export declare function parseInferredSentiment(output: string): InferredSentiment | null;
18
+ export declare const INFERRED_SENTIMENT_FAILURE_REASONS: readonly ["engine_unavailable", "timeout", "parse_failed", "empty"];
19
+ export type InferredSentimentFailureReason = (typeof INFERRED_SENTIMENT_FAILURE_REASONS)[number];
18
20
  export declare function inferAndTrackSentiment(args: {
21
+ /** Explicit engine override; wins over `runEngine`. */
19
22
  engine?: AgentEngine;
23
+ /** The engine that served the run being classified. */
24
+ runEngine?: AgentEngine;
20
25
  classifierModel: string;
21
26
  precedingResponseModel: string;
22
27
  text: string;