@sentry/junior 0.319.0 → 0.320.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 (55) hide show
  1. package/dist/{adapter-8_S6Birm.js → adapter-DlLLoJKj.js} +1 -1
  2. package/dist/{admin-EsbUON1j.js → admin-BzRXDVfh.js} +1 -1
  3. package/dist/{agent-CtzMl32d.js → agent-DxZ7nHfD.js} +40 -50
  4. package/dist/{agent-update-delivery-pAvsbuGL.js → agent-update-delivery-CO4FU5Gg.js} +3 -3
  5. package/dist/api/schema.d.ts +2 -0
  6. package/dist/api/schema.js +1 -1
  7. package/dist/api.js +28 -23
  8. package/dist/{app-tACXxJPI.d.ts → app-CHCFIIDu.d.ts} +1 -0
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +20 -217
  11. package/dist/{channel-access-DET5hzZM.js → channel-access-BghWqlXx.js} +1 -1
  12. package/dist/{chat-core-engine-DpM3tMVi.js → chat-core-engine-BgfSLrDu.js} +31 -14
  13. package/dist/cli/chat.js +16 -16
  14. package/dist/cli/check.js +4 -4
  15. package/dist/cli/main.js +2 -2
  16. package/dist/cli/plugins.js +3 -3
  17. package/dist/cli/snapshot-create.js +4 -4
  18. package/dist/cli/upgrade.js +2 -2
  19. package/dist/{continue-in-slack-CFzDyxkH.js → continue-in-slack-DBlQP4PC.js} +3 -3
  20. package/dist/{conversation-privacy-C2vYK55O.js → conversation-privacy-qoh95v90.js} +1 -1
  21. package/dist/{create-Ta3SEIB5.js → create-jZSaDrCR.js} +2 -2
  22. package/dist/{credential-sync-DyRqDmY4.js → credential-sync-Bj9-UlNE.js} +11 -11
  23. package/dist/{db-BCaNWl9p.js → db-BacvswT0.js} +36 -23
  24. package/dist/{deployment-CfOew1Tm.js → deployment-BoJkRPDt.js} +1 -1
  25. package/dist/{engine-context-CiExoy1B.js → engine-context-Bi3Ync5t.js} +388 -12
  26. package/dist/{html-Bb2Si1bR.js → html-DW0pw5Pr.js} +4 -4
  27. package/dist/instrumentation.js +2 -2
  28. package/dist/{list-wwDcROh9.js → list-Dz3CdP3g.js} +20 -11
  29. package/dist/{logging-BRPTXAdf.js → logging-DsTnMqyi.js} +1 -1
  30. package/dist/{markers-9QoqW5ov.js → markers-C33gNYNE.js} +31 -30
  31. package/dist/nitro.d.ts +1 -1
  32. package/dist/nitro.js +2 -2
  33. package/dist/{oauth-callback-server-vhL9b-PZ.js → oauth-callback-server-C-pEhAQK.js} +2 -2
  34. package/dist/{oauth-relay-CH2v7WiB.js → oauth-relay-DIXdH-io.js} +1 -1
  35. package/dist/{profile-D9LdwmZi.js → profile-v9vA3RvH.js} +4 -4
  36. package/dist/{prompt-3TqxEOtc.js → prompt-C5CW2wKO.js} +1 -1
  37. package/dist/{reports-K-tbtEyx.js → reports-eBgrhPXS.js} +2 -2
  38. package/dist/{resolve-BBV2qf8A.js → resolve-HVXmbeCr.js} +5 -5
  39. package/dist/{result-5IdGJP4M.js → result-BPNzgeTl.js} +4 -4
  40. package/dist/{runner-BK_joPlM.js → runner-aNSDTST6.js} +6 -6
  41. package/dist/{sandbox-egress-signals-DXgWXXmm.js → sandbox-egress-signals-nzp9Ykf7.js} +1 -1
  42. package/dist/{schema-zWGG6VC1.js → schema-BlTO5M1d.js} +3 -1
  43. package/dist/{service-account-CateFyhw.js → service-account-DWIf1t6p.js} +2 -2
  44. package/dist/{skills-Ccjw8h2P.js → skills-50izzzdK.js} +4 -4
  45. package/dist/{slack-conversation-unfurl-ZC_TSpc4.js → slack-conversation-unfurl-C6jXhVYg.js} +7 -7
  46. package/dist/{storage-C9U7R5rM.js → storage-BtCxXiNt.js} +2 -2
  47. package/dist/{system-prompt-table-YBTHIFlP.js → system-prompt-table-CIR1B44Z.js} +3 -3
  48. package/dist/{users-CCRAqYb_.js → users-DOVo9sdU.js} +1 -1
  49. package/dist/{validation-BCUpJa8K.js → validation-CK0vuEHB.js} +1 -1
  50. package/dist/{version-BNm0JYj3.js → version-BuLVNlxB.js} +1 -1
  51. package/dist/version.js +1 -1
  52. package/dist/{worker-BhgpZ7_b.js → worker-C82kHU1R.js} +4 -4
  53. package/migrations/20261127150242_drop_space_members/migration.sql +9 -0
  54. package/migrations/20261127150242_drop_space_members/snapshot.json +53 -0
  55. package/package.json +6 -6
@@ -1,18 +1,18 @@
1
- import { $ as resolveGatewayModel, L as botConfig, f as credentialContextForActor } from "./adapter-8_S6Birm.js";
2
- import { $a as microUsdToUsd, Ap as juniorTurns, Bp as juniorConversations, Dd as getGatewayApiKey, Ff as addAgentTurnUsage, If as agentTurnCostUsd, Jr as verifyQueueMessage, Kr as QUEUE_SIGNATURE_MAX_AGE_MS, Lf as agentTurnTotalTokens, M as locationSchema, Ms as resolveRootVisibility, Yr as getQueueProvider, _ as unseenEvents, a as getDb, cd as requestPrefixAttributes, eo as usdToMicroUsd, g as readEventCursor, h as insertEventRows, hd as gatewayRoutingAttributes, kp as juniorConversationEvents, np as juniorTurnInbox, o as getSqlExecutor, qr as signQueueMessage, tp as juniorTurnOutbox, v as withConversationEventLock } from "./db-BCaNWl9p.js";
1
+ import { $ as resolveGatewayModel, L as botConfig, f as credentialContextForActor } from "./adapter-DlLLoJKj.js";
2
+ import { $a as usdToMicroUsd, Ed as getGatewayApiKey, Ff as agentTurnCostUsd, Gr as QUEUE_SIGNATURE_MAX_AGE_MS, If as agentTurnTotalTokens, Jr as getQueueProvider, Kr as signQueueMessage, M as locationSchema, N as claimProviderConversation, O as withConversationMutationLock, Op as juniorConversationEvents, Pf as addAgentTurnUsage, Qa as microUsdToUsd, Qn as sendSlackReply, R as replaceConversationMetrics, _ as unseenEvents, a as getDb, d as createSqlConversationEventStore, ep as juniorTurnOutbox, g as readEventCursor, h as insertEventRows, j as startLocationThread, js as resolveRootVisibility, kp as juniorTurns, md as gatewayRoutingAttributes, o as getSqlExecutor, qr as verifyQueueMessage, sd as requestPrefixAttributes, ti as runWithSlackInstallation, tp as juniorTurnInbox, v as withConversationEventLock, zp as juniorConversations } from "./db-BacvswT0.js";
3
3
  import { St as contextProvenance, dt as agentHistoryFromRow, ft as encodeAgentHistoryPayload, gt as historyItemFromPiMessage, ht as HISTORY_REPLACEMENT_TYPES, mt as AGENT_HISTORY_ITEM_TYPES, qn as usageTokensSchema, vt as isHistoryReplacement, wt as instructionProvenanceFor, yt as piMessageFromHistoryItem } from "./types-BNHkJrOP.js";
4
- import { _ as serializeGenAiAttribute, f as logException, h as normalizeGenAiFinishReason, i as extractGenAiUsageSummary, m as logWarn, r as extractGenAiUsageAttributes } from "./logging-BRPTXAdf.js";
5
- import { h as SERVICE_INSTANCE_ID } from "./deployment-CfOew1Tm.js";
6
- import { G as mapBounded } from "./prompt-3TqxEOtc.js";
7
- import { a as toCanonicalInputMessage, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-C2vYK55O.js";
8
- import { $r as reviewToolActions, Fr as TURN_LIMIT_WRAP_UP_MESSAGE, Ir as TurnBudgetExceededError, J as getPersistedSandboxState, Qt as getWorkspace, Rr as TurnToolCallLimitExceededError, X as persistThreadRuntimeState, Y as getPersistedThreadState, fn as buildDeploymentSystemPrompt } from "./markers-9QoqW5ov.js";
9
- import { D as createReadFileTool, E as createWriteFileTool, O as createEditFileTool, T as createSystemTimeTool, c as createAgentSandbox, k as createBashTool, l as normalizeToolResult, n as buildSandboxInput, u as capToolResult } from "./agent-CtzMl32d.js";
4
+ import { _ as serializeGenAiAttribute, f as logException, h as normalizeGenAiFinishReason, i as extractGenAiUsageSummary, m as logWarn, r as extractGenAiUsageAttributes } from "./logging-DsTnMqyi.js";
5
+ import { h as SERVICE_INSTANCE_ID } from "./deployment-BoJkRPDt.js";
6
+ import { G as mapBounded } from "./prompt-C5CW2wKO.js";
7
+ import { a as toCanonicalInputMessage, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-qoh95v90.js";
8
+ import { $n as normalizeConversationText, Br as TurnToolCallLimitExceededError, Fr as turnTerminalKey, J as getPersistedThreadState, K as getLocationConfigurationService, Lr as TURN_LIMIT_WRAP_UP_MESSAGE, Pr as turnStartedKey, Rr as TurnBudgetExceededError, Wn as toStoredConversationMessage, Y as persistThreadRuntimeState, Zt as getWorkspace, dn as buildDeploymentSystemPrompt, q as getPersistedSandboxState, ti as reviewToolActions } from "./markers-C33gNYNE.js";
9
+ import { A as createBashTool, D as createWriteFileTool, E as createSystemTimeTool, O as createReadFileTool, c as createAgentSandbox, dn as isRetryableSlackPostError, k as createEditFileTool, l as normalizeToolResult, n as buildSandboxInput, u as capToolResult } from "./agent-DxZ7nHfD.js";
10
10
  import { n as TURN_STEP_TOPIC, t as TURN_ENDED_TOPIC } from "./topic-B2EWKKBT.js";
11
11
  import * as z from "zod";
12
12
  import { streamSimple } from "@earendil-works/pi-ai/compat";
13
13
  import { and, asc, eq, exists, inArray, like, lt, lte, max, ne, notExists, or, sql } from "drizzle-orm";
14
14
  import { alias } from "drizzle-orm/pg-core";
15
- import { actorSchema, markdownNodes, parseMarkdown } from "@sentry/junior-plugin-api";
15
+ import { actorSchema, destinationSchema, markdownNodes, parseMarkdown } from "@sentry/junior-plugin-api";
16
16
  import * as Sentry from "@sentry/node";
17
17
  import { randomUUID } from "node:crypto";
18
18
  import { toToolDeclaration, validateToolArguments } from "@earendil-works/pi-ai";
@@ -658,6 +658,7 @@ async function findUnreadInputs({ executor }, turnId) {
658
658
  const readEvent = db.select({ one: sql`1` }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, juniorTurnInbox.conversationId), eq(juniorConversationEvents.idempotencyKey, sql`${INPUT_EVENT_KEY_PREFIX}::text || ${juniorTurnInbox.id}::text`)));
659
659
  return db.select({
660
660
  inputId: juniorTurnInbox.id,
661
+ actorIdentityId: juniorTurnInbox.actorIdentityId,
661
662
  groupKey: juniorTurnInbox.groupKey,
662
663
  payload: juniorTurnInbox.payload,
663
664
  sentAt: juniorTurnInbox.sentAt,
@@ -1621,7 +1622,8 @@ async function advanceTurn({ executor, queue, owner, leaseMs }, message, options
1621
1622
  throw error;
1622
1623
  }
1623
1624
  }
1624
- async function runClaimedStep({ executor, queue }, claim, unread, { client, prompt, modelSettings, tools, maxAttempts }) {
1625
+ async function runClaimedStep({ executor, queue }, claim, unread, { client, prompt, modelSettings, tools, maxAttempts, compat__inputsRead }) {
1626
+ if (unread.length > 0) await compat__inputsRead?.(claim, unread);
1625
1627
  const history = await loadAgentHistory({ executor }, claim.conversationId);
1626
1628
  setActiveSpanAttributes({
1627
1629
  "app.turn.step_seq": claim.stepSeq,
@@ -1788,6 +1790,47 @@ const turnInputPayloadSchema = z.object({
1788
1790
  text: z.string().min(1),
1789
1791
  actor: actorSchema
1790
1792
  }).strict();
1793
+ // src/turn-steps/compat__message-id.ts
1794
+ /** The visible message id of a core Turn's input, for main's readers. */
1795
+ function compat__personMessageId(inputId) {
1796
+ return `inbox:${inputId}`;
1797
+ }
1798
+ // src/turn-steps/compat__inputs-read.ts
1799
+ /**
1800
+ * Compat: writes the person's visible `message` event for each input that a
1801
+ * step reads, and at the Turn's first step its `turn_started` event with
1802
+ * those inputs. Idempotency keys make a second run write nothing.
1803
+ */
1804
+ async function compat__writeInputsRead({ executor }, turn, inputs) {
1805
+ const messages = inputs.map((input) => {
1806
+ const messageId = compat__personMessageId(input.inputId);
1807
+ return {
1808
+ idempotencyKey: `message:${messageId}`,
1809
+ createdAtMs: input.sentAt.getTime(),
1810
+ data: {
1811
+ type: "message",
1812
+ messageId,
1813
+ role: "user",
1814
+ text: turnInputPayloadSchema.parse(input.payload).text,
1815
+ authorIdentityId: input.actorIdentityId
1816
+ }
1817
+ };
1818
+ });
1819
+ const started = turn.stepSeq === 0 ? [{
1820
+ idempotencyKey: turnStartedKey(turn.turnId),
1821
+ createdAtMs: Date.now(),
1822
+ data: {
1823
+ type: "turn_started",
1824
+ turnId: turn.turnId,
1825
+ inputMessageIds: messages.map((message) => message.data.messageId),
1826
+ surface: await turnSurface({ executor }, turn.turnId)
1827
+ }
1828
+ }] : [];
1829
+ await executor.transaction(() => createSqlConversationEventStore(executor).append(turn.conversationId, [...messages, ...started]));
1830
+ }
1831
+ async function turnSurface({ executor }, turnId) {
1832
+ return (await findTurnDestination({ executor }, turnId))?.["platform"] === "slack" ? "slack" : "api";
1833
+ }
1791
1834
  // src/turn-steps/prompt.ts
1792
1835
  function formatInput(input) {
1793
1836
  const payload = turnInputPayloadSchema.parse(input.payload);
@@ -1874,7 +1917,8 @@ async function turnStepConsumer(engineCtx, { client, bot, tools }) {
1874
1917
  prompt,
1875
1918
  modelSettings,
1876
1919
  tools,
1877
- maxAttempts: MAX_ATTEMPTS
1920
+ maxAttempts: MAX_ATTEMPTS,
1921
+ compat__inputsRead: (turn, inputs) => compat__writeInputsRead(engineCtx, turn, inputs)
1878
1922
  }));
1879
1923
  }
1880
1924
  // src/turn-steps/usage.ts
@@ -2044,6 +2088,338 @@ async function turnTools(turn, inputs) {
2044
2088
  close: () => sandbox.close()
2045
2089
  };
2046
2090
  }
2091
+ // src/delivery/compat__turn-ended.ts
2092
+ const SENTRY_EVENT_ID = /^[a-f0-9]{32}$/i;
2093
+ /**
2094
+ * Compat: after the sender posted a reply, writes its visible
2095
+ * `message`, the `message_handled` events, and for Slack the thread claim.
2096
+ * Call it in the transaction that marks the reply sent.
2097
+ */
2098
+ async function compat__writeReplyDelivered({ executor }, args) {
2099
+ await createSqlConversationEventStore(executor).append(args.conversationId, await compatReplyEvents({ executor }, args.conversationId, args.turnId, [args.reply]));
2100
+ const { destination } = args.reply;
2101
+ if (destination?.platform !== "slack" || !args.providerConversationId) return;
2102
+ const binding = {
2103
+ conversationId: args.conversationId,
2104
+ provider: "slack",
2105
+ providerTenantId: destination.teamId,
2106
+ providerDestinationId: destination.channelId,
2107
+ providerConversationId: args.providerConversationId
2108
+ };
2109
+ if (await claimProviderConversation(executor, binding)) await startLocationThread(executor, binding);
2110
+ }
2111
+ /**
2112
+ * Compat: writes the end event of an ended Turn once its replies are
2113
+ * settled. A Turn with no Destination gets its reply messages here, in the
2114
+ * same commit and before the end. A Turn with a pending reply waits for the
2115
+ * Turn-ended message that its delivery sends again.
2116
+ */
2117
+ async function compat__writeTurnEnded({ executor }, message) {
2118
+ const turn = await findTurn({ executor }, message.turnId);
2119
+ const endedAt = turn?.endedAt;
2120
+ if (!turn || !endedAt || !turn.startedAt) return;
2121
+ const [pending] = await executor.db().select({ id: juniorTurnOutbox.id }).from(juniorTurnOutbox).where(and(eq(juniorTurnOutbox.turnId, turn.turnId), eq(juniorTurnOutbox.state, "pending"))).limit(1);
2122
+ if (pending) return;
2123
+ const replies = await findTurnReplies({ executor }, turn.conversationId, turn.turnId);
2124
+ const undelivered = await findTurnDestination({ executor }, turn.turnId) === null ? replies.flatMap((row) => {
2125
+ const text = replyText(row);
2126
+ return text ? [{
2127
+ eventSeq: row.seq,
2128
+ text,
2129
+ createdAtMs: row.createdAt.getTime()
2130
+ }] : [];
2131
+ }) : [];
2132
+ await executor.transaction(async () => createSqlConversationEventStore(executor).append(turn.conversationId, [...await compatReplyEvents({ executor }, turn.conversationId, turn.turnId, undelivered), compatEndEvent(turn, endedAt.getTime(), replies.length > 0)]));
2133
+ }
2134
+ /**
2135
+ * Main's events for delivered replies: each reply's `message` and its
2136
+ * `message_handled`, then `message_handled` for the Turn's input messages.
2137
+ * An input message is marked only once its `message` exists, because a
2138
+ * `message_handled` before its `message` breaks main's projection.
2139
+ */
2140
+ async function compatReplyEvents({ executor }, conversationId, turnId, replies) {
2141
+ if (replies.length === 0) return [];
2142
+ const inputMessageIds = (await findTurnInputs({ executor }, turnId)).map((input) => compat__personMessageId(input.inputId));
2143
+ const stored = await executor.db().select({ key: juniorConversationEvents.idempotencyKey }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), inArray(juniorConversationEvents.idempotencyKey, inputMessageIds.map((id) => `message:${id}`))));
2144
+ const storedKeys = new Set(stored.map((row) => row.key));
2145
+ const handledAtMs = Date.now();
2146
+ const handled = (messageId) => ({
2147
+ idempotencyKey: `message:${messageId}:handled`,
2148
+ createdAtMs: handledAtMs,
2149
+ data: {
2150
+ type: "message_handled",
2151
+ messageId
2152
+ }
2153
+ });
2154
+ return [...replies.flatMap((reply) => {
2155
+ const message = toStoredConversationMessage({
2156
+ id: `${turnId}:assistant:${reply.eventSeq}`,
2157
+ role: "assistant",
2158
+ text: normalizeConversationText(reply.text),
2159
+ createdAtMs: reply.createdAtMs,
2160
+ author: {
2161
+ userName: botConfig.userName,
2162
+ isBot: true
2163
+ },
2164
+ ...reply.destination?.platform === "slack" ? { meta: {
2165
+ source: "slack",
2166
+ ...reply.providerMessageId ? { slackTs: reply.providerMessageId } : void 0
2167
+ } } : void 0
2168
+ });
2169
+ return [{
2170
+ idempotencyKey: `message:${message.messageId}`,
2171
+ createdAtMs: message.createdAtMs,
2172
+ data: {
2173
+ type: "message",
2174
+ messageId: message.messageId,
2175
+ role: message.role,
2176
+ text: message.text,
2177
+ ...message.meta ? { meta: message.meta } : void 0
2178
+ }
2179
+ }, handled(message.messageId)];
2180
+ }), ...inputMessageIds.filter((id) => storedKeys.has(`message:${id}`)).map(handled)];
2181
+ }
2182
+ /** Main's end event of an ended Turn, from its core state. */
2183
+ function compatEndEvent(turn, endedAtMs, replied) {
2184
+ const base = {
2185
+ idempotencyKey: turnTerminalKey(turn.turnId),
2186
+ createdAtMs: endedAtMs
2187
+ };
2188
+ if (turn.state === "failed") return {
2189
+ ...base,
2190
+ data: {
2191
+ type: "turn_failed",
2192
+ turnId: turn.turnId,
2193
+ failureCode: turn.failureCode ?? "agent_run_failed",
2194
+ ...turn.failureReason ? { failureReason: turn.failureReason } : void 0,
2195
+ ...turn.failureEventId && SENTRY_EVENT_ID.test(turn.failureEventId) ? { eventId: turn.failureEventId } : void 0
2196
+ }
2197
+ };
2198
+ return {
2199
+ ...base,
2200
+ data: {
2201
+ type: "turn_completed",
2202
+ turnId: turn.turnId,
2203
+ outcome: turn.state === "cancelled" ? "cancelled" : replied ? "success" : "no_reply"
2204
+ }
2205
+ };
2206
+ }
2207
+ // src/delivery/deliver.ts
2208
+ /**
2209
+ * A send that failed but can work on a later try. The sender sets
2210
+ * `retryAfterMs` when the provider says when to try again.
2211
+ */
2212
+ var DeliveryRetryableError = class extends Error {
2213
+ retryAfterMs;
2214
+ constructor(message, options = {}) {
2215
+ super(message, { cause: options.cause });
2216
+ this.name = "DeliveryRetryableError";
2217
+ this.retryAfterMs = options.retryAfterMs;
2218
+ }
2219
+ };
2220
+ const LOCK_MISS_DELAY_MS = 1e3;
2221
+ const MAX_DELIVERY_ATTEMPTS = 5;
2222
+ const RETRY_BASE_DELAY_MS = 1e3;
2223
+ const RETRY_MAX_DELAY_MS = 6e4;
2224
+ const tryLockResultSchema = z.object({ rows: z.tuple([z.object({ locked: z.boolean() })]) });
2225
+ /**
2226
+ * Sends the Conversation's pending outbox rows in event order, each to the
2227
+ * Destination stored on its row. To try again later, it sends the message
2228
+ * that the Turn ended again, with a delay.
2229
+ */
2230
+ async function deliverTurn({ executor, queue }, message, delivery) {
2231
+ while (true) {
2232
+ const next = await executor.transaction(() => sendNextRow({ executor }, message.conversationId, delivery));
2233
+ if (next.kind === "idle") return;
2234
+ if (next.kind === "later") {
2235
+ await publishTurnEnded({ queue }, message, { delayMs: next.delayMs });
2236
+ return;
2237
+ }
2238
+ }
2239
+ }
2240
+ /**
2241
+ * Sends the Conversation's first pending row, if this transaction gets the
2242
+ * Conversation's lock and the row's Turn has ended. A retryable failure
2243
+ * leaves the row pending, so the rows after it wait.
2244
+ */
2245
+ async function sendNextRow({ executor }, conversationId, delivery) {
2246
+ const db = executor.db();
2247
+ if (!tryLockResultSchema.parse(await db.execute(sql`select pg_try_advisory_xact_lock(hashtext(${`junior:delivery:${conversationId}`})) as locked`)).rows[0].locked) return {
2248
+ kind: "later",
2249
+ delayMs: LOCK_MISS_DELAY_MS
2250
+ };
2251
+ const [row] = await db.select({
2252
+ id: juniorTurnOutbox.id,
2253
+ turnId: juniorTurnOutbox.turnId,
2254
+ eventSeq: juniorTurnOutbox.eventSeq,
2255
+ destination: juniorTurnOutbox.destination,
2256
+ attempts: juniorTurnOutbox.attempts,
2257
+ turnState: juniorTurns.state
2258
+ }).from(juniorTurnOutbox).innerJoin(juniorTurns, eq(juniorTurns.id, juniorTurnOutbox.turnId)).where(and(eq(juniorTurnOutbox.conversationId, conversationId), eq(juniorTurnOutbox.state, "pending"))).orderBy(asc(juniorTurnOutbox.eventSeq)).limit(1);
2259
+ if (!row || row.turnState === "queued" || row.turnState === "running") return { kind: "idle" };
2260
+ const markFailed = async (error) => {
2261
+ await db.update(juniorTurnOutbox).set({
2262
+ state: "failed",
2263
+ error,
2264
+ updatedAt: /* @__PURE__ */ new Date()
2265
+ }).where(eq(juniorTurnOutbox.id, row.id));
2266
+ return { kind: "settled" };
2267
+ };
2268
+ const parsed = destinationSchema.safeParse(row.destination);
2269
+ if (!parsed.success) {
2270
+ logException(parsed.error, "turn.delivery.failed", { "gen_ai.conversation.id": conversationId });
2271
+ return markFailed("The Destination is not valid");
2272
+ }
2273
+ const destination = parsed.data;
2274
+ const [event] = await db.select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.seq, row.eventSeq)));
2275
+ const text = event ? replyText(event) : void 0;
2276
+ if (!text) return markFailed("The event is not a reply");
2277
+ let result;
2278
+ try {
2279
+ result = await delivery.send({
2280
+ conversationId,
2281
+ destination,
2282
+ text
2283
+ });
2284
+ } catch (error) {
2285
+ const attempts = row.attempts + 1;
2286
+ if (error instanceof DeliveryRetryableError && attempts < MAX_DELIVERY_ATTEMPTS) {
2287
+ await db.update(juniorTurnOutbox).set({
2288
+ attempts,
2289
+ updatedAt: /* @__PURE__ */ new Date()
2290
+ }).where(eq(juniorTurnOutbox.id, row.id));
2291
+ return {
2292
+ kind: "later",
2293
+ delayMs: retryDelayMs(error, attempts)
2294
+ };
2295
+ }
2296
+ logException(error, "turn.delivery.failed", { "gen_ai.conversation.id": conversationId });
2297
+ await db.update(juniorTurnOutbox).set({
2298
+ state: "failed",
2299
+ attempts,
2300
+ error: error instanceof Error ? error.message : String(error),
2301
+ updatedAt: /* @__PURE__ */ new Date()
2302
+ }).where(eq(juniorTurnOutbox.id, row.id));
2303
+ return { kind: "settled" };
2304
+ }
2305
+ const now = /* @__PURE__ */ new Date();
2306
+ await db.update(juniorTurnOutbox).set({
2307
+ state: "sent",
2308
+ sentAt: now,
2309
+ updatedAt: now,
2310
+ providerMessageId: result.providerMessageId ?? null
2311
+ }).where(eq(juniorTurnOutbox.id, row.id));
2312
+ await compat__writeReplyDelivered({ executor }, {
2313
+ conversationId,
2314
+ turnId: row.turnId,
2315
+ reply: {
2316
+ eventSeq: row.eventSeq,
2317
+ text,
2318
+ createdAtMs: now.getTime(),
2319
+ destination,
2320
+ ...result.providerMessageId ? { providerMessageId: result.providerMessageId } : void 0
2321
+ },
2322
+ ...result.providerConversationId ? { providerConversationId: result.providerConversationId } : void 0
2323
+ });
2324
+ return { kind: "settled" };
2325
+ }
2326
+ /**
2327
+ * The wait before the next try of a retryable send. The cap keeps a row that
2328
+ * waits for its retry well inside the sweep's stale window.
2329
+ */
2330
+ function retryDelayMs(error, attempts) {
2331
+ return Math.min(error.retryAfterMs ?? RETRY_BASE_DELAY_MS * 2 ** (attempts - 1), RETRY_MAX_DELAY_MS);
2332
+ }
2333
+ // src/delivery/slack.ts
2334
+ /**
2335
+ * Creates the sender of replies to Slack Destinations. A Slack failure that a
2336
+ * later try can fix throws `DeliveryRetryableError`.
2337
+ */
2338
+ function createSlackSender(args) {
2339
+ return async (reply) => {
2340
+ const { channelId, teamId, threadTs } = reply.destination;
2341
+ let messageIds;
2342
+ try {
2343
+ messageIds = await runWithSlackInstallation({
2344
+ adapter: args.getSlackAdapter(),
2345
+ installation: { teamId },
2346
+ task: async () => sendSlackReply({
2347
+ channelId,
2348
+ threadTs,
2349
+ conversationId: reply.conversationId,
2350
+ formatting: {
2351
+ configuration: await getLocationConfigurationService({
2352
+ platform: "slack",
2353
+ teamId,
2354
+ channelId
2355
+ }).resolveValues(),
2356
+ teamId
2357
+ },
2358
+ text: reply.text
2359
+ })
2360
+ });
2361
+ } catch (error) {
2362
+ if (isRetryableSlackPostError(error)) throw new DeliveryRetryableError("Slack did not take the reply", { cause: error });
2363
+ throw error;
2364
+ }
2365
+ const providerMessageId = messageIds.at(-1);
2366
+ const providerConversationId = threadTs ? void 0 : messageIds[0];
2367
+ return {
2368
+ ...providerMessageId ? { providerMessageId } : void 0,
2369
+ ...providerConversationId ? { providerConversationId } : void 0
2370
+ };
2371
+ };
2372
+ }
2373
+ // src/turn-steps/metrics.ts
2374
+ /**
2375
+ * Writes the metrics of an ended Turn. A rerun replaces the same rows, so a
2376
+ * Turn counts once however often its Turn-ended message arrives. A Turn that
2377
+ * never ran or has not ended writes nothing.
2378
+ */
2379
+ async function recordTurnMetrics(ctx, message) {
2380
+ const turn = await findTurn(ctx, message.turnId);
2381
+ if (!turn?.startedAt || !turn.endedAt) return;
2382
+ const [history, actorIdentityId] = await Promise.all([loadTurnAgentHistory(ctx, message.turnId), findTurnActor(ctx, message.turnId)]);
2383
+ const usage = await turnUsage(ctx, message.turnId, history);
2384
+ const { startedAt, endedAt } = turn;
2385
+ await withConversationMutationLock(ctx.executor, message.conversationId, () => replaceConversationMetrics(ctx.executor, {
2386
+ actorIdentityId,
2387
+ conversationId: message.conversationId,
2388
+ runId: message.turnId,
2389
+ occurredAtMs: startedAt.getTime(),
2390
+ updatedAtMs: endedAt.getTime(),
2391
+ durationMs: endedAt.getTime() - startedAt.getTime(),
2392
+ usage
2393
+ }));
2394
+ }
2395
+ // src/turn-steps/turn-ended.ts
2396
+ /**
2397
+ * Creates the Delivery of this deployment. It sends replies to Slack
2398
+ * Destinations. Other platforms have no sender yet, so their replies fail.
2399
+ */
2400
+ function createDeploymentDelivery(args) {
2401
+ const sendToSlack = createSlackSender(args);
2402
+ return { send: async (reply) => {
2403
+ const { destination } = reply;
2404
+ if (destination.platform === "slack") return sendToSlack({
2405
+ ...reply,
2406
+ destination
2407
+ });
2408
+ throw new Error(`No sender for ${destination.platform} Destinations`);
2409
+ } };
2410
+ }
2411
+ /**
2412
+ * The queue consumer of the messages that a Turn ended. It records the Turn's
2413
+ * metrics, then sends its replies, so a send that waits does not hold back
2414
+ * the spend. The host mounts it on `engineCtx.queue`.
2415
+ */
2416
+ function turnEndedConsumer(engineCtx, delivery) {
2417
+ return readTurnEndedMessages(engineCtx, async (message) => {
2418
+ await recordTurnMetrics(engineCtx, message);
2419
+ await deliverTurn(engineCtx, message, delivery);
2420
+ await compat__writeTurnEnded(engineCtx, message);
2421
+ });
2422
+ }
2047
2423
  // src/turn-steps/engine-context.ts
2048
2424
  /** Builds the context that core's Turn engine runs with. */
2049
2425
  function createEngineContext(config) {
@@ -2054,4 +2430,4 @@ function createEngineContext(config) {
2054
2430
  leaseMs: config.functionMaxDurationSeconds * 1e3
2055
2431
  };
2056
2432
  }
2057
- export { turnStepConsumer as a, findTurn as c, readTurnEndedMessages as d, publishTurnStep as f, withSpan as g, countMetric as h, createGatewayModelClient as i, replyText as l, loadTurnAgentHistory as m, turnTools as n, scheduleInput as o, findTurnActor as p, turnUsage as r, findStalledTurns as s, createEngineContext as t, publishTurnEnded as u };
2433
+ export { createGatewayModelClient as a, findStalledTurns as c, countMetric as d, withSpan as f, turnTools as i, publishTurnEnded as l, createDeploymentDelivery as n, turnStepConsumer as o, turnEndedConsumer as r, scheduleInput as s, createEngineContext as t, publishTurnStep as u };
@@ -1,7 +1,7 @@
1
- import { L as botConfig } from "./adapter-8_S6Birm.js";
2
- import { Cc as deleteProviderIdentityForUser, Fd as getAppContext, Sc as deleteProviderIdentityForSlackUser, Xd as hasRequiredOAuthScope, if as deleteMcpStoredOAuthCredentials, nf as deleteMcpAuthSessionsForUserProvider, o as getSqlExecutor, rf as deleteMcpServerSessionId } from "./db-BCaNWl9p.js";
3
- import { G as mapBounded } from "./prompt-3TqxEOtc.js";
4
- import { di as startOAuthFlow } from "./markers-9QoqW5ov.js";
1
+ import { L as botConfig } from "./adapter-DlLLoJKj.js";
2
+ import { Pd as getAppContext, Sc as deleteProviderIdentityForUser, Yd as hasRequiredOAuthScope, nf as deleteMcpServerSessionId, o as getSqlExecutor, rf as deleteMcpStoredOAuthCredentials, tf as deleteMcpAuthSessionsForUserProvider, xc as deleteProviderIdentityForSlackUser } from "./db-BacvswT0.js";
3
+ import { G as mapBounded } from "./prompt-C5CW2wKO.js";
4
+ import { pi as startOAuthFlow } from "./markers-C33gNYNE.js";
5
5
  import { randomBytes } from "node:crypto";
6
6
  // src/handlers/oauth-html.ts
7
7
  /** Build pre-escaped callback HTML with the shared response security policy. */
@@ -1,10 +1,10 @@
1
1
  import { a as getClient, c as init, i as getActiveSpan, o as getGlobalScope, p as spanToJSON, s as getTraceData, u as sentry_exports } from "./sentry-CPbZjomA.js";
2
- import { n as getCurrentConversationPrivacy } from "./conversation-privacy-C2vYK55O.js";
2
+ import { n as getCurrentConversationPrivacy } from "./conversation-privacy-qoh95v90.js";
3
3
  import { n as isPushServiceHost } from "./push-endpoint-CO-nomUd.js";
4
4
  import { n as redactSandboxEgressProxyPath } from "./proxy-path-BHYoKZdq.js";
5
5
  import { n as promoteHttpRouteName, r as routeNameMiddleware, t as nameRequestRoute } from "./sentry-route-name-C6EIzAGP.js";
6
6
  import { t as consumePrivateTraceResultMarker } from "./private-trace-result-CE7_lEdq.js";
7
- import { _ as getDeploymentTelemetryAttributes, g as getDeploymentServiceVersion } from "./deployment-CfOew1Tm.js";
7
+ import { _ as getDeploymentTelemetryAttributes, g as getDeploymentServiceVersion } from "./deployment-BoJkRPDt.js";
8
8
  import { performance } from "node:perf_hooks";
9
9
  import { subscribe, unsubscribe } from "node:diagnostics_channel";
10
10
  // src/chat/pi/gateway-request-timing.ts
@@ -1,16 +1,16 @@
1
- import { $ as resolveGatewayModel, L as botConfig, R as getChatConfig, a as getStateValues, i as getStateAdapter, o as setStateValues } from "./adapter-8_S6Birm.js";
2
- import { $ as canActOnInboxItem, $i as basePluginContext, Aa as eventAutomationRunLimitReason, Ar as readConversationAccessFromSql, Ba as existingConversationId, Bc as getInboxItem, Bi as slackMention, Bp as juniorConversations, Bs as lookupSlackUserNames, C as conversationSlackTenantId, Ca as findMatchingEventAutomations, Ci as notifyAutomationBlocked, Cl as getDashboardConversationLink, Ct as inboxItemOwnedByThroughSubject, Dr as conversationAccessFromRows, Es as conversationSubtreeColumns, Et as getPlugins, Fc as closeHandledReplyNotices, Ff as addAgentTurnUsage, Fo as findMatchingWatches, Fp as juniorCodeChanges, Fr as conversationPinnedForUser, G as conversationStatusSql, Hi as wrapBareSlackUserIds, Ho as bindEventAutomationCredentialSubject, Hu as storedMessageJson, Ir as readMemberParticipants, Jc as inboxItemAnswer, Ji as createPluginEmbedder, Jo as verifySlackDirectCredentialSubject, Ju as completeDecision, K as conversationTurnFailedSql, Kc as takeInboxItem, Ki as createPluginState, Ko as verifyEventAutomationCredentialSubject, Kp as juniorUsers, Lr as rootVisibleToViewer, Ma as automationVersionOf, Mp as juniorConversationAnnotations, Nr as conversationIsMemberRoot, Od as JUNIOR_NATIVE_EVENT_NAMESPACE, Or as createConversationAccessReader, Os as conversationSearchVector, Pc as waitingConversationIdsQuery, Pr as conversationIsNotUnsubscribedRoot, Q as treeAwaitsAuthorization, Qc as INBOX_SUBJECT_KINDS, Qf as listedConversation, Qo as canPauseConversationDelivery, Rc as closeInboxItem, Rf as agentTurnUsageSchema, Ro as listConversationsWithWatches, Rp as juniorAttachments, Rr as viewerMarksFromParticipant, S as setArchivedAt, Sr as createPluginCodeChanges, T as lastMessageAtSql, Tr as canInviteToConversation, Ts as conversationSubtree, U as conversationIsActiveSql, Uc as listReplyActionItems, Ui as applyPluginFormatMarkdown, Uo as bindScheduledAutomationCredentialSubject, Up as juniorIdentities, Vf as resolveRootConversationId, Vi as slackMentionedUserIds, Vn as pushInboxSnoozeWakes, Vt as setTodoStatusByUser, Wc as ownerConversationId, Wf as nextDetailVersion, Wo as bindSlackDirectCredentialSubject, X as awaitsAuthorizationFrom, Xa as recordAutomationExecution, Xn as safeLinkUrl, Xo as updateTimerIndex, Xr as buildSentryConversationUrl, Y as conversationKindFromRow, Ya as readAutomationTitlesByConversationId, Yc as inboxItemRequest, Z as hasUnexpiredAuthorizationRequest, Zc as itemQuestion, Zf as spaceLeadIds, _l as listFiringInboxSnoozeTriggers, _o as slackChannelMessageReplyThreadTs, _r as createPluginInboxItems, _t as isPluginInboxItem, a as getDb, al as hasUserPhoto, an as getConversation, ba as collectEventAutomationMatchKeys, bp as juniorInboxItems, br as leavePluginInboxItem, bs as listConversationAnnotations, cs as subjectKey, ct as inboxItemNeedsInput, dl as userAvatarUrlsFromJoinedPhotos, ec as isDmChannel, fl as SNOOZE_TIMER_EVENT_TYPE, fp as juniorAutomationRuns, gi as isTerminalDispatchStatus, gr as PLUGIN_CHOICE_FIELD_ID, gt as isOnlyAssignee, hf as webActorUserIds, hi as getPluginDispatchProjection, hp as juniorAutomations, hr as createPluginConversationChanges, ht as isInboxItemForEveryone, hu as CORE_EVENT_NAMESPACE, i as getConversationStore, il as subjectTodo, ir as createPluginTaskStarter, is as resolveAnnotationFilter, it as conversationOwnsInboxItem, jl as parseDashboardConversationLink, jo as collectEventMatchKeys, jr as readConversationAccessRows, js as isPublicConversation, ka as admitEventAutomationRun, kp as juniorConversationEvents, kr as leaveEndsAccess, lc as createPluginUsers, li as createOrGetDispatch, lp as juniorQuestions, lt as inboxItemOwnedByConversation, mt as isAutomationAlertItem, n as getConversationEventStore, no as AUTOMATION_ALERT_STEPS, nu as isTopLevel, o as getSqlExecutor, oa as createPluginCache, oi as buildDispatchId, ol as identityAvatarUrl, on as getConversationWorkState, op as juniorTodos, ot as inboxItemAddedByAutomation, p as copyMessageLinks, pi as getDispatchRecord, po as getEventCatalog, q as conversationWaitsOnUserSql, qo as verifyScheduledAutomationCredentialSubject, qp as juniorDestinations, qt as cancelHumanFacingPendingMessages, ro as AUTOMATION_ALERT_STEP_FIELD_ID, rs as annotationMatches, rt as canUserReadInboxItem, st as inboxItemForUser, su as turnBehavior, tr as createPluginEventPublisher, tt as canAnswerInboxItem, tu as isThread, u as isPostgresErrorCode, ui as getDispatchConversationId, ut as inboxItemPlugin, v as withConversationEventLock, vo as slackChannelMessageRunsAutomation, vr as dismissPluginInboxItem, vu as eventGuidance, w as loadConversationSlackTenantIds, wp as juniorConversationParticipants, wr as canAddConversationMessages, ws as conversationAncestorsOrSelf, x as readConversationTrees, xr as takeOverPluginClose, xs as listConversationAnnotationsById, y as conversationAncestors, ya as blockEventAutomation, yl as settleInboxSnoozes, yr as hasAssigneeRoles, ys as createPluginConversationAnnotations, z as conversationCostOf, zc as dismissOpenInboxItems, zf as hasAgentTurnUsage, zn as createInboxItemShow, zp as juniorMessageAttachments, zr as getVercelConversationWorkQueue, zs as lookupSlackUser } from "./db-BCaNWl9p.js";
1
+ import { $ as resolveGatewayModel, L as botConfig, R as getChatConfig, a as getStateValues, i as getStateAdapter, o as setStateValues } from "./adapter-DlLLoJKj.js";
2
+ import { $ as canActOnInboxItem, $s as isDmChannel, Al as parseDashboardConversationLink, Ao as collectEventMatchKeys, Ar as readConversationAccessRows, As as isPublicConversation, Bf as resolveRootConversationId, Bi as slackMentionedUserIds, Bn as pushInboxSnoozeWakes, Bt as setTodoStatusByUser, C as conversationSlackTenantId, Cp as juniorConversationParticipants, Cr as canAddConversationMessages, Cs as conversationAncestorsOrSelf, Ct as inboxItemOwnerConversationId, Dd as JUNIOR_NATIVE_EVENT_NAMESPACE, Dr as createConversationAccessReader, Ds as conversationSearchVector, Er as conversationAccessFromRows, Fr as readMemberParticipants, G as conversationStatusSql, Gc as takeInboxItem, Gi as createPluginState, Go as verifyEventAutomationCredentialSubject, Gp as juniorUsers, Hc as listReplyActionItems, Hi as applyPluginFormatMarkdown, Ho as bindScheduledAutomationCredentialSubject, Hp as juniorIdentities, Ir as rootVisibleToViewer, Ja as readAutomationTitlesByConversationId, Jc as inboxItemRequest, K as conversationTurnFailedSql, Ko as verifyScheduledAutomationCredentialSubject, Kp as juniorDestinations, Kt as cancelHumanFacingPendingMessages, Lc as closeInboxItem, Lf as agentTurnUsageSchema, Lo as listConversationsWithWatches, Lp as juniorAttachments, Lr as viewerMarksFromParticipant, Mr as conversationIsMemberRoot, Nc as waitingConversationIdsQuery, Nr as conversationIsNotUnsubscribedRoot, Oa as admitEventAutomationRun, Op as juniorConversationEvents, Or as leaveEndsAccess, Pc as closeHandledReplyNotices, Pf as addAgentTurnUsage, Po as findMatchingWatches, Pp as juniorCodeChanges, Pr as conversationPinnedForUser, Q as treeAwaitsAuthorization, Qi as basePluginContext, Rc as dismissOpenInboxItems, Rf as hasAgentTurnUsage, Rn as createInboxItemShow, Rp as juniorMessageAttachments, Rr as getVercelConversationWorkQueue, Rs as lookupSlackUser, S as setArchivedAt, Sa as findMatchingEventAutomations, Si as notifyAutomationBlocked, Sl as getDashboardConversationLink, St as inboxItemOwnedByThroughSubject, T as lastMessageAtSql, Ts as conversationSubtreeColumns, Tt as getPlugins, U as conversationIsActiveSql, Uc as ownerConversationId, Uf as nextDetailVersion, Uo as bindSlackDirectCredentialSubject, Vi as wrapBareSlackUserIds, Vo as bindEventAutomationCredentialSubject, Vu as storedMessageJson, X as awaitsAuthorizationFrom, Xc as itemQuestion, Xf as spaceLeadIds, Y as conversationKindFromRow, Ya as recordAutomationExecution, Yn as safeLinkUrl, Yo as updateTimerIndex, Yr as buildSentryConversationUrl, Z as hasUnexpiredAuthorizationRequest, Zc as INBOX_SUBJECT_KINDS, Zf as listedConversation, Zo as canPauseConversationDelivery, _o as slackChannelMessageRunsAutomation, _r as dismissPluginInboxItem, _u as eventGuidance, a as getDb, aa as createPluginCache, ai as buildDispatchId, al as identityAvatarUrl, an as getConversationWorkState, ap as juniorTodos, br as takeOverPluginClose, bs as listConversationAnnotationsById, cc as createPluginUsers, ci as createOrGetDispatch, cp as juniorQuestions, ct as inboxItemNeedsInput, dl as SNOOZE_TIMER_EVENT_TYPE, dp as juniorAutomationRuns, er as createPluginEventPublisher, eu as isThread, fi as getDispatchRecord, fo as getEventCatalog, gl as listFiringInboxSnoozeTriggers, go as slackChannelMessageReplyThreadTs, gr as createPluginInboxItems, gt as isPluginInboxItem, hi as isTerminalDispatchStatus, hr as PLUGIN_CHOICE_FIELD_ID, ht as isOnlyAssignee, i as getConversationStore, il as hasUserPhoto, in as getConversation, it as conversationOwnsInboxItem, ja as automationVersionOf, jp as juniorConversationAnnotations, ka as eventAutomationRunLimitReason, kr as readConversationAccessFromSql, li as getDispatchConversationId, lt as inboxItemPlugin, mf as webActorUserIds, mi as getPluginDispatchProjection, mp as juniorAutomations, mr as createPluginConversationChanges, mt as isInboxItemForEveryone, mu as CORE_EVENT_NAMESPACE, n as getConversationEventStore, no as AUTOMATION_ALERT_STEP_FIELD_ID, ns as annotationMatches, o as getSqlExecutor, ot as inboxItemAddedByAutomation, ou as turnBehavior, p as copyMessageLinks, pt as isAutomationAlertItem, q as conversationWaitsOnUserSql, qc as inboxItemAnswer, qi as createPluginEmbedder, qo as verifySlackDirectCredentialSubject, qu as completeDecision, rl as subjectTodo, rr as createPluginTaskStarter, rs as resolveAnnotationFilter, rt as canUserReadInboxItem, ss as subjectKey, st as inboxItemForUser, to as AUTOMATION_ALERT_STEPS, tt as canAnswerInboxItem, tu as isTopLevel, u as isPostgresErrorCode, ul as userAvatarUrlsFromJoinedPhotos, v as withConversationEventLock, va as blockEventAutomation, vl as settleInboxSnoozes, vr as hasAssigneeRoles, vs as createPluginConversationAnnotations, w as loadConversationSlackTenantIds, wr as canInviteToConversation, ws as conversationSubtree, x as readConversationTrees, xr as createPluginCodeChanges, y as conversationAncestors, ya as collectEventAutomationMatchKeys, yp as juniorInboxItems, yr as leavePluginInboxItem, ys as listConversationAnnotations, z as conversationCostOf, za as existingConversationId, zc as getInboxItem, zi as slackMention, zp as juniorConversations, zs as lookupSlackUserNames } from "./db-BacvswT0.js";
3
3
  import { $ as activityPreviewText, Lt as conversationTreeStateSchema, St as contextProvenance, Y as conversationReportStatusSchema, Z as conversationSurfaceSchema, Zt as readMessageAttachments, _n as answeredChoices, at as KNOWN_CONVERSATION_EVENT_TYPES, bn as isEmptyUserInputAnswer, kn as automationTaskText, pn as inboxItemQuestion, t as OPEN_TODO_STATUSES, xn as normalizeUserInputAnswer, yt as piMessageFromHistoryItem } from "./types-BNHkJrOP.js";
4
- import { T as withSpan, f as logException, m as logWarn, p as logInfo, y as setSpanAttributes } from "./logging-BRPTXAdf.js";
4
+ import { T as withSpan, f as logException, m as logWarn, p as logInfo, y as setSpanAttributes } from "./logging-DsTnMqyi.js";
5
5
  import { h as startSpan, n as captureMessage } from "./sentry-CPbZjomA.js";
6
- import { t as JUNIOR_VERSION } from "./version-BNm0JYj3.js";
7
- import { G as mapBounded, h as createPluginLogger } from "./prompt-3TqxEOtc.js";
6
+ import { t as JUNIOR_VERSION } from "./version-BuLVNlxB.js";
7
+ import { G as mapBounded, h as createPluginLogger } from "./prompt-C5CW2wKO.js";
8
8
  import { o as webMessageId } from "./agent-status-Bq_AIpyp.js";
9
- import { An as loadTurnProjection, H as legacyWebMailboxMetadataSchema, Mt as renderTaskInput, O as notInheritedByForkChild, _t as resolveEventAuthor, ft as eventAuthorText, tt as getWebAuthorization, vt as resolveBotSlackTeamId } from "./markers-9QoqW5ov.js";
10
- import { A as readLastUserMessageAtByConversation, An as setConversationTitle, Ar as gapSegment, Bn as isFileAttachment, Bt as conversationRecordColumns, Cn as recordWebConversationActivity, Dr as MINUTE_MS, Et as resolveObjectCards, F as markConversationRead, Fn as jsonResponse, G as getSpaceLead, Gt as conversationEventHistory, H as setConversationSpaceForViewer, Ht as conversationRecordJoins, In as throwApiError, J as getProductionSlackAdapter, Jt as readConversationParticipants, Kt as conversationSummaryFromStoredConversation, L as deliverInboxItemChange, Lt as resolveSlackTeamDomains, Mn as leaveConversation, Nn as setConversationSubscription, On as verifyAttachmentUploads, P as conversationReadPositionQuery, Q as clearSlackPendingReactions, Qn as takeViewerAutomationAlertStep, Rn as slackAttachmentsVersionQuery, Sn as createConversationId, Tn as AttachmentUploadError, Tr as providerCacheTtlMs, Tt as readLiveAnnotationsById, U as readSpaceRefs, Ut as readConversationRecordFromSql, V as requireSpaceForWork, Vt as conversationRecordFromRow, Wt as selectConversationRecords, Yt as readFirstHumanMessageTexts, _ as listConversationWork, _r as historyPeriodSavings, at as enqueueAgentDispatch, cr as AutomationEditError, d as ANSWER_TOOL_ENDINGS, dr as effectiveTaskOutcomes, dt as readConversationEventPage, en as imagePath, er as ViewerTaskNotFoundError, f as CONVERSATION_STATE_TTL_MS, ft as readConversationEventPageAfter, g as isConversationWorkDone, gr as firstLiveSavingsDate, h as segmentGapsKey, hr as addHistoryWarmupCost, j as archiveConversation, kr as NO_REPLY_GAP_MS, lr as findAutomationSkill, m as GLOBAL_GAPS_TTL_MS, mr as addHistoryPeriod, nr as readConversationSourceTask, p as GLOBAL_GAPS_MAX, pt as readConversationEventPageAround, qn as createPluginConversationWatches, qt as readConversationAuthors, rn as readConversationLineage, un as parseContent, ur as missingAutomationSkillReason, vn as acceptsWebMessages, vr as replaceHistorySavings, vt as stopConversation, w as ingestEvent, wn as webActorFromUser, wr as connectedState, wt as readLiveAnnotations, xn as createAndEnqueueConversation, yn as appendAndEnqueueWebMessage, zt as conversationFromRecordRow } from "./agent-CtzMl32d.js";
11
- import { a as getChildAgentLabel } from "./result-5IdGJP4M.js";
9
+ import { D as notInheritedByForkChild, V as legacyWebMailboxMetadataSchema, _t as resolveBotSlackTeamId, dt as eventAuthorText, et as getWebAuthorization, gt as resolveEventAuthor, jt as renderTaskInput, kn as loadTurnProjection } from "./markers-C33gNYNE.js";
10
+ import { An as setConversationTitle, Ar as gapSegment, Bn as isFileAttachment, Bt as conversationRecordColumns, Cn as recordWebConversationActivity, Dr as MINUTE_MS, Et as resolveObjectCards, F as markConversationRead, Fn as jsonResponse, G as getSpaceLead, Gt as conversationEventHistory, H as setConversationSpaceForViewer, Ht as conversationRecordJoins, In as throwApiError, J as getProductionSlackAdapter, Jt as readConversationParticipants, Kt as conversationSummaryFromStoredConversation, L as deliverInboxItemChange, Lt as resolveSlackTeamDomains, Mn as leaveConversation, Nn as setConversationSubscription, On as verifyAttachmentUploads, P as conversationReadPositionQuery, Q as clearSlackPendingReactions, Qn as takeViewerAutomationAlertStep, Rn as slackAttachmentsVersionQuery, Sn as createConversationId, T as ingestEvent, Tn as AttachmentUploadError, Tr as providerCacheTtlMs, Tt as readLiveAnnotationsById, U as readSpaceRefs, Ut as readConversationRecordFromSql, V as requireSpaceForWork, Vt as conversationRecordFromRow, Wt as selectConversationRecords, Yt as readFirstHumanMessageTexts, _ as listConversationWork, _r as historyPeriodSavings, at as enqueueAgentDispatch, cr as AutomationEditError, d as ANSWER_TOOL_ENDINGS, dr as effectiveTaskOutcomes, dt as readConversationEventPage, en as imagePath, er as ViewerTaskNotFoundError, f as CONVERSATION_STATE_TTL_MS, ft as readConversationEventPageAfter, g as isConversationWorkDone, gr as firstLiveSavingsDate, h as segmentGapsKey, hr as addHistoryWarmupCost, j as archiveConversation, kr as NO_REPLY_GAP_MS, lr as findAutomationSkill, m as GLOBAL_GAPS_TTL_MS, mr as addHistoryPeriod, nr as readConversationSourceTask, p as GLOBAL_GAPS_MAX, pt as readConversationEventPageAround, qn as createPluginConversationWatches, qt as readConversationAuthors, rn as readConversationLineage, un as parseContent, ur as missingAutomationSkillReason, v as readLastUserMessageAtByConversation, vn as acceptsWebMessages, vr as replaceHistorySavings, vt as stopConversation, wn as webActorFromUser, wr as connectedState, wt as readLiveAnnotations, xn as createAndEnqueueConversation, yn as appendAndEnqueueWebMessage, zt as conversationFromRecordRow } from "./agent-DxZ7nHfD.js";
11
+ import { a as getChildAgentLabel } from "./result-BPNzgeTl.js";
12
12
  import { C as cancelConversationPendingMessagesBodySchema, D as conversationPendingMessageDeliverySchema, N as healthReportSchema, S as conversationAutoArchiveSchema, b as archiveConversationResponseSchema, c as conversationSubscriptionResponseSchema, g as pinConversationResponseSchema, h as pinConversationBodySchema, l as setConversationSpaceBodySchema, m as renameConversationResponseSchema, o as conversationLeaveResponseSchema, p as renameConversationBodySchema, r as stopConversationTurnResponseSchema, s as conversationSubscriptionBodySchema, u as setConversationSpaceResponseSchema, w as cancelConversationPendingMessagesResponseSchema, x as archiveDoneConversationsResponseSchema, y as archiveConversationBodySchema } from "./conversation-feed-DEUdD7mb.js";
13
- import { r as canContinueInSlack } from "./continue-in-slack-CFzDyxkH.js";
13
+ import { r as canContinueInSlack } from "./continue-in-slack-DBlQP4PC.js";
14
14
  import * as z from "zod";
15
15
  import { and, asc, count, desc, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, min, ne, not, notInArray, or, sql } from "drizzle-orm";
16
16
  import { alias } from "drizzle-orm/pg-core";
@@ -4617,8 +4617,17 @@ function feedMediaSql(db) {
4617
4617
  * closed since.
4618
4618
  */
4619
4619
  function feedViewerAnswerSql(db, userId) {
4620
- const latest = db.select({ answer: sql`jsonb_build_object('answer', ${inboxItemAnswer}, 'closedAt', ${juniorInboxItems.closedAt}, 'request', ${inboxItemRequest})` }).from(juniorInboxItems).leftJoin(juniorQuestions, itemQuestion).where(and(inboxItemOwnedByConversation(juniorConversations.conversationId), eq(juniorInboxItems.closedByUserId, userId), isNotNull(inboxItemAnswer), isNotNull(inboxItemRequest))).orderBy(desc(juniorInboxItems.closedAt), desc(juniorInboxItems.id)).limit(1);
4621
- return sql`(${latest})`;
4620
+ const answered = db.select({
4621
+ answer: sql`jsonb_build_object('answer', ${inboxItemAnswer}, 'closedAt', ${juniorInboxItems.closedAt}, 'request', ${inboxItemRequest})`.as("answer"),
4622
+ closedAt: juniorInboxItems.closedAt,
4623
+ id: juniorInboxItems.id,
4624
+ ownerId: inboxItemOwnerConversationId().as("owner_id")
4625
+ }).from(juniorInboxItems).leftJoin(juniorQuestions, itemQuestion).where(and(eq(juniorInboxItems.closedByUserId, userId), isNotNull(inboxItemAnswer), isNotNull(inboxItemRequest))).as("viewer_answered");
4626
+ const answers = db.selectDistinctOn([answered.ownerId], {
4627
+ answer: answered.answer,
4628
+ ownerId: answered.ownerId
4629
+ }).from(answered).where(isNotNull(answered.ownerId)).orderBy(answered.ownerId, desc(answered.closedAt), desc(answered.id)).as("viewer_answers");
4630
+ return sql`((select jsonb_object_agg(${answers.ownerId}, ${answers.answer}) from ${answers}) -> ${juniorConversations.conversationId})`;
4622
4631
  }
4623
4632
  /**
4624
4633
  * Keep only what a row says about the answer: when it closed and the
@@ -1,5 +1,5 @@
1
1
  import { _ as withScope, d as setTag, f as setUser, h as startSpan, i as getActiveSpan, l as logger, n as captureMessage, p as spanToJSON, s as getTraceData, t as captureException } from "./sentry-CPbZjomA.js";
2
- import { _ as getDeploymentTelemetryAttributes } from "./deployment-CfOew1Tm.js";
2
+ import { _ as getDeploymentTelemetryAttributes } from "./deployment-BoJkRPDt.js";
3
3
  import path from "node:path";
4
4
  import { styleText } from "node:util";
5
5
  import { ConfigError, configureSync, getConfig, getLogger } from "@logtape/logtape";