@sentry/junior 0.319.0 → 0.321.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.
- package/dist/{adapter-8_S6Birm.js → adapter-BkDQYdg6.js} +1 -1
- package/dist/{admin-EsbUON1j.js → admin-XS3G9BOj.js} +1 -1
- package/dist/{agent-CtzMl32d.js → agent-CL9ZkOgx.js} +45 -52
- package/dist/{agent-update-delivery-pAvsbuGL.js → agent-update-delivery-t0bXEgPs.js} +4 -4
- package/dist/api/schema.d.ts +4 -12
- package/dist/api/schema.js +4 -4
- package/dist/api.js +30 -25
- package/dist/{app-tACXxJPI.d.ts → app-CwFRvmEH.d.ts} +2 -1
- package/dist/app.d.ts +1 -1
- package/dist/app.js +22 -219
- package/dist/{change-record-K-KsqNhT.d.ts → change-record-CRuG9Mu3.d.ts} +1 -6
- package/dist/{channel-access-DET5hzZM.js → channel-access-BUHB0saC.js} +1 -1
- package/dist/{chat-core-engine-DpM3tMVi.js → chat-core-engine-DuBaPbqK.js} +31 -14
- package/dist/cli/chat.js +16 -16
- package/dist/cli/check.js +4 -4
- package/dist/cli/main.js +2 -2
- package/dist/cli/plugins.js +3 -3
- package/dist/cli/snapshot-create.js +4 -4
- package/dist/cli/upgrade.js +2 -2
- package/dist/{continue-in-slack-CFzDyxkH.js → continue-in-slack-D9naZmqM.js} +3 -3
- package/dist/{conversation-feed-DEUdD7mb.js → conversation-feed-B1_1NJc8.js} +2 -12
- package/dist/{conversation-privacy-C2vYK55O.js → conversation-privacy-C0mixZKx.js} +1 -1
- package/dist/{create-Ta3SEIB5.js → create-CLV0M1vw.js} +2 -2
- package/dist/{credential-sync-DyRqDmY4.js → credential-sync-DL9r-ry5.js} +11 -11
- package/dist/{db-BCaNWl9p.js → db-CbURDbaB.js} +49 -28
- package/dist/{deployment-CfOew1Tm.js → deployment-D9uPRDMD.js} +1 -1
- package/dist/{engine-context-CiExoy1B.js → engine-context-BP0h6u4m.js} +389 -13
- package/dist/{html-Bb2Si1bR.js → html-l4hKICAL.js} +4 -4
- package/dist/instrumentation.js +2 -2
- package/dist/{list-wwDcROh9.js → list-cGaO9_Hf.js} +12 -37
- package/dist/{logging-BRPTXAdf.js → logging-CqgOoICc.js} +1 -1
- package/dist/{markers-9QoqW5ov.js → markers-BtUv4-oc.js} +40 -37
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +2 -2
- package/dist/{oauth-callback-server-vhL9b-PZ.js → oauth-callback-server-C3GxhsuB.js} +2 -2
- package/dist/{oauth-relay-CH2v7WiB.js → oauth-relay-BGm6sLCB.js} +1 -1
- package/dist/{profile-D9LdwmZi.js → profile-bLo0h7Le.js} +12 -6
- package/dist/{prompt-3TqxEOtc.js → prompt-CX29OGO9.js} +1 -1
- package/dist/{reports-K-tbtEyx.js → reports-DeDCCu_H.js} +2 -2
- package/dist/{resolve-BBV2qf8A.js → resolve-D9RKNH3v.js} +5 -5
- package/dist/{result-5IdGJP4M.js → result-BFBwK1M2.js} +7 -7
- package/dist/{runner-BK_joPlM.js → runner-DNdoVQg8.js} +7 -7
- package/dist/{sandbox-egress-signals-DXgWXXmm.js → sandbox-egress-signals-BBcCiEhm.js} +1 -1
- package/dist/{schema-zWGG6VC1.js → schema-RzsplzdI.js} +5 -3
- package/dist/{service-account-CateFyhw.js → service-account-B7E7OIFP.js} +2 -2
- package/dist/{skills-Ccjw8h2P.js → skills-DMJsS5e4.js} +4 -4
- package/dist/{slack-conversation-unfurl-ZC_TSpc4.js → slack-conversation-unfurl-EWYTnBZI.js} +7 -7
- package/dist/{storage-C9U7R5rM.js → storage-XD0lB4Gk.js} +2 -2
- package/dist/{system-prompt-table-YBTHIFlP.js → system-prompt-table-C886lsT9.js} +4 -4
- package/dist/{types-BNHkJrOP.js → types-CGgQ3-Bb.js} +1 -9
- package/dist/{users-CCRAqYb_.js → users-DBrcQl47.js} +1 -1
- package/dist/{validation-BCUpJa8K.js → validation-CofUHWqz.js} +1 -1
- package/dist/{version-BNm0JYj3.js → version-D_vbXyNw.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{worker-BhgpZ7_b.js → worker-buhFcpl9.js} +4 -4
- package/migrations/20261127150242_drop_space_members/migration.sql +9 -0
- package/migrations/20261127150242_drop_space_members/snapshot.json +53 -0
- package/package.json +6 -6
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import { $ as resolveGatewayModel, L as botConfig, f as credentialContextForActor } from "./adapter-
|
|
2
|
-
import { $a as
|
|
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,
|
|
4
|
-
import { _ as serializeGenAiAttribute, f as logException, h as normalizeGenAiFinishReason, i as extractGenAiUsageSummary, m as logWarn, r as extractGenAiUsageAttributes } from "./logging-
|
|
5
|
-
import { h as SERVICE_INSTANCE_ID } from "./deployment-
|
|
6
|
-
import { G as mapBounded } from "./prompt-
|
|
7
|
-
import { a as toCanonicalInputMessage, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-
|
|
8
|
-
import { $
|
|
9
|
-
import {
|
|
1
|
+
import { $ as resolveGatewayModel, L as botConfig, f as credentialContextForActor } from "./adapter-BkDQYdg6.js";
|
|
2
|
+
import { $a as usdToMicroUsd, $f as juniorTurnOutbox, Dp as juniorConversationEvents, Ff as agentTurnTotalTokens, Gr as QUEUE_SIGNATURE_MAX_AGE_MS, Jr as getQueueProvider, Kr as signQueueMessage, M as locationSchema, N as claimProviderConversation, Nf as addAgentTurnUsage, O as withConversationMutationLock, Op as juniorTurns, Pf as agentTurnCostUsd, Qa as microUsdToUsd, Qn as sendSlackReply, R as replaceConversationMetrics, Rp as juniorConversations, Td as getGatewayApiKey, _ as unseenEvents, a as getDb, d as createSqlConversationEventStore, ep as juniorTurnInbox, g as readEventCursor, h as insertEventRows, j as startLocationThread, js as resolveRootVisibility, o as getSqlExecutor, od as requestPrefixAttributes, pd as gatewayRoutingAttributes, qr as verifyQueueMessage, ti as runWithSlackInstallation, v as withConversationEventLock } from "./db-CbURDbaB.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-CGgQ3-Bb.js";
|
|
4
|
+
import { _ as serializeGenAiAttribute, f as logException, h as normalizeGenAiFinishReason, i as extractGenAiUsageSummary, m as logWarn, r as extractGenAiUsageAttributes } from "./logging-CqgOoICc.js";
|
|
5
|
+
import { h as SERVICE_INSTANCE_ID } from "./deployment-D9uPRDMD.js";
|
|
6
|
+
import { G as mapBounded } from "./prompt-CX29OGO9.js";
|
|
7
|
+
import { a as toCanonicalInputMessage, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-C0mixZKx.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-BtUv4-oc.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-CL9ZkOgx.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 {
|
|
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-
|
|
2
|
-
import {
|
|
3
|
-
import { G as mapBounded } from "./prompt-
|
|
4
|
-
import {
|
|
1
|
+
import { L as botConfig } from "./adapter-BkDQYdg6.js";
|
|
2
|
+
import { Jd as hasRequiredOAuthScope, Nd as getAppContext, Sc as deleteProviderIdentityForUser, ef as deleteMcpAuthSessionsForUserProvider, nf as deleteMcpStoredOAuthCredentials, o as getSqlExecutor, tf as deleteMcpServerSessionId, xc as deleteProviderIdentityForSlackUser } from "./db-CbURDbaB.js";
|
|
3
|
+
import { G as mapBounded } from "./prompt-CX29OGO9.js";
|
|
4
|
+
import { pi as startOAuthFlow } from "./markers-BtUv4-oc.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. */
|
package/dist/instrumentation.js
CHANGED
|
@@ -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-
|
|
2
|
+
import { n as getCurrentConversationPrivacy } from "./conversation-privacy-C0mixZKx.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-
|
|
7
|
+
import { _ as getDeploymentTelemetryAttributes, g as getDeploymentServiceVersion } from "./deployment-D9uPRDMD.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-
|
|
2
|
-
import { $ as canActOnInboxItem, $
|
|
3
|
-
import { $ as activityPreviewText, Lt as conversationTreeStateSchema, St as contextProvenance, Y as conversationReportStatusSchema, Z as conversationSurfaceSchema, Zt as readMessageAttachments,
|
|
4
|
-
import { T as withSpan, f as logException, m as logWarn, p as logInfo, y as setSpanAttributes } from "./logging-
|
|
1
|
+
import { $ as resolveGatewayModel, L as botConfig, R as getChatConfig, a as getStateValues, i as getStateAdapter, o as setStateValues } from "./adapter-BkDQYdg6.js";
|
|
2
|
+
import { $ as canActOnInboxItem, $l as isThread, $s as isDmChannel, Ao as collectEventMatchKeys, Ap as juniorConversationAnnotations, Ar as readConversationAccessRows, As as isPublicConversation, Bi as slackMentionedUserIds, Bn as pushInboxSnoozeWakes, Bt as setTodoStatusByUser, Bu as storedMessageJson, C as conversationSlackTenantId, Cr as canAddConversationMessages, Cs as conversationAncestorsOrSelf, Dp as juniorConversationEvents, Dr as createConversationAccessReader, Ds as conversationSearchVector, Ed as JUNIOR_NATIVE_EVENT_NAMESPACE, Er as conversationAccessFromRows, Fr as readMemberParticipants, G as conversationStatusSql, Gc as takeInboxItem, Gi as createPluginState, Go as verifyEventAutomationCredentialSubject, Gp as juniorDestinations, Hc as listReplyActionItems, Hf as nextDetailVersion, Hi as applyPluginFormatMarkdown, Ho as bindScheduledAutomationCredentialSubject, If as agentTurnUsageSchema, Ip as juniorAttachments, Ir as rootVisibleToViewer, Ja as readAutomationTitlesByConversationId, K as conversationTurnFailedSql, Ko as verifyScheduledAutomationCredentialSubject, Kt as cancelHumanFacingPendingMessages, Ku as completeDecision, Lc as closeInboxItem, Lf as hasAgentTurnUsage, Lo as listConversationsWithWatches, Lp as juniorMessageAttachments, Lr as viewerMarksFromParticipant, Mr as conversationIsMemberRoot, Nc as waitingConversationIdsQuery, Nf as addAgentTurnUsage, Np as juniorCodeChanges, Nr as conversationIsNotUnsubscribedRoot, Oa as admitEventAutomationRun, Or as leaveEndsAccess, Pc as closeHandledReplyNotices, Po as findMatchingWatches, Pr as conversationPinnedForUser, Q as treeAwaitsAuthorization, Qi as basePluginContext, Rc as dismissOpenInboxItems, Rn as createInboxItemShow, Rp as juniorConversations, Rr as getVercelConversationWorkQueue, Rs as lookupSlackUser, S as setArchivedAt, Sa as findMatchingEventAutomations, Si as notifyAutomationBlocked, Sp as juniorConversationParticipants, St as inboxItemOwnedByThroughSubject, T as lastMessageAtSql, Ts as conversationSubtreeColumns, Tt as getPlugins, U as conversationIsActiveSql, Uc as ownerConversationId, Uo as bindSlackDirectCredentialSubject, Vi as wrapBareSlackUserIds, Vo as bindEventAutomationCredentialSubject, Vp as juniorIdentities, Wp as juniorUsers, X as awaitsAuthorizationFrom, Xc as INBOX_SUBJECT_KINDS, Xf as listedConversation, Y as conversationKindFromRow, Ya as recordAutomationExecution, Yc as itemQuestion, Yf as spaceLeadIds, Yn as safeLinkUrl, Yo as updateTimerIndex, Yr as buildSentryConversationUrl, Z as hasUnexpiredAuthorizationRequest, Zo as canPauseConversationDelivery, _l as settleInboxSnoozes, _o as slackChannelMessageRunsAutomation, _r as dismissPluginInboxItem, a as getDb, aa as createPluginCache, ai as buildDispatchId, an as getConversationWorkState, au as turnBehavior, br as takeOverPluginClose, bs as listConversationAnnotationsById, cc as createPluginUsers, ci as createOrGetDispatch, ct as inboxItemNeedsInput, er as createPluginEventPublisher, eu as isTopLevel, fi as getDispatchRecord, fo as getEventCatalog, go as slackChannelMessageReplyThreadTs, gr as createPluginInboxItems, gt as isPluginInboxItem, gu as eventGuidance, hi as isTerminalDispatchStatus, hl as listFiringInboxSnoozeTriggers, hr as PLUGIN_CHOICE_FIELD_ID, ht as isOnlyAssignee, i as getConversationStore, il as identityAvatarUrl, in as getConversation, ip as juniorTodos, it as conversationOwnsInboxItem, ja as automationVersionOf, ka as eventAutomationRunLimitReason, kl as parseDashboardConversationLink, kr as readConversationAccessFromSql, li as getDispatchConversationId, ll as userAvatarUrlsFromJoinedPhotos, lt as inboxItemPlugin, mi as getPluginDispatchProjection, mr as createPluginConversationChanges, mt as isInboxItemForEveryone, n as getConversationEventStore, nl as subjectTodo, no as AUTOMATION_ALERT_STEP_FIELD_ID, ns as annotationMatches, o as getSqlExecutor, ot as inboxItemAddedByAutomation, p as copyMessageLinks, pf as webActorUserIds, pp as juniorAutomations, pt as isAutomationAlertItem, pu as CORE_EVENT_NAMESPACE, q as conversationWaitsOnUserSql, qi as createPluginEmbedder, qo as verifySlackDirectCredentialSubject, rl as hasUserPhoto, rr as createPluginTaskStarter, rs as resolveAnnotationFilter, rt as canUserReadInboxItem, sp as juniorQuestions, ss as subjectKey, st as inboxItemForUser, to as AUTOMATION_ALERT_STEPS, tt as canAnswerInboxItem, u as isPostgresErrorCode, ul as SNOOZE_TIMER_EVENT_TYPE, up as juniorAutomationRuns, v as withConversationEventLock, va as blockEventAutomation, vp as juniorInboxItems, vr as hasAssigneeRoles, vs as createPluginConversationAnnotations, w as loadConversationSlackTenantIds, wr as canInviteToConversation, ws as conversationSubtree, x as readConversationTrees, xl as getDashboardConversationLink, xr as createPluginCodeChanges, y as conversationAncestors, ya as collectEventAutomationMatchKeys, yr as leavePluginInboxItem, ys as listConversationAnnotations, z as conversationCostOf, za as existingConversationId, zc as getInboxItem, zf as resolveRootConversationId, zi as slackMention, zs as lookupSlackUserNames } from "./db-CbURDbaB.js";
|
|
3
|
+
import { $ as activityPreviewText, Lt as conversationTreeStateSchema, On as automationTaskText, St as contextProvenance, Y as conversationReportStatusSchema, Z as conversationSurfaceSchema, Zt as readMessageAttachments, at as KNOWN_CONVERSATION_EVENT_TYPES, bn as normalizeUserInputAnswer, pn as inboxItemQuestion, t as OPEN_TODO_STATUSES, yn as isEmptyUserInputAnswer, yt as piMessageFromHistoryItem } from "./types-CGgQ3-Bb.js";
|
|
4
|
+
import { T as withSpan, f as logException, m as logWarn, p as logInfo, y as setSpanAttributes } from "./logging-CqgOoICc.js";
|
|
5
5
|
import { h as startSpan, n as captureMessage } from "./sentry-CPbZjomA.js";
|
|
6
|
-
import { t as JUNIOR_VERSION } from "./version-
|
|
7
|
-
import { G as mapBounded, h as createPluginLogger } from "./prompt-
|
|
6
|
+
import { t as JUNIOR_VERSION } from "./version-D_vbXyNw.js";
|
|
7
|
+
import { G as mapBounded, h as createPluginLogger } from "./prompt-CX29OGO9.js";
|
|
8
8
|
import { o as webMessageId } from "./agent-status-Bq_AIpyp.js";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import { a as getChildAgentLabel } from "./result-
|
|
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-
|
|
13
|
-
import { r as canContinueInSlack } from "./continue-in-slack-
|
|
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-BtUv4-oc.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-CL9ZkOgx.js";
|
|
11
|
+
import { a as getChildAgentLabel } from "./result-BFBwK1M2.js";
|
|
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-B1_1NJc8.js";
|
|
13
|
+
import { r as canContinueInSlack } from "./continue-in-slack-D9naZmqM.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";
|
|
@@ -4609,28 +4609,6 @@ function feedMediaSql(db) {
|
|
|
4609
4609
|
const files = db.select({ files: sql`jsonb_agg(jsonb_build_object('contentType', ${recentFiles.contentType}, 'filename', ${recentFiles.filename}, 'id', ${recentFiles.id}) order by ${recentFiles.createdAt} desc, ${recentFiles.id} desc)` }).from(recentFiles);
|
|
4610
4610
|
return sql`(${files})`;
|
|
4611
4611
|
}
|
|
4612
|
-
// src/api/conversations/feed-answer.ts
|
|
4613
|
-
/**
|
|
4614
|
-
* A feed row column with the viewer's newest answered Inbox item of its
|
|
4615
|
-
* Conversation, or null. It is a scalar subquery on the row read, so the
|
|
4616
|
-
* answer costs no round trip of its own, however many items the viewer
|
|
4617
|
-
* closed since.
|
|
4618
|
-
*/
|
|
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})`;
|
|
4622
|
-
}
|
|
4623
|
-
/**
|
|
4624
|
-
* Keep only what a row says about the answer: when it closed and the
|
|
4625
|
-
* options that the viewer picked. Text answers have no choices.
|
|
4626
|
-
*/
|
|
4627
|
-
function feedViewerAnswer(stored) {
|
|
4628
|
-
if (!stored) return void 0;
|
|
4629
|
-
return {
|
|
4630
|
-
choices: answeredChoices(stored.request, stored.answer),
|
|
4631
|
-
closedAt: new Date(stored.closedAt).toISOString()
|
|
4632
|
-
};
|
|
4633
|
-
}
|
|
4634
4612
|
// src/api/page-cursor.ts
|
|
4635
4613
|
/**
|
|
4636
4614
|
* Encode the position after the last row of a page as an opaque `cursor`
|
|
@@ -4702,8 +4680,7 @@ async function conversationRows(db, { codeRepository, conversationIds, cursor, f
|
|
|
4702
4680
|
awaitingAuthorization: treeAwaitsAuthorization(juniorConversations.conversationId),
|
|
4703
4681
|
latestTurnFailed: conversationTurnFailedSql(juniorConversations),
|
|
4704
4682
|
links: include.includes("links") ? feedLinksSql(db) : sql`null`,
|
|
4705
|
-
media: include.includes("media") ? feedMediaSql(db) : sql`null
|
|
4706
|
-
viewerAnswer: filter?.kind === "viewer" ? feedViewerAnswerSql(db, filter.userId) : sql`null`
|
|
4683
|
+
media: include.includes("media") ? feedMediaSql(db) : sql`null`
|
|
4707
4684
|
}).from(juniorConversations).leftJoin(juniorDestinations, conversationRecordJoins.location).leftJoin(juniorIdentities, conversationRecordJoins.identity).leftJoin(juniorUsers, conversationRecordJoins.user).where(and(space ? conversationSpaceFilter(space.id, status, space.viewerUserId) : and(listedConversation(), conversationFeedMembershipFilter(status, filter)), conversationIds ? inArray(juniorConversations.conversationId, conversationIds) : void 0, waitingForUserId ? inArray(juniorConversations.conversationId, waitingConversationIdsQuery(db, waitingForUserId)) : void 0, pinnedForUserId ? pinnedForUserId.pinned ? conversationPinnedForUser(pinnedForUserId.userId) : not(conversationPinnedForUser(pinnedForUserId.userId)) : void 0, cursor ? sql`(${juniorConversations.lastActivityAt} < ${cursor.at}::timestamptz or (${juniorConversations.lastActivityAt} = ${cursor.at}::timestamptz and ${juniorConversations.conversationId} > ${cursor.conversationId}))` : void 0, codeRepository ? conversationCodeRepositoryFilter(codeRepository.id, codeRepository.viewerUserId) : void 0, query ? or(sql`strpos(lower(coalesce(${juniorConversations.title}, '')), ${query}) > 0`, and(includePrivateMatches ? void 0 : isPublicConversation(juniorConversations), sql`${conversationSearchVector} @@ websearch_to_tsquery('english', ${query})`), annotationMatch(db, {
|
|
4708
4685
|
includePrivate: includePrivateMatches,
|
|
4709
4686
|
query,
|
|
@@ -4961,7 +4938,6 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
4961
4938
|
const links = access?.canViewPrivateContent && row.links ? pickFeedLinks(conversation.conversationId, row.links, annotationUrls(visibleAnnotationsByConversation.get(conversation.conversationId))) : [];
|
|
4962
4939
|
const lastMessageAt = row.lastMessageAt?.toISOString();
|
|
4963
4940
|
const treeRead = treeStateByConversation.get(conversation.conversationId);
|
|
4964
|
-
const viewerAnswer = access?.canViewPrivateContent ? feedViewerAnswer(row.viewerAnswer) : void 0;
|
|
4965
4941
|
return {
|
|
4966
4942
|
...summary,
|
|
4967
4943
|
...work,
|
|
@@ -4973,7 +4949,6 @@ async function readConversationFeedFromSql(options = {}) {
|
|
|
4973
4949
|
...threads?.omittedThreadCount ? { omittedThreadCount: threads.omittedThreadCount } : void 0,
|
|
4974
4950
|
...participants && participants.length > 0 ? { participants } : void 0,
|
|
4975
4951
|
...activityPreview ? { activityPreview } : void 0,
|
|
4976
|
-
...viewerAnswer ? { viewerAnswer } : void 0,
|
|
4977
4952
|
...media?.length ? { media } : void 0,
|
|
4978
4953
|
...links.length > 0 ? { links } : void 0,
|
|
4979
4954
|
...sidebarAnnotationsByConversation[conversation.conversationId] ? { sidebarAnnotations: sidebarAnnotationsByConversation[conversation.conversationId] } : void 0,
|
|
@@ -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-
|
|
2
|
+
import { _ as getDeploymentTelemetryAttributes } from "./deployment-D9uPRDMD.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";
|