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

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 (106) 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/cli/skills.d.ts +1 -0
  27. package/dist/cli/skills.js +1 -1
  28. package/dist/client/chat/agentkit-agent-native.js +83 -7
  29. package/dist/client/chat/agentkit-protocol.js +140 -67
  30. package/dist/client/chat/runtime.js +5 -3
  31. package/dist/client/use-run-stuck-detection.d.ts +18 -1
  32. package/dist/client/use-run-stuck-detection.js +115 -75
  33. package/dist/db/request-telemetry.d.ts +7 -1
  34. package/dist/db/request-telemetry.js +20 -1
  35. package/dist/deploy/build.d.ts +25 -1
  36. package/dist/deploy/build.js +176 -3
  37. package/dist/deploy/workspace-deploy.js +8 -3
  38. package/dist/extensions/fetch-tool.js +50 -14
  39. package/dist/file-upload/actions/upload-image.d.ts +2 -2
  40. package/dist/integrations/adapters/email.js +11 -3
  41. package/dist/integrations/adapters/telegram.js +4 -2
  42. package/dist/jobs/actions/automation-no-op.d.ts +12 -0
  43. package/dist/jobs/actions/automation-no-op.js +20 -0
  44. package/dist/jobs/actions/manage-recurring-job.d.ts +1 -1
  45. package/dist/jobs/background-automation-runner.d.ts +8 -1
  46. package/dist/jobs/background-automation-runner.js +102 -19
  47. package/dist/jobs/run-history.d.ts +1 -1
  48. package/dist/jobs/run-history.js +8 -4
  49. package/dist/jobs/scheduler.js +25 -12
  50. package/dist/localization/automation-outcome-messages.d.ts +22 -0
  51. package/dist/localization/automation-outcome-messages.js +90 -0
  52. package/dist/localization/default-messages.d.ts +2 -0
  53. package/dist/localization/default-messages.js +4 -2
  54. package/dist/notifications/routes.d.ts +1 -1
  55. package/dist/observability/metrics.d.ts +3 -0
  56. package/dist/observability/metrics.js +10 -0
  57. package/dist/observability/migrations.js +22 -0
  58. package/dist/observability/routes.d.ts +13 -8
  59. package/dist/observability/routes.js +88 -14
  60. package/dist/observability/sentiment.d.ts +5 -0
  61. package/dist/observability/sentiment.js +75 -25
  62. package/dist/observability/store.d.ts +28 -0
  63. package/dist/observability/store.js +58 -0
  64. package/dist/observability/traces.js +37 -5
  65. package/dist/org/index.d.ts +2 -2
  66. package/dist/progress/actions.js +1 -0
  67. package/dist/provider-api/actions/custom-provider-registration.d.ts +12 -12
  68. package/dist/provider-api/actions/provider-api.d.ts +7 -7
  69. package/dist/provider-api/actions/provider-api.js +6 -2
  70. package/dist/provider-api/corpus-jobs.d.ts +2 -2
  71. package/dist/provider-api/index.d.ts +1 -0
  72. package/dist/provider-api/index.js +18 -0
  73. package/dist/provider-api/result-outcome.d.ts +1 -0
  74. package/dist/provider-api/result-outcome.js +20 -0
  75. package/dist/provider-api/staging.js +10 -9
  76. package/dist/server/agent-chat/prompt-resources.d.ts +8 -2
  77. package/dist/server/agent-chat/prompt-resources.js +30 -7
  78. package/dist/server/agent-chat/recurring-jobs-runtime.d.ts +19 -4
  79. package/dist/server/agent-chat/recurring-jobs-runtime.js +52 -16
  80. package/dist/server/agent-chat/sweep-trigger-auth.d.ts +18 -0
  81. package/dist/server/agent-chat/sweep-trigger-auth.js +36 -0
  82. package/dist/server/agent-chat-plugin.js +20 -13
  83. package/dist/server/agent-engine-default-model-route.d.ts +2 -2
  84. package/dist/server/auth.js +4 -4
  85. package/dist/server/framework-request-handler.js +19 -0
  86. package/dist/server/http-response-telemetry.js +4 -1
  87. package/dist/server/realtime-token.d.ts +1 -1
  88. package/dist/server/request-context.d.ts +6 -0
  89. package/dist/shared/context-status.d.ts +21 -0
  90. package/dist/shared/context-status.js +54 -0
  91. package/dist/templates/chat/app/components/chat/ChatRouteContent.tsx +8 -1
  92. package/dist/templates/workspace-core/.agents/skills/automations/SKILL.md +8 -1
  93. package/dist/templates/workspace-core/.agents/skills/recurring-jobs/SKILL.md +3 -1
  94. package/dist/triggers/actions/manage-automation.d.ts +7 -7
  95. package/dist/triggers/dispatcher.js +10 -7
  96. package/docs/content/audit-log.mdx +3 -3
  97. package/docs/content/cloudflare.mdx +27 -0
  98. package/docs/content/deployment-environment-variables.mdx +2 -0
  99. package/docs/content/durable-resume.mdx +3 -1
  100. package/docs/content/environment-variables.mdx +2 -0
  101. package/docs/content/recurring-jobs.mdx +29 -9
  102. package/docs/content/vercel.mdx +30 -0
  103. package/package.json +3 -3
  104. package/src/templates/chat/app/components/chat/ChatRouteContent.tsx +8 -1
  105. package/src/templates/workspace-core/.agents/skills/automations/SKILL.md +8 -1
  106. package/src/templates/workspace-core/.agents/skills/recurring-jobs/SKILL.md +3 -1
@@ -9,6 +9,7 @@
9
9
  * Values are resolved server-side AFTER the model emits the tool call —
10
10
  * the raw secret never enters the model's context.
11
11
  */
12
+ import { fail, isActionContractError } from "../action.js";
12
13
  import { collectSecretValues, MAX_EXTENSION_PROXY_RESPONSE_SIZE, normalizeExtensionProxyMethod, readResponseBytesWithLimit, readResponseTextWithLimit, redactSecrets, redactString, sanitizeOutboundHeaders, } from "./proxy-security.js";
13
14
  import { createSsrfSafeDispatcher, isBlockedExtensionUrlWithDns, } from "./url-safety.js";
14
15
  import { formatWebContentResult, parseWebContentSearchOptions, processWebContent, } from "./web-content.js";
@@ -174,7 +175,7 @@ export function createFetchToolEntry(opts = {}) {
174
175
  const rawUrl = String(args.url ?? "");
175
176
  const method = normalizeExtensionProxyMethod(args.method || "GET");
176
177
  if (!method) {
177
- return "Unsupported HTTP method. Allowed methods: GET, POST, PUT, PATCH, DELETE, HEAD.";
178
+ fail("Unsupported HTTP method. Allowed methods: GET, POST, PUT, PATCH, DELETE, HEAD.", { errorCode: "web_request_invalid_method" });
178
179
  }
179
180
  const rawHeaders = typeof args.headers === "string"
180
181
  ? args.headers
@@ -216,7 +217,9 @@ export function createFetchToolEntry(opts = {}) {
216
217
  }
217
218
  }
218
219
  catch (err) {
219
- return `Error resolving key references: ${err?.message ?? err}`;
220
+ fail(`Error resolving key references: ${err?.message ?? err}`, {
221
+ errorCode: "web_request_key_resolution_failed",
222
+ });
220
223
  }
221
224
  }
222
225
  const secretValues = collectSecretValues(allSecretValues);
@@ -224,17 +227,21 @@ export function createFetchToolEntry(opts = {}) {
224
227
  ? allResolvedKeys
225
228
  : undefined;
226
229
  if (await isBlockedExtensionUrlWithDns(resolvedUrl)) {
227
- return `Requests to private/internal addresses are not allowed: "${rawUrl}".`;
230
+ fail(`Requests to private/internal addresses are not allowed: "${rawUrl}".`, { errorCode: "web_request_url_blocked" });
228
231
  }
229
232
  if (opts.validateUrl && allUsedKeys.length > 0) {
230
233
  try {
231
234
  const allowed = await opts.validateUrl(resolvedUrl, allUsedKeys, resolvedKeys);
232
235
  if (!allowed) {
233
- return `URL "${rawUrl}" is not in the allowlist for the referenced keys. Check your key settings.`;
236
+ fail(`URL "${rawUrl}" is not in the allowlist for the referenced keys. Check your key settings.`, { errorCode: "web_request_url_blocked" });
234
237
  }
235
238
  }
236
239
  catch (err) {
237
- return `URL validation error: ${err?.message ?? err}`;
240
+ if (isActionContractError(err))
241
+ throw err;
242
+ fail(`URL validation error: ${err?.message ?? err}`, {
243
+ errorCode: "web_request_url_validation_failed",
244
+ });
238
245
  }
239
246
  }
240
247
  let headers;
@@ -242,7 +249,9 @@ export function createFetchToolEntry(opts = {}) {
242
249
  headers = sanitizeOutboundHeaders(JSON.parse(resolvedHeaders));
243
250
  }
244
251
  catch {
245
- return `Invalid headers JSON: ${rawHeaders}`;
252
+ fail(`Invalid headers JSON: ${rawHeaders}`, {
253
+ errorCode: "web_request_invalid_headers",
254
+ });
246
255
  }
247
256
  headers = applyBrowserDefaults(headers);
248
257
  const controller = new AbortController();
@@ -272,18 +281,23 @@ export function createFetchToolEntry(opts = {}) {
272
281
  : null;
273
282
  if (redirectUrl &&
274
283
  (await isBlockedExtensionUrlWithDns(redirectUrl))) {
275
- return "Redirect to private/internal address blocked.";
284
+ fail("Redirect to private/internal address blocked.", {
285
+ errorCode: "web_request_url_blocked",
286
+ });
276
287
  }
277
288
  if (redirectUrl && opts.validateUrl && allUsedKeys.length > 0) {
278
289
  const allowed = await opts.validateUrl(redirectUrl, allUsedKeys, resolvedKeys);
279
290
  if (!allowed) {
280
- return "Redirect URL is not in the allowlist for the referenced keys.";
291
+ fail("Redirect URL is not in the allowlist for the referenced keys.", { errorCode: "web_request_url_blocked" });
281
292
  }
282
293
  }
283
- return `HTTP ${response.status} ${response.statusText}\n\nRedirect: ${redirectUrl ? redactString(redirectUrl, secretValues) : "(none)"}`;
294
+ fail(`HTTP ${response.status} ${response.statusText}\n\nRedirect: ${redirectUrl ? redactString(redirectUrl, secretValues) : "(none)"}`, { errorCode: `http_${response.status}` });
284
295
  }
285
296
  const contentType = response.headers.get("content-type")?.split(";")[0].trim() ??
286
297
  "text/plain";
298
+ const httpErrorCode = response.ok
299
+ ? undefined
300
+ : `http_${response.status}`;
287
301
  const saveToFilePath = typeof args.saveToFile === "string"
288
302
  ? args.saveToFile.trim()
289
303
  : "";
@@ -328,9 +342,17 @@ export function createFetchToolEntry(opts = {}) {
328
342
  body = result.text;
329
343
  }
330
344
  catch {
331
- body = "(could not read response body)";
345
+ fail("(could not read response body)", {
346
+ errorCode: httpErrorCode ?? "web_request_body_unreadable",
347
+ });
332
348
  }
333
349
  body = redactString(body, secretValues);
350
+ if (response.ok) {
351
+ const { providerApiResponseOutcomeForUrl } = await import("../provider-api/index.js");
352
+ const outcome = providerApiResponseOutcomeForUrl(resolvedUrl, response, body);
353
+ if (!outcome.ok)
354
+ fail(`HTTP ${response.status} ${outcome.statusText}\n\n${body.slice(0, maxChars)}`, { errorCode: "web_request_provider_failed" });
355
+ }
334
356
  let displayBody;
335
357
  let processedMode = "raw";
336
358
  try {
@@ -350,7 +372,7 @@ export function createFetchToolEntry(opts = {}) {
350
372
  displayBody = formatWebContentResult(processed);
351
373
  }
352
374
  catch (err) {
353
- return `web-request post-processing error: ${err?.message ?? String(err)}`;
375
+ fail(`web-request post-processing error: ${err?.message ?? String(err)}`, { errorCode: httpErrorCode ?? "web_request_processing_failed" });
354
376
  }
355
377
  console.log(`[fetch-tool] ${method} ${rawUrl} → ${response.status} (${elapsed}ms, keys: ${allUsedKeys.join(",") || "none"})`);
356
378
  if (saveToFilePath) {
@@ -375,6 +397,8 @@ export function createFetchToolEntry(opts = {}) {
375
397
  });
376
398
  const bytes = Buffer.byteLength(body, "utf8");
377
399
  const preview = displayBody.slice(0, 2000);
400
+ if (!response.ok)
401
+ fail(`HTTP ${response.status} ${response.statusText}\n\n${displayBody}`, { errorCode: `http_${response.status}` });
378
402
  return JSON.stringify({
379
403
  savedToFile: true,
380
404
  savedTo: saveToFilePath,
@@ -387,20 +411,32 @@ export function createFetchToolEntry(opts = {}) {
387
411
  });
388
412
  }
389
413
  catch (saveErr) {
390
- return `saveToFile error: ${saveErr?.message ?? String(saveErr)}\n\nHTTP ${response.status} ${response.statusText}\n\n${body.slice(0, maxChars)}`;
414
+ if (isActionContractError(saveErr))
415
+ throw saveErr;
416
+ fail(`saveToFile error: ${saveErr?.message ?? String(saveErr)}\n\nHTTP ${response.status} ${response.statusText}\n\n${body.slice(0, maxChars)}`, {
417
+ errorCode: httpErrorCode ?? "web_request_save_failed",
418
+ });
391
419
  }
392
420
  }
421
+ if (!response.ok)
422
+ fail(`HTTP ${response.status} ${response.statusText}\n\n${displayBody}`, { errorCode: `http_${response.status}` });
393
423
  return `HTTP ${response.status} ${response.statusText}\n\n${displayBody}`;
394
424
  }
395
425
  catch (err) {
426
+ if (isActionContractError(err))
427
+ throw err;
396
428
  const elapsed = Date.now() - startTime;
397
429
  if (err?.name === "AbortError") {
398
430
  console.log(`[fetch-tool] ${method} ${rawUrl} → TIMEOUT (${elapsed}ms)`);
399
- return `Request timed out after ${timeoutMs}ms.`;
431
+ fail(`Request timed out after ${timeoutMs}ms.`, {
432
+ errorCode: "web_request_timeout",
433
+ });
400
434
  }
401
435
  const message = redactSecrets(err?.message ?? String(err), secretValues);
402
436
  console.log(`[fetch-tool] ${method} ${rawUrl} → ERROR: ${message} (${elapsed}ms)`);
403
- return `Request failed: ${message}`;
437
+ fail(`Request failed: ${message}`, {
438
+ errorCode: "web_request_failed",
439
+ });
404
440
  }
405
441
  finally {
406
442
  clearTimeout(timeout);
@@ -33,9 +33,9 @@ declare const _default: import("../../action.js").ActionDefinition<{
33
33
  idempotencyKey: string;
34
34
  deleted: boolean;
35
35
  } | {
36
+ id?: undefined;
36
37
  error: string;
37
38
  url?: undefined;
38
- id?: undefined;
39
39
  provider?: undefined;
40
40
  configured?: undefined;
41
41
  } | {
@@ -45,8 +45,8 @@ declare const _default: import("../../action.js").ActionDefinition<{
45
45
  configured?: undefined;
46
46
  error?: undefined;
47
47
  } | {
48
- url?: undefined;
49
48
  id?: undefined;
49
+ url?: undefined;
50
50
  provider?: undefined;
51
51
  error: string;
52
52
  configured: boolean;
@@ -1,9 +1,12 @@
1
1
  import { timingSafeEqual } from "node:crypto";
2
2
  import { getHeader, readRawBody as h3ReadRawBody } from "h3";
3
+ import { fail } from "../../action.js";
3
4
  import { getAppConfig } from "../../app-config/index.js";
4
5
  import { getDbExec } from "../../db/client.js";
6
+ import { automationOutcomeMessagesForUser } from "../../localization/automation-outcome-messages.js";
5
7
  import { resolveSecret } from "../../server/credential-provider.js";
6
8
  import { sendEmail, isEmailConfigured, getEmailProvider, } from "../../server/email.js";
9
+ import { getRequestUserEmail } from "../../server/request-context.js";
7
10
  import { getIntegrationConfig } from "../config-store.js";
8
11
  const EMAIL_MAX_BODY_LENGTH = 15000;
9
12
  const RATE_LIMIT_MAX = 20;
@@ -205,13 +208,14 @@ export function emailAdapter() {
205
208
  async sendMessageToTarget(message, target) {
206
209
  const agentAddress = await resolveSecret("EMAIL_AGENT_ADDRESS");
207
210
  if (!agentAddress) {
208
- console.error("[email] EMAIL_AGENT_ADDRESS not configured");
209
- return;
211
+ fail("[email] EMAIL_AGENT_ADDRESS not configured", {
212
+ errorCode: "config_invalid",
213
+ });
210
214
  }
211
215
  const config = await getIntegrationConfig("email");
212
216
  const displayName = config?.configData?.displayName || "Dispatch Agent";
213
217
  try {
214
- await sendEmail({
218
+ const outcome = await sendEmail({
215
219
  to: target.destination,
216
220
  from: `${displayName} <${agentAddress}>`,
217
221
  subject: target.label || "Message from Dispatch Agent",
@@ -224,6 +228,10 @@ export function emailAdapter() {
224
228
  }
225
229
  : {}),
226
230
  });
231
+ if (outcome.status !== "sent" || outcome.provider === "dev") {
232
+ const messages = await automationOutcomeMessagesForUser(getRequestUserEmail());
233
+ fail(messages.emailNotSent, { errorCode: "email_delivery_not_sent" });
234
+ }
227
235
  }
228
236
  catch (err) {
229
237
  console.error("[email] Failed to send proactive message:", err);
@@ -1,4 +1,5 @@
1
1
  import { getHeader } from "h3";
2
+ import { fail } from "../../action.js";
2
3
  import { getAppConfig } from "../../app-config/index.js";
3
4
  import { resolveSecret } from "../../server/credential-provider.js";
4
5
  import { readBody } from "../../server/h3-helpers.js";
@@ -193,8 +194,9 @@ export function telegramAdapter() {
193
194
  async sendMessageToTarget(message, target) {
194
195
  const token = await resolveSecret("TELEGRAM_BOT_TOKEN");
195
196
  if (!token) {
196
- console.error("[telegram] TELEGRAM_BOT_TOKEN not configured");
197
- return;
197
+ fail("[telegram] TELEGRAM_BOT_TOKEN not configured", {
198
+ errorCode: "config_invalid",
199
+ });
198
200
  }
199
201
  const chunks = splitMessage(message.text, TELEGRAM_MAX_LENGTH);
200
202
  for (const chunk of chunks) {
@@ -0,0 +1,12 @@
1
+ import { z } from "zod";
2
+ export declare const AUTOMATION_NO_OP_TOOL = "automation-no-op";
3
+ export declare const automationNoOpSchema: z.ZodObject<{
4
+ reason: z.ZodString;
5
+ }, z.core.$strip>;
6
+ declare const _default: import("../../action.js").ActionDefinition<{
7
+ reason: string;
8
+ }, {
9
+ status: "skipped";
10
+ reason: string;
11
+ }>;
12
+ export default _default;
@@ -0,0 +1,20 @@
1
+ import { z } from "zod";
2
+ import { defineAction } from "../../action.js";
3
+ import { AUTOMATION_OUTCOME_MESSAGES } from "../../localization/automation-outcome-messages.js";
4
+ export const AUTOMATION_NO_OP_TOOL = "automation-no-op";
5
+ export const automationNoOpSchema = z.object({
6
+ reason: z
7
+ .string()
8
+ .trim()
9
+ .min(1)
10
+ .max(500)
11
+ .describe(AUTOMATION_OUTCOME_MESSAGES["en-US"].noOpReason),
12
+ });
13
+ export default defineAction({
14
+ description: AUTOMATION_OUTCOME_MESSAGES["en-US"].noOpInstruction,
15
+ schema: automationNoOpSchema,
16
+ http: false,
17
+ agentTool: false,
18
+ readOnly: true,
19
+ run: async ({ reason }) => ({ status: "skipped", reason }),
20
+ });
@@ -11,9 +11,9 @@ declare const _default: import("../../action.js").ActionDefinition<{
11
11
  enabled?: undefined;
12
12
  nextRun?: undefined;
13
13
  } | {
14
- deleted?: undefined;
15
14
  name: string;
16
15
  enabled: boolean;
17
16
  nextRun: string;
17
+ deleted?: undefined;
18
18
  }>;
19
19
  export default _default;
@@ -48,10 +48,16 @@ export interface BackgroundAutomationRunOptions {
48
48
  /** The event this run handles; retries of one event move the streak once. */
49
49
  eventId?: string;
50
50
  }
51
- export interface BackgroundAutomationRunResult {
51
+ interface BackgroundAutomationRunOutput {
52
52
  responseText: string;
53
53
  runId: string;
54
54
  }
55
+ export type BackgroundAutomationRunResult = BackgroundAutomationRunOutput & ({
56
+ status: "success";
57
+ } | {
58
+ status: "skipped";
59
+ reason: string;
60
+ });
55
61
  /**
56
62
  * `owner_missing` is permanent (the user or membership is gone);
57
63
  * `owner_unverifiable` means the lookup itself failed and must be retried, not
@@ -119,3 +125,4 @@ export declare function checkBackgroundAutomationCredentials(identity: {
119
125
  ok: false;
120
126
  failure: AutomationFailure;
121
127
  }>;
128
+ export {};
@@ -10,12 +10,14 @@ import { buildAssistantMessage, buildUserMessage, extractThreadMeta, foldAssista
10
10
  import { attachToolSearch } from "../agent/tool-search.js";
11
11
  import { lookupOwnerAccount, resolveAutomationExecutionIdentity, } from "../automations/service.js";
12
12
  import { createThread, getThread, updateThreadData, withThreadDataLock, } from "../chat-threads/store.js";
13
+ import { automationOutcomeMessagesForUser } from "../localization/automation-outcome-messages.js";
13
14
  import { queryOrgMembers } from "../org/context.js";
14
15
  import { organizationIdFromResourceOwner, organizationResourceOwner, } from "../resources/store.js";
15
16
  import { captureError } from "../server/capture-error.js";
16
17
  import { BuilderCredentialLookupError, CredentialStoreUnavailableError, } from "../server/credential-provider.js";
17
18
  import { runWithRequestContext, } from "../server/request-context.js";
18
19
  import { normalizeReasoningEffortForRequest } from "../shared/reasoning-effort.js";
20
+ import automationNoOpAction, { AUTOMATION_NO_OP_TOOL, automationNoOpSchema, } from "./actions/automation-no-op.js";
19
21
  import { applyAutomationFailure, automationOwnerKind, classifyAutomationFailure, CONFIG_INVALID_ERROR_CODE, MISSING_TOOLS_ERROR_CODE, OWNER_MISSING_ERROR_CODE, pausedMessage, withDeliveryNote, } from "./automation-outcome.js";
20
22
  import { recoveredFactoryOwnerOrgId, } from "./frontmatter.js";
21
23
  import { attachAutomationRunThread, finishAutomationRun, startAutomationRun, } from "./run-history.js";
@@ -352,7 +354,7 @@ export async function runBackgroundAutomation(options, deps) {
352
354
  !(failure.precondition && !transition.pause));
353
355
  throw err;
354
356
  }
355
- await recordRunOutcome(historyId, "success");
357
+ await recordRunOutcome(historyId, result.status, result.status === "skipped" ? result.reason : undefined);
356
358
  return result;
357
359
  }
358
360
  async function recordRunThread(historyId, threadId, runId) {
@@ -445,6 +447,45 @@ async function recordRunOutcome(historyId, status, error, errorCode, notify = tr
445
447
  console.error(`[automations] Could not record run ${historyId} as ${status}:`, err);
446
448
  }
447
449
  }
450
+ async function confirmAutomationWork(automation, ownerEmail, run, responseText, actions, noOpReason) {
451
+ const events = run.events ?? [];
452
+ const hasConfirmedAction = events.some(({ event }) => event.type === "tool_done" &&
453
+ !event.isError &&
454
+ event.completedSideEffect === true &&
455
+ actions[event.tool]?.confirmsAutomationWork !== false);
456
+ const lastFailedTool = [...events]
457
+ .reverse()
458
+ .find(({ event }) => event.type === "tool_done" && event.isError);
459
+ if (noOpReason && !hasConfirmedAction && !lastFailedTool) {
460
+ return { status: "skipped", reason: noOpReason };
461
+ }
462
+ const { deliveryPlatform, deliveryDestination } = automation.meta;
463
+ if ((!noOpReason || hasConfirmedAction) &&
464
+ deliveryPlatform &&
465
+ deliveryDestination &&
466
+ responseText.trim()) {
467
+ const { getDefaultAdapter } = await import("../integrations/adapters/index.js");
468
+ const adapter = getDefaultAdapter(deliveryPlatform);
469
+ if (!adapter?.sendMessageToTarget) {
470
+ throw new BackgroundAutomationRunError(`Automation delivery is not supported for ${deliveryPlatform}`, CONFIG_INVALID_ERROR_CODE);
471
+ }
472
+ await adapter.sendMessageToTarget(adapter.formatAgentResponse(responseText), {
473
+ destination: deliveryDestination,
474
+ threadRef: automation.meta.deliveryThreadRef ?? null,
475
+ tenantId: automation.meta.deliveryTenantId,
476
+ });
477
+ return { status: "success" };
478
+ }
479
+ if (hasConfirmedAction)
480
+ return { status: "success" };
481
+ const messages = await automationOutcomeMessagesForUser(ownerEmail);
482
+ const detail = lastFailedTool?.event.type === "tool_done"
483
+ ? lastFailedTool.event.result
484
+ : undefined;
485
+ throw new BackgroundAutomationRunError(`${deliveryPlatform && deliveryDestination ? messages.emptyDelivery : messages.noWork}${detail ? ` ${detail}` : ""}`, lastFailedTool?.event.type === "tool_done"
486
+ ? (lastFailedTool.event.errorCode ?? "automation_no_confirmed_work")
487
+ : "automation_no_confirmed_work");
488
+ }
448
489
  /**
449
490
  * Everything below runs before any thread or `agent_runs` row exists, so an
450
491
  * automation that cannot run fails here, once, instead of leaving a "Job:"
@@ -514,7 +555,38 @@ async function executeBackgroundAutomation(options, deps, historyId, runIdRef) {
514
555
  orgId,
515
556
  }, async () => {
516
557
  assertHardDeadline(options.hardDeadlineAt);
517
- const baseActions = await deps.getActions(automation);
558
+ let noOpReason;
559
+ const messages = await automationOutcomeMessagesForUser(ownerEmail);
560
+ const baseActions = {
561
+ ...(await deps.getActions(automation)),
562
+ [AUTOMATION_NO_OP_TOOL]: {
563
+ ...automationNoOpAction,
564
+ agentTool: true,
565
+ confirmsAutomationWork: false,
566
+ tool: {
567
+ ...automationNoOpAction.tool,
568
+ description: messages.noOpInstruction,
569
+ parameters: {
570
+ ...automationNoOpAction.tool.parameters,
571
+ type: "object",
572
+ properties: {
573
+ ...automationNoOpAction.tool.parameters?.properties,
574
+ reason: {
575
+ ...automationNoOpAction.tool.parameters?.properties
576
+ ?.reason,
577
+ type: "string",
578
+ description: messages.noOpReason,
579
+ },
580
+ },
581
+ },
582
+ },
583
+ run: async (args, ctx) => {
584
+ const result = await automationNoOpAction.run(automationNoOpSchema.parse(args), ctx);
585
+ noOpReason = result.reason;
586
+ return result;
587
+ },
588
+ },
589
+ };
518
590
  assertHardDeadline(options.hardDeadlineAt);
519
591
  assertRequestedMcpToolsAvailable(automation, baseActions);
520
592
  const configuredInitialTools = deps.getInitialToolNames?.(automation);
@@ -524,6 +596,10 @@ async function executeBackgroundAutomation(options, deps, historyId, runIdRef) {
524
596
  ...(automation.meta.mcpTools ?? []),
525
597
  ])
526
598
  : undefined;
599
+ if (initialToolNames &&
600
+ !initialToolNames.includes(AUTOMATION_NO_OP_TOOL)) {
601
+ initialToolNames.push(AUTOMATION_NO_OP_TOOL);
602
+ }
527
603
  const actions = initialToolNames
528
604
  ? attachToolSearch({ ...baseActions })
529
605
  : baseActions;
@@ -535,7 +611,7 @@ async function executeBackgroundAutomation(options, deps, historyId, runIdRef) {
535
611
  assertHardDeadline(options.hardDeadlineAt);
536
612
  const model = await resolveBackgroundAutomationModel(engine, automation.meta.model, deps);
537
613
  assertHardDeadline(options.hardDeadlineAt);
538
- const systemPrompt = await deps.getSystemPrompt(ownerEmail);
614
+ const systemPrompt = `${await deps.getSystemPrompt(ownerEmail)}\n\n${messages.noOpInstruction}`;
539
615
  assertHardDeadline(options.hardDeadlineAt);
540
616
  const thread = await createThread(ownerEmail, {
541
617
  title: threadTitle,
@@ -553,6 +629,7 @@ async function executeBackgroundAutomation(options, deps, historyId, runIdRef) {
553
629
  const softTimeoutMs = resolveBackgroundAutomationSoftTimeoutMs();
554
630
  const usageRef = { current: null };
555
631
  let responseText = "";
632
+ let outcome;
556
633
  let hardAbortTimer = null;
557
634
  let hardTimedOut = false;
558
635
  assertHardDeadline(options.hardDeadlineAt);
@@ -631,12 +708,25 @@ async function executeBackgroundAutomation(options, deps, historyId, runIdRef) {
631
708
  clearTimeout(hardAbortTimer);
632
709
  hardAbortTimer = null;
633
710
  }
634
- const persistFailure = backgroundAutomationPersistFailure({
711
+ let persistFailure = backgroundAutomationPersistFailure({
635
712
  run,
636
713
  hardTimedOut,
637
714
  hardTimeoutMs,
638
715
  });
639
716
  try {
717
+ responseText = collectFinalResponseTextFromAgentEvents((run.events ?? []).map((entry) => entry.event), { fallbackToPreToolText: false });
718
+ if (!persistFailure && run.status === "completed") {
719
+ try {
720
+ outcome = await confirmAutomationWork(automation, ownerEmail, run, responseText, actions, noOpReason);
721
+ }
722
+ catch (error) {
723
+ const failure = classifyAutomationFailure(error);
724
+ persistFailure = {
725
+ message: failure.message,
726
+ errorCode: failure.code,
727
+ };
728
+ }
729
+ }
640
730
  await persistBackgroundAutomationTurn({
641
731
  threadId: thread.id,
642
732
  threadTitle,
@@ -652,6 +742,11 @@ async function executeBackgroundAutomation(options, deps, historyId, runIdRef) {
652
742
  if (hardTimedOut)
653
743
  return;
654
744
  if (persistFailure) {
745
+ run.continuationTerminalEvent = {
746
+ type: "error",
747
+ error: persistFailure.message,
748
+ errorCode: persistFailure.errorCode,
749
+ };
655
750
  reject(new BackgroundAutomationRunError(persistFailure.message, persistFailure.errorCode));
656
751
  return;
657
752
  }
@@ -661,7 +756,6 @@ async function executeBackgroundAutomation(options, deps, historyId, runIdRef) {
661
756
  `Background automation ended with status: ${run.status} and recorded no error detail`, cause?.errorCode ?? `background_automation_${run.status}`));
662
757
  return;
663
758
  }
664
- responseText = collectFinalResponseTextFromAgentEvents((run.events ?? []).map((entry) => entry.event));
665
759
  resolve();
666
760
  }, {
667
761
  softTimeoutMs,
@@ -722,20 +816,9 @@ async function executeBackgroundAutomation(options, deps, historyId, runIdRef) {
722
816
  // Usage attribution must not break an otherwise successful run.
723
817
  }
724
818
  }
725
- if (responseText.trim() &&
726
- automation.meta.deliveryPlatform &&
727
- automation.meta.deliveryDestination) {
728
- const { getDefaultAdapter } = await import("../integrations/adapters/index.js");
729
- const adapter = getDefaultAdapter(automation.meta.deliveryPlatform);
730
- if (!adapter?.sendMessageToTarget) {
731
- throw new BackgroundAutomationRunError(`Automation delivery is not supported for ${automation.meta.deliveryPlatform}`, CONFIG_INVALID_ERROR_CODE);
732
- }
733
- await adapter.sendMessageToTarget(adapter.formatAgentResponse(responseText), {
734
- destination: automation.meta.deliveryDestination,
735
- threadRef: automation.meta.deliveryThreadRef ?? null,
736
- tenantId: automation.meta.deliveryTenantId,
737
- });
819
+ if (!outcome) {
820
+ throw new BackgroundAutomationRunError(messages.noWork, "automation_no_confirmed_work");
738
821
  }
739
- return { responseText, runId };
822
+ return { ...outcome, responseText, runId };
740
823
  });
741
824
  }
@@ -1,5 +1,5 @@
1
1
  import { type MigrationEntry } from "../db/migrations.js";
2
- export type AutomationRunStatus = "running" | "success" | "error" | "interrupted";
2
+ export type AutomationRunStatus = "running" | "success" | "error" | "interrupted" | "skipped";
3
3
  export interface AutomationRun {
4
4
  id: string;
5
5
  owner: string;
@@ -18,7 +18,7 @@ registerEvent({
18
18
  orgId: z.string().nullable(),
19
19
  runId: z.string().nullable(),
20
20
  threadId: z.string().nullable(),
21
- status: z.enum(["success", "error", "interrupted"]),
21
+ status: z.enum(["success", "error", "interrupted", "skipped"]),
22
22
  error: z.string().nullable(),
23
23
  errorCode: z.string().nullable(),
24
24
  durationMs: z.number().nullable(),
@@ -575,7 +575,7 @@ export async function finishAutomationRun(id, status, error, errorCode, options
575
575
  });
576
576
  const row = existing.rows?.[0];
577
577
  const finishedAt = Date.now();
578
- const shouldQueueFailureAlert = status !== "success" &&
578
+ const shouldQueueFailureAlert = (status === "error" || status === "interrupted") &&
579
579
  options.notify !== false &&
580
580
  Boolean(row?.notification_email);
581
581
  const claimGuard = options.expectedClaimedAt !== undefined;
@@ -589,7 +589,9 @@ export async function finishAutomationRun(id, status, error, errorCode, options
589
589
  status,
590
590
  finishedAt,
591
591
  error?.slice(0, MAX_ERROR_LENGTH) ?? null,
592
- errorCode?.slice(0, MAX_ERROR_CODE_LENGTH) ?? null,
592
+ status === "skipped"
593
+ ? null
594
+ : (errorCode?.slice(0, MAX_ERROR_CODE_LENGTH) ?? null),
593
595
  shouldQueueFailureAlert ? "evaluating" : null,
594
596
  shouldQueueFailureAlert ? finishedAt : null,
595
597
  id,
@@ -611,7 +613,9 @@ export async function finishAutomationRun(id, status, error, errorCode, options
611
613
  threadId: row.thread_id == null ? null : stringifyValue(row.thread_id),
612
614
  status,
613
615
  error: error?.slice(0, MAX_ERROR_LENGTH) ?? null,
614
- errorCode: errorCode?.slice(0, MAX_ERROR_CODE_LENGTH) ?? null,
616
+ errorCode: status === "skipped"
617
+ ? null
618
+ : (errorCode?.slice(0, MAX_ERROR_CODE_LENGTH) ?? null),
615
619
  durationMs: startedAt === null ? null : Math.max(0, finishedAt - startedAt),
616
620
  }, { owner: stringifyValue(row.owner) });
617
621
  }
@@ -267,7 +267,7 @@ async function processRecurringJobsWithLease(deps) {
267
267
  });
268
268
  continue;
269
269
  }
270
- await recordIdentityFailure(candidate.resource, candidate.meta, candidate.body, now, identity.reason);
270
+ await recordIdentityFailure(candidate.resource, candidate.meta, candidate.body, now, identity.reason, identity.code);
271
271
  continue;
272
272
  }
273
273
  if (isReservedIdentityBlocked(identity.identity.userEmail)) {
@@ -386,23 +386,32 @@ async function recoverStaleAutomationHistory(owner, path, now) {
386
386
  }
387
387
  }
388
388
  export const jobRunCutOffReason = backgroundRunCutOffReason;
389
- async function recordIdentityFailure(resource, meta, body, now, reason, historyId) {
389
+ async function recordIdentityFailure(resource, meta, body, now, reason, errorCode = "owner_unverifiable", historyId) {
390
390
  const jobName = resource.path.replace(/^jobs\//, "").replace(/\.md$/, "");
391
391
  console.warn(`[recurring-jobs] Skipping job "${jobName}": ${reason}. ` +
392
392
  `User/membership no longer valid — leaving cron entry for admin review.`);
393
393
  const alreadyRecorded = meta.lastError === reason && hasRecentIdentityFailure(meta, now);
394
394
  meta.lastCheck = now.toISOString();
395
- meta.lastStatus = "skipped";
395
+ meta.lastStatus = "error";
396
396
  meta.lastError = reason;
397
+ meta.lastErrorCode = errorCode;
397
398
  if (!alreadyRecorded)
398
- await updateResource(resource, meta, body);
399
+ await updateResource(resource, meta, body, { lastErrorCode: errorCode });
399
400
  if (historyId) {
400
- await finishAutomationRun(historyId, "error", `Automation did not run: ${reason}. No delivery was confirmed.`);
401
+ await finishAutomationRun(historyId, "error", `Automation did not run: ${reason}. No delivery was confirmed.`, errorCode);
401
402
  }
402
- return { status: "skipped", error: reason };
403
+ return { status: "error", error: reason };
403
404
  }
404
405
  function hasRecentIdentityFailure(meta, now) {
405
- if (meta.lastStatus !== "skipped" || !meta.lastCheck || !meta.lastError) {
406
+ if (meta.lastStatus !== "error" ||
407
+ !meta.lastErrorCode ||
408
+ ![
409
+ OWNER_MISSING_ERROR_CODE,
410
+ CONFIG_INVALID_ERROR_CODE,
411
+ "owner_unverifiable",
412
+ ].includes(meta.lastErrorCode) ||
413
+ !meta.lastCheck ||
414
+ !meta.lastError) {
406
415
  return false;
407
416
  }
408
417
  const lastCheckMs = Date.parse(meta.lastCheck);
@@ -571,7 +580,7 @@ async function executeJob(resource, meta, body, deps, now, options = {}) {
571
580
  // failure; leave the cron entry alone so an admin can purge after
572
581
  // investigation.
573
582
  if (!identity.ok) {
574
- return recordIdentityFailure(resource, meta, body, now, identity.reason, options.historyId);
583
+ return recordIdentityFailure(resource, meta, body, now, identity.reason, identity.code, options.historyId);
575
584
  }
576
585
  const jobUserEmail = identity.identity.userEmail;
577
586
  const jobOrgId = identity.identity.orgId;
@@ -693,12 +702,16 @@ async function executeJob(resource, meta, body, deps, now, options = {}) {
693
702
  }, deps);
694
703
  await recordExecutionOutcome(resource, {
695
704
  lastRun: meta.lastRun,
696
- lastStatus: "success",
697
- lastError: undefined,
705
+ lastStatus: result.status,
706
+ lastError: result.status === "skipped" ? result.reason : undefined,
698
707
  advanceSchedule: options.advanceSchedule,
699
708
  });
700
- console.log(`[recurring-jobs] Job "${jobName}" completed.`);
701
- return { status: "success", runId: result.runId };
709
+ console.log(`[recurring-jobs] Job "${jobName}" ${result.status}.`);
710
+ return {
711
+ status: result.status,
712
+ runId: result.runId,
713
+ ...(result.status === "skipped" ? { error: result.reason } : {}),
714
+ };
702
715
  }
703
716
  catch (err) {
704
717
  const failure = classifyAutomationFailure(err);