@sentry/junior 0.316.0 → 0.318.0

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 (124) hide show
  1. package/dist/{admin-QYiDMnsu.js → admin-UOHix_5P.js} +1 -1
  2. package/dist/{agent-runner-Cr5Fhjf-.js → agent-runner-DeYymwh2.js} +13494 -13135
  3. package/dist/{reporting-window-C4dbzDiR.js → agent-status-BA5x3Xtp.js} +33 -1
  4. package/dist/{agent-update-delivery-BY13DPSD.js → agent-update-delivery-DH8bx7jU.js} +5 -5
  5. package/dist/api/schema.d.ts +600 -130
  6. package/dist/api/schema.js +6 -6
  7. package/dist/api.js +228 -214
  8. package/dist/{app-BhvzRD__.d.ts → app-DKAOuaoC.d.ts} +33 -18
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +193 -177
  11. package/dist/{thread-context-fiMNylbg.js → auth-pause-state-f9hJM_zO.js} +6 -59
  12. package/dist/catalog-runtime-BfdAnztW.js +6 -0
  13. package/dist/{change-record-Bqsa5ZXE.d.ts → change-record-BzJgLsv7.d.ts} +60 -1
  14. package/dist/{adapter-context-Bref7aPI.js → channel-access-A0de5lRv.js} +2 -42
  15. package/dist/{chat-core-engine-3dtlMku3.js → chat-core-engine-D3Wd7f5n.js} +6 -5
  16. package/dist/{child-message--2G3Ft26.js → child-message-peFWLcCZ.js} +2 -6
  17. package/dist/cli/chat.js +38 -30
  18. package/dist/cli/check.js +5 -5
  19. package/dist/cli/main.js +2 -2
  20. package/dist/cli/plugins.js +5 -4
  21. package/dist/cli/snapshot-create.js +4 -2
  22. package/dist/cli/upgrade.js +5 -3
  23. package/dist/context-BKF_5zzI.js +1833 -0
  24. package/dist/{continue-in-slack-DbQUFe_F.js → continue-in-slack-YxwMQVeR.js} +3 -3
  25. package/dist/{conversation-feed-B84pMjHo.js → conversation-feed-Cj7IuBtM.js} +3 -3
  26. package/dist/{proxy-path-BTmXDjfx.js → conversation-privacy-Cr_dNW1p.js} +2 -16
  27. package/dist/{conversation-turn-DzEpTIaf.js → conversation-turn-Bru4w_FD.js} +196 -80
  28. package/dist/{create-DUJBXr6E.js → create-Btl1y1rq.js} +12 -11
  29. package/dist/{credential-sync-JH_K9Adg.js → credential-sync-DTarZ63K.js} +20 -15
  30. package/dist/{db-DhzvUY23.js → db-of6e3sGt.js} +20724 -27256
  31. package/dist/{deployment-BhvrhQeh.js → deployment-C0qXa0FD.js} +17 -15
  32. package/dist/{engine-context-C9Nal48K.js → engine-context-C_QL_bMQ.js} +304 -56
  33. package/dist/{html-B_12WjKT.js → html-9_pS9SjY.js} +6 -2
  34. package/dist/instrumentation.js +15 -7
  35. package/dist/{job-runner-DO8nslyY.js → job-runner-B2XEvpif.js} +392 -26
  36. package/dist/{lineage-D3AZAJVe.js → lineage-nh4z9iQN.js} +1 -1
  37. package/dist/{list-B0zsb5Cp.js → list-HRP3TIRl.js} +238 -550
  38. package/dist/{logging-B8KEJegM.js → logging-BnOG0qz2.js} +4 -50
  39. package/dist/{session-stop-DponjDUZ.js → mailbox-turn-Byrry9o1.js} +4807 -7102
  40. package/dist/{list-mkB_GU8R.js → markers-CTTtJqYn.js} +171 -124
  41. package/dist/{message-B5fKDYzz.js → message-BRUuLgrY.js} +13 -24
  42. package/dist/{model-input-CuMWy37l.js → model-input-CFC62mf-.js} +3 -3
  43. package/dist/nitro.d.ts +1 -1
  44. package/dist/nitro.js +21 -7
  45. package/dist/{oauth-callback-server-B3Vvlydo.js → oauth-callback-server-CjnnUr4o.js} +2 -2
  46. package/dist/{oauth-relay-6ERrGPbA.js → oauth-relay-BvHFH0fV.js} +2 -2
  47. package/dist/{package-discovery-BI6T_RkD.js → package-discovery-DD9vencX.js} +1 -50
  48. package/dist/{plugins-BXMdNdyA.js → plugins-D_Ru4CWc.js} +1 -1
  49. package/dist/profile-iHw1uu32.js +4657 -0
  50. package/dist/{transcript-CCi7323k.js → prompt-DEkStuxG.js} +92 -98
  51. package/dist/proxy-path-BHYoKZdq.js +15 -0
  52. package/dist/registry-Cl7Labpe.js +3279 -0
  53. package/dist/reports-C1d9azyV.js +195 -0
  54. package/dist/{resolve-D5JVvv6A.js → resolve-DC6zBuDV.js} +9 -29
  55. package/dist/{result-CS_7mo8a.js → result-DxewDuXb.js} +27 -118
  56. package/dist/run-conversation-Cz2ubZK-.js +337 -0
  57. package/dist/{runner-BzAES5W3.js → runner-99YxVN_r.js} +10 -18
  58. package/dist/{sandbox-egress-signals-Dwhk2Q5F.js → sandbox-egress-signals-CgoX5CTI.js} +1 -1
  59. package/dist/{schema-z5-wA6N4.js → schema-BTojNBr5.js} +48 -86
  60. package/dist/sender-actors-77zTQbSG.js +84 -0
  61. package/dist/{service-account-D6AsAtc1.js → service-account-YDCPSByj.js} +3 -1
  62. package/dist/{skills-DgJ9GBPR.js → skills-CleC0Hze.js} +6 -5
  63. package/dist/{slack-conversation-unfurl-Dq71EkhM.js → slack-conversation-unfurl-BNQLC12R.js} +7 -6
  64. package/dist/{spawn-BJWpdwhQ.js → spawn-DuZfodPa.js} +5 -5
  65. package/dist/{system-prompt-table-iIgpmslr.js → system-prompt-table-Ci6Ck4gk.js} +88 -69
  66. package/dist/{task-runner-BJae4JwE.js → task-runner-BJ9Up3bG.js} +30 -53
  67. package/dist/topics-BoCkoPJJ.js +21 -0
  68. package/dist/turn-membership-VT7XZh-L.js +856 -0
  69. package/dist/{turn-wake-BjDW7x-5.js → turn-wake-C7HeLHAM.js} +3 -4
  70. package/dist/{media-BebquhET.js → types-DCzTAA63.js} +629 -593
  71. package/dist/user-customization-CvfuY9Eo.js +93 -0
  72. package/dist/users-Cb9c1k9q.js +181 -0
  73. package/dist/{validation-D5WmmmhX.js → validation-BiUmWPhy.js} +1 -1
  74. package/dist/{version-CBQoanXb.js → version-VEXiEcZu.js} +1 -1
  75. package/dist/version.js +1 -1
  76. package/dist/{worker-Cyb4kF17.js → worker-ChWYQdhm.js} +5 -4
  77. package/migrations/20261126025226_drop_agent_invocations/migration.sql +6 -0
  78. package/migrations/20261126025226_drop_agent_invocations/snapshot.json +9 -0
  79. package/migrations/20261126033000_space_conversations_lead_children/migration.sql +155 -0
  80. package/migrations/20261126033000_space_conversations_lead_children/snapshot.json +9 -0
  81. package/migrations/20261126144620_drop_user_message_time_index/migration.sql +1 -0
  82. package/migrations/20261126144620_drop_user_message_time_index/snapshot.json +38 -0
  83. package/migrations/20261126153100_inbox_item_subjects/migration.sql +140 -0
  84. package/migrations/20261126153100_inbox_item_subjects/snapshot.json +9 -0
  85. package/migrations/20261126153103_inbox_item_subjects_not_null/migration.sql +12 -0
  86. package/migrations/20261126153103_inbox_item_subjects_not_null/snapshot.json +9 -0
  87. package/migrations/20261126153105_inbox_item_subject_indexes/migration.sql +1 -0
  88. package/migrations/20261126153105_inbox_item_subject_indexes/snapshot.json +9 -0
  89. package/migrations/20261126153108_automation_run_conversation_index/migration.sql +1 -0
  90. package/migrations/20261126153108_automation_run_conversation_index/snapshot.json +9 -0
  91. package/migrations/20261126153159_inbox_item_subjects_schema/migration.sql +4 -0
  92. package/migrations/20261126153159_inbox_item_subjects_schema/snapshot.json +437 -0
  93. package/migrations/20261126153259_inbox_questions/migration.sql +76 -0
  94. package/migrations/20261126153259_inbox_questions/snapshot.json +9 -0
  95. package/migrations/20261126153301_inbox_questions_valid/migration.sql +3 -0
  96. package/migrations/20261126153301_inbox_questions_valid/snapshot.json +9 -0
  97. package/migrations/20261126153343_inbox_questions_schema/migration.sql +5 -0
  98. package/migrations/20261126153343_inbox_questions_schema/snapshot.json +407 -0
  99. package/migrations/20261126154025_inbox_item_owners/migration.sql +74 -0
  100. package/migrations/20261126154025_inbox_item_owners/snapshot.json +9 -0
  101. package/migrations/20261126154048_inbox_item_open_subject_key_index/migration.sql +1 -0
  102. package/migrations/20261126154048_inbox_item_open_subject_key_index/snapshot.json +9 -0
  103. package/migrations/20261126154051_drop_inbox_item_owner_indexes/migration.sql +7 -0
  104. package/migrations/20261126154051_drop_inbox_item_owner_indexes/snapshot.json +9 -0
  105. package/migrations/20261126154121_inbox_item_owners_schema/migration.sql +8 -0
  106. package/migrations/20261126154121_inbox_item_owners_schema/snapshot.json +311 -0
  107. package/migrations/20261126175601_conversation_event_turn/migration.sql +5 -0
  108. package/migrations/20261126175601_conversation_event_turn/snapshot.json +103 -0
  109. package/migrations/20261126175614_conversation_event_turn_index/migration.sql +1 -0
  110. package/migrations/20261126175614_conversation_event_turn_index/snapshot.json +62 -0
  111. package/migrations/20261126230028_merge_leaves/migration.sql +2 -0
  112. package/migrations/20261126230028_merge_leaves/snapshot.json +12 -0
  113. package/migrations/20261126231932_space_lead_holds_name/migration.sql +46 -0
  114. package/migrations/20261126231932_space_lead_holds_name/snapshot.json +58 -0
  115. package/migrations/20261127001022_merge_leaves/migration.sql +2 -0
  116. package/migrations/20261127001022_merge_leaves/snapshot.json +12 -0
  117. package/migrations/20261127002500_turn_discarded_usage/migration.sql +2 -0
  118. package/migrations/20261127002500_turn_discarded_usage/snapshot.json +73 -0
  119. package/package.json +5 -5
  120. package/dist/people-CUtFApfL.js +0 -81
  121. package/dist/start-conversation-B-LIqqNi.js +0 -162
  122. package/dist/turn-session-routing-D15orfwy.js +0 -1309
  123. package/dist/user-customization-B27StpVQ.js +0 -9
  124. package/dist/web-message-id-C6P83ans.js +0 -10
@@ -1,4 +1,4 @@
1
- import { t as JUNIOR_VERSION } from "./version-CBQoanXb.js";
1
+ import { t as JUNIOR_VERSION } from "./version-VEXiEcZu.js";
2
2
  import { randomUUID } from "node:crypto";
3
3
  // src/deployment.ts
4
4
  const JUNIOR_HEARTBEAT_ROUTE = "/api/internal/heartbeat";
@@ -24,23 +24,25 @@ function toOptionalTrimmed(value) {
24
24
  const trimmed = value?.trim();
25
25
  return trimmed ? trimmed : void 0;
26
26
  }
27
- /** Resolve the deployment version used for release and telemetry correlation. */
28
- function getDeploymentServiceVersion() {
29
- const configuredRelease = toOptionalTrimmed(process.env["SENTRY_RELEASE"]);
27
+ /**
28
+ * Resolve the deployment version used for release and telemetry correlation.
29
+ * Telemetry and build code call it before config loads, so it takes env.
30
+ */
31
+ function getDeploymentServiceVersion(env) {
32
+ const configuredRelease = toOptionalTrimmed(env["SENTRY_RELEASE"]);
30
33
  if (configuredRelease) return configuredRelease;
31
- const deploymentRevision = toOptionalTrimmed(process.env["VERCEL_GIT_COMMIT_SHA"]);
34
+ const deploymentRevision = toOptionalTrimmed(env["VERCEL_GIT_COMMIT_SHA"]);
32
35
  return deploymentRevision ? `${JUNIOR_VERSION}+${deploymentRevision}` : void 0;
33
36
  }
34
- /** Vercel deployment that runs this process. Unset outside Vercel. */
35
- function getDeploymentId() {
36
- return toOptionalTrimmed(process.env["VERCEL_DEPLOYMENT_ID"]);
37
- }
38
- /** Resolve deployment-scoped telemetry attributes from host environment. */
39
- function getDeploymentTelemetryAttributes() {
37
+ /**
38
+ * Resolve deployment-scoped telemetry attributes. Telemetry starts before
39
+ * config loads, so it takes env.
40
+ */
41
+ function getDeploymentTelemetryAttributes(env) {
40
42
  const attributes = {};
41
- const serviceVersion = getDeploymentServiceVersion();
42
- const deploymentId = getDeploymentId();
43
- const region = toOptionalTrimmed(process.env["VERCEL_REGION"]);
43
+ const serviceVersion = getDeploymentServiceVersion(env);
44
+ const deploymentId = toOptionalTrimmed(env["VERCEL_DEPLOYMENT_ID"]);
45
+ const region = toOptionalTrimmed(env["VERCEL_REGION"]);
44
46
  attributes["app.junior.version"] = JUNIOR_VERSION;
45
47
  attributes["service.instance.id"] = SERVICE_INSTANCE_ID;
46
48
  if (region) attributes["cloud.region"] = region;
@@ -48,4 +50,4 @@ function getDeploymentTelemetryAttributes() {
48
50
  if (deploymentId) attributes["deployment.id"] = deploymentId;
49
51
  return attributes;
50
52
  }
51
- export { getDeploymentServiceVersion as _, JUNIOR_CONVERSATION_WORK_CALLBACK_ROUTE as a, JUNIOR_HEARTBEAT_ROUTE as c, JUNIOR_RETENTION_ROUTE as d, JUNIOR_TURN_STEP_CALLBACK_ROUTE as f, getDeploymentId as g, SERVICE_INSTANCE_ID as h, JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE as i, JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE as l, LEGACY_JUNIOR_CONVERSATION_WORK_FUNCTION as m, JUNIOR_AUTO_ARCHIVE_ROUTE as n, JUNIOR_DELIVERY_CALLBACK_ROUTE as o, JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE as p, JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE as r, JUNIOR_HEARTBEAT_CRON_SCHEDULE as s, JUNIOR_AUTO_ARCHIVE_CRON_SCHEDULE as t, JUNIOR_RETENTION_CRON_SCHEDULE as u, getDeploymentTelemetryAttributes as v };
53
+ export { getDeploymentTelemetryAttributes as _, JUNIOR_CONVERSATION_WORK_CALLBACK_ROUTE as a, JUNIOR_HEARTBEAT_ROUTE as c, JUNIOR_RETENTION_ROUTE as d, JUNIOR_TURN_STEP_CALLBACK_ROUTE as f, getDeploymentServiceVersion as g, SERVICE_INSTANCE_ID as h, JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE as i, JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE as l, LEGACY_JUNIOR_CONVERSATION_WORK_FUNCTION as m, JUNIOR_AUTO_ARCHIVE_ROUTE as n, JUNIOR_DELIVERY_CALLBACK_ROUTE as o, JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE as p, JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE as r, JUNIOR_HEARTBEAT_CRON_SCHEDULE as s, JUNIOR_AUTO_ARCHIVE_CRON_SCHEDULE as t, JUNIOR_RETENTION_CRON_SCHEDULE as u };
@@ -1,21 +1,22 @@
1
- import { $f as resolveGatewayModel, E as locationSchema, Gl as juniorTurns, Op as getGatewayApiKey, Pn as getWorkspace, Rl as resolveRootVisibility, Tu as juniorConversations, Ul as juniorTurnOutbox, Wl as juniorTurnInbox, a as getDb, aa as QUEUE_SIGNATURE_MAX_AGE_MS, ca as getQueueProvider, d as eventFromRow, gp as gatewayRoutingAttributes, hu as juniorConversationEvents, lp as requestPrefixAttributes, m as withConversationEventLock, o as getSqlExecutor, oa as signQueueMessage, of as credentialContextForActor, sa as verifyQueueMessage, u as createSqlConversationEventStore } from "./db-DhzvUY23.js";
2
- import { G as mapBounded } from "./transcript-CCi7323k.js";
3
- import { g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, p as logException, v as serializeGenAiAttribute } from "./logging-B8KEJegM.js";
4
- import { h as SERVICE_INSTANCE_ID } from "./deployment-BhvrhQeh.js";
5
- import { a as resolveConversationPrivacy, c as toCanonicalOutputMessage, l as toGenAiMessagesTraceAttributes, s as toCanonicalInputMessage } from "./proxy-path-BTmXDjfx.js";
6
- import { bt as instructionProvenanceFor, vt as contextProvenance } from "./media-BebquhET.js";
7
- import { $i as piMessageFromHistoryItem, In as buildDeploymentSystemPrompt, Qi as historyItemFromPiMessage, ea as projectConversationEvents, it as persistThreadRuntimeState, nt as getPersistedSandboxState, rt as getPersistedThreadState } from "./session-stop-DponjDUZ.js";
8
- import { d as createReadFileTool, g as createBashTool, l as createWriteFileTool, p as createEditFileTool, s as createSystemTimeTool } from "./job-runner-DO8nslyY.js";
9
- import { F as createAgentSandbox, I as normalizeToolResult, c as buildSandboxInput } from "./agent-runner-Cr5Fhjf-.js";
1
+ import { $ as resolveGatewayModel, L as botConfig, n as credentialContextForActor } from "./context-BKF_5zzI.js";
2
+ import { Ad as juniorTurnOutbox, Br as QUEUE_SIGNATURE_MAX_AGE_MS, Hr as verifyQueueMessage, Ja as usdToMicroUsd, Ku as gatewayRoutingAttributes, M as locationSchema, Ur as getQueueProvider, Vr as signQueueMessage, _ as unseenEvents, a as getDb, af as juniorTurns, dd as agentTurnCostUsd, fd as agentTurnTotalTokens, g as readEventCursor, h as insertEventRows, hf as juniorConversations, id as getGatewayApiKey, if as juniorConversationEvents, jd as juniorTurnInbox, o as getSqlExecutor, ps as resolveRootVisibility, qa as microUsdToUsd, ud as addAgentTurnUsage, v as withConversationEventLock, zu as requestPrefixAttributes } from "./db-of6e3sGt.js";
3
+ import { Kn as usageTokensSchema, St as contextProvenance, dt as agentHistoryFromRow, ft as encodeAgentHistoryPayload, gt as historyItemFromPiMessage, ht as HISTORY_REPLACEMENT_TYPES, mt as AGENT_HISTORY_ITEM_TYPES, vt as isHistoryReplacement, wt as instructionProvenanceFor, yt as piMessageFromHistoryItem } from "./types-DCzTAA63.js";
4
+ import { _ as serializeGenAiAttribute, f as logException, h as normalizeGenAiFinishReason, i as extractGenAiUsageSummary, m as logWarn, r as extractGenAiUsageAttributes } from "./logging-BnOG0qz2.js";
5
+ import { h as SERVICE_INSTANCE_ID } from "./deployment-C0qXa0FD.js";
6
+ import { G as mapBounded } from "./prompt-DEkStuxG.js";
7
+ import { a as toCanonicalInputMessage, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-Cr_dNW1p.js";
8
+ import { Kr as reviewToolActions, Or as TURN_LIMIT_WRAP_UP_MESSAGE, Wt as getWorkspace, ft as getPersistedSandboxState, in as buildDeploymentSystemPrompt, jr as TurnToolCallLimitExceededError, kr as TurnBudgetExceededError, mt as persistThreadRuntimeState, pt as getPersistedThreadState } from "./mailbox-turn-Byrry9o1.js";
9
+ import { f as createWriteFileTool, g as createEditFileTool, m as createReadFileTool, u as createSystemTimeTool, y as createBashTool } from "./job-runner-B2XEvpif.js";
10
+ import { _ as normalizeToolResult, c as buildSandboxInput, g as createAgentSandbox, v as capToolResult } from "./agent-runner-DeYymwh2.js";
10
11
  import { n as TURN_STEP_TOPIC, t as DELIVERY_TOPIC } from "./topic-CRYYBYp-.js";
11
12
  import * as z from "zod";
12
13
  import { streamSimple } from "@earendil-works/pi-ai/compat";
14
+ import { and, asc, eq, exists, inArray, like, lt, lte, max, ne, notExists, or, sql } from "drizzle-orm";
15
+ import { alias } from "drizzle-orm/pg-core";
16
+ import { actorSchema, destinationSchema, markdownNodes, parseMarkdown } from "@sentry/junior-plugin-api";
13
17
  import * as Sentry from "@sentry/node";
14
18
  import { randomUUID } from "node:crypto";
15
19
  import { toToolDeclaration, validateToolArguments } from "@earendil-works/pi-ai";
16
- import { actorSchema, destinationSchema, markdownNodes, parseMarkdown } from "@sentry/junior-plugin-api";
17
- import { and, asc, eq, exists, inArray, like, lt, lte, ne, notExists, or, sql } from "drizzle-orm";
18
- import { alias } from "drizzle-orm/pg-core";
19
20
  import { performance as performance$1 } from "node:perf_hooks";
20
21
  // src/core/model/failure.ts
21
22
  const RETRYABLE_KINDS = /* @__PURE__ */ new Set([
@@ -353,6 +354,28 @@ function modelClient(dependencies) {
353
354
  } : { message };
354
355
  }, { spanName: `chat ${model.id}` }) };
355
356
  }
357
+ // src/core/history/read.ts
358
+ const READ_TYPES = [...AGENT_HISTORY_ITEM_TYPES, ...HISTORY_REPLACEMENT_TYPES];
359
+ /** Loads the current History version's agent history, as the model reads it. */
360
+ async function loadAgentHistory({ executor }, conversationId) {
361
+ const db = executor.db();
362
+ const currentHistoryVersionQuery = db.select({ historyVersion: max(juniorConversationEvents.historyVersion) }).from(juniorConversationEvents).where(eq(juniorConversationEvents.conversationId, conversationId));
363
+ return (await db.select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.historyVersion, currentHistoryVersionQuery), inArray(juniorConversationEvents.type, READ_TYPES))).orderBy(asc(juniorConversationEvents.seq))).flatMap((row) => {
364
+ const data = agentHistoryFromRow(row);
365
+ return isHistoryReplacement(data) ? data.replacementHistory.map(({ item }) => piMessageFromHistoryItem(item)) : [piMessageFromHistoryItem(data)];
366
+ });
367
+ }
368
+ /**
369
+ * Loads the agent history items that one Turn wrote, oldest first, as the
370
+ * model reads them. It reads every History version, so a Turn's items stay
371
+ * its own after a History replacement.
372
+ */
373
+ async function loadTurnAgentHistory({ executor }, turnId) {
374
+ return (await executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.turnId, turnId), inArray(juniorConversationEvents.type, AGENT_HISTORY_ITEM_TYPES))).orderBy(asc(juniorConversationEvents.seq))).flatMap((row) => {
375
+ const data = agentHistoryFromRow(row);
376
+ return isHistoryReplacement(data) ? [] : [piMessageFromHistoryItem(data)];
377
+ });
378
+ }
356
379
  // src/core/prompt/layout.ts
357
380
  const inputFormats = /* @__PURE__ */ new WeakMap();
358
381
  /**
@@ -623,6 +646,22 @@ async function loadWithTimeout(source, values, signal) {
623
646
  signal.removeEventListener("abort", stopStep);
624
647
  }
625
648
  }
649
+ // src/core/turn/failure.ts
650
+ /**
651
+ * Thrown by host code that runs in a step, such as a tool hook, the tools
652
+ * builder or the prompt layout, to end the Turn as failed now. Core stores
653
+ * `failure` and does not run the step again. Any other error makes the queue
654
+ * retry the step. An optional loader's errors never fail the step, so one
655
+ * from an optional loader does nothing.
656
+ */
657
+ var TurnFailedError = class extends Error {
658
+ failure;
659
+ constructor(message, failure) {
660
+ super(message);
661
+ this.name = "TurnFailedError";
662
+ this.failure = failure;
663
+ }
664
+ };
626
665
  // src/core/turn/inbox.ts
627
666
  /**
628
667
  * Finds the Turn of the input that has this idempotency key in the
@@ -807,6 +846,23 @@ function createDeliveryConsumer(ctx, run) {
807
846
  turnId: message.turnId
808
847
  }, metadata));
809
848
  }
849
+ // src/core/history/write.ts
850
+ /**
851
+ * Appends the agent history items that one Turn writes, in order, at the
852
+ * current History version. Skips an item whose idempotency key is already
853
+ * stored. Call it under `withConversationEventLock`.
854
+ */
855
+ async function appendAgentHistory(executor, conversationId, turnId, items) {
856
+ const pending = await unseenEvents(executor, conversationId, items);
857
+ if (pending.length === 0) return;
858
+ await insertEventRows(executor, conversationId, await readEventCursor(executor, conversationId), pending.map(({ item, idempotencyKey, createdAtMs }) => ({
859
+ type: item.type,
860
+ ...encodeAgentHistoryPayload(item),
861
+ idempotencyKey,
862
+ turnId,
863
+ createdAtMs
864
+ })));
865
+ }
810
866
  // src/core/turn/replies.ts
811
867
  const LEGACY_NO_REPLY_MARKERS = ["[[NO_REPLY]]", "[[QUIET]]"];
812
868
  const THINKING_BLOCK_PATTERN = /[ \t]*<thinking\b[^>]*>[\s\S]*?<\/thinking>[ \t]*(?:\r?\n)?/gi;
@@ -846,7 +902,8 @@ function turnEventKeyPrefix(turnId) {
846
902
  }
847
903
  /** The text that a message event delivers, or undefined when it is no reply. */
848
904
  function replyText(row) {
849
- const { data } = eventFromRow(row);
905
+ if (row.type !== "assistant_message") return;
906
+ const data = agentHistoryFromRow(row);
850
907
  if (data.type !== "assistant_message") return;
851
908
  const message = piMessageFromHistoryItem(data);
852
909
  return message.role === "assistant" ? assistantReplyText(message) : void 0;
@@ -943,6 +1000,30 @@ async function findTurn({ executor }, turnId) {
943
1000
  }).from(juniorTurns).where(eq(juniorTurns.id, turnId));
944
1001
  return turn;
945
1002
  }
1003
+ /** Reads a Turn's discarded usage. Undefined when the Turn does not exist. */
1004
+ async function findDiscardedUsage({ executor }, turnId) {
1005
+ return selectDiscardedUsage({ executor }, eq(juniorTurns.id, turnId));
1006
+ }
1007
+ async function selectDiscardedUsage({ executor }, where) {
1008
+ const [turn] = await executor.db().select({
1009
+ costMicroUsd: juniorTurns.discardedCostMicroUsd,
1010
+ tokens: juniorTurns.discardedTokens
1011
+ }).from(juniorTurns).where(where);
1012
+ if (!turn) return;
1013
+ return turn.tokens === null ? { costMicroUsd: turn.costMicroUsd } : {
1014
+ costMicroUsd: turn.costMicroUsd,
1015
+ tokens: usageTokensSchema.parse(turn.tokens)
1016
+ };
1017
+ }
1018
+ async function discardedUsageUpdate({ executor }, lease, usage) {
1019
+ const current = usage ? await selectDiscardedUsage({ executor }, leaseFence(lease)) : void 0;
1020
+ if (!current) return {};
1021
+ const { cost: _, ...tokens } = addAgentTurnUsage(current.tokens, usage) ?? {};
1022
+ return {
1023
+ discardedCostMicroUsd: current.costMicroUsd + usdToMicroUsd(agentTurnCostUsd(usage) ?? 0),
1024
+ discardedTokens: tokens
1025
+ };
1026
+ }
946
1027
  const runOrder = [
947
1028
  sql`${juniorTurns.state} = 'running' desc`,
948
1029
  asc(juniorTurns.priority),
@@ -1017,6 +1098,7 @@ async function claimTurn({ executor, owner, leaseMs }, turnId) {
1017
1098
  leaseExpiresAt: leaseExpiry(leaseMs),
1018
1099
  leaseEpoch: sql`${juniorTurns.leaseEpoch} + 1`,
1019
1100
  attempts: sql`${juniorTurns.attempts} + 1`,
1101
+ startedAt: sql`coalesce(${juniorTurns.startedAt}, now())`,
1020
1102
  updatedAt: sql`now()`
1021
1103
  }).where(and(eq(juniorTurns.id, turnId), or(and(eq(juniorTurns.state, "queued"), notExists(turnAhead({ executor }))), and(eq(juniorTurns.state, "running"), lte(juniorTurns.leaseExpiresAt, sql`now()`))))).returning({
1022
1104
  turnId: juniorTurns.id,
@@ -1109,16 +1191,16 @@ async function commitStep({ executor }, turn, step, prompt) {
1109
1191
  ...nextStep,
1110
1192
  state: "queued"
1111
1193
  }).where(and(leaseFence(turn), eq(juniorTurns.conversationId, turn.conversationId), eq(juniorTurns.stepSeq, turn.stepSeq))).returning({ id: juniorTurns.id })).length === 0) return;
1112
- await createSqlConversationEventStore(executor).append(turn.conversationId, [...prompt.map((entry, index) => entry.source === "input" ? {
1113
- data: historyItemFromPiMessage(entry.message, entry.provenance),
1194
+ await appendAgentHistory(executor, turn.conversationId, turn.turnId, [...prompt.map((entry, index) => entry.source === "input" ? {
1195
+ item: historyItemFromPiMessage(entry.message, entry.provenance),
1114
1196
  idempotencyKey: inputEventKey(entry.inputId),
1115
1197
  createdAtMs: entry.message.timestamp
1116
1198
  } : {
1117
- data: historyItemFromPiMessage(entry.message, contextProvenance),
1199
+ item: historyItemFromPiMessage(entry.message, contextProvenance),
1118
1200
  idempotencyKey: promptEventKey(turn.turnId, turn.stepSeq, index),
1119
1201
  createdAtMs: entry.message.timestamp
1120
1202
  }), ...step.messages.map((message, index) => ({
1121
- data: historyItemFromPiMessage(message, contextProvenance),
1203
+ item: historyItemFromPiMessage(message, contextProvenance),
1122
1204
  idempotencyKey: stepEventKey(turn.turnId, turn.stepSeq, index),
1123
1205
  createdAtMs: message.timestamp
1124
1206
  }))]);
@@ -1143,8 +1225,9 @@ async function commitOutcome({ executor }, turnId, step, prompt) {
1143
1225
  * False when the lease is lost. The engine calls it through `endFailedTurn`,
1144
1226
  * which also moves the Turn's late inputs.
1145
1227
  */
1146
- async function failTurn({ executor }, lease, endReason, failure) {
1228
+ async function failTurn({ executor }, lease, endReason, failure, discarded) {
1147
1229
  return (await executor.db().update(juniorTurns).set({
1230
+ ...await discardedUsageUpdate({ executor }, lease, discarded),
1148
1231
  state: "failed",
1149
1232
  endReason,
1150
1233
  failureCode: failure.failureCode,
@@ -1159,12 +1242,14 @@ async function failTurn({ executor }, lease, endReason, failure) {
1159
1242
  /**
1160
1243
  * Queues a running Turn again after its invocation failed, so the queue's
1161
1244
  * retry can claim the step at once. The failed attempt still counts. A Turn
1162
- * that another Turn supersedes ends instead, like at a commit. False when the
1245
+ * that another Turn supersedes ends instead, like at a commit. `discarded` is
1246
+ * the usage of the failed model reply that the retry drops. False when the
1163
1247
  * lease is lost.
1164
1248
  */
1165
- async function releaseTurn({ executor }, lease) {
1249
+ async function releaseTurn({ executor }, lease, discarded) {
1166
1250
  return executor.transaction(() => withConversationEventLock(executor, lease.conversationId, async () => {
1167
1251
  const released = {
1252
+ ...await discardedUsageUpdate({ executor }, lease, discarded),
1168
1253
  leaseOwner: null,
1169
1254
  leaseExpiresAt: null,
1170
1255
  updatedAt: sql`now()`
@@ -1288,11 +1373,12 @@ async function moveLeftovers({ executor }, ended) {
1288
1373
  * Ends a running Turn as failed and, in the same commit, moves its inputs
1289
1374
  * that arrived after its last claim to the next Turn. A crash after the
1290
1375
  * commit loses no input: the next Turn is queued, so the sweep finds it.
1376
+ * `discarded` is the usage of a failed model reply that the Turn drops.
1291
1377
  * False when the lease is lost, and then nothing changes.
1292
1378
  */
1293
- async function endFailedTurn({ executor }, lease, endReason, failure) {
1379
+ async function endFailedTurn({ executor }, lease, endReason, failure, discarded) {
1294
1380
  return executor.transaction(() => withConversationEventLock(executor, lease.conversationId, async () => {
1295
- if (!await failTurn({ executor }, lease, endReason, failure)) return false;
1381
+ if (!await failTurn({ executor }, lease, endReason, failure, discarded)) return false;
1296
1382
  await moveLeftovers({ executor }, lease);
1297
1383
  return true;
1298
1384
  }));
@@ -1394,41 +1480,82 @@ function collectPendingToolCalls(messages) {
1394
1480
  };
1395
1481
  }
1396
1482
  async function runToolCalls(pending, input) {
1397
- const results = await Promise.all(pending.calls.map((call) => runToolCall(call, pending.truncated, input)));
1483
+ const hooks = input.hooks ?? {};
1484
+ const checked = await Promise.all(pending.calls.map(async (call) => {
1485
+ const check = checkToolCall(call, pending.truncated, input);
1486
+ if ("run" in check || !hooks.beforeCall) return check;
1487
+ const result = await hooks.beforeCall(check.call, input.signal);
1488
+ return result ? replaced(check, result) : check;
1489
+ }));
1490
+ if (input.signal.aborted) throw input.signal.reason;
1491
+ const ready = checked.flatMap((check) => "run" in check ? [] : [check.call]);
1492
+ const batchResults = hooks.beforeBatch && ready.length > 0 ? await hooks.beforeBatch(ready, input.signal) : /* @__PURE__ */ new Map();
1493
+ if (input.signal.aborted) throw input.signal.reason;
1494
+ const allowed = checked.map((check) => {
1495
+ const result = batchResults.get(check.call.id);
1496
+ return result && !("run" in check) ? replaced(check, result) : check;
1497
+ });
1498
+ const results = await Promise.all(allowed.map((check) => runToolCall(check, hooks, input)));
1398
1499
  if (input.signal.aborted) throw input.signal.reason;
1399
1500
  return {
1400
1501
  outcome: results.every(({ result }) => result.endsTurn === true) ? "completed" : "continue",
1401
1502
  messages: results.map(({ result, call }) => toResultMessage(call, result))
1402
1503
  };
1403
1504
  }
1404
- function runToolCall(call, truncated, input) {
1505
+ /** A call that a before hook stopped: it does not run, and gets `result`. */
1506
+ function replaced({ call }, result) {
1507
+ return {
1508
+ call,
1509
+ run: {
1510
+ status: "replaced",
1511
+ result
1512
+ }
1513
+ };
1514
+ }
1515
+ function runToolCall(check, { afterCall }, input) {
1516
+ const { call } = check;
1405
1517
  return withSpan("gen_ai.execute_tool", {
1406
1518
  "gen_ai.operation.name": "execute_tool",
1407
1519
  "gen_ai.tool.name": call.name,
1408
1520
  "gen_ai.tool.call.id": call.id,
1409
1521
  "gen_ai.tool.type": "function"
1410
1522
  }, async (span) => {
1411
- const { status, result } = await executeToolCall(call, truncated, input);
1523
+ const { status, result } = "run" in check ? check.run : await executeToolCall(check, input);
1412
1524
  span.setAttribute("app.tool_call.outcome", status);
1413
1525
  return {
1414
1526
  call,
1415
- result
1527
+ result: afterCall ? await afterCall(call, result, input.signal) : result
1416
1528
  };
1417
1529
  });
1418
1530
  }
1419
- async function executeToolCall(call, truncated, input) {
1420
- if (input.skipDanglingToolCalls) return danglingRun(call, input);
1421
- if (truncated) return errorRun("truncated", `Tool call "${call.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`);
1531
+ /** Finds the call's tool and checks its arguments, without running it. */
1532
+ function checkToolCall(call, truncated, input) {
1533
+ const skip = (run) => ({
1534
+ call,
1535
+ run
1536
+ });
1537
+ if (input.skipDanglingToolCalls) return skip(danglingRun(call, input));
1538
+ if (truncated) return skip(errorRun("truncated", `Tool call "${call.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`));
1422
1539
  const tool = input.tools.find((candidate) => candidate.name === call.name);
1423
- if (!tool) return errorRun("not_found", `Tool ${call.name} not found`);
1424
- if (input.replay && tool.replay === "never") return errorRun("replay_skipped", "This call was interrupted before its result was saved, so it may have run. Check its effect before you call it again.");
1540
+ if (!tool) return skip(errorRun("not_found", `Tool ${call.name} not found`));
1541
+ if (input.replay && tool.replay === "never") return skip(errorRun("replay_skipped", "This call was interrupted before its result was saved, so it may have run. Check its effect before you call it again."));
1425
1542
  let args;
1426
1543
  try {
1427
1544
  args = validateToolArguments(tool, call);
1428
1545
  } catch (error) {
1429
- return errorRun("invalid_arguments", errorText(error));
1546
+ return skip(errorRun("invalid_arguments", errorText(error)));
1430
1547
  }
1431
- if (!isJsonObject(args)) return errorRun("invalid_arguments", "Tool arguments must be a JSON object");
1548
+ if (!isJsonObject(args)) return skip(errorRun("invalid_arguments", "Tool arguments must be a JSON object"));
1549
+ return {
1550
+ call: {
1551
+ ...call,
1552
+ arguments: args
1553
+ },
1554
+ tool,
1555
+ args
1556
+ };
1557
+ }
1558
+ async function executeToolCall({ call, tool, args }, input) {
1432
1559
  try {
1433
1560
  const result = await tool.execute(args, {
1434
1561
  callId: call.id,
@@ -1518,30 +1645,35 @@ async function advanceTurn({ executor, queue, owner, leaseMs }, message, options
1518
1645
  }
1519
1646
  }
1520
1647
  async function runClaimedStep({ executor, queue }, claim, unread, { client, prompt, modelSettings, tools, maxAttempts }) {
1521
- const events = await createSqlConversationEventStore(executor).loadCurrentHistory(claim.conversationId);
1648
+ const history = await loadAgentHistory({ executor }, claim.conversationId);
1522
1649
  setActiveSpanAttributes({
1523
1650
  "app.turn.step_seq": claim.stepSeq,
1524
1651
  "gen_ai.conversation.id": claim.conversationId
1525
1652
  });
1526
- const history = projectConversationEvents(events).messages;
1527
- const stepTools = await tools(claim, await findTurnInputs({ executor }, claim.turnId));
1528
- const step = await whileLeased({ executor }, claim, (signal) => runStep({
1529
- history,
1530
- request: async () => ({
1531
- ...await assemblePrompt(await prompt(claim), {
1532
- turn: claim,
1533
- history,
1534
- inputs: unread
1535
- }, { signal }),
1536
- model: await modelSettings(claim)
1537
- }),
1538
- tools: stepTools.definitions,
1539
- client,
1540
- session: claim.conversationId,
1541
- replay: claim.attempts > 1,
1542
- skipDanglingToolCalls: claim.stepSeq === 0,
1543
- signal
1544
- })).finally(() => stepTools.close());
1653
+ const step = await endTurnOnTurnFailedError({
1654
+ executor,
1655
+ queue
1656
+ }, claim, async () => {
1657
+ const stepTools = await tools(claim, await findTurnInputs({ executor }, claim.turnId));
1658
+ return whileLeased({ executor }, claim, (signal) => runStep({
1659
+ history,
1660
+ request: async () => ({
1661
+ ...await assemblePrompt(await prompt(claim), {
1662
+ turn: claim,
1663
+ history,
1664
+ inputs: unread
1665
+ }, { signal }),
1666
+ model: await modelSettings(claim)
1667
+ }),
1668
+ tools: stepTools.definitions,
1669
+ hooks: stepTools.hooks,
1670
+ client,
1671
+ session: claim.conversationId,
1672
+ replay: claim.attempts > 1,
1673
+ skipDanglingToolCalls: claim.stepSeq === 0,
1674
+ signal
1675
+ })).finally(() => stepTools.close());
1676
+ });
1545
1677
  if (!step) return;
1546
1678
  const { result, newMessages } = step;
1547
1679
  switch (result.outcome) {
@@ -1553,9 +1685,11 @@ async function runClaimedStep({ executor, queue }, claim, unread, { client, prom
1553
1685
  }, claim.turnId);
1554
1686
  return;
1555
1687
  case "failed": {
1688
+ const usage = extractGenAiUsageSummary(result.reply);
1689
+ const discarded = (agentTurnTotalTokens(usage) ?? 0) > 0 || (agentTurnCostUsd(usage) ?? 0) > 0 ? usage : void 0;
1556
1690
  const delayMs = modelRetryDelayMs(result.failure, claim.attempts, maxAttempts);
1557
1691
  if (delayMs !== void 0) {
1558
- if (await releaseTurn({ executor }, claim)) {
1692
+ if (await releaseTurn({ executor }, claim, discarded)) {
1559
1693
  await publishTurnStep({ queue }, claim.turnId, { delayMs });
1560
1694
  logWarn("agent.turn.provider.retrying", {
1561
1695
  ...modelFailureAttributes(result.failure),
@@ -1566,7 +1700,7 @@ async function runClaimedStep({ executor, queue }, claim, unread, { client, prom
1566
1700
  return;
1567
1701
  }
1568
1702
  const failure = captureModelFailure(result.failure);
1569
- if (await endFailedTurn({ executor }, claim, result.failure.message, failure)) await reconcileTurn({
1703
+ if (await endFailedTurn({ executor }, claim, result.failure.message, failure, discarded)) await reconcileTurn({
1570
1704
  executor,
1571
1705
  queue
1572
1706
  }, claim.turnId);
@@ -1575,6 +1709,32 @@ async function runClaimedStep({ executor, queue }, claim, unread, { client, prom
1575
1709
  default: throw new Error(`Unhandled step result: ${JSON.stringify(result)}`);
1576
1710
  }
1577
1711
  }
1712
+ /**
1713
+ * Runs `run`, the step and the host code it calls. A `TurnFailedError` from
1714
+ * the host ends the Turn as failed with its failure, and gives undefined.
1715
+ * Other errors reach `advanceTurn`, which releases the lease for a retry.
1716
+ */
1717
+ async function endTurnOnTurnFailedError({ executor, queue }, claim, run) {
1718
+ try {
1719
+ return await run();
1720
+ } catch (error) {
1721
+ const failed = findTurnFailedError(error);
1722
+ if (!failed) throw error;
1723
+ if (await endFailedTurn({ executor }, claim, failed.message, failed.failure)) await reconcileTurn({
1724
+ executor,
1725
+ queue
1726
+ }, claim.turnId);
1727
+ return;
1728
+ }
1729
+ }
1730
+ /**
1731
+ * The `TurnFailedError` that `error` is or wraps. `assemblePrompt` wraps a
1732
+ * fragment's or a required loader's error, with the original as `cause`, so
1733
+ * that the error names the fragment or loader.
1734
+ */
1735
+ function findTurnFailedError(error) {
1736
+ for (let cause = error; cause instanceof Error; cause = cause.cause) if (cause instanceof TurnFailedError) return cause;
1737
+ }
1578
1738
  const MODEL_RETRY_BASE_DELAY_MS = 2e3;
1579
1739
  const MODEL_RETRY_MAX_DELAY_MS = 6e4;
1580
1740
  /**
@@ -1736,6 +1896,87 @@ async function turnStepConsumer(engineCtx, { client, bot, tools }) {
1736
1896
  maxAttempts: MAX_ATTEMPTS
1737
1897
  }));
1738
1898
  }
1899
+ // src/turn-steps/limits.ts
1900
+ const WRAPPED_UP = "wrapped_up";
1901
+ /**
1902
+ * Checks one tool batch of a Turn against main's limits. Undefined when the
1903
+ * batch may run. The first time the Turn is over a limit, gives the wrap-up
1904
+ * result for each call. After that, throws `TurnFailedError`.
1905
+ */
1906
+ async function checkTurnLimits(ctx, turnId, calls) {
1907
+ const history = await loadTurnAgentHistory(ctx, turnId);
1908
+ const replies = history.filter((message) => message.role === "assistant");
1909
+ const toolCallCount = replies.flatMap((reply) => reply.content).filter((part) => part.type === "toolCall").length;
1910
+ const results = history.filter((message) => message.role === "toolResult");
1911
+ const discarded = await findDiscardedUsage(ctx, turnId);
1912
+ const costUsd = (agentTurnCostUsd(extractGenAiUsageSummary(...replies)) ?? 0) + microUsdToUsd(discarded?.costMicroUsd ?? 0);
1913
+ const overBudget = costUsd >= botConfig.maxTurnCostUsd;
1914
+ const overToolCalls = toolCallCount > botConfig.maxToolCallsPerTurn;
1915
+ const attributes = {
1916
+ "app.ai.cost.total_usd": costUsd,
1917
+ "app.ai.tool_call_count": toolCallCount
1918
+ };
1919
+ if (results.some((result) => isWrapUp(result.details))) {
1920
+ const error = overToolCalls && !overBudget ? new TurnToolCallLimitExceededError(botConfig.maxToolCallsPerTurn) : new TurnBudgetExceededError(botConfig.maxTurnCostUsd);
1921
+ const failure = { failureCode: "agent_run_failed" };
1922
+ const eventId = logException(error, "agent.turn.limit.exceeded", {
1923
+ ...attributes,
1924
+ "app.turn.id": turnId
1925
+ });
1926
+ if (eventId) failure.eventId = eventId;
1927
+ throw new TurnFailedError(error.message, failure);
1928
+ }
1929
+ if (!overBudget && !overToolCalls) return;
1930
+ logWarn("agent.turn.limit.wrapped_up", attributes);
1931
+ return new Map(calls.map((call) => [call.id, {
1932
+ content: [{
1933
+ type: "text",
1934
+ text: TURN_LIMIT_WRAP_UP_MESSAGE
1935
+ }],
1936
+ details: { turnLimit: WRAPPED_UP },
1937
+ isError: true
1938
+ }]));
1939
+ }
1940
+ function isWrapUp(details) {
1941
+ return typeof details === "object" && details !== null && "turnLimit" in details && details.turnLimit === WRAPPED_UP;
1942
+ }
1943
+ // src/turn-steps/tool-hooks.ts
1944
+ /**
1945
+ * Builds the tool hooks of one step. A batch past the Turn's limits does not
1946
+ * run. Core has no Guardian yet, so a call that needs review gets main's
1947
+ * "review unavailable" error and does not run. Calls that need no review run.
1948
+ */
1949
+ function turnToolHooks(options) {
1950
+ return {
1951
+ async beforeBatch(calls, signal) {
1952
+ const limited = await checkTurnLimits(options.ctx, options.turnId, calls);
1953
+ if (limited) return limited;
1954
+ const reviews = await Promise.all(calls.map(async (call) => {
1955
+ const tool = options.tools.get(call.name);
1956
+ if (!tool) throw new Error(`Tool ${call.name} has no definition`);
1957
+ const action = {
1958
+ toolCallId: call.id,
1959
+ toolName: call.name,
1960
+ tool,
1961
+ input: call.arguments
1962
+ };
1963
+ const results = await reviewToolActions([action], void 0, signal);
1964
+ return [call.id, results.get(call.id)];
1965
+ }));
1966
+ return new Map(reviews.flatMap(([callId, review]) => review && !review.allowed ? [[callId, {
1967
+ content: [{
1968
+ type: "text",
1969
+ text: review.error.message
1970
+ }],
1971
+ isError: true
1972
+ }]] : []));
1973
+ },
1974
+ afterCall: (call, result) => capToolResult(result, {
1975
+ toolCallId: call.id,
1976
+ workspace: options.workspace
1977
+ })
1978
+ };
1979
+ }
1739
1980
  // src/turn-steps/tools.ts
1740
1981
  function storedDetails(details) {
1741
1982
  return details === void 0 ? void 0 : z.json().parse(JSON.parse(JSON.stringify(details)));
@@ -1789,15 +2030,22 @@ async function turnTools(turn, inputs) {
1789
2030
  persistSandboxRef: (sandboxRef) => persistThreadRuntimeState(turn.conversationId, { sandboxRef })
1790
2031
  });
1791
2032
  const systemTime = createSystemTimeTool();
2033
+ const sandboxTools = Object.entries(SANDBOX_TOOLS).map(([name, create]) => [name, create()]);
1792
2034
  return {
1793
2035
  definitions: [coreTool("systemTime", systemTime, (input, { callId, signal }) => Promise.resolve(systemTime.execute(input, {
1794
2036
  signal,
1795
2037
  toolCallId: callId
1796
- }))), ...Object.entries(SANDBOX_TOOLS).map(([name, create]) => coreTool(name, create(), (input, { signal }) => sandbox.tools.execute({
2038
+ }))), ...sandboxTools.map(([name, tool]) => coreTool(name, tool, (input, { signal }) => sandbox.tools.execute({
1797
2039
  toolName: name,
1798
2040
  input: buildSandboxInput(name, sandboxInputSchema.parse(input)),
1799
2041
  signal
1800
2042
  })))],
2043
+ hooks: turnToolHooks({
2044
+ ctx: { executor: getSqlExecutor() },
2045
+ turnId: turn.turnId,
2046
+ tools: new Map([["systemTime", systemTime], ...sandboxTools]),
2047
+ workspace: sandbox.workspace
2048
+ }),
1801
2049
  close: () => sandbox.close()
1802
2050
  };
1803
2051
  }
@@ -1,5 +1,9 @@
1
- import { Hr as hasRequiredOAuthScope, Jr as deleteMcpAuthSessionsForUserProvider, Pf as botConfig, Xr as deleteMcpStoredOAuthCredentials, Yr as deleteMcpServerSessionId, dl as deleteProviderIdentityForUser, ir as startOAuthFlow, jr as pluginCatalogRuntime, o as getSqlExecutor, ul as deleteProviderIdentityForSlackUser } from "./db-DhzvUY23.js";
2
- import { G as mapBounded } from "./transcript-CCi7323k.js";
1
+ import { L as botConfig } from "./context-BKF_5zzI.js";
2
+ import { nc as deleteProviderIdentityForSlackUser, o as getSqlExecutor, rc as deleteProviderIdentityForUser } from "./db-of6e3sGt.js";
3
+ import { G as mapBounded } from "./prompt-DEkStuxG.js";
4
+ import { ii as startOAuthFlow } from "./mailbox-turn-Byrry9o1.js";
5
+ import { S as deleteMcpStoredOAuthCredentials, b as deleteMcpAuthSessionsForUserProvider, m as hasRequiredOAuthScope, x as deleteMcpServerSessionId } from "./registry-Cl7Labpe.js";
6
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-BfdAnztW.js";
3
7
  import { randomBytes } from "node:crypto";
4
8
  // src/handlers/oauth-html.ts
5
9
  /** Build pre-escaped callback HTML with the shared response security policy. */