@sentry/junior 0.321.0 → 0.322.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-BkDQYdg6.js → adapter-CKtEUuWD.js} +23 -2
- package/dist/{admin-XS3G9BOj.js → admin-BGOiUGwR.js} +1 -1
- package/dist/{agent-CL9ZkOgx.js → agent-OUkEw6Bv.js} +272 -1647
- package/dist/{agent-status-Bq_AIpyp.js → agent-status-C_HHxO_d.js} +1 -10
- package/dist/{agent-update-delivery-t0bXEgPs.js → agent-update-delivery-H6mnPI4q.js} +4 -4
- package/dist/api/schema.d.ts +98 -6
- package/dist/api/schema.js +6 -6
- package/dist/api.js +81 -36
- package/dist/{app-CwFRvmEH.d.ts → app-BK_vhZIq.d.ts} +1 -1
- package/dist/app.d.ts +1 -1
- package/dist/app.js +85 -48
- package/dist/{change-record-CRuG9Mu3.d.ts → change-record-DdrJxahk.d.ts} +26 -10
- package/dist/{channel-access-BUHB0saC.js → channel-access-DRhVJIuQ.js} +1 -1
- package/dist/{chat-core-engine-DuBaPbqK.js → chat-core-engine-El308gYr.js} +5 -10
- 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-D9naZmqM.js → continue-in-slack-DYl631oM.js} +3 -3
- package/dist/{conversation-feed-B1_1NJc8.js → conversation-feed-BUaMmSLi.js} +1 -1
- package/dist/{conversation-privacy-C0mixZKx.js → conversation-privacy-DR_j5Tqf.js} +1 -1
- package/dist/{create-CLV0M1vw.js → create-ZkI-_JAs.js} +2 -2
- package/dist/{credential-sync-DL9r-ry5.js → credential-sync-Bo6_FtCI.js} +12 -12
- package/dist/{db-CbURDbaB.js → db-RDpWIeRK.js} +1733 -213
- package/dist/{deployment-D9uPRDMD.js → deployment-CeKaP0ZJ.js} +1 -1
- package/dist/{html-l4hKICAL.js → html-BMv4fAPu.js} +5 -5
- package/dist/instrumentation.js +2 -2
- package/dist/{list-cGaO9_Hf.js → list-CuLf7Ob2.js} +38 -35
- package/dist/{logging-CqgOoICc.js → logging-BQsfrLHl.js} +1 -1
- package/dist/{markers-BtUv4-oc.js → markers-Bh0vqJ5k.js} +3178 -1748
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +3 -4
- package/dist/{oauth-callback-server-C3GxhsuB.js → oauth-callback-server-BxuN0Jqz.js} +2 -2
- package/dist/{oauth-relay-BGm6sLCB.js → oauth-relay-vyG2gOwY.js} +1 -1
- package/dist/{profile-bLo0h7Le.js → profile-DiAB4QfT.js} +31 -6
- package/dist/{prompt-CX29OGO9.js → prompt-5PDkRQ1K.js} +2 -1
- package/dist/{reports-DeDCCu_H.js → reports-CbqB7unq.js} +2 -2
- package/dist/{resolve-D9RKNH3v.js → resolve-C7e0pwuP.js} +5 -5
- package/dist/{result-BFBwK1M2.js → result-D_D-2Adp.js} +5 -5
- package/dist/{runner-DNdoVQg8.js → runner-CCVTdp0x.js} +7 -7
- package/dist/{sandbox-egress-signals-BBcCiEhm.js → sandbox-egress-signals-D4OKOFgy.js} +1 -1
- package/dist/{schema-RzsplzdI.js → schema-CmPO8BfI.js} +50 -12
- package/dist/{service-account-B7E7OIFP.js → service-account-CeWsFrBi.js} +2 -2
- package/dist/{skills-DMJsS5e4.js → skills-DfbOjWxl.js} +5 -5
- package/dist/{slack-conversation-unfurl-EWYTnBZI.js → slack-conversation-unfurl-BxF0Yb3-.js} +10 -9
- package/dist/{system-prompt-table-C886lsT9.js → system-prompt-table-DySHMtu0.js} +15 -15
- package/dist/{topics-DxuKurCX.js → topic-ChZe9WPj.js} +6 -1
- package/dist/{engine-context-BP0h6u4m.js → turn-ended-DQ10G3in.js} +11 -845
- package/dist/{types-CGgQ3-Bb.js → types-BWAgOJtR.js} +95 -70
- package/dist/{user-customization-CvfuY9Eo.js → user-customization-DNzu_r1x.js} +10 -1
- package/dist/{users-DBrcQl47.js → users-BmZlg_ci.js} +13 -7
- package/dist/{validation-CofUHWqz.js → validation-BU4tXvH3.js} +1 -1
- package/dist/{version-D_vbXyNw.js → version-D9yLYOBu.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{worker-buhFcpl9.js → worker-C7EDSL3d.js} +4 -4
- package/migrations/20261127184420_question_answerer/migration.sql +36 -0
- package/migrations/20261127184420_question_answerer/snapshot.json +108 -0
- package/migrations/20261127224730_inbox_item_close_action/migration.sql +1 -0
- package/migrations/20261127224730_inbox_item_close_action/snapshot.json +42 -0
- package/package.json +6 -6
- package/skills/design-automation-skill/SKILL.md +1 -1
- package/dist/storage-XD0lB4Gk.js +0 -273
- package/dist/topic-B2EWKKBT.js +0 -6
|
@@ -1,19 +1,21 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
|
|
2
|
-
import { $ as resolveGatewayModel, B as getSlackBotToken, C as parseActorUserId, D as parseSlackChannelReferenceId, J as normalizeSlackEmojiName, L as botConfig, O as parseSlackTeamId, P as parseSlackMessageTs, Q as findGatewayModel, R as getChatConfig, S as isUserActor, Y as TURN_REASONING_LEVELS, Z as GATEWAY_PROVIDER, a as getStateValues, at as streamSimpleAnthropic, b as isActorUserId, et as calculateCost, g as credentialUserSubjectId, h as credentialSubjectSchema, i as getStateAdapter, it as streamAnthropic, k as parseSlackUserId, l as fenceLock, nt as getEnvApiKey, o as setStateValues, p as credentialContextSchema, r as getDefaultRedisStateAdapterFor, rt as registerApiProvider, s as MUTATION_LOCK_TTL_MS, tt as completeSimple, u as withLock, v as createSlackActor, w as parseStoredSlackActor, x as isSlackUserId } from "./adapter-
|
|
3
|
-
import { A as automationVersionSchema,
|
|
4
|
-
import {
|
|
5
|
-
import { A as toOptionalString, D as GOOGLE_IDENTITY_PROVIDER, T as withSpan, _ as serializeGenAiAttribute, b as setSpanStatus, f as logException, g as runBestEffort, i as extractGenAiUsageSummary, k as normalizeIdentityEmail, m as logWarn, p as logInfo, r as extractGenAiUsageAttributes, s as getLogContextAttributes, y as setSpanAttributes } from "./logging-
|
|
6
|
-
import { G as mapBounded, R as unwrapCurrentInstruction, d as SANDBOX_WORKSPACE_ROOT, g as RUNTIME_CONTEXT_TEXT_STARTS, h as createPluginLogger, n as toPromptContributionContext, r as runPluginHooksAtOnce, s as SANDBOX_JUNIOR_ROOT } from "./prompt-
|
|
7
|
-
import { a as toCanonicalInputMessage, n as getCurrentConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes, t as canExposeConversationPayload } from "./conversation-privacy-
|
|
2
|
+
import { $ as resolveGatewayModel, B as getSlackBotToken, C as parseActorUserId, D as parseSlackChannelReferenceId, E as parseSlackChannelId, J as normalizeSlackEmojiName, L as botConfig, O as parseSlackTeamId, P as parseSlackMessageTs, Q as findGatewayModel, R as getChatConfig, S as isUserActor, Y as TURN_REASONING_LEVELS, Z as GATEWAY_PROVIDER, a as getStateValues, at as streamSimpleAnthropic, b as isActorUserId, et as calculateCost, g as credentialUserSubjectId, h as credentialSubjectSchema, i as getStateAdapter, it as streamAnthropic, k as parseSlackUserId, l as fenceLock, nt as getEnvApiKey, o as setStateValues, p as credentialContextSchema, r as getDefaultRedisStateAdapterFor, rt as registerApiProvider, s as MUTATION_LOCK_TTL_MS, tt as completeSimple, u as withLock, v as createSlackActor, w as parseStoredSlackActor, x as isSlackUserId } from "./adapter-CKtEUuWD.js";
|
|
3
|
+
import { A as automationVersionSchema, Bt as inboxItemChangeRecordSchema, Dn as automationTaskColumns, En as automationSkillNameSchema, Jn as usageTokensSchema, Kn as gatewayOnlyProviders, Ln as isValidTimeZone, Mn as isWithinNotificationSchedule, Nn as notificationScheduleSchema, On as automationTaskDescription, Rn as CONTENT_VERSION_HEADER, St as contextProvenance, Tt as sameActorIdentity, Vn as AGENT_UPDATE_EVENT_TYPE, _n as inboxItemQuestion, _t as historyReplacementSchema, a as UPDATE_TODOS_TOOL_NAME, bn as USER_INPUT_NOTE, dn as eventAutomationSchema, dt as agentHistoryFromRow, fn as eventAutomationTriggerSchema, ft as encodeAgentHistoryPayload, gt as historyItemFromPiMessage, i as TODO_STATUSES, in as scheduledAutomationSchema, jn as DEFAULT_NOTIFICATION_SCHEDULE, kn as automationTaskSchema, lt as decodeStoredConversationEvent, n as SELF_TODO_ASSIGNEE, o as isOpenTodoStatus, ot as conversationEventDataSchema, pt as isAgentHistoryData, qn as usageSchema, r as TODOS_REGISTRATION_NAME, rt as agentTypeSchema, t as OPEN_TODO_STATUSES, ut as newConversationEventSchema, vn as inboxItemRequestSchema, wn as normalizeUserInputAnswer, xn as buttonUserInputField, yn as USER_INPUT_LIMITS, yt as piMessageFromHistoryItem } from "./types-BWAgOJtR.js";
|
|
4
|
+
import { c as discoverInstalledPluginPackageContent, l as normalizePluginPackageNames, n as TURN_STEP_TOPIC, o as PLUGIN_TASK_QUEUE_TOPIC, p as pluginRoots, t as TURN_ENDED_TOPIC, y as toOptionalTrimmed } from "./topic-ChZe9WPj.js";
|
|
5
|
+
import { A as toOptionalString, D as GOOGLE_IDENTITY_PROVIDER, T as withSpan$1, _ as serializeGenAiAttribute, b as setSpanStatus, f as logException, g as runBestEffort, i as extractGenAiUsageSummary, k as normalizeIdentityEmail, m as logWarn, p as logInfo, r as extractGenAiUsageAttributes, s as getLogContextAttributes, y as setSpanAttributes } from "./logging-BQsfrLHl.js";
|
|
6
|
+
import { G as mapBounded, R as unwrapCurrentInstruction, d as SANDBOX_WORKSPACE_ROOT, g as RUNTIME_CONTEXT_TEXT_STARTS, h as createPluginLogger, n as toPromptContributionContext, r as runPluginHooksAtOnce, s as SANDBOX_JUNIOR_ROOT } from "./prompt-5PDkRQ1K.js";
|
|
7
|
+
import { a as toCanonicalInputMessage, n as getCurrentConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes, t as canExposeConversationPayload } from "./conversation-privacy-DR_j5Tqf.js";
|
|
8
8
|
import { _ as withScope, a as getClient$1, n as captureMessage } from "./sentry-CPbZjomA.js";
|
|
9
|
+
import { h as SERVICE_INSTANCE_ID } from "./deployment-CeKaP0ZJ.js";
|
|
9
10
|
import * as z from "zod";
|
|
10
11
|
import path from "node:path";
|
|
11
12
|
import { SQL, and, arrayOverlaps, asc, count, desc, eq, exists, getTableName, gt, gte, ilike, inArray, is, isNotNull, isNull, like, lt, lte, max, ne, not, notExists, or, sql } from "drizzle-orm";
|
|
12
13
|
import { PgAsyncDatabase, QueryBuilder, alias, bigint, boolean, check, customType, date, doublePrecision, foreignKey, index, integer, jsonb, pgSequence, pgTable, primaryKey, text as text$1, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
|
|
13
|
-
import { MAX_CONVERSATION_CHANGES, PluginInboxItemOwnerError, PluginToolInputError, actorSchema, agentEventMatchSchema, anyResourceMatchFields, codeChangeFilterSchema, codeChangeInputSchema, codeRepositoryInputSchema, conversationAnnotationInputSchema, conversationEventPresentationSchema, defineConversationEvent, defineJuniorPlugin, definePluginTool, definePromptContext, describeEventTrigger, destinationSchema, destinationVisibilitySchema, escapeTagText, eventDataSchema, eventInputSchema, eventMatchFieldsSchema, eventMatchSchema, eventMatches, eventTriggerChoices, eventTriggerProblems, eventTypeSchema, getSourceKey, identitySchema, isPluginModelCostEventName, isSlackDestination, locationSchema, markdownPlainText, normalizeEventIdentifier, normalizeEventMatch, objectFactFields, objectIconPath, objectLinkFilterMatches, objectLinkFilterSchema, objectLinkFilterSpecificity, objectPresentation, objectSubjectSchema, objectTypeSchema, pluginApiRouteRequestContextSchema, pluginEventsSchema, pluginModelCostEventNames, pluginTaskStartInputSchema, pluginToolOutputSchema, promptContextSchema, promptMessageSchema, renderInlineTag, renderTag, replyAttributionSchema, sourceSchema, stableEventMatchKey, taskOutcomeSchema, userSchema, withToolContext } from "@sentry/junior-plugin-api";
|
|
14
|
+
import { CACHE_LOAD_TIMEOUT_MS, MAX_CONVERSATION_CHANGES, PluginInboxItemOwnerError, PluginToolInputError, actorSchema, agentEventMatchSchema, anyResourceMatchFields, codeChangeFilterSchema, codeChangeInputSchema, codeRepositoryInputSchema, conversationAnnotationInputSchema, conversationEventPresentationSchema, createEventSource, createSlackSource, createWebSource, defineConversationEvent, defineJuniorPlugin, definePluginTool, definePromptContext, describeEventTrigger, destinationSchema, destinationVisibilitySchema, escapeTagText, eventDataSchema, eventInputSchema, eventMatchFieldsSchema, eventMatchSchema, eventMatches, eventTriggerChoices, eventTriggerProblems, eventTypeSchema, getSourceKey, identitySchema, isPluginModelCostEventName, isSlackDestination, locationSchema, markdownNodes, markdownPlainText, normalizeEventIdentifier, normalizeEventMatch, objectFactFields, objectIconPath, objectLinkFilterMatches, objectLinkFilterSchema, objectLinkFilterSpecificity, objectPresentation, objectSubjectSchema, objectTypeSchema, parseMarkdown, pluginApiRouteRequestContextSchema, pluginEventsSchema, pluginModelCostEventNames, pluginTaskStartInputSchema, pluginToolOutputSchema, promptContextSchema, promptMessageSchema, renderInlineTag, renderTag, replyAttributionSchema, sourceSchema, stableEventMatchKey, taskOutcomeSchema, untilAborted, userSchema, withToolContext } from "@sentry/junior-plugin-api";
|
|
14
15
|
import { readFileSync, readdirSync, statSync } from "node:fs";
|
|
15
16
|
import { isDeepStrictEqual } from "node:util";
|
|
16
17
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
18
|
+
import * as Sentry from "@sentry/node";
|
|
17
19
|
import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
18
20
|
import { parse } from "yaml";
|
|
19
21
|
import { UnauthorizedError, auth } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
@@ -1031,8 +1033,9 @@ const juniorInboxItems = pgTable("junior_inbox_items", {
|
|
|
1031
1033
|
status: text$1("status").$type().notNull(),
|
|
1032
1034
|
/**
|
|
1033
1035
|
* A `question` item's question holds its title, body, request, and
|
|
1034
|
-
* answer (`junior_questions`). The item keeps a copy
|
|
1035
|
-
* before this one, and new code
|
|
1036
|
+
* answer (`junior_questions`). The item keeps a copy of the title,
|
|
1037
|
+
* body, and request for the release before this one, and new code
|
|
1038
|
+
* never reads it.
|
|
1036
1039
|
*/
|
|
1037
1040
|
title: text$1("title"),
|
|
1038
1041
|
body: text$1("body"),
|
|
@@ -1049,6 +1052,11 @@ const juniorInboxItems = pgTable("junior_inbox_items", {
|
|
|
1049
1052
|
closedAt: timestamptz("closed_at"),
|
|
1050
1053
|
closedByUserId: text$1("closed_by_user_id").references(() => juniorUsers.id, { onDelete: "set null" }),
|
|
1051
1054
|
closeReason: text$1("close_reason"),
|
|
1055
|
+
/**
|
|
1056
|
+
* The id of the subject kind's action that a person ran to close it,
|
|
1057
|
+
* such as `resume` (`PluginInboxSubjectKind.actions`).
|
|
1058
|
+
*/
|
|
1059
|
+
closeAction: text$1("close_action"),
|
|
1052
1060
|
createdAt: timestamptz("created_at").notNull(),
|
|
1053
1061
|
updatedAt: timestamptz("updated_at").notNull()
|
|
1054
1062
|
}, (table) => [
|
|
@@ -1309,9 +1317,10 @@ function questionFuzzyTitle(table) {
|
|
|
1309
1317
|
}
|
|
1310
1318
|
/**
|
|
1311
1319
|
* One question or notice that an agent gave a person in a Conversation. It
|
|
1312
|
-
* belongs to that Conversation
|
|
1313
|
-
*
|
|
1314
|
-
* the subject `{ kind: "question", id }` and
|
|
1320
|
+
* belongs to that Conversation and holds its title, body, request (the form
|
|
1321
|
+
* and the related links), and its answer, who gave it, and when. Its Inbox
|
|
1322
|
+
* item has the subject `{ kind: "question", id }` and keeps only its own
|
|
1323
|
+
* open, done, or dismissed state.
|
|
1315
1324
|
*/
|
|
1316
1325
|
const juniorQuestions = pgTable("junior_questions", {
|
|
1317
1326
|
id: text$1("id").primaryKey(),
|
|
@@ -1322,6 +1331,8 @@ const juniorQuestions = pgTable("junior_questions", {
|
|
|
1322
1331
|
body: text$1("body").notNull(),
|
|
1323
1332
|
request: jsonb("request").$type(),
|
|
1324
1333
|
answer: jsonb("answer").$type(),
|
|
1334
|
+
answeredByUserId: text$1("answered_by_user_id").references(() => juniorUsers.id, { onDelete: "set null" }),
|
|
1335
|
+
answeredAt: timestamptz("answered_at"),
|
|
1325
1336
|
createdAt: timestamptz("created_at").notNull(),
|
|
1326
1337
|
updatedAt: timestamptz("updated_at").notNull()
|
|
1327
1338
|
}, (table) => [
|
|
@@ -4655,7 +4666,7 @@ async function mintAzure(azure) {
|
|
|
4655
4666
|
* the failing step and HTTP status. Each mint records one span.
|
|
4656
4667
|
*/
|
|
4657
4668
|
async function mintWorkloadIdentityToken(provider, credentials) {
|
|
4658
|
-
return await withSpan("credential.workload_identity.mint", "credential.workload_identity.mint", {}, async (setSpanAttributes) => {
|
|
4669
|
+
return await withSpan$1("credential.workload_identity.mint", "credential.workload_identity.mint", {}, async (setSpanAttributes) => {
|
|
4659
4670
|
try {
|
|
4660
4671
|
const minted = credentials.gcp ? await mintGcp(credentials.gcp) : await mintAzure(credentials.azure);
|
|
4661
4672
|
setSpanAttributes({ "app.workload_identity.outcome": "completed" });
|
|
@@ -5950,7 +5961,8 @@ function cacheKeyPrefix(namespace) {
|
|
|
5950
5961
|
* Create a cache in the state adapter under `junior:cache:{namespace}:`.
|
|
5951
5962
|
* Entries are wrapped, so `null` and `false` values are cache hits. A stale
|
|
5952
5963
|
* `staleIfError` entry is returned when its reload throws, unless the caller
|
|
5953
|
-
* asked for `refresh
|
|
5964
|
+
* asked for `refresh`, or to a `stale` get. `onStale` then gets the time
|
|
5965
|
+
* that it was stored.
|
|
5954
5966
|
*/
|
|
5955
5967
|
function createCache(state, namespace, hooks = {}) {
|
|
5956
5968
|
const stateKey = (key) => {
|
|
@@ -5959,15 +5971,23 @@ function createCache(state, namespace, hooks = {}) {
|
|
|
5959
5971
|
return `${cacheKeyPrefix(namespace)}${key}`;
|
|
5960
5972
|
};
|
|
5961
5973
|
return {
|
|
5962
|
-
async get(key) {
|
|
5974
|
+
async get(key, options) {
|
|
5963
5975
|
const cacheKey = stateKey(key);
|
|
5964
5976
|
await state.connect();
|
|
5965
5977
|
const hit = await state.get(cacheKey);
|
|
5966
|
-
|
|
5978
|
+
if (!hit) return void 0;
|
|
5979
|
+
if (isFresh(hit)) return hit.value;
|
|
5980
|
+
if (!options?.stale) return void 0;
|
|
5981
|
+
if (hit.storedAtMs !== void 0) hooks.onStale?.(hit.storedAtMs);
|
|
5982
|
+
return hit.value;
|
|
5967
5983
|
},
|
|
5968
5984
|
async getOrLoad(key, load, options) {
|
|
5969
5985
|
const cacheKey = stateKey(key);
|
|
5970
5986
|
const cached = async () => options?.refresh ? void 0 : await state.get(cacheKey) ?? void 0;
|
|
5987
|
+
const stale = (entry) => {
|
|
5988
|
+
if (entry.storedAtMs !== void 0) hooks.onStale?.(entry.storedAtMs);
|
|
5989
|
+
return entry.value;
|
|
5990
|
+
};
|
|
5971
5991
|
await state.connect();
|
|
5972
5992
|
const hit = await cached();
|
|
5973
5993
|
if (hit && isFresh(hit)) return hit.value;
|
|
@@ -5991,11 +6011,10 @@ function createCache(state, namespace, hooks = {}) {
|
|
|
5991
6011
|
waitMs: LOAD_WAIT_MS
|
|
5992
6012
|
});
|
|
5993
6013
|
if (attempt.acquired) return attempt.value;
|
|
5994
|
-
return (await load()).value;
|
|
6014
|
+
return hit ? stale(hit) : (await load()).value;
|
|
5995
6015
|
} catch (error) {
|
|
5996
6016
|
if (!hit) throw error;
|
|
5997
|
-
|
|
5998
|
-
return hit.value;
|
|
6017
|
+
return stale(hit);
|
|
5999
6018
|
}
|
|
6000
6019
|
},
|
|
6001
6020
|
async update(key, next) {
|
|
@@ -6073,7 +6092,7 @@ async function readServedProviders(state, modelId) {
|
|
|
6073
6092
|
}));
|
|
6074
6093
|
}
|
|
6075
6094
|
async function gatewayOnlyForModel(modelId) {
|
|
6076
|
-
const { getStateAdapter } = await import("./adapter-
|
|
6095
|
+
const { getStateAdapter } = await import("./adapter-CKtEUuWD.js").then((n) => n.t);
|
|
6077
6096
|
const state = getStateAdapter();
|
|
6078
6097
|
const enabled = await readLocal(localEnabledProviders, "enabled", () => readEnabledProviders(state));
|
|
6079
6098
|
if (enabled === null) return void 0;
|
|
@@ -6185,7 +6204,7 @@ async function completeText$1(params) {
|
|
|
6185
6204
|
"gen_ai.input.messages": recordContent ? serializeGenAiAttribute(params.messages.map(toCanonicalInputMessage)) : void 0,
|
|
6186
6205
|
"gen_ai.provider.auth_mode": authMode
|
|
6187
6206
|
};
|
|
6188
|
-
return withSpan(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
|
|
6207
|
+
return withSpan$1(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
|
|
6189
6208
|
let message;
|
|
6190
6209
|
try {
|
|
6191
6210
|
message = await completeSimple(model, {
|
|
@@ -6295,7 +6314,7 @@ async function completeObject$1(params) {
|
|
|
6295
6314
|
const provider = createGatewayProvider({ apiKey: credential.token });
|
|
6296
6315
|
let result;
|
|
6297
6316
|
try {
|
|
6298
|
-
result = await withSpan(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
|
|
6317
|
+
result = await withSpan$1(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
|
|
6299
6318
|
const result = await generateObject({
|
|
6300
6319
|
model: provider.chat(params.modelId),
|
|
6301
6320
|
schema: params.schema,
|
|
@@ -6337,7 +6356,7 @@ async function completeDecision$1(params) {
|
|
|
6337
6356
|
const credential = await resolveGatewayCredential();
|
|
6338
6357
|
const provider = createGatewayProvider({ apiKey: credential.token });
|
|
6339
6358
|
try {
|
|
6340
|
-
const result = await withSpan(`${GEN_AI_OPERATION_DECIDE} ${params.modelId}`, "gen_ai.decide", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
|
|
6359
|
+
const result = await withSpan$1(`${GEN_AI_OPERATION_DECIDE} ${params.modelId}`, "gen_ai.decide", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
|
|
6341
6360
|
const result = await experimental_decide({
|
|
6342
6361
|
model: provider.decisionModel(params.modelId),
|
|
6343
6362
|
state: params.state,
|
|
@@ -6385,7 +6404,7 @@ async function embedTexts$1(params) {
|
|
|
6385
6404
|
const provider = createGatewayProvider({ apiKey: credential.token });
|
|
6386
6405
|
const providerOptions = embeddingProviderOptions(params.modelId, params.inputType);
|
|
6387
6406
|
try {
|
|
6388
|
-
const result = await withSpan(`${GEN_AI_OPERATION_EMBEDDINGS} ${params.modelId}`, "gen_ai.embeddings", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
|
|
6407
|
+
const result = await withSpan$1(`${GEN_AI_OPERATION_EMBEDDINGS} ${params.modelId}`, "gen_ai.embeddings", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
|
|
6389
6408
|
const result = await embedMany({
|
|
6390
6409
|
model: provider.embeddingModel(params.modelId),
|
|
6391
6410
|
values: texts,
|
|
@@ -6451,7 +6470,7 @@ async function rerankTexts(params) {
|
|
|
6451
6470
|
const credential = await resolveGatewayCredential();
|
|
6452
6471
|
const provider = createGatewayProvider({ apiKey: credential.token });
|
|
6453
6472
|
try {
|
|
6454
|
-
return await withSpan(`${GEN_AI_OPERATION_RERANK} ${params.modelId}`, "gen_ai.rerank", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
|
|
6473
|
+
return await withSpan$1(`${GEN_AI_OPERATION_RERANK} ${params.modelId}`, "gen_ai.rerank", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
|
|
6455
6474
|
const result = await rerank({
|
|
6456
6475
|
model: provider.rerankingModel(params.modelId),
|
|
6457
6476
|
query,
|
|
@@ -6493,7 +6512,7 @@ const WEB_SEARCH_TOOL_NAME = "parallelSearch";
|
|
|
6493
6512
|
async function searchWeb$1(params) {
|
|
6494
6513
|
const credential = await resolveGatewayCredential();
|
|
6495
6514
|
const provider = createGatewayProvider({ apiKey: credential.token });
|
|
6496
|
-
return await withSpan(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", {}, async (setSpanAttributes) => {
|
|
6515
|
+
return await withSpan$1(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", {}, async (setSpanAttributes) => {
|
|
6497
6516
|
const response = await generateText({
|
|
6498
6517
|
model: provider.chat(params.modelId),
|
|
6499
6518
|
prompt: params.query,
|
|
@@ -6632,7 +6651,7 @@ async function transcribeFromUrl$1(params) {
|
|
|
6632
6651
|
const credential = await resolveGatewayCredential();
|
|
6633
6652
|
const provider = createGatewayProvider({ apiKey: credential.token });
|
|
6634
6653
|
try {
|
|
6635
|
-
return await withSpan(`${GEN_AI_OPERATION_TRANSCRIPTION} ${params.modelId}`, "gen_ai.transcription", {
|
|
6654
|
+
return await withSpan$1(`${GEN_AI_OPERATION_TRANSCRIPTION} ${params.modelId}`, "gen_ai.transcription", {
|
|
6636
6655
|
modelId: params.modelId,
|
|
6637
6656
|
...params.conversationId ? { conversationId: params.conversationId } : void 0
|
|
6638
6657
|
}, async (setSpanAttributes) => {
|
|
@@ -7139,7 +7158,7 @@ async function embedConversationEvents(db, embedder, conversationId, limits = {}
|
|
|
7139
7158
|
*/
|
|
7140
7159
|
async function indexConversationEvents(args) {
|
|
7141
7160
|
const { conversationId, turnId } = args;
|
|
7142
|
-
await withSpan("event_search.index", "event_search.index", { conversationId }, async (setSpanAttributes) => {
|
|
7161
|
+
await withSpan$1("event_search.index", "event_search.index", { conversationId }, async (setSpanAttributes) => {
|
|
7143
7162
|
const waitStartedAtMs = Date.now();
|
|
7144
7163
|
const attempt = await withLock(getStateAdapter(), eventIndexLockKey(conversationId), async () => {
|
|
7145
7164
|
setSpanAttributes({ "app.event_search.index.lock.wait_ms": Date.now() - waitStartedAtMs });
|
|
@@ -7505,7 +7524,7 @@ const LEAD_TOOLS = [
|
|
|
7505
7524
|
"searchConversationEvents",
|
|
7506
7525
|
"readConversationEvent",
|
|
7507
7526
|
"searchInboxItems",
|
|
7508
|
-
"
|
|
7527
|
+
"askUserQuestion",
|
|
7509
7528
|
"updateInboxItem",
|
|
7510
7529
|
"searchEventTypes",
|
|
7511
7530
|
"watchEvents",
|
|
@@ -7609,6 +7628,13 @@ function copiesRootVisibility(conversation) {
|
|
|
7609
7628
|
function remindsNoReplyForChildStatus(kind) {
|
|
7610
7629
|
return kind === "lead";
|
|
7611
7630
|
}
|
|
7631
|
+
/**
|
|
7632
|
+
* Return whether a feed row of this kind shows its child Threads. A Lead
|
|
7633
|
+
* shows as its Space, whose page lists them.
|
|
7634
|
+
*/
|
|
7635
|
+
function feedRowShowsThreads(kind) {
|
|
7636
|
+
return kind !== "lead";
|
|
7637
|
+
}
|
|
7612
7638
|
/** Return whether a Conversation of this kind stores its Space: a Lead. */
|
|
7613
7639
|
function storesSpace(kind) {
|
|
7614
7640
|
return kind === "lead";
|
|
@@ -11829,6 +11855,18 @@ async function lockUserSnoozes(tx, userId) {
|
|
|
11829
11855
|
const lockKey = `junior:inbox-snooze:${userId}`;
|
|
11830
11856
|
await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${lockKey}))`);
|
|
11831
11857
|
}
|
|
11858
|
+
/**
|
|
11859
|
+
* A new snooze timer id. It ends with the wake time, so a snooze can say
|
|
11860
|
+
* when it wakes without a read of the timer index.
|
|
11861
|
+
*/
|
|
11862
|
+
function snoozeTimerId(wakeAtMs) {
|
|
11863
|
+
return `inbox-snooze:${randomUUID()}:${wakeAtMs}`;
|
|
11864
|
+
}
|
|
11865
|
+
/** The wake time in a snooze timer id. Older ids have none. */
|
|
11866
|
+
function snoozeTimerWakeAtMs(timerId) {
|
|
11867
|
+
const time = /^inbox-snooze:[^:]+:(\d+)$/.exec(timerId)?.[1];
|
|
11868
|
+
return time === void 0 ? void 0 : Number(time);
|
|
11869
|
+
}
|
|
11832
11870
|
/** The trigger of a snooze timer: its `timer.fired` Event wakes the item. */
|
|
11833
11871
|
function snoozeTimerTrigger(timerId) {
|
|
11834
11872
|
return {
|
|
@@ -11921,25 +11959,38 @@ async function clearInboxWakeReasons(db, input) {
|
|
|
11921
11959
|
await db.update(juniorInboxSnoozes).set({ wakeReason: null }).where(and(eq(juniorInboxSnoozes.userId, input.userId), inArray(juniorInboxSnoozes.inboxItemId, [...input.inboxItemIds]), isNotNull(juniorInboxSnoozes.wakeReason)));
|
|
11922
11960
|
}
|
|
11923
11961
|
/**
|
|
11924
|
-
* Read this User's snoozes of these items:
|
|
11925
|
-
*
|
|
11926
|
-
*
|
|
11927
|
-
*
|
|
11962
|
+
* Read this User's snoozes of these items: each snooze that has not woken,
|
|
11963
|
+
* with its triggers, and why each woken snooze woke. An item whose snooze
|
|
11964
|
+
* the User woke, or whose reason they cleared, has no reason. A new snooze
|
|
11965
|
+
* clears the last reason, so an item has at most one of either.
|
|
11928
11966
|
*/
|
|
11929
11967
|
async function readViewerInboxSnoozes(db, input) {
|
|
11930
|
-
const snoozed = /* @__PURE__ */ new
|
|
11968
|
+
const snoozed = /* @__PURE__ */ new Map();
|
|
11931
11969
|
const wakeReasons = /* @__PURE__ */ new Map();
|
|
11932
11970
|
if (input.inboxItemIds.length === 0) return {
|
|
11933
11971
|
snoozed,
|
|
11934
11972
|
wakeReasons
|
|
11935
11973
|
};
|
|
11936
11974
|
const rows = await db.select({
|
|
11975
|
+
createdAt: juniorInboxSnoozes.createdAt,
|
|
11937
11976
|
inboxItemId: juniorInboxSnoozes.inboxItemId,
|
|
11938
11977
|
state: juniorInboxSnoozes.state,
|
|
11978
|
+
trigger: {
|
|
11979
|
+
eventType: juniorInboxSnoozeTriggers.eventType,
|
|
11980
|
+
identifier: juniorInboxSnoozeTriggers.identifier,
|
|
11981
|
+
namespace: juniorInboxSnoozeTriggers.namespace,
|
|
11982
|
+
outcome: juniorInboxSnoozeTriggers.outcome
|
|
11983
|
+
},
|
|
11939
11984
|
wakeReason: juniorInboxSnoozes.wakeReason
|
|
11940
|
-
}).from(juniorInboxSnoozes).where(and(eq(juniorInboxSnoozes.userId, input.userId), inArray(juniorInboxSnoozes.inboxItemId, [...input.inboxItemIds]), or(eq(juniorInboxSnoozes.state, "snoozed"), and(eq(juniorInboxSnoozes.state, "woken"), isNotNull(juniorInboxSnoozes.wakeReason)))));
|
|
11941
|
-
for (const row of rows) if (row.state === "snoozed")
|
|
11942
|
-
|
|
11985
|
+
}).from(juniorInboxSnoozes).leftJoin(juniorInboxSnoozeTriggers, and(eq(juniorInboxSnoozeTriggers.snoozeId, juniorInboxSnoozes.id), eq(juniorInboxSnoozes.state, "snoozed"))).where(and(eq(juniorInboxSnoozes.userId, input.userId), inArray(juniorInboxSnoozes.inboxItemId, [...input.inboxItemIds]), or(eq(juniorInboxSnoozes.state, "snoozed"), and(eq(juniorInboxSnoozes.state, "woken"), isNotNull(juniorInboxSnoozes.wakeReason)))));
|
|
11986
|
+
for (const row of rows) if (row.state === "snoozed") {
|
|
11987
|
+
const snooze = snoozed.get(row.inboxItemId) ?? {
|
|
11988
|
+
createdAt: row.createdAt,
|
|
11989
|
+
triggers: []
|
|
11990
|
+
};
|
|
11991
|
+
if (row.trigger) snooze.triggers.push(row.trigger);
|
|
11992
|
+
snoozed.set(row.inboxItemId, snooze);
|
|
11993
|
+
} else if (row.wakeReason) wakeReasons.set(row.inboxItemId, row.wakeReason);
|
|
11943
11994
|
return {
|
|
11944
11995
|
snoozed,
|
|
11945
11996
|
wakeReasons
|
|
@@ -12132,6 +12183,17 @@ function subjectKindDismissNote(kind, plugins, object, viewer) {
|
|
|
12132
12183
|
return registered?.dismissNote?.(object, reader);
|
|
12133
12184
|
}
|
|
12134
12185
|
/**
|
|
12186
|
+
* Return the actions that a plugin kind puts on its open items, such as
|
|
12187
|
+
* Resume. Core kinds have none here: a To-do closes with Mark done.
|
|
12188
|
+
*/
|
|
12189
|
+
function subjectKindActions(kind, plugins) {
|
|
12190
|
+
return registeredSubjectKind(kind, plugins, void 0).registered?.actions ?? [];
|
|
12191
|
+
}
|
|
12192
|
+
/** Return the label of a kind action by its id, such as Resume. */
|
|
12193
|
+
function subjectKindActionLabel(kind, plugins, id) {
|
|
12194
|
+
return subjectKindActions(kind, plugins).find((action) => action.id === id)?.label;
|
|
12195
|
+
}
|
|
12196
|
+
/**
|
|
12135
12197
|
* Return the To-do of an item's subject, or undefined for another kind. A
|
|
12136
12198
|
* Conversation id can hold colons, so the To-do id is after the last one.
|
|
12137
12199
|
*/
|
|
@@ -12161,7 +12223,6 @@ const inboxItemTitle = sql`coalesce(${juniorQuestions.title}, ${juniorInboxItems
|
|
|
12161
12223
|
const inboxItemBody = sql`coalesce(${juniorQuestions.body}, ${juniorInboxItems.body}, '')`;
|
|
12162
12224
|
/** SQL: the request of an item, from its question when it has one. */
|
|
12163
12225
|
const inboxItemRequest = sql`coalesce(${juniorQuestions.request}, ${juniorInboxItems.request})`;
|
|
12164
|
-
sql`coalesce(${juniorQuestions.answer}, ${juniorInboxItems.answer})`;
|
|
12165
12226
|
// src/chat/inbox-items/store.ts
|
|
12166
12227
|
/**
|
|
12167
12228
|
* Close reason of an action item that a person answered with a reply in
|
|
@@ -12242,11 +12303,17 @@ async function hydrate(db, itemRows) {
|
|
|
12242
12303
|
const rows = owned.map((row) => row.item);
|
|
12243
12304
|
const ids = rows.map((row) => row.id);
|
|
12244
12305
|
const [assigneeRows, conversationRows] = await Promise.all([db.select().from(juniorInboxItemAssignees).where(inArray(juniorInboxItemAssignees.itemId, ids)), db.select().from(juniorInboxItemConversations).where(inArray(juniorInboxItemConversations.itemId, ids))]);
|
|
12245
|
-
const users = await readUsers(db, [
|
|
12306
|
+
const users = await readUsers(db, [
|
|
12307
|
+
...assigneeRows.map((row) => row.userId),
|
|
12308
|
+
...rows.flatMap((row) => row.closedByUserId ? [row.closedByUserId] : []),
|
|
12309
|
+
...owned.flatMap(({ question }) => question?.answeredByUserId ? [question.answeredByUserId] : [])
|
|
12310
|
+
]);
|
|
12246
12311
|
return rows.map((row, index) => {
|
|
12247
12312
|
const { addedByAutomationId, owner, question } = owned[index];
|
|
12248
12313
|
const content = question ?? row;
|
|
12249
12314
|
const closedBy = row.closedByUserId ? users.get(row.closedByUserId) : void 0;
|
|
12315
|
+
const answeredByUserId = question ? question.answeredByUserId : content.answer && row.closedByUserId;
|
|
12316
|
+
const answeredBy = answeredByUserId ? users.get(answeredByUserId) : void 0;
|
|
12250
12317
|
return {
|
|
12251
12318
|
assignedToEveryone: row.assignedToEveryone,
|
|
12252
12319
|
assignees: assigneeRows.filter((assignee) => assignee.itemId === row.id).flatMap((assignee) => users.get(assignee.userId) ?? []).sort((a, b) => a.email.localeCompare(b.email)),
|
|
@@ -12268,8 +12335,10 @@ async function hydrate(db, itemRows) {
|
|
|
12268
12335
|
updatedAt: row.updatedAt,
|
|
12269
12336
|
visibility: owner.visibility,
|
|
12270
12337
|
...content.answer ? { answer: content.answer } : void 0,
|
|
12338
|
+
...answeredBy ? { answeredBy } : void 0,
|
|
12271
12339
|
...row.addedByTurnId ? { addedByTurnId: row.addedByTurnId } : void 0,
|
|
12272
12340
|
...addedByAutomationId ? { addedByAutomationId } : void 0,
|
|
12341
|
+
...row.closeAction ? { closeAction: row.closeAction } : void 0,
|
|
12273
12342
|
...row.closeReason ? { closeReason: row.closeReason } : void 0,
|
|
12274
12343
|
...row.closedAt ? { closedAt: row.closedAt } : void 0,
|
|
12275
12344
|
...closedBy ? { closedBy } : void 0,
|
|
@@ -12340,7 +12409,14 @@ async function listReplyActionItems(db, conversationId) {
|
|
|
12340
12409
|
* names at most one open item.
|
|
12341
12410
|
*/
|
|
12342
12411
|
async function getOpenInboxItemBySubject(db, subject) {
|
|
12343
|
-
return (await hydrate(db, await selectItemRows(db).where(and(
|
|
12412
|
+
return (await hydrate(db, await selectItemRows(db).where(and(subjectIs(subject), eq(juniorInboxItems.status, "open")))))[0];
|
|
12413
|
+
}
|
|
12414
|
+
/** Read every Inbox item of one subject, open and closed, newest first. */
|
|
12415
|
+
async function listInboxItemsBySubject(db, subject) {
|
|
12416
|
+
return await hydrate(db, await selectItemRows(db).where(subjectIs(subject)).orderBy(desc(juniorInboxItems.createdAt), desc(juniorInboxItems.id)));
|
|
12417
|
+
}
|
|
12418
|
+
function subjectIs(subject) {
|
|
12419
|
+
return and(eq(juniorInboxItems.subjectKind, subject.kind), eq(juniorInboxItems.subjectId, subject.id));
|
|
12344
12420
|
}
|
|
12345
12421
|
/**
|
|
12346
12422
|
* Add one open Inbox item. Return undefined when another open item already
|
|
@@ -12418,7 +12494,8 @@ async function closeInboxItem(db, input) {
|
|
|
12418
12494
|
const now = new Date(input.nowMs);
|
|
12419
12495
|
if ((await db.transaction(async (tx) => {
|
|
12420
12496
|
const closed = await tx.update(juniorInboxItems).set({
|
|
12421
|
-
answer: input.answer
|
|
12497
|
+
answer: input.answer ? sql`case when ${juniorInboxItems.subjectKind} = ${INBOX_SUBJECT_KINDS.question} then null else ${JSON.stringify(input.answer)}::jsonb end` : null,
|
|
12498
|
+
closeAction: input.action ?? null,
|
|
12422
12499
|
closeReason: input.reason ?? null,
|
|
12423
12500
|
closedAt: now,
|
|
12424
12501
|
closedByUserId: input.closedByUserId ?? null,
|
|
@@ -12432,6 +12509,8 @@ async function closeInboxItem(db, input) {
|
|
|
12432
12509
|
const item = closed[0];
|
|
12433
12510
|
if (input.answer && item?.subjectKind === INBOX_SUBJECT_KINDS.question) await tx.update(juniorQuestions).set({
|
|
12434
12511
|
answer: input.answer,
|
|
12512
|
+
answeredAt: now,
|
|
12513
|
+
answeredByUserId: input.closedByUserId ?? null,
|
|
12435
12514
|
updatedAt: now
|
|
12436
12515
|
}).where(eq(juniorQuestions.id, item.subjectId));
|
|
12437
12516
|
await touchConversationDetail(tx, ownerConversationIds(closed));
|
|
@@ -12490,7 +12569,7 @@ async function takeInboxItem(db, input) {
|
|
|
12490
12569
|
});
|
|
12491
12570
|
}
|
|
12492
12571
|
function searchConditions(reader, filters) {
|
|
12493
|
-
const conditions = [inboxItemVisibleTo(reader), inArray(juniorInboxItems.status, [...filters.statuses])];
|
|
12572
|
+
const conditions = [inboxItemVisibleTo(reader, filters.statuses), inArray(juniorInboxItems.status, [...filters.statuses])];
|
|
12494
12573
|
if (filters.after) conditions.push(or(gt(juniorInboxItems.createdAt, filters.after.createdAt), and(eq(juniorInboxItems.createdAt, filters.after.createdAt), gt(juniorInboxItems.id, filters.after.id))));
|
|
12495
12574
|
if (filters.afterWaiting) {
|
|
12496
12575
|
if (typeof filters.order !== "object") throw new Error("afterWaiting needs the waiting-first order");
|
|
@@ -12503,9 +12582,9 @@ function searchConditions(reader, filters) {
|
|
|
12503
12582
|
if (filters.subjectId) conditions.push(eq(juniorInboxItems.subjectId, filters.subjectId));
|
|
12504
12583
|
if (filters.automationId) conditions.push(inboxItemAddedByAutomation(filters.automationId));
|
|
12505
12584
|
if (filters.conversationId) conditions.push(inboxItemLinkedTo(filters.conversationId));
|
|
12506
|
-
if (filters.assignee) conditions.push("everyone" in filters.assignee ? eq(juniorInboxItems.assignedToEveryone, true) : inboxItemAssignedTo(filters.assignee.userId));
|
|
12585
|
+
if (filters.assignee) conditions.push("everyone" in filters.assignee ? eq(juniorInboxItems.assignedToEveryone, true) : inboxItemAssignedTo(filters.assignee.userId, filters.statuses));
|
|
12507
12586
|
if (filters.ownerKind) conditions.push(eq(inboxItemOwnerKind(), filters.ownerKind));
|
|
12508
|
-
if (filters.forUserId) conditions.push(inboxItemForUser(filters.forUserId));
|
|
12587
|
+
if (filters.forUserId) conditions.push(inboxItemForUser(filters.forUserId, filters.statuses));
|
|
12509
12588
|
if (filters.awakeForUserId) conditions.push(not(inboxItemSnoozedBy(filters.awakeForUserId)));
|
|
12510
12589
|
if (filters.snoozedForUserId) conditions.push(inboxItemSnoozedBy(filters.snoozedForUserId));
|
|
12511
12590
|
if (filters.query) {
|
|
@@ -12647,7 +12726,7 @@ async function closeHandledReplyNotices(db, input) {
|
|
|
12647
12726
|
}
|
|
12648
12727
|
}
|
|
12649
12728
|
async function openReplyNoticeId(db, input) {
|
|
12650
|
-
const [notice] = await db.select({ id: juniorInboxItems.id }).from(juniorInboxItems).where(and(eq(juniorInboxItems.subjectKind, INBOX_SUBJECT_KINDS.reply), eq(juniorInboxItems.subjectId, input.conversationId), eq(juniorInboxItems.status, "open"), inboxItemAssignedTo(input.userId))).limit(1);
|
|
12729
|
+
const [notice] = await db.select({ id: juniorInboxItems.id }).from(juniorInboxItems).where(and(eq(juniorInboxItems.subjectKind, INBOX_SUBJECT_KINDS.reply), eq(juniorInboxItems.subjectId, input.conversationId), eq(juniorInboxItems.status, "open"), inboxItemAssignedTo(input.userId, ["open"]))).limit(1);
|
|
12651
12730
|
return notice?.id;
|
|
12652
12731
|
}
|
|
12653
12732
|
async function closeRead(db, id, input) {
|
|
@@ -12677,7 +12756,7 @@ function inboxItemNeedsUserNow(userId) {
|
|
|
12677
12756
|
async function countInboxItemsNeedingUserBySubject(db, userId) {
|
|
12678
12757
|
return await db.select({
|
|
12679
12758
|
automations: sql`count(*) filter (where ${eq(juniorInboxItems.subjectKind, INBOX_SUBJECT_KINDS.automation)})`.mapWith(Number),
|
|
12680
|
-
decisions: sql`count(*) filter (where ${inboxItemRequest} -> '
|
|
12759
|
+
decisions: sql`count(*) filter (where ${inboxItemRequest} -> 'fields' is not null)`.mapWith(Number),
|
|
12681
12760
|
subjectId: juniorInboxItems.subjectId,
|
|
12682
12761
|
subjectKind: juniorInboxItems.subjectKind,
|
|
12683
12762
|
todos: sql`count(*) filter (where ${eq(juniorInboxItems.subjectKind, INBOX_SUBJECT_KINDS.todo)})`.mapWith(Number),
|
|
@@ -12928,7 +13007,7 @@ async function readCachedLinkedHandle(lookup, load) {
|
|
|
12928
13007
|
lookup.query
|
|
12929
13008
|
])).digest("hex");
|
|
12930
13009
|
return await cache().getOrLoad(`linked-handle:${lookup.provider}:${version.token}:${lookupHash}`, async () => {
|
|
12931
|
-
const value = await load();
|
|
13010
|
+
const value = await untilAborted(load(), AbortSignal.timeout(CACHE_LOAD_TIMEOUT_MS));
|
|
12932
13011
|
return value.status === "found" && settled ? {
|
|
12933
13012
|
value,
|
|
12934
13013
|
ttlMs: LINKED_HANDLE_TTL_MS,
|
|
@@ -13655,9 +13734,9 @@ async function withSlackRetries(task, maxAttempts = 3, context = {}) {
|
|
|
13655
13734
|
attempt += 1;
|
|
13656
13735
|
const attemptNumber = attempt;
|
|
13657
13736
|
try {
|
|
13658
|
-
return await withSpan(`POST slack.com/api/${action}`, "http.client", {}, async () => {
|
|
13737
|
+
return await withSpan$1(`POST slack.com/api/${action}`, "http.client", {}, async () => {
|
|
13659
13738
|
try {
|
|
13660
|
-
return await task();
|
|
13739
|
+
return await untilAborted(task(), context.signal);
|
|
13661
13740
|
} catch (error) {
|
|
13662
13741
|
const mapped = mapSlackError(error);
|
|
13663
13742
|
const errorAttrs = { "error.type": mapped.code };
|
|
@@ -13696,7 +13775,7 @@ async function withSlackRetries(task, maxAttempts = 3, context = {}) {
|
|
|
13696
13775
|
...mapped.statusCode !== void 0 ? { "http.response.status_code": mapped.statusCode } : void 0,
|
|
13697
13776
|
...context.attributes ?? {}
|
|
13698
13777
|
};
|
|
13699
|
-
if (!isRetryable || attempt >= maxAttempts || remainingDelayBudgetMs <= 0) {
|
|
13778
|
+
if (!isRetryable || attempt >= maxAttempts || remainingDelayBudgetMs <= 0 || context.signal?.aborted) {
|
|
13700
13779
|
if (context.expectedErrorCodes?.includes(mapped.code)) throw mapped;
|
|
13701
13780
|
logWarn("slack.action.failed", {
|
|
13702
13781
|
...baseLogAttributes,
|
|
@@ -13713,7 +13792,9 @@ async function withSlackRetries(task, maxAttempts = 3, context = {}) {
|
|
|
13713
13792
|
const backoffMs = Math.min(2e3, 250 * 2 ** (attempt - 1));
|
|
13714
13793
|
const delayMs = Math.min(retryAfterMs ?? backoffMs, MAX_RETRY_DELAY_MS, remainingDelayBudgetMs);
|
|
13715
13794
|
totalDelayMs += delayMs;
|
|
13716
|
-
await sleep$2(delayMs)
|
|
13795
|
+
await sleep$2(delayMs, context.signal).catch(() => {
|
|
13796
|
+
throw mapped;
|
|
13797
|
+
});
|
|
13717
13798
|
}
|
|
13718
13799
|
}
|
|
13719
13800
|
throw new SlackActionError("Slack action exhausted retries", "internal_error");
|
|
@@ -13821,12 +13902,13 @@ const dndInfoSchema = z.object({
|
|
|
13821
13902
|
* at `nowMs`, from `dnd.info`. Return undefined when Slack cannot answer,
|
|
13822
13903
|
* such as before the install grants `dnd:read`.
|
|
13823
13904
|
*/
|
|
13824
|
-
async function isSlackDndActive(userId, nowMs) {
|
|
13905
|
+
async function isSlackDndActive(userId, nowMs, signal) {
|
|
13825
13906
|
let response;
|
|
13826
13907
|
try {
|
|
13827
13908
|
response = await withSlackRetries(() => getSlackClient().dnd.info({ user: userId }), 3, {
|
|
13828
13909
|
action: "dnd.info",
|
|
13829
|
-
idempotent: true
|
|
13910
|
+
idempotent: true,
|
|
13911
|
+
signal
|
|
13830
13912
|
});
|
|
13831
13913
|
} catch (error) {
|
|
13832
13914
|
if (error instanceof SlackActionError) return void 0;
|
|
@@ -13866,7 +13948,7 @@ async function isPausedBySlack(db, userId, nowMs) {
|
|
|
13866
13948
|
return await createCache(getStateAdapter(), "core").getOrLoad(`notifications:slack-paused:${userId}:${bucket}`, async () => {
|
|
13867
13949
|
const slack = await linkedSlackUser(db, userId);
|
|
13868
13950
|
return {
|
|
13869
|
-
value: (slack ? await isSlackDndActive(slack.userId, nowMs) : null) ?? null,
|
|
13951
|
+
value: (slack ? await isSlackDndActive(slack.userId, nowMs, AbortSignal.timeout(CACHE_LOAD_TIMEOUT_MS)) : null) ?? null,
|
|
13870
13952
|
ttlMs: SLACK_PAUSE_BUCKET_MS
|
|
13871
13953
|
};
|
|
13872
13954
|
}) ?? void 0;
|
|
@@ -14203,7 +14285,7 @@ function pushErrorType(error) {
|
|
|
14203
14285
|
*/
|
|
14204
14286
|
async function sendToDevice(subscription, body, config) {
|
|
14205
14287
|
const serverAddress = new URL(subscription.endpoint).hostname;
|
|
14206
|
-
return await withSpan("notification.push.send", "notification.push.send", {}, async (setSpanAttributes) => {
|
|
14288
|
+
return await withSpan$1("notification.push.send", "notification.push.send", {}, async (setSpanAttributes) => {
|
|
14207
14289
|
let outcome;
|
|
14208
14290
|
let statusCode;
|
|
14209
14291
|
try {
|
|
@@ -14508,7 +14590,7 @@ async function writeConversationMetadata(db, input) {
|
|
|
14508
14590
|
* imports search and the tools that save Annotations, so they load lazily.
|
|
14509
14591
|
*/
|
|
14510
14592
|
async function loadAnnotationLabeler() {
|
|
14511
|
-
const [{ annotationLabel }, { readObjectLinkTypes }] = await Promise.all([import("./agent-
|
|
14593
|
+
const [{ annotationLabel }, { readObjectLinkTypes }] = await Promise.all([import("./agent-OUkEw6Bv.js").then((n) => n.xt), import("./agent-OUkEw6Bv.js").then((n) => n.At)]);
|
|
14512
14594
|
const linkTypes = readObjectLinkTypes();
|
|
14513
14595
|
return (annotation) => annotationLabel(annotation, linkTypes);
|
|
14514
14596
|
}
|
|
@@ -16196,7 +16278,7 @@ async function publishAgentUpdate(conversationId, key, options) {
|
|
|
16196
16278
|
const eventKey = updateEventKey(conversationId, key);
|
|
16197
16279
|
let update;
|
|
16198
16280
|
const readUpdate = () => update ??= options.update();
|
|
16199
|
-
const delivery = () => import("./agent-update-delivery-
|
|
16281
|
+
const delivery = () => import("./agent-update-delivery-H6mnPI4q.js");
|
|
16200
16282
|
if (options.starter !== false) {
|
|
16201
16283
|
const { deliverToStarter } = await delivery();
|
|
16202
16284
|
await deliverToStarter({
|
|
@@ -17865,8 +17947,8 @@ function getConfigDefaults() {
|
|
|
17865
17947
|
function createPluginCache(plugin, onStale) {
|
|
17866
17948
|
const cache = () => createCache(getStateAdapter(), `plugin:${plugin}`, onStale ? { onStale } : void 0);
|
|
17867
17949
|
return {
|
|
17868
|
-
async get(key) {
|
|
17869
|
-
return await cache().get(key);
|
|
17950
|
+
async get(key, options) {
|
|
17951
|
+
return await cache().get(key, options);
|
|
17870
17952
|
},
|
|
17871
17953
|
async getOrLoad(key, load, options) {
|
|
17872
17954
|
return await cache().getOrLoad(key, load, options);
|
|
@@ -17985,7 +18067,7 @@ function pluginConfigValues(pluginName, configuration) {
|
|
|
17985
18067
|
}
|
|
17986
18068
|
/** Time one plugin hook call so slow plugins show up in turn traces. */
|
|
17987
18069
|
async function withPluginHookSpan(pluginName, hookName, callback) {
|
|
17988
|
-
return await withSpan(`plugin.hook ${hookName}`, "plugin.hook", {}, callback, {
|
|
18070
|
+
return await withSpan$1(`plugin.hook ${hookName}`, "plugin.hook", {}, callback, {
|
|
17989
18071
|
"app.plugin.name": pluginName,
|
|
17990
18072
|
"app.plugin.hook": hookName
|
|
17991
18073
|
});
|
|
@@ -18258,7 +18340,7 @@ function createPluginState(plugin, adapter) {
|
|
|
18258
18340
|
* returned to this plugin.
|
|
18259
18341
|
*/
|
|
18260
18342
|
async function loadPluginPromptHistory(args) {
|
|
18261
|
-
return await withSpan("plugin.prompt_history.load", "plugin.prompt_history.load", { conversationId: args.conversationId }, async (setSpanAttributes) => {
|
|
18343
|
+
return await withSpan$1("plugin.prompt_history.load", "plugin.prompt_history.load", { conversationId: args.conversationId }, async (setSpanAttributes) => {
|
|
18262
18344
|
const eventStore = getConversationEventStore();
|
|
18263
18345
|
const [replacement, contextEvents] = await Promise.all([eventStore.loadLatestEventOfTypes(args.conversationId, ["compaction", "handoff"]), eventStore.loadCurrentEventsOfType(args.conversationId, "turn_context")]);
|
|
18264
18346
|
const contexts = contextEvents.flatMap((event) => event.data.type === "turn_context" && event.data.pluginName === args.pluginName ? [{
|
|
@@ -20011,11 +20093,22 @@ function getVercelQueueClients() {
|
|
|
20011
20093
|
function visibility(consumer) {
|
|
20012
20094
|
return consumer.visibilityTimeoutSeconds === void 0 ? {} : { visibilityTimeoutSeconds: consumer.visibilityTimeoutSeconds };
|
|
20013
20095
|
}
|
|
20096
|
+
const MAX_IDEMPOTENCY_KEY_LENGTH = 256;
|
|
20097
|
+
function withBoundedIdempotencyKey(options) {
|
|
20098
|
+
const key = options?.idempotencyKey;
|
|
20099
|
+
if (!key || key.length <= MAX_IDEMPOTENCY_KEY_LENGTH) return options;
|
|
20100
|
+
const digest = createHash("sha256").update(key).digest("hex");
|
|
20101
|
+
const prefix = key.slice(0, MAX_IDEMPOTENCY_KEY_LENGTH - digest.length - 1);
|
|
20102
|
+
return {
|
|
20103
|
+
...options,
|
|
20104
|
+
idempotencyKey: `${prefix}:${digest}`
|
|
20105
|
+
};
|
|
20106
|
+
}
|
|
20014
20107
|
/** Queue provider backed by Vercel Queues. */
|
|
20015
20108
|
const vercelQueueProvider = {
|
|
20016
20109
|
messagingSystem: "vercel_queue",
|
|
20017
20110
|
send: async (topic, payload, options) => {
|
|
20018
|
-
const { messageId } = await getVercelQueueClients().send(topic, payload, options);
|
|
20111
|
+
const { messageId } = await getVercelQueueClients().send(topic, payload, withBoundedIdempotencyKey(options));
|
|
20019
20112
|
return messageId ? { messageId } : {};
|
|
20020
20113
|
},
|
|
20021
20114
|
createCallback: (consumer) => getVercelQueueClients().callbacks.handleCallback(consumer.handler, {
|
|
@@ -20168,7 +20261,7 @@ function createVercelConversationWorkQueue(options = {}) {
|
|
|
20168
20261
|
const client = options.client ?? getQueueProvider();
|
|
20169
20262
|
return { async send(message, sendOptions) {
|
|
20170
20263
|
const payload = signConversationQueueMessage(message);
|
|
20171
|
-
return await withSpan("conversation.work.publish", "queue.publish", { conversationId: message.conversationId }, async (setSpanAttributes) => {
|
|
20264
|
+
return await withSpan$1("conversation.work.publish", "queue.publish", { conversationId: message.conversationId }, async (setSpanAttributes) => {
|
|
20172
20265
|
const result = await client.send(topic, payload, {
|
|
20173
20266
|
idempotencyKey: sendOptions?.idempotencyKey,
|
|
20174
20267
|
delaySeconds: toDelaySeconds(sendOptions),
|
|
@@ -20668,19 +20761,16 @@ function sameContent(item, content) {
|
|
|
20668
20761
|
}
|
|
20669
20762
|
/** Why a plugin item closes when nobody on it has an ask now. */
|
|
20670
20763
|
const NOBODY_LEFT_REASON = "Nobody on the item has an ask now.";
|
|
20671
|
-
/**
|
|
20672
|
-
|
|
20673
|
-
|
|
20674
|
-
|
|
20675
|
-
|
|
20676
|
-
|
|
20677
|
-
|
|
20678
|
-
|
|
20679
|
-
|
|
20680
|
-
|
|
20681
|
-
options: notice.choices
|
|
20682
|
-
}]
|
|
20683
|
-
});
|
|
20764
|
+
/**
|
|
20765
|
+
* Return the kind action of a plugin item that closed with a pick of a
|
|
20766
|
+
* choice field named `choice`, as items did before kinds defined actions.
|
|
20767
|
+
* The picked label names the action by its label or, after the label
|
|
20768
|
+
* changed, by its id, as "Resume" names `resume`.
|
|
20769
|
+
*/
|
|
20770
|
+
function legacyChoiceAction(item) {
|
|
20771
|
+
const label = item.answer?.values["choice"]?.[0];
|
|
20772
|
+
if (!label) return void 0;
|
|
20773
|
+
return subjectKindActions(item.subject.kind, getPlugins()).find((action) => action.label === label || action.id === label.toLowerCase())?.id;
|
|
20684
20774
|
}
|
|
20685
20775
|
/**
|
|
20686
20776
|
* The stored subject of a plugin item: the plugin's own kind as
|
|
@@ -20751,10 +20841,9 @@ function createPluginInboxItems(args) {
|
|
|
20751
20841
|
assigneeUserIds: userIds,
|
|
20752
20842
|
body: notice.body,
|
|
20753
20843
|
conversationIds: [.../* @__PURE__ */ new Set([conversationId, ...existing?.conversationIds ?? []])],
|
|
20754
|
-
kind: notice.waitsOnAssignees ||
|
|
20844
|
+
kind: notice.waitsOnAssignees || subjectKindActions(subject.kind, getPlugins()).length > 0 ? "action" : "notice",
|
|
20755
20845
|
title: notice.title,
|
|
20756
|
-
subject
|
|
20757
|
-
...notice.choices ? { request: choicesRequest(notice) } : void 0
|
|
20846
|
+
subject
|
|
20758
20847
|
};
|
|
20759
20848
|
if (existing && askedNow.size === 0 && sameContent(existing, content)) return;
|
|
20760
20849
|
let itemId;
|
|
@@ -20795,10 +20884,24 @@ function createPluginInboxItems(args) {
|
|
|
20795
20884
|
}
|
|
20796
20885
|
return open && content.kind === "action" ? {
|
|
20797
20886
|
itemId,
|
|
20798
|
-
waitText:
|
|
20887
|
+
waitText: content.body
|
|
20799
20888
|
} : { itemId };
|
|
20800
20889
|
};
|
|
20801
20890
|
return {
|
|
20891
|
+
async history(subject) {
|
|
20892
|
+
const items = await listInboxItemsBySubject(getDb(), pluginItemSubject(args.plugin, subject));
|
|
20893
|
+
if (items[0]) requireOwner(items[0], conversationId);
|
|
20894
|
+
return items.map((item) => {
|
|
20895
|
+
const record = {
|
|
20896
|
+
id: item.id,
|
|
20897
|
+
status: item.status
|
|
20898
|
+
};
|
|
20899
|
+
const action = item.closeAction ?? legacyChoiceAction(item);
|
|
20900
|
+
if (action) record.action = action;
|
|
20901
|
+
if (item.closedAt) record.closedAtMs = item.closedAt.getTime();
|
|
20902
|
+
return record;
|
|
20903
|
+
});
|
|
20904
|
+
},
|
|
20802
20905
|
async upsert(notice) {
|
|
20803
20906
|
const subject = pluginItemSubject(args.plugin, notice.subject);
|
|
20804
20907
|
if (!subjectKindLabel(subject.kind, getPlugins())) throw new Error(`Plugin "${args.plugin}" has no inbox subject kind "${notice.subject.kind}"`);
|
|
@@ -21271,7 +21374,7 @@ function pluginTaskCallback(options) {
|
|
|
21271
21374
|
onRejected: logPluginTaskQueueMessageRejected,
|
|
21272
21375
|
retryDelaySeconds: pluginTaskRetryDelaySeconds,
|
|
21273
21376
|
run: async (message, metadata) => {
|
|
21274
|
-
const { processPluginTask } = await import("./agent-
|
|
21377
|
+
const { processPluginTask } = await import("./agent-OUkEw6Bv.js").then((n) => n.st);
|
|
21275
21378
|
await processPluginTask(message, {
|
|
21276
21379
|
...options,
|
|
21277
21380
|
deliveryCount: metadata.deliveryCount
|
|
@@ -21868,14 +21971,18 @@ const SUGGESTED_SUFFIX = " (suggested)";
|
|
|
21868
21971
|
function optionLabel(option, maxChars = Number.POSITIVE_INFINITY) {
|
|
21869
21972
|
return option.recommended ? `${truncate$1(option.label, maxChars - 12)}${SUGGESTED_SUFFIX}` : option.label;
|
|
21870
21973
|
}
|
|
21871
|
-
|
|
21974
|
+
function fieldDetail(field) {
|
|
21975
|
+
return field.kind === "text" ? "short answer" : `${field.kind === "multi_choice" ? "pick any" : "pick one"}: ${field.options.map((option) => optionLabel(option)).join(", ")}`;
|
|
21976
|
+
}
|
|
21977
|
+
/**
|
|
21978
|
+
* The question and a short list of what to answer, in Slack markdown. A
|
|
21979
|
+
* request without a shared question shows each field's own question, so
|
|
21980
|
+
* each answer sits under its question.
|
|
21981
|
+
*/
|
|
21872
21982
|
function slackUserInputText(request) {
|
|
21873
21983
|
const buttonField = buttonUserInputField(request);
|
|
21874
|
-
const
|
|
21875
|
-
|
|
21876
|
-
return `- **${field.label}** (${detail})${field.description ? `: ${field.description}` : ""}`;
|
|
21877
|
-
});
|
|
21878
|
-
return normalizeSlackReplyMarkdown([request.question, ...notes.length ? [notes.join("\n")] : []].join("\n\n"));
|
|
21984
|
+
const optionNotes = buttonField ? buttonField.options.filter((option) => option.description).map((option) => `- **${optionLabel(option)}**: ${option.description}`) : [];
|
|
21985
|
+
return normalizeSlackReplyMarkdown((request.question ? [request.question, (buttonField ? optionNotes : request.fields.map((field) => `- **${field.label}** (${fieldDetail(field)})${field.description ? `: ${field.description}` : ""}`)).join("\n")] : request.fields.map((field) => [`**${field.label}**${field.description ? `: ${field.description}` : ""}`, ...buttonField ? optionNotes : [fieldDetail(field)]].join("\n"))).filter(Boolean).join("\n\n"));
|
|
21879
21986
|
}
|
|
21880
21987
|
function toOption(option) {
|
|
21881
21988
|
return {
|
|
@@ -21886,17 +21993,16 @@ function toOption(option) {
|
|
|
21886
21993
|
}
|
|
21887
21994
|
/**
|
|
21888
21995
|
* Render a request as a Slack modal form: one input for each field and one
|
|
21889
|
-
* optional
|
|
21890
|
-
* so a person can answer with free text only. `callbackId` and
|
|
21891
|
-
* handler what the form answers.
|
|
21996
|
+
* optional notes input that goes with the answers. Every input is optional,
|
|
21997
|
+
* so a person can answer with free text only. `callbackId` and
|
|
21998
|
+
* `privateMetadata` tell the submit handler what the form answers.
|
|
21892
21999
|
*/
|
|
21893
22000
|
function buildSlackUserInputForm(request, form) {
|
|
21894
22001
|
const inputs = request.fields.map((field) => ({
|
|
21895
22002
|
type: "input",
|
|
21896
22003
|
block_id: `${FIELD_BLOCK_ID_PREFIX}${field.id}`,
|
|
21897
|
-
label: plainText$1(field.label),
|
|
22004
|
+
label: plainText$1(field.description ? `${field.label}: ${field.description}` : field.label),
|
|
21898
22005
|
optional: true,
|
|
21899
|
-
...field.description ? { hint: plainText$1(field.description) } : void 0,
|
|
21900
22006
|
element: field.kind === "text" ? {
|
|
21901
22007
|
type: "plain_text_input",
|
|
21902
22008
|
action_id: VALUE_ACTION_ID,
|
|
@@ -21968,7 +22074,7 @@ function slackUserInputAnswerNote(args) {
|
|
|
21968
22074
|
const values = answer.values[field.id];
|
|
21969
22075
|
return values?.length ? [`*${escapeSlackMrkdwnText(field.label)}*: ${escapeSlackMrkdwnText(values.join(", "))}`] : [];
|
|
21970
22076
|
});
|
|
21971
|
-
if (answer.other) lines.push(
|
|
22077
|
+
if (answer.other) lines.push(`*${USER_INPUT_NOTE.label}*: ${escapeSlackMrkdwnText(answer.other)}`);
|
|
21972
22078
|
return truncate$1([`${who} answered`, ...lines].join("\n"), MAX_NOTE_CHARS);
|
|
21973
22079
|
}
|
|
21974
22080
|
// src/net/link-url.ts
|
|
@@ -21988,6 +22094,7 @@ const SLACK_INBOX_ITEM_VIEW_ID = "junior_review_item";
|
|
|
21988
22094
|
const ACTION_ID_PREFIX = "junior_review_item:";
|
|
21989
22095
|
const CHOICE_ACTION_ID_PREFIX = `${ACTION_ID_PREFIX}choice:`;
|
|
21990
22096
|
const ANSWER_ACTION_ID = `${ACTION_ID_PREFIX}answer`;
|
|
22097
|
+
const KIND_ACTION_ID_PREFIX = `${ACTION_ID_PREFIX}action:`;
|
|
21991
22098
|
const DISMISS_ACTION_ID = `${ACTION_ID_PREFIX}dismiss`;
|
|
21992
22099
|
const SNOOZE_ACTION_ID = `${ACTION_ID_PREFIX}snooze`;
|
|
21993
22100
|
const MAX_BODY_CHARS = 3e3;
|
|
@@ -22050,9 +22157,10 @@ function relatedText(item) {
|
|
|
22050
22157
|
function itemText(item, subjectUrl) {
|
|
22051
22158
|
const question = inboxItemQuestion(item.request);
|
|
22052
22159
|
const related = relatedText(item);
|
|
22160
|
+
const fromFields = question !== void 0 && !question.question;
|
|
22053
22161
|
const render = (bodyChars) => normalizeSlackReplyMarkdown([
|
|
22054
|
-
titleText(item, subjectUrl),
|
|
22055
|
-
...question?.question === item.body ? [] : [truncate(item.body, bodyChars)],
|
|
22162
|
+
...fromFields ? [] : [titleText(item, subjectUrl)],
|
|
22163
|
+
...fromFields || question?.question === item.body ? [] : [truncate(item.body, bodyChars)],
|
|
22056
22164
|
...related ? [related] : [],
|
|
22057
22165
|
...question ? [slackUserInputText(question)] : []
|
|
22058
22166
|
].join("\n\n"));
|
|
@@ -22080,8 +22188,15 @@ function controls(item) {
|
|
|
22080
22188
|
text: plainText("Snooze"),
|
|
22081
22189
|
url: snoozeUrl
|
|
22082
22190
|
}] : []];
|
|
22191
|
+
if (item.kind === "notice") return quiet;
|
|
22083
22192
|
const question = inboxItemQuestion(item.request);
|
|
22084
|
-
if (item.kind
|
|
22193
|
+
if (!question) return [...quiet, ...subjectKindActions(item.subject.kind, getPlugins()).map((action) => ({
|
|
22194
|
+
type: "button",
|
|
22195
|
+
action_id: `${KIND_ACTION_ID_PREFIX}${action.id}`,
|
|
22196
|
+
style: "primary",
|
|
22197
|
+
text: plainText(action.label),
|
|
22198
|
+
value: item.id
|
|
22199
|
+
}))];
|
|
22085
22200
|
const buttonField = buttonUserInputField(question);
|
|
22086
22201
|
if (!buttonField) return [...quiet, {
|
|
22087
22202
|
type: "button",
|
|
@@ -22114,11 +22229,13 @@ function controls(item) {
|
|
|
22114
22229
|
function closedNote(item) {
|
|
22115
22230
|
const who = item.closedBy ? personName(item.closedBy) : void 0;
|
|
22116
22231
|
if (item.closeReason === "Replied in thread") return `${who ?? "A person"} replied in the thread`;
|
|
22232
|
+
const action = subjectKindActionLabel(item.subject.kind, getPlugins(), item.closeAction);
|
|
22233
|
+
if (item.status === "done" && action && who) return `${who} chose *${escapeSlackMrkdwnText(action)}*`;
|
|
22117
22234
|
const question = inboxItemQuestion(item.request);
|
|
22118
|
-
if (item.status === "done" && question && item.answer &&
|
|
22235
|
+
if (item.status === "done" && question && item.answer && item.answeredBy) return slackUserInputAnswerNote({
|
|
22119
22236
|
answer: item.answer,
|
|
22120
22237
|
request: question,
|
|
22121
|
-
who
|
|
22238
|
+
who: personName(item.answeredBy)
|
|
22122
22239
|
});
|
|
22123
22240
|
if (who) return item.status === "done" ? `${who} marked this done` : `${who} dismissed this`;
|
|
22124
22241
|
const status = item.status === "done" ? "Closed as done" : "Dismissed";
|
|
@@ -22127,8 +22244,8 @@ function closedNote(item) {
|
|
|
22127
22244
|
/**
|
|
22128
22245
|
* Render an Inbox item as one Slack message. An open item shows its
|
|
22129
22246
|
* controls: one button per choice when one click can answer it, an Answer
|
|
22130
|
-
* button that opens a form otherwise,
|
|
22131
|
-
* notice. A
|
|
22247
|
+
* button that opens a form otherwise, the buttons of its kind for an action
|
|
22248
|
+
* item without a question, and only Dismiss and Snooze for a notice. A
|
|
22132
22249
|
* closed item shows a note instead, so nobody can act on it again.
|
|
22133
22250
|
*/
|
|
22134
22251
|
function buildSlackInboxItemCard(item, subjectUrl) {
|
|
@@ -22186,6 +22303,14 @@ function parseChoiceValue(value) {
|
|
|
22186
22303
|
function parseSlackInboxItemClick(action) {
|
|
22187
22304
|
const value = action.value?.trim();
|
|
22188
22305
|
if (!value || !action.action_id?.startsWith(ACTION_ID_PREFIX)) return;
|
|
22306
|
+
if (action.action_id.startsWith(KIND_ACTION_ID_PREFIX)) {
|
|
22307
|
+
const id = action.action_id.slice(KIND_ACTION_ID_PREFIX.length);
|
|
22308
|
+
return id ? {
|
|
22309
|
+
kind: "action",
|
|
22310
|
+
itemId: value,
|
|
22311
|
+
action: id
|
|
22312
|
+
} : void 0;
|
|
22313
|
+
}
|
|
22189
22314
|
if (action.action_id.startsWith(CHOICE_ACTION_ID_PREFIX)) {
|
|
22190
22315
|
const choice = parseChoiceValue(value);
|
|
22191
22316
|
return choice ? {
|
|
@@ -22350,6 +22475,179 @@ async function syncInboxItemSlackCards(args) {
|
|
|
22350
22475
|
}, { waitMs: SYNC_LOCK_WAIT_MS })).acquired) throw new Error("Another Inbox item card sync held the lock");
|
|
22351
22476
|
}, "inbox_item.slack_card.sync.failed", { "app.inbox_item.id": itemId });
|
|
22352
22477
|
}
|
|
22478
|
+
// src/chat/tool-support/zod-tool.ts
|
|
22479
|
+
function isContentOnlyToolResult(value) {
|
|
22480
|
+
return value !== null && typeof value === "object" && Array.isArray(value.content) && !("details" in value);
|
|
22481
|
+
}
|
|
22482
|
+
function isStructuredToolResultEnvelope(value) {
|
|
22483
|
+
return value !== null && typeof value === "object" && Array.isArray(value.content) && "details" in value;
|
|
22484
|
+
}
|
|
22485
|
+
function parseToolContent(content) {
|
|
22486
|
+
for (const item of content) if (!item || typeof item !== "object" || (item.type === "text" ? typeof item.text !== "string" : item.type === "image" ? typeof item.data !== "string" || typeof item.mimeType !== "string" : true)) throw new TypeError("zodTool() content must contain valid text or image items.");
|
|
22487
|
+
return content;
|
|
22488
|
+
}
|
|
22489
|
+
function formatZodPath(path) {
|
|
22490
|
+
return path.length > 0 ? path.map(String).join(".") : "root";
|
|
22491
|
+
}
|
|
22492
|
+
function formatToolInputError(error) {
|
|
22493
|
+
return `Invalid tool arguments: ${error.issues.slice(0, 5).map((issue) => `${formatZodPath(issue.path)}: ${issue.message}`).join("; ") || "input did not match schema"}`;
|
|
22494
|
+
}
|
|
22495
|
+
/** Parse tool input with its Zod schema, as a model-repairable error on failure. */
|
|
22496
|
+
function parseToolInput(schema, args) {
|
|
22497
|
+
const result = schema.safeParse(args);
|
|
22498
|
+
if (!result.success) throw new ToolInputError(formatToolInputError(result.error), { cause: result.error });
|
|
22499
|
+
return result.data;
|
|
22500
|
+
}
|
|
22501
|
+
/** Declare the static definition of a Zod tool once, for the registry and its factory. */
|
|
22502
|
+
function zodToolDefinition(definition) {
|
|
22503
|
+
return definition;
|
|
22504
|
+
}
|
|
22505
|
+
function zodTool(definition) {
|
|
22506
|
+
const { inputSchema, outputSchema, prepareArguments, execute, ...toolDef } = definition;
|
|
22507
|
+
let modelInputSchema;
|
|
22508
|
+
try {
|
|
22509
|
+
modelInputSchema = z.toJSONSchema(inputSchema);
|
|
22510
|
+
} catch (error) {
|
|
22511
|
+
throw new TypeError("zodTool() inputSchema must be representable as JSON Schema.", { cause: error });
|
|
22512
|
+
}
|
|
22513
|
+
let modelOutputSchema;
|
|
22514
|
+
if (outputSchema) try {
|
|
22515
|
+
modelOutputSchema = z.toJSONSchema(outputSchema);
|
|
22516
|
+
} catch (error) {
|
|
22517
|
+
throw new TypeError("zodTool() outputSchema must be representable as JSON Schema.", { cause: error });
|
|
22518
|
+
}
|
|
22519
|
+
return {
|
|
22520
|
+
...toolDef,
|
|
22521
|
+
inputSchema: modelInputSchema,
|
|
22522
|
+
...modelOutputSchema ? { outputSchema: modelOutputSchema } : void 0,
|
|
22523
|
+
prepareArguments(args) {
|
|
22524
|
+
return parseToolInput(inputSchema, prepareArguments ? prepareArguments(args) : args);
|
|
22525
|
+
},
|
|
22526
|
+
...execute ? { async execute(input, options) {
|
|
22527
|
+
const result = await execute(input, options);
|
|
22528
|
+
if (!outputSchema) {
|
|
22529
|
+
if (isContentOnlyToolResult(result)) return result;
|
|
22530
|
+
throw new TypeError("zodTool() content-only tools must return { content } without details.");
|
|
22531
|
+
}
|
|
22532
|
+
if (isStructuredToolResultEnvelope(result)) return {
|
|
22533
|
+
content: parseToolContent(result.content),
|
|
22534
|
+
details: outputSchema.parse(result.details)
|
|
22535
|
+
};
|
|
22536
|
+
return outputSchema.parse(result);
|
|
22537
|
+
} } : void 0
|
|
22538
|
+
};
|
|
22539
|
+
}
|
|
22540
|
+
// src/chat/inbox-items/tool-support.ts
|
|
22541
|
+
/** Shared input and result shapes of the Inbox item tools. */
|
|
22542
|
+
/** Deferred tool catalog source for the Inbox item tools. */
|
|
22543
|
+
const INBOX_TOOL_SOURCE = {
|
|
22544
|
+
id: "inbox",
|
|
22545
|
+
description: "Update and search Inbox items: work that needs a person."
|
|
22546
|
+
};
|
|
22547
|
+
/** Who can act on an Inbox item. */
|
|
22548
|
+
const assigneesSchema = z.array(z.string().trim().min(1).max(320)).min(1).max(20).describe("Who can act on the item. Each entry is `everyone`, an email, or a mention such as `<@U123>`. Everyone means any person who can see the item.");
|
|
22549
|
+
/** Conversations that an Inbox item links to. */
|
|
22550
|
+
const conversationIdsSchema = z.array(z.string().trim().min(1).max(500)).max(10);
|
|
22551
|
+
/** Deliver an Inbox item change through the services of the tools. */
|
|
22552
|
+
function inboxItemDelivery(services) {
|
|
22553
|
+
return {
|
|
22554
|
+
queue: services.queue(),
|
|
22555
|
+
show: services.show
|
|
22556
|
+
};
|
|
22557
|
+
}
|
|
22558
|
+
/** The owner Conversation of an item, as a list of Conversations to check. */
|
|
22559
|
+
function ownerLinks(item) {
|
|
22560
|
+
const conversationId = item ? ownerConversationId(item) : void 0;
|
|
22561
|
+
return conversationId ? [conversationId] : [];
|
|
22562
|
+
}
|
|
22563
|
+
/** Read an Inbox item that the agent may read, or fail with a tool input error. */
|
|
22564
|
+
async function readableItem(id, scope) {
|
|
22565
|
+
const item = await getInboxItem(getDb(), id);
|
|
22566
|
+
if (!item || !canReadInboxItem(item, scope.reader)) throw new ToolInputError(`Inbox item ${id} is not found. Use searchInboxItems to find its id.`);
|
|
22567
|
+
return item;
|
|
22568
|
+
}
|
|
22569
|
+
/** Render one Inbox item for a tool result. */
|
|
22570
|
+
function itemResult(item) {
|
|
22571
|
+
return {
|
|
22572
|
+
id: item.id,
|
|
22573
|
+
kind: item.kind,
|
|
22574
|
+
status: item.status,
|
|
22575
|
+
title: item.title,
|
|
22576
|
+
body: item.body,
|
|
22577
|
+
assignees: [...item.assignedToEveryone ? [EVERYONE_ASSIGNEE] : [], ...item.assignees.map((assignee) => assignee.email)],
|
|
22578
|
+
conversation_ids: item.conversationIds,
|
|
22579
|
+
visibility: item.visibility,
|
|
22580
|
+
updated_at: item.updatedAt.toISOString(),
|
|
22581
|
+
subject: item.subject,
|
|
22582
|
+
...item.addedByAutomationId ? { automation_id: item.addedByAutomationId } : void 0,
|
|
22583
|
+
...item.request ? { request: requestResult(item.request) } : void 0,
|
|
22584
|
+
...item.answer ? { answer: item.answer } : void 0,
|
|
22585
|
+
...item.closedAt ? {
|
|
22586
|
+
closed_at: item.closedAt.toISOString(),
|
|
22587
|
+
closed_by: (item.answer ? item.answeredBy : item.closedBy)?.email ?? "agent"
|
|
22588
|
+
} : void 0,
|
|
22589
|
+
...item.closeReason ? { close_reason: item.closeReason } : void 0
|
|
22590
|
+
};
|
|
22591
|
+
}
|
|
22592
|
+
/** Show the stored question with the tool's snake_case related link keys. */
|
|
22593
|
+
function requestResult({ related, ...question }) {
|
|
22594
|
+
return {
|
|
22595
|
+
...question,
|
|
22596
|
+
...related ? { related: related.map(({ conversationId, ...entry }) => ({
|
|
22597
|
+
...entry,
|
|
22598
|
+
...conversationId ? { conversation_id: conversationId } : void 0
|
|
22599
|
+
})) } : void 0
|
|
22600
|
+
};
|
|
22601
|
+
}
|
|
22602
|
+
const RECOMMENDED_SUFFIX = /\s*\(recommended\)$/i;
|
|
22603
|
+
const MAX_TITLE_CHARS = 200;
|
|
22604
|
+
const questionOptionSchema = z.object({
|
|
22605
|
+
label: z.string().trim().min(1).max(USER_INPUT_LIMITS.maxLabelChars).describe("The choice the person picks, 1-5 words. The answer uses this text."),
|
|
22606
|
+
description: z.string().trim().min(1).max(USER_INPUT_LIMITS.maxDescriptionChars).describe("What this choice means or what happens if it is picked.")
|
|
22607
|
+
}).strict();
|
|
22608
|
+
/**
|
|
22609
|
+
* The questions of `askUserQuestion` and `updateInboxItem`. The keys are
|
|
22610
|
+
* the ones of Claude Code's `AskUserQuestion`, which models know, so they
|
|
22611
|
+
* are camelCase where it is (`multiSelect`).
|
|
22612
|
+
*/
|
|
22613
|
+
const questionsSchema = z.array(z.object({
|
|
22614
|
+
question: z.string().trim().min(1).max(USER_INPUT_LIMITS.maxFieldDescriptionChars).describe("The complete question, clear and specific, ending with a question mark."),
|
|
22615
|
+
header: z.string().trim().min(1).max(12).describe("A very short label for the question, max 12 characters, such as `Approach`."),
|
|
22616
|
+
options: z.array(questionOptionSchema).min(USER_INPUT_LIMITS.minOptions).max(4).describe("The 2-4 choices. Put the recommended one first and end its label with \"(Recommended)\". Do not add an \"Other\" choice: the person can always write their own answer."),
|
|
22617
|
+
multiSelect: z.boolean().nullable().optional().describe("True lets the person pick more than one choice. Default false.")
|
|
22618
|
+
}).strict()).min(1).max(USER_INPUT_LIMITS.maxFields).describe("The questions to ask, 1-4. Ask each decision as its own question, with its own choices, not several decisions in one question.");
|
|
22619
|
+
/** Cut text to the length of an item title, as a question's title is cut. */
|
|
22620
|
+
function cutInboxItemTitle(text) {
|
|
22621
|
+
return text.length <= MAX_TITLE_CHARS ? text : `${text.slice(0, 199)}…`;
|
|
22622
|
+
}
|
|
22623
|
+
/**
|
|
22624
|
+
* Store each question as one field with its own question, header, and
|
|
22625
|
+
* choices, and no question that the fields share, so every surface shows
|
|
22626
|
+
* each question with its own answer. A label that ends with
|
|
22627
|
+
* "(Recommended)" becomes a recommended choice.
|
|
22628
|
+
*/
|
|
22629
|
+
function questionContent(questions) {
|
|
22630
|
+
const fields = questions.map((entry, index) => ({
|
|
22631
|
+
id: `q${index + 1}`,
|
|
22632
|
+
label: entry.header,
|
|
22633
|
+
description: entry.question,
|
|
22634
|
+
kind: entry.multiSelect ? "multi_choice" : "choice",
|
|
22635
|
+
options: entry.options.map((option) => {
|
|
22636
|
+
const label = option.label.replace(RECOMMENDED_SUFFIX, "").trim();
|
|
22637
|
+
return {
|
|
22638
|
+
label: label || option.label,
|
|
22639
|
+
description: option.description,
|
|
22640
|
+
...label && label !== option.label ? { recommended: true } : void 0
|
|
22641
|
+
};
|
|
22642
|
+
})
|
|
22643
|
+
}));
|
|
22644
|
+
const request = parseToolInput(inboxItemRequestSchema, { fields });
|
|
22645
|
+
return {
|
|
22646
|
+
body: questions.map((entry) => entry.question).join("\n\n"),
|
|
22647
|
+
request,
|
|
22648
|
+
title: cutInboxItemTitle(questions.length === 1 ? questions[0].question : questions.map((entry) => entry.header).join(" · "))
|
|
22649
|
+
};
|
|
22650
|
+
}
|
|
22353
22651
|
// src/chat/notifications/inbox-item-push.ts
|
|
22354
22652
|
/**
|
|
22355
22653
|
* How long a Slack card waits before its item pushes. A User who saw the
|
|
@@ -22427,12 +22725,13 @@ async function deliverPush(args) {
|
|
|
22427
22725
|
logInfo("notification.inbox_item.skipped", { "app.notification.skip_reason": reason });
|
|
22428
22726
|
return;
|
|
22429
22727
|
}
|
|
22728
|
+
const repeatsTitle = item.title === cutInboxItemTitle(item.body);
|
|
22430
22729
|
await sendPushNotificationToUser({
|
|
22431
22730
|
config: args.config,
|
|
22432
22731
|
db,
|
|
22433
22732
|
kind: args.kind,
|
|
22434
22733
|
payload: {
|
|
22435
|
-
body: notificationPreview(item.body),
|
|
22734
|
+
body: repeatsTitle ? "" : notificationPreview(item.body),
|
|
22436
22735
|
tag: item.id,
|
|
22437
22736
|
title: item.title,
|
|
22438
22737
|
url: args.url
|
|
@@ -22477,7 +22776,7 @@ async function syncInboxItemPush(itemId, options = {}) {
|
|
|
22477
22776
|
await scheduleSlackCardPushes(db, item);
|
|
22478
22777
|
return;
|
|
22479
22778
|
}
|
|
22480
|
-
await withSpan("notification.inbox_item.push", "notification.inbox_item.push", {}, async () => {
|
|
22779
|
+
await withSpan$1("notification.inbox_item.push", "notification.inbox_item.push", {}, async () => {
|
|
22481
22780
|
const pushed = await listInboxItemPushUserIds(db, item.id);
|
|
22482
22781
|
await mapBounded(userIds.filter((userId) => !pushed.has(userId)), (userId) => deliverPush({
|
|
22483
22782
|
config,
|
|
@@ -22518,7 +22817,7 @@ async function pushInboxSnoozeWakes(wakes) {
|
|
|
22518
22817
|
const item = await getInboxItem(db, wake.inboxItemId);
|
|
22519
22818
|
const url = item && wakePushUrl(item, wake.userId);
|
|
22520
22819
|
if (!item || !url) return;
|
|
22521
|
-
await withSpan("notification.inbox_item.push", "notification.inbox_item.push", {}, () => deliverPush({
|
|
22820
|
+
await withSpan$1("notification.inbox_item.push", "notification.inbox_item.push", {}, () => deliverPush({
|
|
22522
22821
|
config,
|
|
22523
22822
|
db,
|
|
22524
22823
|
item,
|
|
@@ -22565,7 +22864,7 @@ async function pushAfterSlackCard(db, config, timerId, unassigned) {
|
|
|
22565
22864
|
}
|
|
22566
22865
|
const url = getDashboardInboxItemLink(item.id);
|
|
22567
22866
|
if (!url) return;
|
|
22568
|
-
await withSpan("notification.inbox_item.push", "notification.inbox_item.push", {}, () => deliverPush({
|
|
22867
|
+
await withSpan$1("notification.inbox_item.push", "notification.inbox_item.push", {}, () => deliverPush({
|
|
22569
22868
|
afterSlackCard: true,
|
|
22570
22869
|
config,
|
|
22571
22870
|
db,
|
|
@@ -22821,6 +23120,1299 @@ function normalizeMessageSenders(value) {
|
|
|
22821
23120
|
}
|
|
22822
23121
|
return Object.keys(senders).length ? senders : void 0;
|
|
22823
23122
|
}
|
|
23123
|
+
// src/conversation-events/lock.ts
|
|
23124
|
+
/** Serialize event sequence allocation with other conversation writes. */
|
|
23125
|
+
async function withConversationEventLock(executor, conversationId, callback) {
|
|
23126
|
+
return executor.withLock(`junior_conversation:${conversationId}`, callback);
|
|
23127
|
+
}
|
|
23128
|
+
// src/chat/conversations/stop-state.ts
|
|
23129
|
+
/** Return when a Conversation stopped, or undefined when it is not stopped. */
|
|
23130
|
+
async function getConversationStoppedAtMs(conversationId) {
|
|
23131
|
+
const [row] = await getSqlExecutor().db().select({ stoppedAt: juniorConversations.stoppedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
|
|
23132
|
+
return row?.stoppedAt?.getTime();
|
|
23133
|
+
}
|
|
23134
|
+
/**
|
|
23135
|
+
* End the stop of a Conversation and of the child agents below it, for new
|
|
23136
|
+
* work sent at `sentAtMs`: a person's input, or new work from its parent.
|
|
23137
|
+
* Nothing changes for work sent at or before the stop, so the input that a
|
|
23138
|
+
* stop drops does not undo it. Only Conversations that stopped no later than
|
|
23139
|
+
* this Conversation change, so a later stop of one child agent stays.
|
|
23140
|
+
*/
|
|
23141
|
+
async function resumeConversationTree(conversationId, sentAtMs) {
|
|
23142
|
+
const subtree = sql`(select ${conversationSubtreeColumns.conversationId} from ${conversationSubtree([conversationId])})`;
|
|
23143
|
+
const executor = getSqlExecutor();
|
|
23144
|
+
await withConversationEventLock(executor, conversationId, () => executor.transaction(async () => {
|
|
23145
|
+
const tx = executor.db();
|
|
23146
|
+
const stoppedAt = (await tx.select({
|
|
23147
|
+
conversationId: juniorConversations.conversationId,
|
|
23148
|
+
stoppedAt: juniorConversations.stoppedAt
|
|
23149
|
+
}).from(juniorConversations).where(inArray(juniorConversations.conversationId, subtree)).orderBy(asc(juniorConversations.conversationId)).for("update")).find((row) => row.conversationId === conversationId)?.stoppedAt;
|
|
23150
|
+
if (!stoppedAt || sentAtMs <= stoppedAt.getTime()) return;
|
|
23151
|
+
await tx.update(juniorConversations).set({
|
|
23152
|
+
stoppedAt: null,
|
|
23153
|
+
detailVersion: nextDetailVersion
|
|
23154
|
+
}).where(and(inArray(juniorConversations.conversationId, subtree), lte(juniorConversations.stoppedAt, stoppedAt)));
|
|
23155
|
+
}));
|
|
23156
|
+
}
|
|
23157
|
+
// src/chat/conversations/web-mailbox.ts
|
|
23158
|
+
/** Parse web mailbox metadata written before Source and Actor were complete. */
|
|
23159
|
+
const legacyWebMailboxMetadataSchema = z.object({
|
|
23160
|
+
authorEmail: z.string().email(),
|
|
23161
|
+
authorFullName: z.string().min(1).optional(),
|
|
23162
|
+
authorUserId: z.string().min(1),
|
|
23163
|
+
authorUserName: z.string().min(1).optional(),
|
|
23164
|
+
kind: z.literal("api_turn"),
|
|
23165
|
+
messageId: z.string().min(1)
|
|
23166
|
+
}).strict();
|
|
23167
|
+
// src/chat/slack/context.ts
|
|
23168
|
+
function toTrimmedSlackString(value) {
|
|
23169
|
+
return toOptionalString(value)?.trim() || void 0;
|
|
23170
|
+
}
|
|
23171
|
+
const slackMessageEnvelopeSchema = z.object({ raw: z.unknown().optional() });
|
|
23172
|
+
const rawSlackMessageSchema = z.object({
|
|
23173
|
+
channel: z.unknown().optional(),
|
|
23174
|
+
message: z.unknown().optional(),
|
|
23175
|
+
team: z.unknown().optional(),
|
|
23176
|
+
team_id: z.unknown().optional(),
|
|
23177
|
+
thread_ts: z.unknown().optional(),
|
|
23178
|
+
ts: z.unknown().optional(),
|
|
23179
|
+
user_team: z.unknown().optional()
|
|
23180
|
+
});
|
|
23181
|
+
const nestedRawSlackMessageSchema = z.object({ ts: z.unknown().optional() });
|
|
23182
|
+
/** Project only the Slack raw fields consumed by runtime thread context. */
|
|
23183
|
+
function readSlackRawMessageContext(message) {
|
|
23184
|
+
const envelope = slackMessageEnvelopeSchema.safeParse(message);
|
|
23185
|
+
if (!envelope.success) return;
|
|
23186
|
+
const raw = rawSlackMessageSchema.safeParse(envelope.data.raw);
|
|
23187
|
+
if (!raw.success) return;
|
|
23188
|
+
const nestedMessage = nestedRawSlackMessageSchema.safeParse(raw.data.message);
|
|
23189
|
+
const channelId = parseSlackChannelId(raw.data.channel);
|
|
23190
|
+
const threadTs = parseSlackMessageTs(raw.data.thread_ts);
|
|
23191
|
+
const messageTs = parseSlackMessageTs(raw.data.ts);
|
|
23192
|
+
const nestedMessageTs = nestedMessage.success && parseSlackMessageTs(nestedMessage.data.ts);
|
|
23193
|
+
const teamId = parseSlackTeamId(raw.data.team_id) ?? parseSlackTeamId(raw.data.team);
|
|
23194
|
+
const authorTeamId = parseSlackTeamId(raw.data.user_team);
|
|
23195
|
+
return {
|
|
23196
|
+
...channelId ? { channelId } : void 0,
|
|
23197
|
+
...threadTs ? { threadTs } : void 0,
|
|
23198
|
+
...messageTs ? { messageTs } : void 0,
|
|
23199
|
+
...nestedMessageTs ? { nestedMessageTs } : void 0,
|
|
23200
|
+
...teamId ? { teamId } : void 0,
|
|
23201
|
+
...authorTeamId ? { authorTeamId } : void 0
|
|
23202
|
+
};
|
|
23203
|
+
}
|
|
23204
|
+
/** Extract a channel ID and validated Slack timestamp from `slack:<channel>:<ts>`. */
|
|
23205
|
+
function parseSlackThreadId(threadId) {
|
|
23206
|
+
const normalizedThreadId = toTrimmedSlackString(threadId);
|
|
23207
|
+
if (!normalizedThreadId) return;
|
|
23208
|
+
const parts = normalizedThreadId.split(":");
|
|
23209
|
+
if (parts.length !== 3 || parts[0] !== "slack") return;
|
|
23210
|
+
const channelId = parseSlackChannelId(parts[1]);
|
|
23211
|
+
const threadTs = parseSlackMessageTs(parts[2]);
|
|
23212
|
+
if (!channelId || !threadTs) return;
|
|
23213
|
+
return {
|
|
23214
|
+
channelId,
|
|
23215
|
+
threadTs
|
|
23216
|
+
};
|
|
23217
|
+
}
|
|
23218
|
+
/** Best-effort channel ID extraction from a raw Slack message payload. */
|
|
23219
|
+
function resolveSlackChannelIdFromMessage(message) {
|
|
23220
|
+
const messageChannelId = parseSlackChannelId(message.channelId);
|
|
23221
|
+
if (messageChannelId) return messageChannelId;
|
|
23222
|
+
const raw = message.raw;
|
|
23223
|
+
if (raw && typeof raw === "object") {
|
|
23224
|
+
const rawChannel = parseSlackChannelId(raw.channel);
|
|
23225
|
+
if (rawChannel) return rawChannel;
|
|
23226
|
+
}
|
|
23227
|
+
}
|
|
23228
|
+
// src/chat/slack/conversation-context.ts
|
|
23229
|
+
function normalizeConversationName(type, channelName) {
|
|
23230
|
+
const trimmed = channelName?.trim();
|
|
23231
|
+
if (!trimmed) return void 0;
|
|
23232
|
+
if (type === "public_channel" || type === "private_channel" || type === "private_channel_or_group_dm") return trimmed.startsWith("#") ? trimmed : `#${trimmed}`;
|
|
23233
|
+
return trimmed;
|
|
23234
|
+
}
|
|
23235
|
+
function typeFromSlackChannelType(channelType) {
|
|
23236
|
+
if (channelType === "channel") return "public_channel";
|
|
23237
|
+
if (channelType === "group") return "private_channel";
|
|
23238
|
+
if (channelType === "mpim") return "group_dm";
|
|
23239
|
+
if (channelType === "im") return "direct_message";
|
|
23240
|
+
}
|
|
23241
|
+
function typeFromChannelId(channelId, channelName) {
|
|
23242
|
+
const normalized = normalizeSlackConversationId(channelId);
|
|
23243
|
+
if (!normalized) return void 0;
|
|
23244
|
+
if (normalized.startsWith("C")) return "public_channel";
|
|
23245
|
+
if (normalized.startsWith("D")) return "direct_message";
|
|
23246
|
+
if (normalized.startsWith("G")) return channelName?.trim().startsWith("mpdm-") ? "group_dm" : "private_channel_or_group_dm";
|
|
23247
|
+
}
|
|
23248
|
+
function toSlackEventChannelType(channelType) {
|
|
23249
|
+
if (channelType === "channel" || channelType === "group" || channelType === "mpim" || channelType === "im") return channelType;
|
|
23250
|
+
}
|
|
23251
|
+
/**
|
|
23252
|
+
* Map Slack's Events API channel_type to a source-confirmed visibility.
|
|
23253
|
+
*
|
|
23254
|
+
* Slack's event metadata and live conversation metadata are the only
|
|
23255
|
+
* visibility authorities; channel IDs never classify visibility.
|
|
23256
|
+
*/
|
|
23257
|
+
function conversationVisibilityFromSlackChannelType(channelType) {
|
|
23258
|
+
if (!channelType) return void 0;
|
|
23259
|
+
return channelType === "channel" ? "public" : "private";
|
|
23260
|
+
}
|
|
23261
|
+
/**
|
|
23262
|
+
* Map live `conversations.info` metadata to Slack's Events API channel type,
|
|
23263
|
+
* for events that carry no `channel_type`.
|
|
23264
|
+
*/
|
|
23265
|
+
function slackChannelTypeFromConversationInfo(info) {
|
|
23266
|
+
if (info.isIm) return "im";
|
|
23267
|
+
if (info.isMpim) return "mpim";
|
|
23268
|
+
if (info.isPrivate) return "group";
|
|
23269
|
+
return info.isChannel ? "channel" : void 0;
|
|
23270
|
+
}
|
|
23271
|
+
/** Resolve Slack's raw event channel type from a Chat SDK message-like object. */
|
|
23272
|
+
function resolveSlackChannelTypeFromMessage(message) {
|
|
23273
|
+
const raw = message.raw;
|
|
23274
|
+
if (!raw || typeof raw !== "object") return;
|
|
23275
|
+
const channelType = raw["channel_type"];
|
|
23276
|
+
return typeof channelType === "string" ? toSlackEventChannelType(channelType.trim()) : void 0;
|
|
23277
|
+
}
|
|
23278
|
+
/** Build Slack conversation facts available to runtime consumers. */
|
|
23279
|
+
function resolveSlackConversationContext(input) {
|
|
23280
|
+
const type = typeFromSlackChannelType(input.channelType) ?? typeFromChannelId(input.channelId, input.channelName);
|
|
23281
|
+
if (!type) return void 0;
|
|
23282
|
+
const name = normalizeConversationName(type, input.channelName);
|
|
23283
|
+
const topic = input.channelTopic?.trim();
|
|
23284
|
+
const description = input.channelDescription?.trim();
|
|
23285
|
+
const visibility = conversationVisibilityFromSlackChannelType(input.channelType);
|
|
23286
|
+
return {
|
|
23287
|
+
type,
|
|
23288
|
+
...name ? { name } : void 0,
|
|
23289
|
+
...topic ? { topic } : void 0,
|
|
23290
|
+
...description ? { description } : void 0,
|
|
23291
|
+
...visibility ? { visibility } : void 0,
|
|
23292
|
+
...input.botUserId ? { botUserId: input.botUserId } : void 0
|
|
23293
|
+
};
|
|
23294
|
+
}
|
|
23295
|
+
/** Build Slack conversation facts from Junior's persisted Slack thread id. */
|
|
23296
|
+
function resolveSlackConversationContextFromThreadId(input) {
|
|
23297
|
+
const context = resolveSlackConversationContext({
|
|
23298
|
+
channelId: parseSlackThreadId(input.threadId)?.channelId,
|
|
23299
|
+
channelName: input.channelName
|
|
23300
|
+
});
|
|
23301
|
+
if (!context || !input.visibility) return context;
|
|
23302
|
+
return {
|
|
23303
|
+
...context,
|
|
23304
|
+
type: input.visibility === "private" && context.type === "public_channel" ? "private_channel" : context.type,
|
|
23305
|
+
visibility: input.visibility
|
|
23306
|
+
};
|
|
23307
|
+
}
|
|
23308
|
+
/** Render a human label for a privacy-preserving Slack conversation type. */
|
|
23309
|
+
function formatSlackConversationTypeLabel(type) {
|
|
23310
|
+
if (type === "public_channel") return "Public Channel";
|
|
23311
|
+
if (type === "private_channel") return "Private Channel";
|
|
23312
|
+
if (type === "group_dm") return "Group DM";
|
|
23313
|
+
if (type === "direct_message") return "Direct Message";
|
|
23314
|
+
return "Private Channel or Group DM";
|
|
23315
|
+
}
|
|
23316
|
+
/** Render a Slack conversation label without exposing conversation names. */
|
|
23317
|
+
function formatSlackConversationRedactedLabel(context) {
|
|
23318
|
+
if (!context) return void 0;
|
|
23319
|
+
return formatSlackConversationTypeLabel(context.type);
|
|
23320
|
+
}
|
|
23321
|
+
// src/core/telemetry.ts
|
|
23322
|
+
const SENTRY_TRACE_PATTERN = /^([0-9a-f]{32})-([0-9a-f]{16})(?:-([01]))?$/;
|
|
23323
|
+
function spanLink({ sentryTrace }) {
|
|
23324
|
+
const [, traceId, spanId, sampled] = SENTRY_TRACE_PATTERN.exec(sentryTrace) ?? [];
|
|
23325
|
+
return traceId && spanId ? [{ context: {
|
|
23326
|
+
traceId,
|
|
23327
|
+
spanId,
|
|
23328
|
+
traceFlags: sampled === "1" ? 1 : 0
|
|
23329
|
+
} }] : [];
|
|
23330
|
+
}
|
|
23331
|
+
/** Returns the trace context of the active span, so other work can link to it. */
|
|
23332
|
+
function activeTraceContext() {
|
|
23333
|
+
const sentryTrace = Sentry.getTraceData()["sentry-trace"];
|
|
23334
|
+
return sentryTrace ? { sentryTrace } : void 0;
|
|
23335
|
+
}
|
|
23336
|
+
/** Sets attributes on the active span, such as ids that a step learns late. */
|
|
23337
|
+
function setActiveSpanAttributes(attributes) {
|
|
23338
|
+
Sentry.getActiveSpan()?.setAttributes(attributes);
|
|
23339
|
+
}
|
|
23340
|
+
/** Adds one to a counter metric. Metrics are not sampled, unlike spans. */
|
|
23341
|
+
function countMetric(name, attributes) {
|
|
23342
|
+
Sentry.metrics.count(name, 1, { attributes });
|
|
23343
|
+
}
|
|
23344
|
+
const SPAN_STATUS_ERROR = 2;
|
|
23345
|
+
/** Runs `run` in a span whose op is `name`, and whose name is too by default. */
|
|
23346
|
+
function withSpan(name, attributes, run, options = {}) {
|
|
23347
|
+
const start = () => Sentry.startSpanManual({
|
|
23348
|
+
name: options.spanName ?? name,
|
|
23349
|
+
op: name,
|
|
23350
|
+
attributes,
|
|
23351
|
+
links: options.links?.flatMap(spanLink)
|
|
23352
|
+
}, async (span) => {
|
|
23353
|
+
try {
|
|
23354
|
+
return await run({
|
|
23355
|
+
setAttribute: (key, value) => span.setAttribute(key, value),
|
|
23356
|
+
setAttributes: (values) => span.setAttributes(values),
|
|
23357
|
+
fail: (message) => span.setStatus({
|
|
23358
|
+
code: SPAN_STATUS_ERROR,
|
|
23359
|
+
message
|
|
23360
|
+
})
|
|
23361
|
+
});
|
|
23362
|
+
} catch (error) {
|
|
23363
|
+
if (!options.isExpectedError?.(error)) {
|
|
23364
|
+
span.setStatus({
|
|
23365
|
+
code: SPAN_STATUS_ERROR,
|
|
23366
|
+
message: "internal_error"
|
|
23367
|
+
});
|
|
23368
|
+
span.setAttribute("error.type", error instanceof Error ? error.name : typeof error);
|
|
23369
|
+
}
|
|
23370
|
+
throw error;
|
|
23371
|
+
} finally {
|
|
23372
|
+
span.end();
|
|
23373
|
+
}
|
|
23374
|
+
});
|
|
23375
|
+
return options.newTrace ? Sentry.startNewTrace(start) : start();
|
|
23376
|
+
}
|
|
23377
|
+
// src/core/queue.ts
|
|
23378
|
+
const VISIBILITY_TIMEOUT_BUFFER_SECONDS = 30;
|
|
23379
|
+
/** Defines one signed topic. Returns its publish function and its consumer. */
|
|
23380
|
+
function signedTopic(def) {
|
|
23381
|
+
const publish = async ({ queue }, message, options = {}) => {
|
|
23382
|
+
await withSpan("queue.publish", {
|
|
23383
|
+
...def.attributes(message),
|
|
23384
|
+
"messaging.destination.name": def.topic,
|
|
23385
|
+
"messaging.system": queue.messagingSystem
|
|
23386
|
+
}, async (span) => {
|
|
23387
|
+
const traceContext = activeTraceContext();
|
|
23388
|
+
const payload = signQueueMessage(def.sign, traceContext ? {
|
|
23389
|
+
...message,
|
|
23390
|
+
traceContext
|
|
23391
|
+
} : message);
|
|
23392
|
+
span.setAttribute("messaging.message.body.size", Buffer.byteLength(JSON.stringify(payload)));
|
|
23393
|
+
const result = await queue.send(def.topic, payload, {
|
|
23394
|
+
delaySeconds: options.delayMs && options.delayMs > 0 ? Math.ceil(options.delayMs / 1e3) : void 0,
|
|
23395
|
+
idempotencyKey: options.idempotencyKey,
|
|
23396
|
+
retentionSeconds: QUEUE_SIGNATURE_MAX_AGE_MS / 1e3
|
|
23397
|
+
});
|
|
23398
|
+
if (result.messageId) span.setAttribute("messaging.message.id", result.messageId);
|
|
23399
|
+
});
|
|
23400
|
+
};
|
|
23401
|
+
const consumer = ({ queue, leaseMs }, run) => ({
|
|
23402
|
+
handler: async (value, metadata) => {
|
|
23403
|
+
const checked = verifyQueueMessage(def.sign, value);
|
|
23404
|
+
if (checked.status === "rejected") {
|
|
23405
|
+
def.onRejected({
|
|
23406
|
+
"app.queue.consumer_group": metadata.consumerGroup,
|
|
23407
|
+
"app.queue.delivery_count": metadata.deliveryCount,
|
|
23408
|
+
"app.queue.message_id": metadata.messageId,
|
|
23409
|
+
"app.queue.reject_reason": checked.reason,
|
|
23410
|
+
"app.queue.topic_name": metadata.topicName
|
|
23411
|
+
});
|
|
23412
|
+
return;
|
|
23413
|
+
}
|
|
23414
|
+
if (checked.status === "unavailable") throw new Error(`Queue message verification unavailable: ${checked.reason}`);
|
|
23415
|
+
const message = checked.message;
|
|
23416
|
+
await withSpan("queue.process", {
|
|
23417
|
+
...def.attributes(message),
|
|
23418
|
+
"messaging.destination.name": metadata.topicName,
|
|
23419
|
+
"messaging.system": queue.messagingSystem,
|
|
23420
|
+
"messaging.message.id": metadata.messageId,
|
|
23421
|
+
"messaging.message.receive.latency": Date.now() - metadata.createdAt.getTime(),
|
|
23422
|
+
"messaging.message.retry.count": metadata.deliveryCount - 1
|
|
23423
|
+
}, () => run(message, metadata), {
|
|
23424
|
+
links: message.traceContext ? [message.traceContext] : [],
|
|
23425
|
+
newTrace: true
|
|
23426
|
+
});
|
|
23427
|
+
},
|
|
23428
|
+
retry: () => void 0,
|
|
23429
|
+
visibilityTimeoutSeconds: leaseMs / 1e3 + VISIBILITY_TIMEOUT_BUFFER_SECONDS
|
|
23430
|
+
});
|
|
23431
|
+
return {
|
|
23432
|
+
publish,
|
|
23433
|
+
consumer
|
|
23434
|
+
};
|
|
23435
|
+
}
|
|
23436
|
+
// src/core/turn/ended.ts
|
|
23437
|
+
const turnEndedMessageSchema = z.object({
|
|
23438
|
+
conversationId: z.string().min(1),
|
|
23439
|
+
turnId: z.string().min(1),
|
|
23440
|
+
traceContext: z.object({ sentryTrace: z.string().min(1) }).strict().optional()
|
|
23441
|
+
}).strict();
|
|
23442
|
+
const turnEndedTopic = signedTopic({
|
|
23443
|
+
topic: TURN_ENDED_TOPIC,
|
|
23444
|
+
sign: {
|
|
23445
|
+
context: "junior.turn_ended.v1",
|
|
23446
|
+
schema: turnEndedMessageSchema,
|
|
23447
|
+
signatureVersion: "v1",
|
|
23448
|
+
parts: (message) => [
|
|
23449
|
+
message.conversationId,
|
|
23450
|
+
message.turnId,
|
|
23451
|
+
message.traceContext?.sentryTrace ?? ""
|
|
23452
|
+
]
|
|
23453
|
+
},
|
|
23454
|
+
onRejected: (attributes) => logWarn("turn.ended.queue_message.rejected", attributes),
|
|
23455
|
+
attributes: (message) => ({
|
|
23456
|
+
"app.turn.id": message.turnId,
|
|
23457
|
+
"gen_ai.conversation.id": message.conversationId
|
|
23458
|
+
})
|
|
23459
|
+
});
|
|
23460
|
+
/**
|
|
23461
|
+
* Sends the message that the Turn ended, after `delayMs` if set. A handler
|
|
23462
|
+
* that must try its work again later sends it again with a delay.
|
|
23463
|
+
*/
|
|
23464
|
+
async function publishTurnEnded(ctx, message, options = {}) {
|
|
23465
|
+
await turnEndedTopic.publish(ctx, message, options);
|
|
23466
|
+
}
|
|
23467
|
+
/**
|
|
23468
|
+
* Reads the messages that a Turn ended: it checks that core sent each one,
|
|
23469
|
+
* then calls `handle`. It acknowledges a message with a bad or expired
|
|
23470
|
+
* signature and retries one that cannot be checked yet. The host mounts the
|
|
23471
|
+
* consumer on its queue provider.
|
|
23472
|
+
*/
|
|
23473
|
+
function readTurnEndedMessages(ctx, handle) {
|
|
23474
|
+
return turnEndedTopic.consumer(ctx, (message, metadata) => handle({
|
|
23475
|
+
conversationId: message.conversationId,
|
|
23476
|
+
turnId: message.turnId
|
|
23477
|
+
}, metadata));
|
|
23478
|
+
}
|
|
23479
|
+
// src/core/turn/inbox.ts
|
|
23480
|
+
/**
|
|
23481
|
+
* Finds the Turn of the input that has this idempotency key in the
|
|
23482
|
+
* Conversation. Undefined when no such input exists.
|
|
23483
|
+
*/
|
|
23484
|
+
async function findInputTurn({ executor }, args) {
|
|
23485
|
+
const [turn] = await executor.db().select({
|
|
23486
|
+
turnId: juniorTurns.id,
|
|
23487
|
+
state: juniorTurns.state
|
|
23488
|
+
}).from(juniorTurnInbox).innerJoin(juniorTurns, eq(juniorTurns.id, juniorTurnInbox.turnId)).where(and(eq(juniorTurnInbox.conversationId, args.conversationId), eq(juniorTurnInbox.idempotencyKey, args.idempotencyKey)));
|
|
23489
|
+
return turn;
|
|
23490
|
+
}
|
|
23491
|
+
/**
|
|
23492
|
+
* Finds where a Turn's answer goes: the Destination of its first input. Null
|
|
23493
|
+
* when the Turn answers only in the Conversation history.
|
|
23494
|
+
*/
|
|
23495
|
+
async function findTurnDestination({ executor }, turnId) {
|
|
23496
|
+
const [input] = await executor.db().select({ destination: juniorTurnInbox.destination }).from(juniorTurnInbox).where(eq(juniorTurnInbox.turnId, turnId)).orderBy(asc(juniorTurnInbox.createdAt), asc(juniorTurnInbox.id)).limit(1);
|
|
23497
|
+
return input?.destination ?? null;
|
|
23498
|
+
}
|
|
23499
|
+
/**
|
|
23500
|
+
* Finds who a Turn acts for: the sender of its first input. Undefined when
|
|
23501
|
+
* the Turn has no input.
|
|
23502
|
+
*/
|
|
23503
|
+
async function findTurnActor({ executor }, turnId) {
|
|
23504
|
+
const [input] = await executor.db().select({ actorIdentityId: juniorTurnInbox.actorIdentityId }).from(juniorTurnInbox).where(eq(juniorTurnInbox.turnId, turnId)).orderBy(asc(juniorTurnInbox.createdAt), asc(juniorTurnInbox.id)).limit(1);
|
|
23505
|
+
return input?.actorIdentityId;
|
|
23506
|
+
}
|
|
23507
|
+
/** Finds every input of a Turn, oldest first. */
|
|
23508
|
+
async function findTurnInputs({ executor }, turnId) {
|
|
23509
|
+
return executor.db().select({
|
|
23510
|
+
inputId: juniorTurnInbox.id,
|
|
23511
|
+
payload: juniorTurnInbox.payload
|
|
23512
|
+
}).from(juniorTurnInbox).where(eq(juniorTurnInbox.turnId, turnId)).orderBy(asc(juniorTurnInbox.sentAt), asc(juniorTurnInbox.createdAt));
|
|
23513
|
+
}
|
|
23514
|
+
const INPUT_EVENT_KEY_PREFIX = "inbox:";
|
|
23515
|
+
/** The idempotency key of the history event that reads an input. */
|
|
23516
|
+
function inputEventKey(inputId) {
|
|
23517
|
+
return `${INPUT_EVENT_KEY_PREFIX}${inputId}`;
|
|
23518
|
+
}
|
|
23519
|
+
function unreadOf({ executor }, turnId) {
|
|
23520
|
+
const readEvent = executor.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`)));
|
|
23521
|
+
return and(eq(juniorTurnInbox.turnId, turnId), notExists(readEvent));
|
|
23522
|
+
}
|
|
23523
|
+
const unreadColumns = {
|
|
23524
|
+
inputId: juniorTurnInbox.id,
|
|
23525
|
+
actorIdentityId: juniorTurnInbox.actorIdentityId,
|
|
23526
|
+
groupKey: juniorTurnInbox.groupKey,
|
|
23527
|
+
payload: juniorTurnInbox.payload,
|
|
23528
|
+
sentAt: juniorTurnInbox.sentAt,
|
|
23529
|
+
traceContext: juniorTurnInbox.traceContext,
|
|
23530
|
+
attemptedAt: juniorTurnInbox.attemptedAt
|
|
23531
|
+
};
|
|
23532
|
+
/** Finds the inputs of a Turn that the history has not read, oldest first. */
|
|
23533
|
+
async function findUnreadInputs({ executor }, turnId) {
|
|
23534
|
+
return executor.db().select(unreadColumns).from(juniorTurnInbox).where(unreadOf({ executor }, turnId)).orderBy(asc(juniorTurnInbox.sentAt), asc(juniorTurnInbox.createdAt));
|
|
23535
|
+
}
|
|
23536
|
+
/** Finds the unread inputs of a Turn, oldest first, with their Source. */
|
|
23537
|
+
async function findSourcedUnreadInputs({ executor }, turnId) {
|
|
23538
|
+
return executor.db().select({
|
|
23539
|
+
...unreadColumns,
|
|
23540
|
+
idempotencyKey: juniorTurnInbox.idempotencyKey,
|
|
23541
|
+
source: juniorTurnInbox.source,
|
|
23542
|
+
receivedAt: juniorTurnInbox.createdAt
|
|
23543
|
+
}).from(juniorTurnInbox).where(unreadOf({ executor }, turnId)).orderBy(asc(juniorTurnInbox.sentAt), asc(juniorTurnInbox.createdAt));
|
|
23544
|
+
}
|
|
23545
|
+
/**
|
|
23546
|
+
* Records that an attempt of the Turn claimed it with these inputs unread.
|
|
23547
|
+
* The first attempt keeps its time. It does not mark the inputs read.
|
|
23548
|
+
*/
|
|
23549
|
+
async function markInputsAttempted({ executor }, inputIds) {
|
|
23550
|
+
if (inputIds.length === 0) return;
|
|
23551
|
+
await executor.db().update(juniorTurnInbox).set({ attemptedAt: sql`coalesce(${juniorTurnInbox.attemptedAt}, now())` }).where(inArray(juniorTurnInbox.id, inputIds));
|
|
23552
|
+
}
|
|
23553
|
+
// src/core/turn/queue.ts
|
|
23554
|
+
const turnStepMessageSchema = z.object({
|
|
23555
|
+
turnId: z.string().min(1),
|
|
23556
|
+
traceContext: z.object({ sentryTrace: z.string().min(1) }).strict().optional()
|
|
23557
|
+
}).strict();
|
|
23558
|
+
const turnStepTopic = signedTopic({
|
|
23559
|
+
topic: TURN_STEP_TOPIC,
|
|
23560
|
+
sign: {
|
|
23561
|
+
context: "junior.turn_step.v1",
|
|
23562
|
+
schema: turnStepMessageSchema,
|
|
23563
|
+
signatureVersion: "v1",
|
|
23564
|
+
parts: (message) => [message.turnId, message.traceContext?.sentryTrace ?? ""]
|
|
23565
|
+
},
|
|
23566
|
+
onRejected: (attributes) => logWarn("turn.step.queue_message.rejected", attributes),
|
|
23567
|
+
attributes: (message) => ({ "app.turn.id": message.turnId })
|
|
23568
|
+
});
|
|
23569
|
+
/**
|
|
23570
|
+
* Sends a message that runs the next step of a Turn. `idempotencyKey` drops a
|
|
23571
|
+
* second send with the same key.
|
|
23572
|
+
*/
|
|
23573
|
+
async function publishTurnStep(ctx, turnId, options = {}) {
|
|
23574
|
+
await turnStepTopic.publish(ctx, { turnId }, options);
|
|
23575
|
+
}
|
|
23576
|
+
/**
|
|
23577
|
+
* Builds the queue consumer of Turn step messages. It acknowledges a message
|
|
23578
|
+
* with a bad or expired signature and retries one that cannot be checked yet.
|
|
23579
|
+
* advanceTurn fails a Turn after `maxAttempts` tries of one step. The host
|
|
23580
|
+
* mounts the consumer on its queue provider.
|
|
23581
|
+
*/
|
|
23582
|
+
function createTurnStepConsumer(ctx, run) {
|
|
23583
|
+
return turnStepTopic.consumer(ctx, (message, metadata) => run({ turnId: message.turnId }, metadata));
|
|
23584
|
+
}
|
|
23585
|
+
// src/db/postgres-json.ts
|
|
23586
|
+
/**
|
|
23587
|
+
* Replace actual NUL characters that PostgreSQL cannot store in JSONB.
|
|
23588
|
+
* Literal `\\u0000` text is preserved because it contains no NUL character.
|
|
23589
|
+
*/
|
|
23590
|
+
function sanitizePostgresJson(value) {
|
|
23591
|
+
if (typeof value === "string") return value.replaceAll("\0", " ");
|
|
23592
|
+
if (Array.isArray(value)) return value.map((item) => sanitizePostgresJson(item));
|
|
23593
|
+
if (value === null || typeof value !== "object") return value;
|
|
23594
|
+
const prototype = Object.getPrototypeOf(value);
|
|
23595
|
+
if (prototype !== Object.prototype && prototype !== null) return value;
|
|
23596
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, sanitizePostgresJson(item)]));
|
|
23597
|
+
}
|
|
23598
|
+
// src/conversation-events/store.ts
|
|
23599
|
+
/** Read the next seq and the current History version of a Conversation. */
|
|
23600
|
+
async function readEventCursor(executor, conversationId) {
|
|
23601
|
+
const [row] = await executor.db().select({
|
|
23602
|
+
maxSeq: sql`max(${juniorConversationEvents.seq})`,
|
|
23603
|
+
maxHistoryVersion: sql`max(${juniorConversationEvents.historyVersion})`
|
|
23604
|
+
}).from(juniorConversationEvents).where(eq(juniorConversationEvents.conversationId, conversationId));
|
|
23605
|
+
return {
|
|
23606
|
+
nextSeq: row?.maxSeq == null ? 0 : Number(row.maxSeq) + 1,
|
|
23607
|
+
historyVersion: row?.maxHistoryVersion == null ? 0 : Number(row.maxHistoryVersion)
|
|
23608
|
+
};
|
|
23609
|
+
}
|
|
23610
|
+
/**
|
|
23611
|
+
* Drop the events whose idempotency key is already stored, or repeats an
|
|
23612
|
+
* earlier event of the same call. Events without a key are always kept.
|
|
23613
|
+
*/
|
|
23614
|
+
async function unseenEvents(executor, conversationId, events) {
|
|
23615
|
+
const keys = events.flatMap((event) => event.idempotencyKey === void 0 ? [] : [event.idempotencyKey]);
|
|
23616
|
+
const seen = /* @__PURE__ */ new Set();
|
|
23617
|
+
if (keys.length > 0) {
|
|
23618
|
+
const rows = await executor.db().select({ key: juniorConversationEvents.idempotencyKey }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), inArray(juniorConversationEvents.idempotencyKey, keys)));
|
|
23619
|
+
for (const row of rows) if (row.key) seen.add(row.key);
|
|
23620
|
+
}
|
|
23621
|
+
return events.filter((event) => {
|
|
23622
|
+
if (event.idempotencyKey === void 0) return true;
|
|
23623
|
+
if (seen.has(event.idempotencyKey)) return false;
|
|
23624
|
+
seen.add(event.idempotencyKey);
|
|
23625
|
+
return true;
|
|
23626
|
+
});
|
|
23627
|
+
}
|
|
23628
|
+
/** Store rows in order from the cursor, at its History version. */
|
|
23629
|
+
async function insertEventRows(executor, conversationId, cursor, rows) {
|
|
23630
|
+
return await insertAt(executor, conversationId, cursor.historyVersion, rows.map((row, index) => ({
|
|
23631
|
+
row,
|
|
23632
|
+
seq: cursor.nextSeq + index
|
|
23633
|
+
})));
|
|
23634
|
+
}
|
|
23635
|
+
/**
|
|
23636
|
+
* Store a History replacement row. It starts the next History version, so
|
|
23637
|
+
* every later row belongs to the history that it sets.
|
|
23638
|
+
*/
|
|
23639
|
+
async function insertHistoryReplacementRow(executor, conversationId, cursor, row) {
|
|
23640
|
+
const [inserted] = await insertAt(executor, conversationId, cursor.historyVersion + 1, [{
|
|
23641
|
+
row,
|
|
23642
|
+
seq: cursor.nextSeq
|
|
23643
|
+
}]);
|
|
23644
|
+
return inserted;
|
|
23645
|
+
}
|
|
23646
|
+
async function insertAt(executor, conversationId, historyVersion, rows) {
|
|
23647
|
+
const values = rows.map(({ row, seq }) => ({
|
|
23648
|
+
conversationId,
|
|
23649
|
+
seq,
|
|
23650
|
+
historyVersion,
|
|
23651
|
+
schemaVersion: row.schemaVersion,
|
|
23652
|
+
idempotencyKey: row.idempotencyKey ?? null,
|
|
23653
|
+
type: row.type,
|
|
23654
|
+
payload: sanitizePostgresJson(row.payload),
|
|
23655
|
+
actorIdentityId: row.actorIdentityId ?? null,
|
|
23656
|
+
turnId: row.turnId ?? null,
|
|
23657
|
+
createdAt: new Date(row.createdAtMs)
|
|
23658
|
+
}));
|
|
23659
|
+
if (values.length === 0) return [];
|
|
23660
|
+
const db = executor.db();
|
|
23661
|
+
await db.with(conversationDetailTouch(db, [conversationId])).insert(juniorConversationEvents).values(values);
|
|
23662
|
+
return values;
|
|
23663
|
+
}
|
|
23664
|
+
// src/core/history/write.ts
|
|
23665
|
+
/**
|
|
23666
|
+
* Appends the agent history items that one Turn writes, in order, at the
|
|
23667
|
+
* current History version. Skips an item whose idempotency key is already
|
|
23668
|
+
* stored. Call it under `withConversationEventLock`.
|
|
23669
|
+
*/
|
|
23670
|
+
async function appendAgentHistory(executor, conversationId, turnId, items) {
|
|
23671
|
+
const pending = await unseenEvents(executor, conversationId, items);
|
|
23672
|
+
if (pending.length === 0) return;
|
|
23673
|
+
await insertEventRows(executor, conversationId, await readEventCursor(executor, conversationId), pending.map(({ item, idempotencyKey, createdAtMs }) => ({
|
|
23674
|
+
type: item.type,
|
|
23675
|
+
...encodeAgentHistoryPayload(item),
|
|
23676
|
+
idempotencyKey,
|
|
23677
|
+
turnId,
|
|
23678
|
+
createdAtMs
|
|
23679
|
+
})));
|
|
23680
|
+
}
|
|
23681
|
+
// src/core/turn/replies.ts
|
|
23682
|
+
const LEGACY_NO_REPLY_MARKERS = ["[[NO_REPLY]]", "[[QUIET]]"];
|
|
23683
|
+
const THINKING_BLOCK_PATTERN = /[ \t]*<thinking\b[^>]*>[\s\S]*?<\/thinking>[ \t]*(?:\r?\n)?/gi;
|
|
23684
|
+
function isClosedFence(source) {
|
|
23685
|
+
const opener = source.trimStart();
|
|
23686
|
+
const marker = opener.startsWith("```") ? "`" : opener.startsWith("~~~") ? "~" : void 0;
|
|
23687
|
+
const lastLine = source.lastIndexOf("\n");
|
|
23688
|
+
let closer = lastLine < 0 ? "" : source.slice(lastLine + 1).trim();
|
|
23689
|
+
while (closer.startsWith(">")) closer = closer.slice(1).trimStart();
|
|
23690
|
+
return marker !== void 0 && closer.length >= 3 && closer === marker.repeat(closer.length);
|
|
23691
|
+
}
|
|
23692
|
+
function stripThinking(text) {
|
|
23693
|
+
let result = "";
|
|
23694
|
+
let cursor = 0;
|
|
23695
|
+
for (const { position } of markdownNodes(parseMarkdown(text), ["code"])) {
|
|
23696
|
+
const start = position?.start.offset ?? 0;
|
|
23697
|
+
const end = position?.end.offset ?? 0;
|
|
23698
|
+
if (!isClosedFence(text.slice(start, end))) continue;
|
|
23699
|
+
result += text.slice(cursor, start).replace(THINKING_BLOCK_PATTERN, "");
|
|
23700
|
+
result += text.slice(start, end);
|
|
23701
|
+
cursor = end;
|
|
23702
|
+
}
|
|
23703
|
+
return result + text.slice(cursor).replace(THINKING_BLOCK_PATTERN, "");
|
|
23704
|
+
}
|
|
23705
|
+
/**
|
|
23706
|
+
* The text that an assistant message delivers to a person, or undefined when
|
|
23707
|
+
* it is no reply. Text next to a tool call is the model working, not a reply.
|
|
23708
|
+
*/
|
|
23709
|
+
function assistantReplyText(message) {
|
|
23710
|
+
if (message.content.some((part) => part.type === "toolCall")) return;
|
|
23711
|
+
const text = stripThinking(message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n")).trim();
|
|
23712
|
+
return text && !LEGACY_NO_REPLY_MARKERS.includes(text) ? text : void 0;
|
|
23713
|
+
}
|
|
23714
|
+
/** The key prefix of the message events that a Turn's steps wrote. */
|
|
23715
|
+
function turnEventKeyPrefix(turnId) {
|
|
23716
|
+
return `step:${turnId}:`;
|
|
23717
|
+
}
|
|
23718
|
+
/** The text that a message event delivers, or undefined when it is no reply. */
|
|
23719
|
+
function replyText(row) {
|
|
23720
|
+
if (row.type !== "assistant_message") return;
|
|
23721
|
+
const data = agentHistoryFromRow(row);
|
|
23722
|
+
if (data.type !== "assistant_message") return;
|
|
23723
|
+
const message = piMessageFromHistoryItem(data);
|
|
23724
|
+
return message.role === "assistant" ? assistantReplyText(message) : void 0;
|
|
23725
|
+
}
|
|
23726
|
+
/** Finds the reply events of a Turn, in history order. */
|
|
23727
|
+
async function findTurnReplies({ executor }, conversationId, turnId) {
|
|
23728
|
+
return (await executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "assistant_message"), like(juniorConversationEvents.idempotencyKey, `${turnEventKeyPrefix(turnId)}%`))).orderBy(asc(juniorConversationEvents.seq))).filter((row) => replyText(row) !== void 0);
|
|
23729
|
+
}
|
|
23730
|
+
// src/core/turn/outbox.ts
|
|
23731
|
+
/**
|
|
23732
|
+
* Adds an outbox row for each reply of the Turn that has none, but only while
|
|
23733
|
+
* the Turn has a Destination. Call it in the transaction that commits the
|
|
23734
|
+
* replies.
|
|
23735
|
+
*/
|
|
23736
|
+
async function recordReplies({ executor }, turn) {
|
|
23737
|
+
const destination = await findTurnDestination({ executor }, turn.turnId);
|
|
23738
|
+
if (!destination) return;
|
|
23739
|
+
const replies = await findTurnReplies({ executor }, turn.conversationId, turn.turnId);
|
|
23740
|
+
if (replies.length === 0) return;
|
|
23741
|
+
await executor.db().insert(juniorTurnOutbox).values(replies.map((row) => ({
|
|
23742
|
+
id: randomUUID(),
|
|
23743
|
+
conversationId: turn.conversationId,
|
|
23744
|
+
turnId: turn.turnId,
|
|
23745
|
+
eventSeq: row.seq,
|
|
23746
|
+
destination,
|
|
23747
|
+
state: "pending"
|
|
23748
|
+
}))).onConflictDoNothing({ target: [juniorTurnOutbox.conversationId, juniorTurnOutbox.eventSeq] });
|
|
23749
|
+
}
|
|
23750
|
+
// src/core/turn/state.ts
|
|
23751
|
+
/**
|
|
23752
|
+
* Turn priorities: a lower number runs first. A Turn that supersedes the
|
|
23753
|
+
* running Turn runs before every other queued Turn.
|
|
23754
|
+
*/
|
|
23755
|
+
const TURN_PRIORITY = {
|
|
23756
|
+
supersede: 0,
|
|
23757
|
+
normal: 1
|
|
23758
|
+
};
|
|
23759
|
+
const SUPERSEDED_END = {
|
|
23760
|
+
state: "cancelled",
|
|
23761
|
+
endReason: "superseded",
|
|
23762
|
+
endedAt: sql`now()`
|
|
23763
|
+
};
|
|
23764
|
+
function leaseExpiry(leaseMs) {
|
|
23765
|
+
return sql`now() + ${leaseMs}::integer * interval '1 millisecond'`;
|
|
23766
|
+
}
|
|
23767
|
+
function leaseFence(lease) {
|
|
23768
|
+
return and(eq(juniorTurns.id, lease.turnId), eq(juniorTurns.state, "running"), eq(juniorTurns.leaseEpoch, lease.leaseEpoch));
|
|
23769
|
+
}
|
|
23770
|
+
/**
|
|
23771
|
+
* Inserts a queued Turn. It sends no step message: the caller publishes the
|
|
23772
|
+
* Turn after its transaction commits, so a worker can claim it.
|
|
23773
|
+
*/
|
|
23774
|
+
async function createTurn({ executor }, args) {
|
|
23775
|
+
const turnId = randomUUID();
|
|
23776
|
+
await executor.db().insert(juniorTurns).values({
|
|
23777
|
+
...args,
|
|
23778
|
+
id: turnId,
|
|
23779
|
+
state: "queued"
|
|
23780
|
+
});
|
|
23781
|
+
return {
|
|
23782
|
+
turnId,
|
|
23783
|
+
state: "queued"
|
|
23784
|
+
};
|
|
23785
|
+
}
|
|
23786
|
+
/** Finds a Turn by id. Undefined when it does not exist. */
|
|
23787
|
+
async function findTurn({ executor }, turnId) {
|
|
23788
|
+
const [turn] = await executor.db().select({
|
|
23789
|
+
turnId: juniorTurns.id,
|
|
23790
|
+
state: juniorTurns.state,
|
|
23791
|
+
conversationId: juniorTurns.conversationId,
|
|
23792
|
+
failureCode: juniorTurns.failureCode,
|
|
23793
|
+
failureReason: juniorTurns.failureReason,
|
|
23794
|
+
failureEventId: juniorTurns.failureEventId,
|
|
23795
|
+
startedAt: juniorTurns.startedAt,
|
|
23796
|
+
endedAt: juniorTurns.endedAt
|
|
23797
|
+
}).from(juniorTurns).where(eq(juniorTurns.id, turnId));
|
|
23798
|
+
return turn;
|
|
23799
|
+
}
|
|
23800
|
+
/** Reads a Turn's discarded usage. Undefined when the Turn does not exist. */
|
|
23801
|
+
async function findDiscardedUsage({ executor }, turnId) {
|
|
23802
|
+
return selectDiscardedUsage({ executor }, eq(juniorTurns.id, turnId));
|
|
23803
|
+
}
|
|
23804
|
+
async function selectDiscardedUsage({ executor }, where) {
|
|
23805
|
+
const [turn] = await executor.db().select({
|
|
23806
|
+
costMicroUsd: juniorTurns.discardedCostMicroUsd,
|
|
23807
|
+
tokens: juniorTurns.discardedTokens
|
|
23808
|
+
}).from(juniorTurns).where(where);
|
|
23809
|
+
if (!turn) return;
|
|
23810
|
+
return turn.tokens === null ? { costMicroUsd: turn.costMicroUsd } : {
|
|
23811
|
+
costMicroUsd: turn.costMicroUsd,
|
|
23812
|
+
tokens: usageTokensSchema.parse(turn.tokens)
|
|
23813
|
+
};
|
|
23814
|
+
}
|
|
23815
|
+
async function discardedUsageUpdate({ executor }, lease, usage) {
|
|
23816
|
+
const current = usage ? await selectDiscardedUsage({ executor }, leaseFence(lease)) : void 0;
|
|
23817
|
+
if (!current) return {};
|
|
23818
|
+
const { cost: _, ...tokens } = addAgentTurnUsage(current.tokens, usage) ?? {};
|
|
23819
|
+
return {
|
|
23820
|
+
discardedCostMicroUsd: current.costMicroUsd + usdToMicroUsd(agentTurnCostUsd(usage) ?? 0),
|
|
23821
|
+
discardedTokens: tokens
|
|
23822
|
+
};
|
|
23823
|
+
}
|
|
23824
|
+
const runOrder = [
|
|
23825
|
+
sql`${juniorTurns.state} = 'running' desc`,
|
|
23826
|
+
asc(juniorTurns.priority),
|
|
23827
|
+
asc(juniorTurns.createdAt),
|
|
23828
|
+
asc(juniorTurns.id)
|
|
23829
|
+
];
|
|
23830
|
+
/**
|
|
23831
|
+
* Finds the Turn of a Conversation that has not ended: the running Turn, else
|
|
23832
|
+
* the next queued Turn by priority and age.
|
|
23833
|
+
*/
|
|
23834
|
+
async function findOpenTurn({ executor }, conversationId) {
|
|
23835
|
+
const [turn] = await executor.db().select({
|
|
23836
|
+
turnId: juniorTurns.id,
|
|
23837
|
+
state: juniorTurns.state
|
|
23838
|
+
}).from(juniorTurns).where(and(eq(juniorTurns.conversationId, conversationId), inArray(juniorTurns.state, ["queued", "running"]))).orderBy(...runOrder).limit(1);
|
|
23839
|
+
return turn;
|
|
23840
|
+
}
|
|
23841
|
+
/**
|
|
23842
|
+
* Finds the Turns of a Conversation that can still take inputs, in run order:
|
|
23843
|
+
* those that have not ended, less a running Turn that another Turn
|
|
23844
|
+
* supersedes.
|
|
23845
|
+
*/
|
|
23846
|
+
async function findOpenTurns({ executor }, conversationId) {
|
|
23847
|
+
return (await executor.db().select({
|
|
23848
|
+
turnId: juniorTurns.id,
|
|
23849
|
+
state: juniorTurns.state,
|
|
23850
|
+
groupKey: juniorTurnInbox.groupKey,
|
|
23851
|
+
stepSeq: juniorTurns.stepSeq,
|
|
23852
|
+
attempts: juniorTurns.attempts
|
|
23853
|
+
}).from(juniorTurns).innerJoin(juniorTurnInbox, eq(juniorTurnInbox.turnId, juniorTurns.id)).where(and(eq(juniorTurns.conversationId, conversationId), or(eq(juniorTurns.state, "queued"), and(eq(juniorTurns.state, "running"), notExists(turnAhead({ executor })))))).groupBy(juniorTurns.id, juniorTurnInbox.groupKey).orderBy(...runOrder)).map(({ stepSeq, attempts, ...turn }) => ({
|
|
23854
|
+
...turn,
|
|
23855
|
+
started: stepSeq > 0 || attempts > 0
|
|
23856
|
+
}));
|
|
23857
|
+
}
|
|
23858
|
+
function turnAhead({ executor }) {
|
|
23859
|
+
const ahead = alias(juniorTurns, "ahead");
|
|
23860
|
+
return executor.db().select({ one: sql`1` }).from(ahead).where(and(eq(ahead.conversationId, juniorTurns.conversationId), ne(ahead.id, juniorTurns.id), or(eq(ahead.state, "running"), and(eq(ahead.state, "queued"), sql`(${ahead.priority}, ${ahead.createdAt}, ${ahead.id}) < (${juniorTurns.priority}, ${juniorTurns.createdAt}, ${juniorTurns.id})`))));
|
|
23861
|
+
}
|
|
23862
|
+
async function isSuperseded({ executor }, turnId) {
|
|
23863
|
+
return (await executor.db().select({ id: juniorTurns.id }).from(juniorTurns).where(and(eq(juniorTurns.id, turnId), exists(turnAhead({ executor }))))).length > 0;
|
|
23864
|
+
}
|
|
23865
|
+
/**
|
|
23866
|
+
* Makes way for a Turn that supersedes this one. Call it under the
|
|
23867
|
+
* Conversation lock. A queued Turn has no step in flight, so it ends now and
|
|
23868
|
+
* moves `lease_epoch`. A running Turn moves behind the new Turn, and
|
|
23869
|
+
* `commitStep` or `releaseTurn` ends it, so the step's work is kept. True
|
|
23870
|
+
* when the Turn ended now.
|
|
23871
|
+
*/
|
|
23872
|
+
async function supersedeTurn({ executor }, turnId) {
|
|
23873
|
+
const db = executor.db();
|
|
23874
|
+
const ended = await db.update(juniorTurns).set({
|
|
23875
|
+
...SUPERSEDED_END,
|
|
23876
|
+
leaseEpoch: sql`${juniorTurns.leaseEpoch} + 1`,
|
|
23877
|
+
updatedAt: sql`now()`
|
|
23878
|
+
}).where(and(eq(juniorTurns.id, turnId), eq(juniorTurns.state, "queued"))).returning({ id: juniorTurns.id });
|
|
23879
|
+
await db.update(juniorTurns).set({
|
|
23880
|
+
priority: TURN_PRIORITY.normal,
|
|
23881
|
+
updatedAt: sql`now()`
|
|
23882
|
+
}).where(and(eq(juniorTurns.id, turnId), eq(juniorTurns.state, "running")));
|
|
23883
|
+
return ended.length > 0;
|
|
23884
|
+
}
|
|
23885
|
+
/**
|
|
23886
|
+
* Claims a Turn to run its next step: the Conversation's next queued Turn, or
|
|
23887
|
+
* a running Turn whose lease expired, so the queue's redelivery after a crash
|
|
23888
|
+
* resumes it. Any other Turn gets undefined, so one of two racing claims wins,
|
|
23889
|
+
* and a Conversation runs one Turn at a time, in order. Each claim moves
|
|
23890
|
+
* `lease_epoch` and `attempts` and holds the Conversation lock.
|
|
23891
|
+
*/
|
|
23892
|
+
async function claimTurn({ executor, owner, leaseMs }, turnId) {
|
|
23893
|
+
const turn = await findTurn({ executor }, turnId);
|
|
23894
|
+
if (!turn) return;
|
|
23895
|
+
const claim = () => executor.db().update(juniorTurns).set({
|
|
23896
|
+
state: "running",
|
|
23897
|
+
leaseOwner: owner,
|
|
23898
|
+
leaseExpiresAt: leaseExpiry(leaseMs),
|
|
23899
|
+
leaseEpoch: sql`${juniorTurns.leaseEpoch} + 1`,
|
|
23900
|
+
attempts: sql`${juniorTurns.attempts} + 1`,
|
|
23901
|
+
startedAt: sql`coalesce(${juniorTurns.startedAt}, now())`,
|
|
23902
|
+
updatedAt: sql`now()`
|
|
23903
|
+
}).where(and(eq(juniorTurns.id, turnId), or(and(eq(juniorTurns.state, "queued"), notExists(turnAhead({ executor }))), and(eq(juniorTurns.state, "running"), lte(juniorTurns.leaseExpiresAt, sql`now()`))))).returning({
|
|
23904
|
+
turnId: juniorTurns.id,
|
|
23905
|
+
leaseEpoch: juniorTurns.leaseEpoch,
|
|
23906
|
+
conversationId: juniorTurns.conversationId,
|
|
23907
|
+
stepSeq: juniorTurns.stepSeq,
|
|
23908
|
+
attempts: juniorTurns.attempts
|
|
23909
|
+
});
|
|
23910
|
+
const [claimed] = await executor.transaction(() => withConversationEventLock(executor, turn.conversationId, claim));
|
|
23911
|
+
return claimed;
|
|
23912
|
+
}
|
|
23913
|
+
/**
|
|
23914
|
+
* Checks without a write that the lease still holds: the Turn runs under the
|
|
23915
|
+
* caller's `lease_epoch`. False after a cancel or a takeover.
|
|
23916
|
+
*/
|
|
23917
|
+
async function holdsLease({ executor }, lease) {
|
|
23918
|
+
return (await executor.db().select({ id: juniorTurns.id }).from(juniorTurns).where(leaseFence(lease))).length > 0;
|
|
23919
|
+
}
|
|
23920
|
+
/**
|
|
23921
|
+
* Finds Turns that a claim could take now but that no message is likely to
|
|
23922
|
+
* reach: the next queued Turn of its Conversation, unchanged for `staleMs`,
|
|
23923
|
+
* and running Turns whose lease expired `staleMs` ago. The queue redelivers
|
|
23924
|
+
* a dead step's message soon after its lease expires, so only a Turn that
|
|
23925
|
+
* missed that redelivery is stalled.
|
|
23926
|
+
*/
|
|
23927
|
+
async function findStalledTurns({ executor }, { staleMs, limit }) {
|
|
23928
|
+
const staleBefore = sql`now() - make_interval(secs => ${staleMs / 1e3})`;
|
|
23929
|
+
const rows = await executor.db().select({
|
|
23930
|
+
turnId: juniorTurns.id,
|
|
23931
|
+
conversationId: juniorTurns.conversationId,
|
|
23932
|
+
state: juniorTurns.state,
|
|
23933
|
+
updatedAt: juniorTurns.updatedAt,
|
|
23934
|
+
leaseExpiresAt: juniorTurns.leaseExpiresAt
|
|
23935
|
+
}).from(juniorTurns).where(or(and(eq(juniorTurns.state, "queued"), lt(juniorTurns.updatedAt, staleBefore), notExists(turnAhead({ executor }))), and(eq(juniorTurns.state, "running"), lt(juniorTurns.leaseExpiresAt, staleBefore)))).limit(limit);
|
|
23936
|
+
const nowMs = Date.now();
|
|
23937
|
+
return rows.map((row) => {
|
|
23938
|
+
const since = row.state === "running" && row.leaseExpiresAt ? row.leaseExpiresAt : row.updatedAt;
|
|
23939
|
+
return {
|
|
23940
|
+
turnId: row.turnId,
|
|
23941
|
+
conversationId: row.conversationId,
|
|
23942
|
+
reason: row.state === "running" ? "lease_expired" : "queued_lost",
|
|
23943
|
+
stalledMs: Math.max(0, nowMs - since.getTime())
|
|
23944
|
+
};
|
|
23945
|
+
});
|
|
23946
|
+
}
|
|
23947
|
+
/**
|
|
23948
|
+
* The idempotency key of one message event of a step. It names the Turn and
|
|
23949
|
+
* the step that wrote it, so Delivery finds a Turn's replies without reading
|
|
23950
|
+
* the rest of the history.
|
|
23951
|
+
*/
|
|
23952
|
+
function stepEventKey(turnId, stepSeq, index) {
|
|
23953
|
+
return `${turnEventKeyPrefix(turnId)}${stepSeq}:${index}`;
|
|
23954
|
+
}
|
|
23955
|
+
/**
|
|
23956
|
+
* The idempotency key of one new message that a step's prompt added from a
|
|
23957
|
+
* message fragment. It is not a step event key, so Delivery does not read it.
|
|
23958
|
+
*/
|
|
23959
|
+
function promptEventKey(turnId, stepSeq, index) {
|
|
23960
|
+
return `prompt:${turnId}:${stepSeq}:${index}`;
|
|
23961
|
+
}
|
|
23962
|
+
/**
|
|
23963
|
+
* Commits a step in one transaction: appends the prompt's new messages, with
|
|
23964
|
+
* the inputs the step read, then the step's messages to history, adds an
|
|
23965
|
+
* outbox row per new reply, and releases the lease. A Turn that continues
|
|
23966
|
+
* queues for a new claim. A `stale` final reply is not committed. Undefined,
|
|
23967
|
+
* with no write, when the lease is lost or the step is already committed.
|
|
23968
|
+
*/
|
|
23969
|
+
async function commitStep({ executor }, turn, step, prompt) {
|
|
23970
|
+
const nextStep = {
|
|
23971
|
+
stepSeq: sql`${juniorTurns.stepSeq} + 1`,
|
|
23972
|
+
attempts: 0,
|
|
23973
|
+
leaseOwner: null,
|
|
23974
|
+
leaseExpiresAt: null,
|
|
23975
|
+
updatedAt: sql`now()`
|
|
23976
|
+
};
|
|
23977
|
+
return executor.transaction(() => withConversationEventLock(executor, turn.conversationId, async () => {
|
|
23978
|
+
const outcome = await commitOutcome({ executor }, turn.turnId, step, prompt);
|
|
23979
|
+
if (outcome === "stale") return await requeueStep({ executor }, turn, step) ? outcome : void 0;
|
|
23980
|
+
if ((await executor.db().update(juniorTurns).set(outcome === "completed" ? {
|
|
23981
|
+
...nextStep,
|
|
23982
|
+
state: "completed",
|
|
23983
|
+
endedAt: sql`now()`
|
|
23984
|
+
} : outcome === "superseded" ? {
|
|
23985
|
+
...nextStep,
|
|
23986
|
+
...SUPERSEDED_END
|
|
23987
|
+
} : {
|
|
23988
|
+
...nextStep,
|
|
23989
|
+
state: "queued"
|
|
23990
|
+
}).where(and(leaseFence(turn), eq(juniorTurns.conversationId, turn.conversationId), eq(juniorTurns.stepSeq, turn.stepSeq))).returning({ id: juniorTurns.id })).length === 0) return;
|
|
23991
|
+
await appendAgentHistory(executor, turn.conversationId, turn.turnId, [...prompt.map((entry, index) => entry.source === "input" ? {
|
|
23992
|
+
item: historyItemFromPiMessage(entry.message, entry.provenance),
|
|
23993
|
+
idempotencyKey: inputEventKey(entry.inputId),
|
|
23994
|
+
createdAtMs: entry.message.timestamp
|
|
23995
|
+
} : {
|
|
23996
|
+
item: historyItemFromPiMessage(entry.message, contextProvenance),
|
|
23997
|
+
idempotencyKey: promptEventKey(turn.turnId, turn.stepSeq, index),
|
|
23998
|
+
createdAtMs: entry.message.timestamp
|
|
23999
|
+
}), ...step.messages.map((message, index) => ({
|
|
24000
|
+
item: historyItemFromPiMessage(message, contextProvenance),
|
|
24001
|
+
idempotencyKey: stepEventKey(turn.turnId, turn.stepSeq, index),
|
|
24002
|
+
createdAtMs: message.timestamp
|
|
24003
|
+
}))]);
|
|
24004
|
+
await recordReplies({ executor }, turn);
|
|
24005
|
+
return outcome;
|
|
24006
|
+
}));
|
|
24007
|
+
}
|
|
24008
|
+
/**
|
|
24009
|
+
* A completed step ends the Turn only when the commit reads every unread
|
|
24010
|
+
* input. The scheduler can add an input after the step read them, and the
|
|
24011
|
+
* Conversation lock keeps more out until the commit ends. A final reply that
|
|
24012
|
+
* missed an input is `stale`, so the Turn ends with one reply to every input.
|
|
24013
|
+
*/
|
|
24014
|
+
async function commitOutcome({ executor }, turnId, step, prompt) {
|
|
24015
|
+
if (step.outcome === "completed") {
|
|
24016
|
+
const read = new Set(prompt.flatMap((entry) => entry.source === "input" ? [entry.inputId] : []));
|
|
24017
|
+
if ((await findUnreadInputs({ executor }, turnId)).every((input) => read.has(input.inputId))) return "completed";
|
|
24018
|
+
}
|
|
24019
|
+
if (await isSuperseded({ executor }, turnId)) return "superseded";
|
|
24020
|
+
return step.outcome === "completed" && finalReplyOf(step) ? "stale" : "continue";
|
|
24021
|
+
}
|
|
24022
|
+
function finalReplyOf(step) {
|
|
24023
|
+
const [message] = step.messages;
|
|
24024
|
+
return message?.role === "assistant" ? message : void 0;
|
|
24025
|
+
}
|
|
24026
|
+
/**
|
|
24027
|
+
* Queues the Turn for the same step again, with nothing committed, after a
|
|
24028
|
+
* stale final reply. The attempt does not count: the step did not fail. The
|
|
24029
|
+
* dropped reply's usage adds to the Turn's discarded usage.
|
|
24030
|
+
*/
|
|
24031
|
+
async function requeueStep({ executor }, turn, step) {
|
|
24032
|
+
return (await executor.db().update(juniorTurns).set({
|
|
24033
|
+
...await discardedUsageUpdate({ executor }, turn, extractGenAiUsageSummary(finalReplyOf(step))),
|
|
24034
|
+
state: "queued",
|
|
24035
|
+
attempts: 0,
|
|
24036
|
+
leaseOwner: null,
|
|
24037
|
+
leaseExpiresAt: null,
|
|
24038
|
+
updatedAt: sql`now()`
|
|
24039
|
+
}).where(and(leaseFence(turn), eq(juniorTurns.conversationId, turn.conversationId), eq(juniorTurns.stepSeq, turn.stepSeq))).returning({ id: juniorTurns.id })).length > 0;
|
|
24040
|
+
}
|
|
24041
|
+
/**
|
|
24042
|
+
* Ends a running Turn as failed, with the reason and the failure details.
|
|
24043
|
+
* `discarded` is the usage of the model reply that the step drops. False when
|
|
24044
|
+
* the lease is lost. The engine calls it through `endFailedTurn`, which also
|
|
24045
|
+
* moves the Turn's late inputs.
|
|
24046
|
+
*/
|
|
24047
|
+
async function failTurn({ executor }, lease, endReason, failure, discarded) {
|
|
24048
|
+
return (await executor.db().update(juniorTurns).set({
|
|
24049
|
+
...await discardedUsageUpdate({ executor }, lease, discarded),
|
|
24050
|
+
state: "failed",
|
|
24051
|
+
endReason,
|
|
24052
|
+
failureCode: failure.failureCode,
|
|
24053
|
+
failureReason: failure.failureReason ?? null,
|
|
24054
|
+
failureEventId: failure.eventId ?? null,
|
|
24055
|
+
leaseOwner: null,
|
|
24056
|
+
leaseExpiresAt: null,
|
|
24057
|
+
updatedAt: sql`now()`,
|
|
24058
|
+
endedAt: sql`now()`
|
|
24059
|
+
}).where(leaseFence(lease)).returning({ id: juniorTurns.id })).length > 0;
|
|
24060
|
+
}
|
|
24061
|
+
/**
|
|
24062
|
+
* Queues a running Turn again after its invocation failed, so the queue's
|
|
24063
|
+
* retry can claim the step at once. The failed attempt still counts. A Turn
|
|
24064
|
+
* that another Turn supersedes ends instead, like at a commit. `discarded` is
|
|
24065
|
+
* the usage of the failed model reply that the retry drops. Returns the
|
|
24066
|
+
* Turn's new state, or undefined when the lease is lost.
|
|
24067
|
+
*/
|
|
24068
|
+
async function releaseTurn({ executor }, lease, discarded) {
|
|
24069
|
+
return executor.transaction(() => withConversationEventLock(executor, lease.conversationId, async () => {
|
|
24070
|
+
const released = {
|
|
24071
|
+
...await discardedUsageUpdate({ executor }, lease, discarded),
|
|
24072
|
+
leaseOwner: null,
|
|
24073
|
+
leaseExpiresAt: null,
|
|
24074
|
+
updatedAt: sql`now()`
|
|
24075
|
+
};
|
|
24076
|
+
return (await executor.db().update(juniorTurns).set(await isSuperseded({ executor }, lease.turnId) ? {
|
|
24077
|
+
...released,
|
|
24078
|
+
...SUPERSEDED_END
|
|
24079
|
+
} : {
|
|
24080
|
+
...released,
|
|
24081
|
+
state: "queued"
|
|
24082
|
+
}).where(leaseFence(lease)).returning({ state: juniorTurns.state }))[0]?.state;
|
|
24083
|
+
}));
|
|
24084
|
+
}
|
|
24085
|
+
/**
|
|
24086
|
+
* Cancels every queued and running Turn of a Conversation, with no lease, and
|
|
24087
|
+
* returns their ids in run order. Call it under the Conversation lock, as
|
|
24088
|
+
* `stopTurns` does. Moving each `lease_epoch` keeps a running step from
|
|
24089
|
+
* committing.
|
|
24090
|
+
*/
|
|
24091
|
+
async function cancelTurns({ executor }, conversationId) {
|
|
24092
|
+
const db = executor.db();
|
|
24093
|
+
const turnIds = (await db.select({ id: juniorTurns.id }).from(juniorTurns).where(and(eq(juniorTurns.conversationId, conversationId), inArray(juniorTurns.state, ["queued", "running"]))).orderBy(...runOrder)).map(({ id }) => id);
|
|
24094
|
+
if (turnIds.length === 0) return [];
|
|
24095
|
+
await db.update(juniorTurns).set({
|
|
24096
|
+
state: "cancelled",
|
|
24097
|
+
leaseEpoch: sql`${juniorTurns.leaseEpoch} + 1`,
|
|
24098
|
+
leaseOwner: null,
|
|
24099
|
+
leaseExpiresAt: null,
|
|
24100
|
+
updatedAt: sql`now()`,
|
|
24101
|
+
endedAt: sql`now()`
|
|
24102
|
+
}).where(inArray(juniorTurns.id, turnIds));
|
|
24103
|
+
return turnIds;
|
|
24104
|
+
}
|
|
24105
|
+
// src/core/turn/schedule.ts
|
|
24106
|
+
async function addInput({ executor }, input) {
|
|
24107
|
+
await executor.db().insert(juniorTurnInbox).values({
|
|
24108
|
+
...input,
|
|
24109
|
+
id: randomUUID()
|
|
24110
|
+
});
|
|
24111
|
+
}
|
|
24112
|
+
/**
|
|
24113
|
+
* The rule for which Turn takes an input that is not a duplicate. Core owns
|
|
24114
|
+
* it, so every Source schedules the same way, and the host decides who may
|
|
24115
|
+
* share a Turn through the group key. An input joins a Turn only when its
|
|
24116
|
+
* group key matches. An interrupt joins the Turn that has started, and an
|
|
24117
|
+
* interrupt with another group key supersedes that Turn. Any input
|
|
24118
|
+
* joins the last Turn in line while no step of it has started. Otherwise the
|
|
24119
|
+
* input waits in a new Turn at the end of the line, so A1 B1 A2 makes A2 wait
|
|
24120
|
+
* for B1. It runs under the Conversation lock, so `openTurns` cannot change
|
|
24121
|
+
* before the write.
|
|
24122
|
+
*/
|
|
24123
|
+
function assignTurn(input, openTurns) {
|
|
24124
|
+
const sameGroup = (turn) => turn.groupKey === input.groupKey;
|
|
24125
|
+
const started = openTurns.find((turn) => turn.started);
|
|
24126
|
+
if (input.delivery === "interrupt" && started) return sameGroup(started) ? { join: started } : {
|
|
24127
|
+
create: { priority: TURN_PRIORITY.supersede },
|
|
24128
|
+
supersede: started
|
|
24129
|
+
};
|
|
24130
|
+
const last = openTurns.at(-1);
|
|
24131
|
+
if (last && !last.started && sameGroup(last)) return { join: last };
|
|
24132
|
+
return { create: { priority: TURN_PRIORITY.normal } };
|
|
24133
|
+
}
|
|
24134
|
+
async function placeInput({ executor }, { delivery, ...input }) {
|
|
24135
|
+
const existing = await findInputTurn({ executor }, input);
|
|
24136
|
+
if (existing) return {
|
|
24137
|
+
turnId: existing.turnId,
|
|
24138
|
+
created: false,
|
|
24139
|
+
duplicate: true,
|
|
24140
|
+
publish: existing.state === "queued"
|
|
24141
|
+
};
|
|
24142
|
+
const openTurns = await findOpenTurns({ executor }, input.conversationId);
|
|
24143
|
+
const choice = assignTurn({
|
|
24144
|
+
...input,
|
|
24145
|
+
delivery
|
|
24146
|
+
}, openTurns);
|
|
24147
|
+
if ("join" in choice) {
|
|
24148
|
+
const { turnId } = choice.join;
|
|
24149
|
+
await addInput({ executor }, {
|
|
24150
|
+
...input,
|
|
24151
|
+
turnId
|
|
24152
|
+
});
|
|
24153
|
+
return {
|
|
24154
|
+
turnId,
|
|
24155
|
+
created: false,
|
|
24156
|
+
duplicate: false,
|
|
24157
|
+
publish: false
|
|
24158
|
+
};
|
|
24159
|
+
}
|
|
24160
|
+
const ended = choice.supersede && await supersedeTurn({ executor }, choice.supersede.turnId) ? choice.supersede.turnId : void 0;
|
|
24161
|
+
const turn = await createTurn({ executor }, {
|
|
24162
|
+
conversationId: input.conversationId,
|
|
24163
|
+
priority: choice.create.priority
|
|
24164
|
+
});
|
|
24165
|
+
await addInput({ executor }, {
|
|
24166
|
+
...input,
|
|
24167
|
+
turnId: turn.turnId
|
|
24168
|
+
});
|
|
24169
|
+
return {
|
|
24170
|
+
turnId: turn.turnId,
|
|
24171
|
+
created: true,
|
|
24172
|
+
duplicate: false,
|
|
24173
|
+
publish: openTurns.length === 0 || choice.supersede !== void 0,
|
|
24174
|
+
ended
|
|
24175
|
+
};
|
|
24176
|
+
}
|
|
24177
|
+
async function scheduleInput({ executor, queue }, { startDelayMs, ...input }, options = {}) {
|
|
24178
|
+
const placement = await withConversationEventLock(executor, input.conversationId, async () => options.admit && !await options.admit() ? void 0 : placeInput({ executor }, input));
|
|
24179
|
+
if (!placement) return { refused: true };
|
|
24180
|
+
if (placement.ended) await publishTurnEnded({ queue }, {
|
|
24181
|
+
conversationId: input.conversationId,
|
|
24182
|
+
turnId: placement.ended
|
|
24183
|
+
});
|
|
24184
|
+
if (placement.publish) await publishTurnStep({ queue }, placement.turnId, startDelayMs ? { delayMs: startDelayMs } : {});
|
|
24185
|
+
return {
|
|
24186
|
+
turnId: placement.turnId,
|
|
24187
|
+
created: placement.created,
|
|
24188
|
+
duplicate: placement.duplicate
|
|
24189
|
+
};
|
|
24190
|
+
}
|
|
24191
|
+
async function moveInputs({ executor }, inputIds, turnId) {
|
|
24192
|
+
await executor.db().update(juniorTurnInbox).set({ turnId }).where(inArray(juniorTurnInbox.id, inputIds));
|
|
24193
|
+
}
|
|
24194
|
+
/**
|
|
24195
|
+
* Moves inputs of one Turn that ended to the Turn that `assignTurn` picks for
|
|
24196
|
+
* a deferred input. They share the ended Turn's group key, so they move
|
|
24197
|
+
* together. Call it under the Conversation lock.
|
|
24198
|
+
*/
|
|
24199
|
+
async function moveToNextTurn({ executor }, conversationId, inputs) {
|
|
24200
|
+
const [first] = inputs;
|
|
24201
|
+
if (!first) return;
|
|
24202
|
+
const choice = assignTurn({
|
|
24203
|
+
...first,
|
|
24204
|
+
delivery: "defer"
|
|
24205
|
+
}, await findOpenTurns({ executor }, conversationId));
|
|
24206
|
+
const target = "join" in choice ? choice.join : await createTurn({ executor }, {
|
|
24207
|
+
conversationId,
|
|
24208
|
+
priority: choice.create.priority
|
|
24209
|
+
});
|
|
24210
|
+
await moveInputs({ executor }, inputs.map((input) => input.inputId), target.turnId);
|
|
24211
|
+
}
|
|
24212
|
+
/**
|
|
24213
|
+
* Ends a running Turn as failed and, in the same commit, moves its inputs
|
|
24214
|
+
* that arrived after its last claim to the next Turn; it drops the rest. A
|
|
24215
|
+
* crash after the commit loses no input: the sweep finds the queued Turn.
|
|
24216
|
+
* `discarded` is the usage of a failed model reply that the Turn drops.
|
|
24217
|
+
* False when the lease is lost, and then nothing changes.
|
|
24218
|
+
*/
|
|
24219
|
+
async function endFailedTurn({ executor }, lease, endReason, failure, discarded) {
|
|
24220
|
+
return executor.transaction(() => withConversationEventLock(executor, lease.conversationId, async () => {
|
|
24221
|
+
if (!await failTurn({ executor }, lease, endReason, failure, discarded)) return false;
|
|
24222
|
+
const leftovers = (await findUnreadInputs({ executor }, lease.turnId)).filter((input) => input.attemptedAt === null);
|
|
24223
|
+
await moveToNextTurn({ executor }, lease.conversationId, leftovers);
|
|
24224
|
+
return true;
|
|
24225
|
+
}));
|
|
24226
|
+
}
|
|
24227
|
+
/**
|
|
24228
|
+
* Stops a Conversation's work by sent time. In one commit under the lock it
|
|
24229
|
+
* cancels every queued and running Turn. Their unread inputs sent after
|
|
24230
|
+
* `sentAtOrBeforeMs` that `canMove` accepts move to a queued Turn; the rest,
|
|
24231
|
+
* or all of them with no cutoff, stay and drop. Then it reconciles each
|
|
24232
|
+
* stopped Turn.
|
|
24233
|
+
*/
|
|
24234
|
+
async function stopTurns({ executor, queue }, conversationId, { sentAtOrBeforeMs, canMove = () => true } = {}) {
|
|
24235
|
+
const afterCutoff = (input) => sentAtOrBeforeMs !== void 0 && input.sentAt.getTime() > sentAtOrBeforeMs && canMove(input);
|
|
24236
|
+
const stopped = await executor.transaction(() => withConversationEventLock(executor, conversationId, async () => {
|
|
24237
|
+
const turnIds = await cancelTurns({ executor }, conversationId);
|
|
24238
|
+
const dropped = [];
|
|
24239
|
+
const moved = [];
|
|
24240
|
+
for (const turnId of turnIds) {
|
|
24241
|
+
const unread = await findSourcedUnreadInputs({ executor }, turnId);
|
|
24242
|
+
const later = unread.filter(afterCutoff);
|
|
24243
|
+
dropped.push(...unread.filter((input) => !afterCutoff(input)));
|
|
24244
|
+
moved.push(...later);
|
|
24245
|
+
await moveToNextTurn({ executor }, conversationId, later);
|
|
24246
|
+
}
|
|
24247
|
+
return {
|
|
24248
|
+
turnIds,
|
|
24249
|
+
dropped,
|
|
24250
|
+
moved
|
|
24251
|
+
};
|
|
24252
|
+
}));
|
|
24253
|
+
for (const turnId of stopped.turnIds) try {
|
|
24254
|
+
await reconcileTurn({
|
|
24255
|
+
executor,
|
|
24256
|
+
queue
|
|
24257
|
+
}, turnId);
|
|
24258
|
+
} catch (error) {
|
|
24259
|
+
logException(error, "turn.stop.reconcile.failed", {
|
|
24260
|
+
"app.turn.id": turnId,
|
|
24261
|
+
"gen_ai.conversation.id": conversationId
|
|
24262
|
+
});
|
|
24263
|
+
}
|
|
24264
|
+
return stopped;
|
|
24265
|
+
}
|
|
24266
|
+
/**
|
|
24267
|
+
* Brings the queue in line with this Turn's stored state, so it is safe to
|
|
24268
|
+
* repeat: it says the Turn ended if it has, then publishes the Conversation's
|
|
24269
|
+
* open Turn if it is queued. Call it after the commit that it follows,
|
|
24270
|
+
* outside a transaction, so a worker that takes a message sees that commit.
|
|
24271
|
+
*/
|
|
24272
|
+
async function reconcileTurn({ executor, queue }, turnId) {
|
|
24273
|
+
const turn = await findTurn({ executor }, turnId);
|
|
24274
|
+
if (!turn) return;
|
|
24275
|
+
if (turn.state !== "queued" && turn.state !== "running") await publishTurnEnded({ queue }, {
|
|
24276
|
+
conversationId: turn.conversationId,
|
|
24277
|
+
turnId
|
|
24278
|
+
});
|
|
24279
|
+
const openTurn = await findOpenTurn({ executor }, turn.conversationId);
|
|
24280
|
+
if (openTurn?.state === "queued") await publishTurnStep({ queue }, openTurn.turnId);
|
|
24281
|
+
}
|
|
24282
|
+
// src/turn-steps/engine-context.ts
|
|
24283
|
+
/** Builds the context that core's Turn engine runs with. */
|
|
24284
|
+
function createEngineContext(config) {
|
|
24285
|
+
return {
|
|
24286
|
+
executor: getSqlExecutor(),
|
|
24287
|
+
queue: getQueueProvider(),
|
|
24288
|
+
owner: SERVICE_INSTANCE_ID,
|
|
24289
|
+
leaseMs: config.functionMaxDurationSeconds * 1e3
|
|
24290
|
+
};
|
|
24291
|
+
}
|
|
24292
|
+
// src/turn-steps/group-key.ts
|
|
24293
|
+
/** The group key of an input that this Actor Identity sent from this Source. */
|
|
24294
|
+
function turnGroupKey(actorIdentityId, source) {
|
|
24295
|
+
return `${actorIdentityId}:${source.kind}`;
|
|
24296
|
+
}
|
|
24297
|
+
// src/turn-steps/input-payload.ts
|
|
24298
|
+
/** Parses the payload of an inbox row that the host wrote. */
|
|
24299
|
+
const turnInputPayloadSchema = z.object({
|
|
24300
|
+
text: z.string().min(1),
|
|
24301
|
+
actor: actorSchema
|
|
24302
|
+
}).strict();
|
|
24303
|
+
// src/turn-steps/ingress.ts
|
|
24304
|
+
function slackFacts(message) {
|
|
24305
|
+
const { destination } = message;
|
|
24306
|
+
const { authorId, metadata } = message.input;
|
|
24307
|
+
if (destination?.platform !== "slack" || !authorId) throw new Error("Slack input requires a Slack Destination and an author");
|
|
24308
|
+
const slackMessage = metadata?.["message"];
|
|
24309
|
+
const raw = readSlackRawMessageContext(slackMessage);
|
|
24310
|
+
const threadTs = raw?.threadTs ?? raw?.messageTs;
|
|
24311
|
+
return {
|
|
24312
|
+
actor: createSlackActor(destination.teamId, authorId, null),
|
|
24313
|
+
actorIdentityId: message.input.authorIdentityId,
|
|
24314
|
+
destination: {
|
|
24315
|
+
...destination,
|
|
24316
|
+
...threadTs ? { threadTs } : void 0
|
|
24317
|
+
},
|
|
24318
|
+
source: createSlackSource({
|
|
24319
|
+
channelId: destination.channelId,
|
|
24320
|
+
messageTs: raw?.messageTs,
|
|
24321
|
+
teamId: destination.teamId,
|
|
24322
|
+
threadTs,
|
|
24323
|
+
visibility: conversationVisibilityFromSlackChannelType(resolveSlackChannelTypeFromMessage(slackMessage)) ?? "private"
|
|
24324
|
+
}),
|
|
24325
|
+
text: message.input.text
|
|
24326
|
+
};
|
|
24327
|
+
}
|
|
24328
|
+
async function webVisibility(conversationId) {
|
|
24329
|
+
const conversation = await getConversationStore().get({ conversationId });
|
|
24330
|
+
return (!conversation || isTopLevel(conversation) ? conversation?.visibility : conversation.visibility ?? "private") === "private" ? "private" : "public";
|
|
24331
|
+
}
|
|
24332
|
+
async function webFacts(message) {
|
|
24333
|
+
const metadata = legacyWebMailboxMetadataSchema.parse(message.input.metadata);
|
|
24334
|
+
return {
|
|
24335
|
+
actor: {
|
|
24336
|
+
platform: "web",
|
|
24337
|
+
userId: metadata.authorUserId,
|
|
24338
|
+
email: metadata.authorEmail,
|
|
24339
|
+
...metadata.authorFullName ? { fullName: metadata.authorFullName } : void 0,
|
|
24340
|
+
...metadata.authorUserName ? { userName: metadata.authorUserName } : void 0
|
|
24341
|
+
},
|
|
24342
|
+
actorIdentityId: message.input.authorIdentityId,
|
|
24343
|
+
destination: null,
|
|
24344
|
+
source: createWebSource(message.conversationId, await webVisibility(message.conversationId)),
|
|
24345
|
+
text: message.input.text
|
|
24346
|
+
};
|
|
24347
|
+
}
|
|
24348
|
+
function eventFacts(message) {
|
|
24349
|
+
const { metadata } = message.input;
|
|
24350
|
+
if (!isEventMailboxMetadata(metadata)) throw new Error("Event input has invalid metadata");
|
|
24351
|
+
return {
|
|
24352
|
+
actor: EVENT_SYSTEM_ACTOR,
|
|
24353
|
+
actorIdentityId: message.input.authorIdentityId ?? "system",
|
|
24354
|
+
destination: null,
|
|
24355
|
+
source: createEventSource(metadata.event),
|
|
24356
|
+
text: message.input.text
|
|
24357
|
+
};
|
|
24358
|
+
}
|
|
24359
|
+
async function dispatchFacts(message) {
|
|
24360
|
+
const dispatchId = getDispatchIdForConversation(message.conversationId);
|
|
24361
|
+
const dispatch = dispatchId && await getDispatchRecord(dispatchId);
|
|
24362
|
+
if (!dispatch) throw new Error(`No dispatch for ${message.conversationId}`);
|
|
24363
|
+
return {
|
|
24364
|
+
actor: dispatch.actor,
|
|
24365
|
+
actorIdentityId: message.input.authorIdentityId ?? "system",
|
|
24366
|
+
destination: dispatch.destination,
|
|
24367
|
+
source: dispatch.source,
|
|
24368
|
+
text: dispatch.input
|
|
24369
|
+
};
|
|
24370
|
+
}
|
|
24371
|
+
async function inputFacts(message) {
|
|
24372
|
+
switch (message.source) {
|
|
24373
|
+
case "slack": return slackFacts(message);
|
|
24374
|
+
case "web": return await webFacts(message);
|
|
24375
|
+
case "event": return eventFacts(message);
|
|
24376
|
+
case "plugin": return await dispatchFacts(message);
|
|
24377
|
+
default: throw new Error(`Core has no input for ${message.source} messages`);
|
|
24378
|
+
}
|
|
24379
|
+
}
|
|
24380
|
+
/**
|
|
24381
|
+
* Schedules a mailbox message as a core input. The message id is the
|
|
24382
|
+
* idempotency key, so a redelivery writes nothing and is a `duplicate`.
|
|
24383
|
+
* `startDelayMs` holds a new Turn so that inputs sent soon after join it, as
|
|
24384
|
+
* main's delayed wake does. Call it outside a transaction, as
|
|
24385
|
+
* `scheduleInput` requires.
|
|
24386
|
+
*/
|
|
24387
|
+
async function scheduleInboundMessage(message, options = {}) {
|
|
24388
|
+
const facts = await inputFacts(message);
|
|
24389
|
+
if (!facts.actorIdentityId) throw new Error(`${message.source} input has no author Identity`);
|
|
24390
|
+
const scheduled = await scheduleInput(createEngineContext(getChatConfig()), {
|
|
24391
|
+
conversationId: message.conversationId,
|
|
24392
|
+
actorIdentityId: facts.actorIdentityId,
|
|
24393
|
+
groupKey: turnGroupKey(facts.actorIdentityId, facts.source),
|
|
24394
|
+
payload: turnInputPayloadSchema.parse({
|
|
24395
|
+
text: facts.text,
|
|
24396
|
+
actor: facts.actor
|
|
24397
|
+
}),
|
|
24398
|
+
idempotencyKey: message.inboundMessageId,
|
|
24399
|
+
sentAt: new Date(message.createdAtMs),
|
|
24400
|
+
source: facts.source,
|
|
24401
|
+
destination: facts.destination,
|
|
24402
|
+
delivery: message.delivery,
|
|
24403
|
+
...message.traceContext ? { traceContext: message.traceContext } : void 0,
|
|
24404
|
+
startDelayMs: options.startDelayMs
|
|
24405
|
+
}, { admit: async () => {
|
|
24406
|
+
if (!isPersonInput(message.source)) return true;
|
|
24407
|
+
const stoppedAtMs = await getConversationStoppedAtMs(message.conversationId);
|
|
24408
|
+
if (stoppedAtMs === void 0) return true;
|
|
24409
|
+
if (message.createdAtMs <= stoppedAtMs) return false;
|
|
24410
|
+
await resumeConversationTree(message.conversationId, message.createdAtMs);
|
|
24411
|
+
return true;
|
|
24412
|
+
} });
|
|
24413
|
+
if ("refused" in scheduled) return { status: "appended" };
|
|
24414
|
+
return { status: scheduled.duplicate ? "duplicate" : "appended" };
|
|
24415
|
+
}
|
|
22824
24416
|
// src/chat/child-agents/parent-message-input.ts
|
|
22825
24417
|
/**
|
|
22826
24418
|
* A parent agent task or message to a child: who sent it and the
|
|
@@ -24557,8 +26149,12 @@ async function enqueueAfterAppend(args) {
|
|
|
24557
26149
|
...wake.status === "enqueued" ? { queueMessageId: wake.queueMessageId } : void 0
|
|
24558
26150
|
};
|
|
24559
26151
|
}
|
|
24560
|
-
/**
|
|
26152
|
+
/**
|
|
26153
|
+
* Persist inbound work and ensure a worker wake-up. On the core Turn engine,
|
|
26154
|
+
* schedule it as a core input instead.
|
|
26155
|
+
*/
|
|
24561
26156
|
async function appendAndEnqueueInboundMessage(args) {
|
|
26157
|
+
if (getChatConfig().turnEngine === "core") return await scheduleInboundMessage(args.message, { startDelayMs: args.queueDelayMs });
|
|
24562
26158
|
const nowMs = args.nowMs ?? now$1();
|
|
24563
26159
|
const result = await enqueueAfterAppend({
|
|
24564
26160
|
...args,
|
|
@@ -24573,8 +26169,12 @@ async function appendAndEnqueueInboundMessage(args) {
|
|
|
24573
26169
|
if (result.status === "active") throw new Error("Non-exclusive mailbox enqueue returned active");
|
|
24574
26170
|
return result;
|
|
24575
26171
|
}
|
|
24576
|
-
/**
|
|
26172
|
+
/**
|
|
26173
|
+
* Persist exclusive inbound work and wake its worker when admitted. On the
|
|
26174
|
+
* core Turn engine, schedule it as a core input instead.
|
|
26175
|
+
*/
|
|
24577
26176
|
async function appendAndEnqueueExclusiveInboundMessage(args) {
|
|
26177
|
+
if (getChatConfig().turnEngine === "core") return await scheduleInboundMessage(args.message);
|
|
24578
26178
|
const nowMs = args.nowMs ?? now$1();
|
|
24579
26179
|
return await enqueueAfterAppend({
|
|
24580
26180
|
...args,
|
|
@@ -24705,7 +26305,7 @@ async function runDeferredMove(args) {
|
|
|
24705
26305
|
const move = await takeDeferredConversationMove(args);
|
|
24706
26306
|
if (move === void 0) return;
|
|
24707
26307
|
try {
|
|
24708
|
-
const { continueDeferredSlackClick } = await import("./slack-conversation-unfurl-
|
|
26308
|
+
const { continueDeferredSlackClick } = await import("./slack-conversation-unfurl-BxF0Yb3-.js").then((n) => n.r);
|
|
24709
26309
|
await continueDeferredSlackClick(move, args.getSlackAdapter);
|
|
24710
26310
|
} catch (error) {
|
|
24711
26311
|
logException(error, "slack.continue_here.deferred.failed", { "gen_ai.conversation.id": args.conversationId });
|
|
@@ -25722,14 +27322,14 @@ function ownerConversationOpenTo(userId, ownerConversationId) {
|
|
|
25722
27322
|
return exists(query.where(and(eq(todoOwner.conversationId, ownerConversationId), open)));
|
|
25723
27323
|
}
|
|
25724
27324
|
/**
|
|
25725
|
-
* SQL: the Inbox item has this assigned User
|
|
25726
|
-
*
|
|
25727
|
-
*
|
|
25728
|
-
*
|
|
25729
|
-
*
|
|
27325
|
+
* SQL: the Inbox item has this assigned User and one of `statuses`, the
|
|
27326
|
+
* statuses that the outer query reads. A To-do's item counts only while
|
|
27327
|
+
* the User can see its Conversation's private content. The set has no
|
|
27328
|
+
* outer reference, so Postgres reads it once and checks the owner of only
|
|
27329
|
+
* the User's To-dos.
|
|
25730
27330
|
*/
|
|
25731
|
-
function inboxItemAssignedTo(userId) {
|
|
25732
|
-
const assigned = getDb().select({ id: juniorInboxItems.id }).from(juniorInboxItemAssignees).innerJoin(juniorInboxItems, eq(juniorInboxItems.id, juniorInboxItemAssignees.itemId)).where(and(eq(juniorInboxItemAssignees.userId, userId), or(ne(juniorInboxItems.subjectKind, INBOX_SUBJECT_KINDS.todo), ownerConversationOpenTo(userId, todoItemOwnerConversationId()))));
|
|
27331
|
+
function inboxItemAssignedTo(userId, statuses) {
|
|
27332
|
+
const assigned = getDb().select({ id: juniorInboxItems.id }).from(juniorInboxItemAssignees).innerJoin(juniorInboxItems, eq(juniorInboxItems.id, juniorInboxItemAssignees.itemId)).where(and(eq(juniorInboxItemAssignees.userId, userId), inArray(juniorInboxItems.status, [...statuses]), or(ne(juniorInboxItems.subjectKind, INBOX_SUBJECT_KINDS.todo), ownerConversationOpenTo(userId, todoItemOwnerConversationId()))));
|
|
25733
27333
|
return sql`${juniorInboxItems.id} = any(array(${assigned}))`;
|
|
25734
27334
|
}
|
|
25735
27335
|
/**
|
|
@@ -25740,7 +27340,7 @@ function inboxItemAssignedTo(userId) {
|
|
|
25740
27340
|
* "Waiting on you" marker use this rule.
|
|
25741
27341
|
*/
|
|
25742
27342
|
function inboxItemNeedsUser(userId) {
|
|
25743
|
-
return and(eq(juniorInboxItems.status, "open"), eq(juniorInboxItems.kind, "action"), inboxItemAssignedTo(userId));
|
|
27343
|
+
return and(eq(juniorInboxItems.status, "open"), eq(juniorInboxItems.kind, "action"), inboxItemAssignedTo(userId, ["open"]));
|
|
25744
27344
|
}
|
|
25745
27345
|
/**
|
|
25746
27346
|
* SQL: the Inbox item waits for a person's input: an open `action` item,
|
|
@@ -25765,8 +27365,8 @@ function inboxItemSetsConversationStatus() {
|
|
|
25765
27365
|
* to this User, to Everyone, or to no one. This is the assignee rule of
|
|
25766
27366
|
* `canActOnInboxItem`; keep the two the same.
|
|
25767
27367
|
*/
|
|
25768
|
-
function inboxItemForUser(userId) {
|
|
25769
|
-
return or(eq(juniorInboxItems.assignedToEveryone, true), sql`not exists (select 1 from ${juniorInboxItemAssignees} where ${juniorInboxItemAssignees.itemId} = ${juniorInboxItems.id})`, inboxItemAssignedTo(userId));
|
|
27368
|
+
function inboxItemForUser(userId, statuses) {
|
|
27369
|
+
return or(eq(juniorInboxItems.assignedToEveryone, true), sql`not exists (select 1 from ${juniorInboxItemAssignees} where ${juniorInboxItemAssignees.itemId} = ${juniorInboxItems.id})`, inboxItemAssignedTo(userId, statuses));
|
|
25770
27370
|
}
|
|
25771
27371
|
/**
|
|
25772
27372
|
* SQL: the private Inbox item is for Everyone, and the User can see its
|
|
@@ -25803,8 +27403,8 @@ function inboxItemAddedByAnyAutomation() {
|
|
|
25803
27403
|
* Inbox item access test checks that they agree. Only the SQL form reads
|
|
25804
27404
|
* `ownerAudienceUserId`.
|
|
25805
27405
|
*/
|
|
25806
|
-
function inboxItemVisibleTo(reader) {
|
|
25807
|
-
return or(...publicIn(reader.tenants ?? []), ...reader.userId ? [inboxItemAssignedTo(reader.userId)] : [], ...reader.ownerAudienceUserId ? [inboxItemForEveryoneOfOwner(reader.ownerAudienceUserId)] : [], ...reader.conversationId ? [inboxItemLinkedTo(reader.conversationId)] : [], ...reader.publicConversationId ? [and(eq(inboxItemVisibility(), "public"), eq(juniorInboxItems.kind, "action"), inboxItemLinkedTo(reader.publicConversationId))] : [], ...reader.automationId ? [inboxItemAddedByAutomation(reader.automationId)] : []) ?? sql`false`;
|
|
27406
|
+
function inboxItemVisibleTo(reader, statuses) {
|
|
27407
|
+
return or(...publicIn(reader.tenants ?? []), ...reader.userId ? [inboxItemAssignedTo(reader.userId, statuses)] : [], ...reader.ownerAudienceUserId ? [inboxItemForEveryoneOfOwner(reader.ownerAudienceUserId)] : [], ...reader.conversationId ? [inboxItemLinkedTo(reader.conversationId)] : [], ...reader.publicConversationId ? [and(eq(inboxItemVisibility(), "public"), eq(juniorInboxItems.kind, "action"), inboxItemLinkedTo(reader.publicConversationId))] : [], ...reader.automationId ? [inboxItemAddedByAutomation(reader.automationId)] : []) ?? sql`false`;
|
|
25808
27408
|
}
|
|
25809
27409
|
/** Return whether an Inbox item is a public question (`action` item). */
|
|
25810
27410
|
function isPublicQuestion(item) {
|
|
@@ -25972,12 +27572,11 @@ function canActOnInboxItem(item, userId) {
|
|
|
25972
27572
|
return item.assignees.some((assignee) => assignee.userId === userId);
|
|
25973
27573
|
}
|
|
25974
27574
|
/**
|
|
25975
|
-
* Return whether a User can answer an open
|
|
25976
|
-
* it can (`canActOnInboxItem`). A public question that an agent
|
|
25977
|
-
* Conversation is open to anyone who can see it, such as a
|
|
25978
|
-
* public Slack channel.
|
|
25979
|
-
*
|
|
25980
|
-
* caller checks that the User can see the item.
|
|
27575
|
+
* Return whether a User can answer or dismiss an open item. Anyone who can
|
|
27576
|
+
* act on it can (`canActOnInboxItem`). A public question that an agent
|
|
27577
|
+
* asked in a Conversation is open to anyone who can see it, such as a
|
|
27578
|
+
* member of its public Slack channel. Other items, and Take, keep the
|
|
27579
|
+
* assignee rule. The caller checks that the User can see the item.
|
|
25981
27580
|
*/
|
|
25982
27581
|
function canAnswerInboxItem(item, userId) {
|
|
25983
27582
|
if (canActOnInboxItem(item, userId)) return true;
|
|
@@ -26203,15 +27802,20 @@ function isLeadSql(conversationId) {
|
|
|
26203
27802
|
* the Lead's actor the starter of all Space work.
|
|
26204
27803
|
*/
|
|
26205
27804
|
function conversationTopLevelIdSql(conversation) {
|
|
27805
|
+
const { conversationId, parentConversationId, rootConversationId } = conversation;
|
|
26206
27806
|
const ancestorParent = sql`status_ancestor.parent_conversation_id`;
|
|
26207
|
-
|
|
27807
|
+
const belowRoot = sql`${ancestorParent} is not distinct from ${rootConversationId}`;
|
|
27808
|
+
return sql`(case
|
|
27809
|
+
when ${parentConversationId} is null then ${conversationId}
|
|
27810
|
+
when ${rootConversationId} <> ${conversationId} and not ${isLeadSql(rootConversationId)} then ${rootConversationId}
|
|
27811
|
+
else (
|
|
26208
27812
|
with recursive status_ancestor(conversation_id, parent_conversation_id) as (
|
|
26209
|
-
select ${
|
|
27813
|
+
select ${conversationId}::text, ${parentConversationId}::text
|
|
26210
27814
|
union
|
|
26211
27815
|
select parent.conversation_id, parent.parent_conversation_id
|
|
26212
27816
|
from status_ancestor
|
|
26213
27817
|
join junior_conversations parent on parent.conversation_id = ${ancestorParent}
|
|
26214
|
-
where not ${
|
|
27818
|
+
where not ${belowRoot}
|
|
26215
27819
|
)
|
|
26216
27820
|
select conversation_id from status_ancestor
|
|
26217
27821
|
where ${ancestorParent} is null or ${isLeadSql(ancestorParent)}
|
|
@@ -27504,90 +29108,6 @@ async function restoreArchivedPath(db, conversationId) {
|
|
|
27504
29108
|
if (!node) return;
|
|
27505
29109
|
await setArchivedAt(db, [node, ...conversationAncestors(tree, conversationId)].filter((entry) => entry.archivedAt).map((entry) => entry.conversationId), null);
|
|
27506
29110
|
}
|
|
27507
|
-
// src/conversation-events/lock.ts
|
|
27508
|
-
/** Serialize event sequence allocation with other conversation writes. */
|
|
27509
|
-
async function withConversationEventLock(executor, conversationId, callback) {
|
|
27510
|
-
return executor.withLock(`junior_conversation:${conversationId}`, callback);
|
|
27511
|
-
}
|
|
27512
|
-
// src/db/postgres-json.ts
|
|
27513
|
-
/**
|
|
27514
|
-
* Replace actual NUL characters that PostgreSQL cannot store in JSONB.
|
|
27515
|
-
* Literal `\\u0000` text is preserved because it contains no NUL character.
|
|
27516
|
-
*/
|
|
27517
|
-
function sanitizePostgresJson(value) {
|
|
27518
|
-
if (typeof value === "string") return value.replaceAll("\0", " ");
|
|
27519
|
-
if (Array.isArray(value)) return value.map((item) => sanitizePostgresJson(item));
|
|
27520
|
-
if (value === null || typeof value !== "object") return value;
|
|
27521
|
-
const prototype = Object.getPrototypeOf(value);
|
|
27522
|
-
if (prototype !== Object.prototype && prototype !== null) return value;
|
|
27523
|
-
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, sanitizePostgresJson(item)]));
|
|
27524
|
-
}
|
|
27525
|
-
// src/conversation-events/store.ts
|
|
27526
|
-
/** Read the next seq and the current History version of a Conversation. */
|
|
27527
|
-
async function readEventCursor(executor, conversationId) {
|
|
27528
|
-
const [row] = await executor.db().select({
|
|
27529
|
-
maxSeq: sql`max(${juniorConversationEvents.seq})`,
|
|
27530
|
-
maxHistoryVersion: sql`max(${juniorConversationEvents.historyVersion})`
|
|
27531
|
-
}).from(juniorConversationEvents).where(eq(juniorConversationEvents.conversationId, conversationId));
|
|
27532
|
-
return {
|
|
27533
|
-
nextSeq: row?.maxSeq == null ? 0 : Number(row.maxSeq) + 1,
|
|
27534
|
-
historyVersion: row?.maxHistoryVersion == null ? 0 : Number(row.maxHistoryVersion)
|
|
27535
|
-
};
|
|
27536
|
-
}
|
|
27537
|
-
/**
|
|
27538
|
-
* Drop the events whose idempotency key is already stored, or repeats an
|
|
27539
|
-
* earlier event of the same call. Events without a key are always kept.
|
|
27540
|
-
*/
|
|
27541
|
-
async function unseenEvents(executor, conversationId, events) {
|
|
27542
|
-
const keys = events.flatMap((event) => event.idempotencyKey === void 0 ? [] : [event.idempotencyKey]);
|
|
27543
|
-
const seen = /* @__PURE__ */ new Set();
|
|
27544
|
-
if (keys.length > 0) {
|
|
27545
|
-
const rows = await executor.db().select({ key: juniorConversationEvents.idempotencyKey }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), inArray(juniorConversationEvents.idempotencyKey, keys)));
|
|
27546
|
-
for (const row of rows) if (row.key) seen.add(row.key);
|
|
27547
|
-
}
|
|
27548
|
-
return events.filter((event) => {
|
|
27549
|
-
if (event.idempotencyKey === void 0) return true;
|
|
27550
|
-
if (seen.has(event.idempotencyKey)) return false;
|
|
27551
|
-
seen.add(event.idempotencyKey);
|
|
27552
|
-
return true;
|
|
27553
|
-
});
|
|
27554
|
-
}
|
|
27555
|
-
/** Store rows in order from the cursor, at its History version. */
|
|
27556
|
-
async function insertEventRows(executor, conversationId, cursor, rows) {
|
|
27557
|
-
return await insertAt(executor, conversationId, cursor.historyVersion, rows.map((row, index) => ({
|
|
27558
|
-
row,
|
|
27559
|
-
seq: cursor.nextSeq + index
|
|
27560
|
-
})));
|
|
27561
|
-
}
|
|
27562
|
-
/**
|
|
27563
|
-
* Store a History replacement row. It starts the next History version, so
|
|
27564
|
-
* every later row belongs to the history that it sets.
|
|
27565
|
-
*/
|
|
27566
|
-
async function insertHistoryReplacementRow(executor, conversationId, cursor, row) {
|
|
27567
|
-
const [inserted] = await insertAt(executor, conversationId, cursor.historyVersion + 1, [{
|
|
27568
|
-
row,
|
|
27569
|
-
seq: cursor.nextSeq
|
|
27570
|
-
}]);
|
|
27571
|
-
return inserted;
|
|
27572
|
-
}
|
|
27573
|
-
async function insertAt(executor, conversationId, historyVersion, rows) {
|
|
27574
|
-
const values = rows.map(({ row, seq }) => ({
|
|
27575
|
-
conversationId,
|
|
27576
|
-
seq,
|
|
27577
|
-
historyVersion,
|
|
27578
|
-
schemaVersion: row.schemaVersion,
|
|
27579
|
-
idempotencyKey: row.idempotencyKey ?? null,
|
|
27580
|
-
type: row.type,
|
|
27581
|
-
payload: sanitizePostgresJson(row.payload),
|
|
27582
|
-
actorIdentityId: row.actorIdentityId ?? null,
|
|
27583
|
-
turnId: row.turnId ?? null,
|
|
27584
|
-
createdAt: new Date(row.createdAtMs)
|
|
27585
|
-
}));
|
|
27586
|
-
if (values.length === 0) return [];
|
|
27587
|
-
const db = executor.db();
|
|
27588
|
-
await db.with(conversationDetailTouch(db, [conversationId])).insert(juniorConversationEvents).values(values);
|
|
27589
|
-
return values;
|
|
27590
|
-
}
|
|
27591
29111
|
// src/chat/conversations/message-links.ts
|
|
27592
29112
|
/**
|
|
27593
29113
|
* Web link matches in message text. Slack wraps links as <url|label>, and
|
|
@@ -28706,4 +30226,4 @@ async function closeDb() {
|
|
|
28706
30226
|
current = void 0;
|
|
28707
30227
|
await previous?.db.close();
|
|
28708
30228
|
}
|
|
28709
|
-
export { canActOnInboxItem as $, usdToMicroUsd as $a, subjectKindDismissNote as $c, deleteMcpAuthSession as $d, juniorTurnOutbox as $f, createSandboxCapability as $i, isThread as $l, resolveEventMentions as $n, pauseConversationDelivery as $o, annotationKeyDigest as $r, isDmChannel as $s, completeConversationWork as $t, GEN_AI_PROVIDER_NAME as $u, setFirstConversationLocation as A, automationDefinition as Aa, countInboxItemsNeedingUserBySubject as Ac, renderJuniorNativeConversationEvent as Ad, parseInlinePluginManifest as Af, removeReactionFromMessage as Ai, parseDashboardPersonLink as Al, canJoinTurn as An, collectEventMatchKeys as Ao, juniorConversationAnnotations as Ap, readConversationAccessRows as Ar, isPublicConversation as As, injectContinuationToolName as At, eventIndexLockKey as Au, conversationAggregateColumns as B, linkAutomationRunConversation as Ba, getOpenInboxItemBySubject as Bc, finishServiceAccountSignIn as Bd, rootConversationIsArchived as Bf, slackMentionedUserIds as Bi, fuzzyMatch as Bl, pushInboxSnoozeWakes as Bn, turnEvents as Bo, juniorSpaces as Bp, verifyConversationQueueMessage as Br, deletePushSubscription as Bs, setTodoStatusByUser as Bt, storedMessageJson as Bu, conversationSlackTenantId as C, getEventAutomation as Ca, findLinkedSlackUser as Cc, isProviderRefusal as Cd, toMcpProviderError as Cf, addReactionToMessage as Ci, getDashboardLinkFilter as Cl, isFinalAttempt as Cn, AGENT_RESOURCE_TYPE as Co, juniorConversationEventLexemes as Cp, canAddConversationMessages as Cr, conversationAncestorsOrSelf as Cs, inboxItemOwnerConversationId as Ct, registeredResourceTypeSchema as Cu, createSqlStore as D, setEventAutomationStatus as Da, upsertLinkedIdentity as Dc, agentsInstructionsUpdatedEvent as Dd, CredentialMintError as Df, openSlackModal as Di, getDashboardTaskLink as Dl, releaseInboundMessage as Dn, starterWatchId as Do, juniorConversationEvents as Dp, createConversationAccessReader as Dr, conversationSearchVector as Ds, validatePlugins as Dt, isToolInputError as Du, latestUserMessageQuery as E, saveEventAutomation as Ea, recordGoogleSignIn as Ec, JUNIOR_NATIVE_EVENT_NAMESPACE as Ed, getOAuthProviderErrorAttributes as Ef, openSlackDirectMessage as Ei, getDashboardSpaceLink as El, pruneActiveConversation as En, publishAgentUpdate as Eo, juniorConversationMetrics as Ep, conversationAccessFromRows as Er, loadAnnotationLabeler as Es, getRegistrations as Et, ToolInputError as Eu, destinationUpsertFromDestination as F, AutomationConflictError as Fa, closeReadReplyNotice as Fc, createPluginCatalogRuntime as Fd, agentTurnTotalTokens as Ff, SLACK_USER_MENTION_RE as Fi, contentVersionHeaders as Fl, readInboundMessageSender as Fn, getWatch as Fo, juniorAttachmentUploads as Fp, readMemberParticipants as Fr, defaultTimezone as Fs, CHILD_AGENT_KINDS as Ft, storeConversationEventLexemes as Fu, conversationStatusSql as G, readAutomationExecutions as Ga, takeInboxItem as Gc, startServiceAccountSignIn as Gd, requireSlackDestination as Gf, createPluginState as Gi, scoredSearchMatches as Gl, SLACK_INBOX_ITEM_VIEW_ID as Gn, verifyEventAutomationCredentialSubject as Go, juniorDestinations as Gp, QUEUE_SIGNATURE_MAX_AGE_MS as Gr, isPausedBySlack as Gs, beginConversationResume as Gt, storeConversationEmbedding as Gu, conversationUsageCostExpr as H, readAutomationExecutionStatusDays as Ha, listReplyActionItems as Hc, serviceAccountAllows as Hd, nextDetailVersion as Hf, applyPluginFormatMarkdown as Hi, prefixMatch as Hl, resolveSlackInboxItemCardConversationId as Hn, bindScheduledAutomationCredentialSubject as Ho, slackPersonPredicate as Hp, conversationQueueMessageSchema as Hr, readNotificationSchedule as Hs, appendAndEnqueueExclusiveInboundMessage as Ht, backfillConversationEmbeddings as Hu, upsertDestination as I, automationRevision as Ia, INBOX_ITEM_REPLIED_REASON as Ic, HOST_MANAGED_CREDENTIAL_PLACEHOLDER as Id, agentTurnUsageSchema as If, escapeSlackMrkdwnText as Ii, revalidateContent as Il, isEventMailboxMetadata as In, isQuietEvent as Io, juniorAttachments as Ip, rootVisibleToViewer as Ir, findActorTimezone as Is, PARENT_AGENT_TARGET as It, SEARCHABLE_EVENT_TYPES as Iu, executionIsActive as J, readAutomationTitlesByConversationId as Ja, inboxItemTitle as Jc, hasRequiredOAuthScope as Jd, rootSpaceIdSql as Jf, createPluginModel as Ji, deliversFinalText as Jl, parseSlackInboxItemFormTarget as Jn, verifyTimerWatchCredentialSubject as Jo, getQueueProvider as Jr, getFilePermalink as Js, claimConversationAttempt as Jt, completeText as Ju, conversationTurnFailedSql as K, readAutomationRowStats as Ka, updateInboxItemContent as Kc, buildOAuthTokenRequest as Kd, sameDestination as Kf, createPluginDecider as Ki, fuseRankedLists as Kl, buildSlackInboxItemModal as Kn, verifyScheduledAutomationCredentialSubject as Ko, guardedCosineDistance as Kp, signQueueMessage as Kr, SlackActionError as Ks, cancelHumanFacingPendingMessages as Kt, completeDecision as Ku, parseSessionSource as L, requireAutomationRevision as La, closeInboxItem as Lc, resolveAuthTokenPlaceholder as Ld, hasAgentTurnUsage as Lf, formatSlackLink as Li, memoryDb as Ll, createSlackInboxItemToolServices as Ln, listConversationsWithWatches as Lo, juniorMessageAttachments as Lp, viewerMarksFromParticipant as Lr, resolveUserTimezone as Ls, agentNameSchema as Lt, callsToolSql as Lu, locationSchema as M, listAutomationVersions as Ma, listWaitingConversations as Mc, createAppContext as Md, workloadIdentityHeader as Mf, uploadFilesToConversation as Mi, projectConversationMessages as Ml, isAttemptInterrupt as Mn, createWatch as Mo, codeRepositorySearchDocument as Mp, conversationIsMemberRoot as Mr, readWebPushConfig as Ms, makeStructuredToolOutput as Mt, lexemesSql as Mu, claimProviderConversation as N, readAutomationVersion as Na, waitingConversationIdsQuery as Nc, getAppContext as Nd, addAgentTurnUsage as Nf, slackEntitySchema as Ni, REVALIDATED_READ_PATHS as Nl, selectAttemptMessages as Nn, deliverWatch as No, juniorCodeChanges as Np, conversationIsNotUnsubscribedRoot as Nr, sendPushNotificationToUser as Ns, findChildAgentConversationId as Nt, searchedEventTextSql as Nu, withConversationMutationLock as O, admitEventAutomationRun as Oa, readCachedLinkedHandle as Oc, authenticationLinkedEvent as Od, CredentialUnavailableError as Of, postSlackEphemeralMessage as Oi, isDashboardLink as Ol, traceContextSchema as On, cancelSubscriptions as Oo, juniorTurns as Op, leaveEndsAccess as Or, readConversationMetadata as Os, apiRoutePrefix as Ot, EVENT_INDEX_LOCK_TTL_MS as Ou, getConversationIdByProviderConversation as P, sameDefinitionValue as Pa, closeHandledReplyNotices as Pc, installAppContext as Pd, agentTurnCostUsd as Pf, slackExternalRefIdSchema as Pi, contentVersion as Pl, readParentMessage as Pn, findMatchingWatches as Po, juniorCodeRepositories as Pp, conversationPinnedForUser as Pr, resolveNotificationTimezone as Ps, getAgentBinding as Pt, seqIn as Pu, treeAwaitsAuthorization as Q, microUsdToUsd as Qa, questionLinks as Qc, PluginMcpClient as Qd, topLevelConversation as Qf, basePluginContext as Qi, isPersonInput as Ql, sendSlackReply as Qn, isConversationDeliveryPaused as Qo, renderSlackObjectCard as Qr, isConversationScopedChannel as Qs, completeConversationStop as Qt, NoAudioError as Qu, replaceConversationMetrics as R, emptyAutomationRunWindows as Ra, dismissOpenInboxItems as Rc, mergeHeaderTransforms as Rd, isLeadConversation as Rf, normalizeSlackStatusText as Ri, searchTypedMemories as Rl, createInboxItemShow as Rn, listWatches as Ro, juniorConversations as Rp, getVercelConversationWorkQueue as Rr, lookupSlackUser as Rs, spawnChildAgentInputSchema as Rt, eventExcerpt as Ru, setArchivedAt as S, findMatchingEventAutomations as Sa, deleteProviderIdentityForUser as Sc, getProviderErrorUserMessage as Sd, getMcpProviderErrorAttributes as Sf, notifyAutomationBlocked as Si, getDashboardInboxItemLink as Sl, hasRunnableConversationWork as Sn, workspaceSnapshotWatch as So, juniorConversationParticipants as Sp, canAccessConversation as Sr, upsertPluginAnnotation as Ss, inboxItemOwnedByThroughSubject as St, registeredEventTypeSchema as Su, lastMessageAtSql as T, parseEventAutomationRow as Ta, findUserByVerifiedEmails as Tc, getGatewayApiKey as Td, fetchWithBoundedOAuthErrorBodies as Tf, getSlackMessagePermalink as Ti, getDashboardSettingsLink as Tl, moveIdleConversationDestination as Tn, isAgentResourceType as To, juniorConversationEmbeddings as Tp, canReadConversation as Tr, conversationSubtreeColumns as Ts, getPlugins as Tt, requireValidEventTrigger as Tu, conversationIsActiveSql as U, readAutomationExecutionStatusHours as Ua, ownerConversationId as Uc, serviceAccountOnly as Ud, touchConversationDetail as Uf, getPluginUserPromptContributions as Ui, prefixRank as Ul, syncInboxItemSlackCards as Un, bindSlackDirectCredentialSubject as Uo, slackPersonSearchDocument as Up, isConversationQueueMessageRejectedError as Ur, saveNotificationSchedule as Us, appendAndEnqueueInboundMessage as Ut, createConversationEmbedder as Uu, conversationRangeColumns as V, readAutomationExecutionByConversationId as Va, insertInboxItem as Vc, getServiceAccountStatus as Vd, conversationDetailTouch as Vf, wrapBareSlackUserIds as Vi, fuzzyRank as Vl, runInboxItemPushTimers as Vn, bindEventAutomationCredentialSubject as Vo, juniorIdentities as Vp, ConversationQueueMessageRejectedError as Vr, listPushSubscriptions as Vs, ackMessages as Vt, isEventEmbeddingsEnabled as Vu, conversationLastTurnOutcomeSql as W, readAutomationExecutionSummaries as Wa, searchInboxItems as Wc, serviceAccountPlugins as Wd, createSlackDestination as Wf, pluginMcpContext as Wi, rankSearchMatches as Wl, findSlackThreadOwnerId as Wn, createSlackDirectCredentialSubject as Wo, juniorUsers as Wp, nudgeIdempotencyKey as Wr, savePushSubscription as Ws, appendInboundMessage as Wt, embedConversationQuery as Wu, awaitsAuthorizationFrom as X, refreshAutomationLastRun as Xa, INBOX_SUBJECT_KINDS as Xc, getMcpServiceAccountCredentials as Xd, listedConversation as Xf, createPluginConversationEvents as Xi, hasConversationMetadata as Xl, parseSlackUserInputSubmission as Xn, JUNIOR_THREAD_STATE_TTL_MS as Xo, buildSentryEventUrl as Xr, getSlackClient as Xs, clearConsumedConversationWake as Xt, searchWeb as Xu, conversationKindFromRow as Y, recordAutomationExecution as Ya, itemQuestion as Yc, createMcpServiceAccountClientProvider as Yd, spaceLeadIds as Yf, createPluginModelCostRecorder as Yi, dispatchInstructionsInvokeSkills as Yl, safeLinkUrl as Yn, updateTimerIndex as Yo, buildSentryConversationUrl as Yr, getHeaderString as Ys, claimInboundMessage as Yt, generateImages as Yu, hasUnexpiredAuthorizationRequest as Z, microUsdSql as Za, pluginSubjectKind as Zc, McpAuthorizationRequiredError as Zd, notLeadConversation as Zf, renderPluginConversationEvent as Zi, instructionAuthor as Zl, resolveSlackReplyTarget as Zn, canPauseConversationDelivery as Zo, formatSentryEventReference as Zr, isConversationChannel as Zs, clearExpiredConversationLease as Zt, transcribeFromUrl as Zu, unseenEvents as _, withScheduledAutomationLock as _a, updateViewerDisplayName as _c, ProviderError as _d, McpProviderError as _f, markDispatchAwaitingResume as _i, settleInboxSnoozes as _l, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as _n, slackChannelMessageRunsAutomation as _o, juniorInboxItemConversations as _p, dismissPluginInboxItem as _r, createPluginAnnotations as _s, itemNeedsUser as _t, eventNamespaceSchema as _u, getDb as a, createPluginCache as aa, sleep$2 as ac, createCache as ad, getMcpStoredOAuthCredentials as af, buildDispatchId as ai, parseAvatarUrl as al, getConversationWorkState as an, generateShortTitle as ao, todoFuzzyTitle as ap, createVercelPluginTaskCallback as ar, codeChangeSubjectProvider as as, inboxItemAddedByAnyAutomation as at, turnBehavior as au, conversationDescendants as b, createEventAutomation as ba, saveActorAvatar as bc, findProviderError as bd, getMcpAwareErrorType as bf, markDispatchFailed as bi, unsnoozeInboxRow as bl, deferConversationMove as bn, WORKSPACE_SNAPSHOT_READY_EVENT as bo, juniorAgentBindings as bp, takeOverPluginClose as br, listConversationAnnotationsById as bs, requireInboxItemAssignees as bt, registeredEventMatchSchema as bu, pendingMigrations as c, blockScheduledAutomation as ca, createPluginUsers as cc, estimateMessagesTokens as cd, putMcpServerSessionId as cf, createOrGetDispatch as ci, userAvatarUrlsFromIdentities as cl, recordAttemptFailure as cn, activeParticipantUserIds as co, questionFuzzyTitle as cp, sendVercelPluginTask as cr, codeChangeUrl as cs, inboxItemNeedsInput as ct, EVENT_MESSAGE_AUTHOR as cu, createSqlConversationEventStore as d, listScheduledAutomationsForTeam as da, readActorIdentity as dc, textCharsForTokens as dd, readEncryptedState as df, getDispatchInputMessageId as di, clearInboxWakeReasons as dl, requestAnotherSlice as dn, resolveAssignees as do, automationFuzzyTitle as dp, readThroughHttpCache as dr, assertNoObjectLinkConflicts as ds, inboxItemReaderForUserInConversation as dt, isEventAuthorId as du, pluginConfigValues as ea, isSlackRequestTimeout as ec, GEN_AI_SERVER_ADDRESS as ed, deleteMcpAuthSessionsForUserProvider as ef, decodeAnnotationRef as ei, subjectKindLabel as el, deadLetterAttempt as en, usdToMicroUsdUnbiased as eo, juniorTurnInbox as ep, createPluginEventPublisher as er, resumeConversationDelivery as es, canAgentChangeInboxItem as et, isTopLevel as eu, eventFromRow as f, parseScheduledAutomationRow as fa, readIdentityById as fc, readImageDimensions as fd, findLegacyWebActorUserId as ff, getDispatchRecord as fi, deleteExpiredInboxSnoozes as fl, requestConversationWork as fn, getEventCatalog as fo, automationSearchDocument as fp, createPluginConversationEventStats as fr, findObjectLinkType as fs, inboxItemVisibleTo as ft, isEventConversationMessage as fu, readEventCursor as g, scheduledRunId as ga, setUserAdminFromSql as gc, isCompactionSummaryText as gd, resolvePluginCommandEnv as gf, listPendingDispatchMailboxAppends as gi, readViewerInboxSnoozes as gl, takePendingEventMessages as gn, slackChannelMessageReplyThreadTs as go, inboxItemSearchDocument as gp, createPluginInboxItems as gr, annotationSubject as gs, isPluginInboxItem as gt, eventGuidance as gu, insertEventRows as h, saveScheduledAutomationInLock as ha, resolveViewerUser as hc, hasCompactedConversationContext as hd, resolvePluginHeaderEnvRefs as hf, isTerminalDispatchStatus as hi, listFiringInboxSnoozeTriggers as hl, stopConversationWork as hn, slackChannelMessageEvent as ho, inboxItemFuzzyTitle as hp, PLUGIN_CHOICE_FIELD_ID as hr, CORE_ANNOTATION_PLUGIN as hs, isOnlyAssignee as ht, describeRegisteredEventTrigger as hu, getConversationStore as i, runNonInteractiveCommand as ia, withSlackRetries as ic, cacheKeyPrefix as id, getMcpServerSessionId as if, resolveTurnResumeRouting as ii, identityAvatarUrl as il, getConversation as in, fallbackShortTitle as io, juniorTodos as ip, startedTaskDefinition as ir, codeChangeSubjectKinds as is, conversationOwnsInboxItem as it, remindsNoReplyForChildStatus as iu, startLocationThread as j, automationVersionOf as ja, inboxItemsNeedingUserVersionQuery as jc, context_exports as jd, parsePluginManifest as jf, unfurlSlackLinks as ji, parseDashboardTaskLink as jl, canShareTurn as jn, createTimerWatch as jo, codeChangeSearchDocument as jp, readableSlackTeamId as jr, resolveRootVisibility as js, juniorToolOutputSchema as jt, indexEndedTurnEvents as ju, locationFromRow as k, eventAutomationRunLimitReason as ka, readCachedUserByEmail as kc, conversationNoteEvent as kd, ServiceAccountUnavailableError as kf, postSlackMessage as ki, parseDashboardConversationLink as kl, withIdleConversation as kn, cancelWatch as ko, juniorApiTokens as kp, readConversationAccessFromSql as kr, writeConversationMetadata as ks, coreRegistrations as kt, embedConversationEvents as ku, readMigrationRecords as l, createScheduledAutomation as la, findUserByEmail as lc, estimateRequestOverheadTokens as ld, putMcpStoredOAuthCredentials as lf, getDispatchConversationId as li, userAvatarUrlsFromJoinedPhotos as ll, recordConversationRetry as ln, automationCreatorUserId as lo, questionSearchDocument as lp, queueCallback as lr, codeRepositoryUrl as ls, inboxItemPlugin as lt, EVENT_SYSTEM_ACTOR as lu, deleteMessageLinks as m, saveScheduledAutomation as ma, readViewerAvatarUrl as mc, COMPACTION_SUMMARY_PREFIX as md, resolveApiHeaderTransforms as mf, getPluginDispatchProjection as mi, inboxItemSnoozedBy as ml, steerWebPendingMessages as mn, requireSlackChannelMessageScope as mo, juniorStats as mp, createPluginConversationChanges as mr, ANNOTATION_SUBJECT_KINDS as ms, isInboxItemForEveryone as mt, automationEventCatalog as mu, getConversationEventStore as n, buildCommandScript as na, readPrivateSlackFile as nc, readServedProviders as nd, deleteMcpStoredOAuthCredentials as nf, verifySlackSignature as ni, subjectTodo as nl, dropPendingMessages as nn, AUTOMATION_ALERT_STEP_FIELD_ID as no, juniorWorkspaceRepos as np, getPluginRoutes as nr, annotationMatches as ns, canReadInboxItem as nt, postsRunNotices as nu, getSqlExecutor as o, getConfigDefaults as oa, getWorkspaceTeamId as oc, requestPrefixAttributes as od, patchMcpAuthSession as of, claimDispatchMailboxAppend as oi, readAvatarFetch as ol, getConversationWorkStates as on, resolveTaskTitle as oo, todoSearchDocument as op, pluginTaskId as or, readSubjectLinks as os, inboxItemAddedByAutomation as ot, watcherStartedConversation as ou, copyMessageLinks as p, readScheduledAutomation as pa, readIdentityByIdFromSql as pc, gatewayRoutingAttributes as pd, webActorUserIds as pf, getDispatchTurnId as pi, inboxItemInRow as pl, startConversationWork as pn, SLACK_EVENT_NAMESPACE as po, juniorAutomations as pp, createPluginTurnEventReader as pr, linkTypeName as ps, isAutomationAlertItem as pt, CORE_EVENT_NAMESPACE as pu, conversationWaitsOnUserSql as q, readAutomationRuns as qa, inboxItemRequest as qc, parseOAuthTokenResponse as qd, isLeadSql$1 as qf, createPluginEmbedder as qi, canMoveToSpace as ql, parseSlackInboxItemClick as qn, verifySlackDirectCredentialSubject as qo, juniorArtifacts as qp, verifyQueueMessage as qr, downloadPrivateSlackFile as qs, checkInConversationWork as qt, completeObject as qu, getConversationMessageSearchStore as r, buildNonInteractiveShellScript as ra, streamPrivateSlackFile as rc, saveEnabledProviders as rd, getMcpAuthSession as rf, resolveConversationRouting as ri, hasUserPhoto as rl, ensureConversationWake as rn, syncAutomationAlerts as ro, juniorWorkspaces as rp, createPluginTaskStarter as rr, resolveAnnotationFilter as rs, canUserReadInboxItem as rt, promptModeTurnTools as ru, createJuniorSqlExecutor as s, truncateStatusText as sa, runWithWorkspaceTeamId as sc, claudeMaxImageSize as sd, putMcpAuthSession as sf, confirmDispatchMailboxAppend as si, readUserAvatarUrls as sl, listActiveConversationIds as sn, EVERYONE_ASSIGNEE as so, juniorQuestions as sp, pluginTaskParamsSchema as sr, subjectKey as ss, inboxItemForUser as st, EVENT_AUTHOR_ID as su, db_exports as t, withPluginHookSpan as ta, normalizeSlackConversationId as tc, readEnabledProviders as td, deleteMcpServerSessionId as tf, runWithSlackInstallation as ti, subjectKindPlugin as tl, drainConversationMailbox as tn, AUTOMATION_ALERT_STEPS as to, juniorSnapshots as tp, getPluginApiRoutes as tr, searchConversations as ts, canAnswerInboxItem as tt, parentResultActor as tu, isPostgresErrorCode as u, deleteScheduledAutomation as ua, listAdminUsersFromSql as uc, estimateTextTokens as ud, createEncryptedState as uf, getDispatchIdForConversation as ui, SNOOZE_TIMER_EVENT_TYPE as ul, releaseConversationWork as un, resolveAssignee as uo, juniorAutomationRuns as up, getTurnRequestDeadline as ur, linkedCodeProviders as us, inboxItemReaderForUser as ut, eventBotAuthorId as uu, withConversationEventLock as v, blockEventAutomation as va, SYSTEM_IDENTITY_ID as vc, createAssistantProviderError as vd, McpServiceAccountRequiredError as vf, markDispatchBlocked as vi, snoozeInboxItems as vl, CONVERSATION_WORK_STALE_ENQUEUE_MS as vn, slackChannelMessageTrigger as vo, juniorInboxItems as vp, hasAssigneeRoles as vr, createPluginConversationAnnotations as vs, questionSubject as vt, eventWatchUnavailable as vu, loadConversationSlackTenantIds as w, listDeletedEventAutomationsCreatedBy as wa, findSlackUserByPrimaryEmail as wc, isProviderRetryError as wd, OAuthProviderError as wf, deleteSlackMessage as wi, getDashboardPersonLink as wl, isInvalidConversationRecordError as wn, agentWatch as wo, juniorConversationEventEmbeddings as wp, canInviteToConversation as wr, conversationSubtree as ws, inboxItemVisibility as wt, requireEventIdentifier as wu, readConversationTrees as x, deleteEventAutomation as xa, deleteProviderIdentityForSlackUser as xc, getProviderErrorAttributes as xd, getMcpAwareTelemetryMessage as xf, markDispatchRunning as xi, getDashboardConversationLink as xl, hasConversationStop as xn, workspaceSnapshotFinishedEvent as xo, juniorConversationReadPositions as xp, createPluginCodeChanges as xr, replaceAnnotationSubjectId as xs, requireInboxItemLinks as xt, registeredEventTriggerProblems as xu, conversationAncestors as y, collectEventAutomationMatchKeys as ya, resolveActorIdentityId as yc, createProviderError as yd, McpToolError as yf, markDispatchCompleted as yi, snoozeTimerTrigger as yl, countPendingConversationMessages as yn, WORKSPACE_SNAPSHOT_FAILED_EVENT as yo, juniorLocationConfigurations as yp, leavePluginInboxItem as yr, listConversationAnnotations as ys, readInboxItemAgentScope as yt, hasEventCatalogEntries as yu, conversationCostOf as z, existingConversationId as za, getInboxItem as zc, disconnectServiceAccount as zd, resolveRootConversationId as zf, slackMention as zi, parseTypedQuery as zl, pushConversationInboxItemsNow as zn, takeDueTimerWatches as zo, juniorSpaceConfigurations as zp, resolveConversationWorkTopic as zr, lookupSlackUserNames as zs, listTodos as zt, excerptTerms as zu };
|
|
30229
|
+
export { conversationOwnsInboxItem as $, createPluginCache as $a, getWorkspaceTeamId as $c, readEnabledProviders as $d, deleteMcpServerSessionId as $f, buildDispatchId as $i, identityAvatarUrl as $l, publishTurnEnded as $n, generateShortTitle as $o, juniorSnapshots as $p, createVercelPluginTaskCallback as $r, readSubjectLinks as $s, getConversation as $t, parentResultActor as $u, getConversationIdByProviderConversation as A, escapeSlackMrkdwnText as Aa, resolveUserTimezone as Ac, lexemesSql as Ad, createAppContext as Af, rootVisibleToViewer as Ai, closeInboxItem as Al, codeRepositorySearchDocument as Am, turnInputPayloadSchema as An, automationRevision as Ao, workloadIdentityHeader as Ap, questionContent as Ar, listConversationsWithWatches as As, CHILD_AGENT_KINDS as At, REVALIDATED_READ_PATHS as Au, conversationLastTurnOutcomeSql as B, createPluginDecider as Ba, downloadPrivateSlackFile as Bc, backfillConversationEmbeddings as Bd, serviceAccountAllows as Bf, signQueueMessage as Bi, inboxItemRequest as Bl, slackPersonPredicate as Bm, findStalledTurns as Bn, readAutomationRowStats as Bo, nextDetailVersion as Bp, buildSlackInboxItemModal as Br, verifySlackDirectCredentialSubject as Bs, beginConversationResume as Bt, prefixRank as Bu, createSqlStore as C, postSlackMessage as Ca, isPublicConversation as Cc, requireValidEventTrigger as Cd, getGatewayApiKey as Cf, readConversationAccessFromSql as Ci, countInboxItemsNeedingUserBySubject as Cl, juniorConversationEmbeddings as Cm, traceContextSchema as Cn, eventAutomationRunLimitReason as Co, fetchWithBoundedOAuthErrorBodies as Cp, runInboxItemPushTimers as Cr, collectEventMatchKeys as Cs, apiRoutePrefix as Ct, getDashboardSpaceLink as Cu, startLocationThread as D, slackEntitySchema as Da, resolveNotificationTimezone as Dc, embedConversationEvents as Dd, conversationNoteEvent as Df, conversationIsNotUnsubscribedRoot as Di, closeHandledReplyNotices as Dl, juniorApiTokens as Dm, isAttemptInterrupt as Dn, readAutomationVersion as Do, ServiceAccountUnavailableError as Dp, inboxItemDelivery as Dr, findMatchingWatches as Ds, makeStructuredToolOutput as Dt, parseDashboardPersonLink as Du, setFirstConversationLocation as E, uploadFilesToConversation as Ea, sendPushNotificationToUser as Ec, EVENT_INDEX_LOCK_TTL_MS as Ed, authenticationLinkedEvent as Ef, conversationIsMemberRoot as Ei, waitingConversationIdsQuery as El, juniorTurns as Em, canShareTurn as En, listAutomationVersions as Eo, CredentialUnavailableError as Ep, conversationIdsSchema as Er, deliverWatch as Es, juniorToolOutputSchema as Et, parseDashboardConversationLink as Eu, conversationCostOf as F, wrapBareSlackUserIds as Fa, readNotificationSchedule as Fc, callsToolSql as Fd, resolveAuthTokenPlaceholder as Ff, ConversationQueueMessageRejectedError as Fi, listReplyActionItems as Fl, juniorMessageAttachments as Fm, scheduleInput as Fn, readAutomationExecutionByConversationId as Fo, hasAgentTurnUsage as Fp, zodToolDefinition as Fr, bindScheduledAutomationCredentialSubject as Fs, setTodoStatusByUser as Ft, searchTypedMemories as Fu, conversationKindFromRow as G, renderPluginConversationEvent as Ga, isConversationScopedChannel as Gc, completeObject as Gd, parseOAuthTokenResponse as Gf, formatSentryEventReference as Gi, questionLinks as Gl, juniorArtifacts as Gm, replyText as Gn, microUsdSql as Go, isLeadSql$1 as Gp, resolveSlackReplyTarget as Gr, isConversationDeliveryPaused as Gs, clearConsumedConversationWake as Gt, deliversFinalText as Gu, conversationTurnFailedSql as H, createPluginModel as Ha, getHeaderString as Hc, embedConversationQuery as Hd, serviceAccountPlugins as Hf, getQueueProvider as Hi, itemQuestion as Hl, juniorUsers as Hm, holdsLease as Hn, readAutomationTitlesByConversationId as Ho, createSlackDestination as Hp, parseSlackInboxItemFormTarget as Hr, updateTimerIndex as Hs, checkInConversationWork as Ht, scoredSearchMatches as Hu, conversationAggregateColumns as I, applyPluginFormatMarkdown as Ia, saveNotificationSchedule as Ic, eventExcerpt as Id, mergeHeaderTransforms as If, conversationQueueMessageSchema as Ii, ownerConversationId as Il, juniorConversations as Im, stopTurns as In, readAutomationExecutionStatusDays as Io, isLeadConversation as Ip, resolveSlackInboxItemCardConversationId as Ir, bindSlackDirectCredentialSubject as Is, ackMessages as It, parseTypedQuery as Iu, treeAwaitsAuthorization as J, pluginConfigValues as Ja, normalizeSlackConversationId as Jc, searchWeb as Jd, getMcpServiceAccountCredentials as Jf, decodeAnnotationRef as Ji, subjectKindDismissNote as Jl, findTurnActor as Jn, usdToMicroUsdUnbiased as Jo, listedConversation as Jp, createPluginEventPublisher as Jr, searchConversations as Js, completeConversationWork as Jt, hasConversationMetadata as Ju, awaitsAuthorizationFrom as K, basePluginContext as Ka, isDmChannel as Kc, completeText as Kd, hasRequiredOAuthScope as Kf, renderSlackObjectCard as Ki, subjectKindActionLabel as Kl, createTurnStepConsumer as Kn, microUsdToUsd as Ko, rootSpaceIdSql as Kp, sendSlackReply as Kr, pauseConversationDelivery as Ks, clearExpiredConversationLease as Kt, dispatchInstructionsInvokeSkills as Ku, conversationRangeColumns as L, getPluginUserPromptContributions as La, savePushSubscription as Lc, excerptTerms as Ld, disconnectServiceAccount as Lf, isConversationQueueMessageRejectedError as Li, searchInboxItems as Ll, juniorSpaceConfigurations as Lm, claimTurn as Ln, readAutomationExecutionStatusHours as Lo, resolveRootConversationId as Lp, syncInboxItemSlackCards as Lr, createSlackDirectCredentialSubject as Ls, appendAndEnqueueExclusiveInboundMessage as Lt, fuzzyMatch as Lu, upsertDestination as M, normalizeSlackStatusText as Ma, lookupSlackUserNames as Mc, seqIn as Md, installAppContext as Mf, getVercelConversationWorkQueue as Mi, getInboxItem as Ml, juniorCodeRepositories as Mm, createEngineContext as Mn, emptyAutomationRunWindows as Mo, agentTurnCostUsd as Mp, readableItem as Mr, takeDueTimerWatches as Ms, agentNameSchema as Mt, contentVersionHeaders as Mu, parseSessionSource as N, slackMention as Na, deletePushSubscription as Nc, storeConversationEventLexemes as Nd, createPluginCatalogRuntime as Nf, resolveConversationWorkTopic as Ni, getOpenInboxItemBySubject as Nl, juniorAttachmentUploads as Nm, endFailedTurn as Nn, existingConversationId as No, agentTurnTotalTokens as Np, parseToolInput as Nr, turnEvents as Ns, spawnChildAgentInputSchema as Nt, revalidateContent as Nu, locationSchema as O, slackExternalRefIdSchema as Oa, defaultTimezone as Oc, eventIndexLockKey as Od, renderJuniorNativeConversationEvent as Of, conversationPinnedForUser as Oi, closeReadReplyNotice as Ol, juniorConversationAnnotations as Om, selectAttemptMessages as On, sameDefinitionValue as Oo, parseInlinePluginManifest as Op, itemResult as Or, getWatch as Os, findChildAgentConversationId as Ot, parseDashboardTaskLink as Ou, replaceConversationMetrics as P, slackMentionedUserIds as Pa, listPushSubscriptions as Pc, SEARCHABLE_EVENT_TYPES as Pd, HOST_MANAGED_CREDENTIAL_PLACEHOLDER as Pf, verifyConversationQueueMessage as Pi, insertInboxItem as Pl, juniorAttachments as Pm, reconcileTurn as Pn, linkAutomationRunConversation as Po, agentTurnUsageSchema as Pp, zodTool as Pr, bindEventAutomationCredentialSubject as Ps, listTodos as Pt, memoryDb as Pu, canUserReadInboxItem as Q, runNonInteractiveCommand as Qa, sleep$2 as Qc, GEN_AI_SERVER_ADDRESS as Qd, deleteMcpAuthSessionsForUserProvider as Qf, resolveTurnResumeRouting as Qi, hasUserPhoto as Ql, markInputsAttempted as Qn, fallbackShortTitle as Qo, juniorTurnInbox as Qp, startedTaskDefinition as Qr, codeChangeSubjectProvider as Qs, ensureConversationWake as Qt, isTopLevel as Qu, conversationUsageCostExpr as R, pluginMcpContext as Ra, isPausedBySlack as Rc, storedMessageJson as Rd, finishServiceAccountSignIn as Rf, nudgeIdempotencyKey as Ri, takeInboxItem as Rl, juniorSpaces as Rm, commitStep as Rn, readAutomationExecutionSummaries as Ro, rootConversationIsArchived as Rp, findSlackThreadOwnerId as Rr, verifyEventAutomationCredentialSubject as Rs, appendAndEnqueueInboundMessage as Rt, fuzzyRank as Ru, latestUserMessageQuery as S, postSlackEphemeralMessage as Sa, writeConversationMetadata as Sc, requireEventIdentifier as Sd, isProviderRetryError as Sf, leaveEndsAccess as Si, readCachedUserByEmail as Sl, juniorConversationEventEmbeddings as Sm, releaseInboundMessage as Sn, admitEventAutomationRun as So, OAuthProviderError as Sp, pushInboxSnoozeWakes as Sr, cancelWatch as Ss, validatePlugins as St, getDashboardSettingsLink as Su, locationFromRow as T, unfurlSlackLinks as Ta, readWebPushConfig as Tc, isToolInputError as Td, agentsInstructionsUpdatedEvent as Tf, readableSlackTeamId as Ti, listWaitingConversations as Tl, juniorConversationEvents as Tm, canJoinTurn as Tn, automationVersionOf as To, CredentialMintError as Tp, assigneesSchema as Tr, createWatch as Ts, injectContinuationToolName as Tt, isDashboardLink as Tu, conversationWaitsOnUserSql as U, createPluginModelCostRecorder as Ua, getSlackClient as Uc, storeConversationEmbedding as Ud, startServiceAccountSignIn as Uf, buildSentryConversationUrl as Ui, INBOX_SUBJECT_KINDS as Ul, juniorDestinations as Um, releaseTurn as Un, recordAutomationExecution as Uo, requireSlackDestination as Up, safeLinkUrl as Ur, JUNIOR_THREAD_STATE_TTL_MS as Us, claimConversationAttempt as Ut, fuseRankedLists as Uu, conversationStatusSql as V, createPluginEmbedder as Va, getFilePermalink as Vc, createConversationEmbedder as Vd, serviceAccountOnly as Vf, verifyQueueMessage as Vi, inboxItemTitle as Vl, slackPersonSearchDocument as Vm, findTurn as Vn, readAutomationRuns as Vo, touchConversationDetail as Vp, parseSlackInboxItemClick as Vr, verifyTimerWatchCredentialSubject as Vs, cancelHumanFacingPendingMessages as Vt, rankSearchMatches as Vu, executionIsActive as W, createPluginConversationEvents as Wa, isConversationChannel as Wc, completeDecision as Wd, buildOAuthTokenRequest as Wf, buildSentryEventUrl as Wi, pluginSubjectKind as Wl, guardedCosineDistance as Wm, findTurnReplies as Wn, refreshAutomationLastRun as Wo, sameDestination as Wp, parseSlackUserInputSubmission as Wr, canPauseConversationDelivery as Ws, claimInboundMessage as Wt, canMoveToSpace as Wu, canAgentChangeInboxItem as X, buildCommandScript as Xa, streamPrivateSlackFile as Xc, NoAudioError as Xd, PluginMcpClient as Xf, verifySlackSignature as Xi, subjectKindPlugin as Xl, findTurnInputs as Xn, AUTOMATION_ALERT_STEP_FIELD_ID as Xo, topLevelConversation as Xp, getPluginRoutes as Xr, resolveAnnotationFilter as Xs, drainConversationMailbox as Xt, isPersonInput as Xu, canActOnInboxItem as Y, withPluginHookSpan as Ya, readPrivateSlackFile as Yc, transcribeFromUrl as Yd, McpAuthorizationRequiredError as Yf, runWithSlackInstallation as Yi, subjectKindLabel as Yl, findTurnDestination as Yn, AUTOMATION_ALERT_STEPS as Yo, notLeadConversation as Yp, getPluginApiRoutes as Yr, annotationMatches as Ys, deadLetterAttempt as Yt, instructionAuthor as Yu, canAnswerInboxItem as Z, buildNonInteractiveShellScript as Za, withSlackRetries as Zc, GEN_AI_PROVIDER_NAME as Zd, deleteMcpAuthSession as Zf, resolveConversationRouting as Zi, subjectTodo as Zl, findUnreadInputs as Zn, syncAutomationAlerts as Zo, juniorTurnOutbox as Zp, createPluginTaskStarter as Zr, codeChangeSubjectKinds as Zs, dropPendingMessages as Zt, isThread as Zu, readConversationTrees as _, addReactionToMessage as _a, conversationSubtree as _c, hasEventCatalogEntries as _d, createProviderError as _f, canAddConversationMessages as _i, findSlackUserByPrimaryEmail as _l, juniorLocationConfigurations as _m, hasRunnableConversationWork as _n, getEventAutomation as _o, McpToolError as _p, readInboundMessageSender as _r, agentWatch as _s, inboxItemOwnedByThroughSubject as _t, unsnoozeInboxRow as _u, getDb as a, getDispatchInputMessageId as aa, findObjectLinkType as ac, EVENT_AUTHOR_ID as ad, claudeMaxImageSize as af, readThroughHttpCache as ai, readIdentityById as al, juniorQuestions as am, releaseConversationWork as an, listScheduledAutomationsForTeam as ao, putMcpAuthSession as ap, formatSlackConversationRedactedLabel as ar, getEventCatalog as as, inboxItemReaderForUser as at, SNOOZE_TIMER_EVENT_TYPE as au, loadConversationSlackTenantIds as b, openSlackDirectMessage as ba, conversationSearchVector as bc, registeredEventTypeSchema as bd, getProviderErrorUserMessage as bf, conversationAccessFromRows as bi, upsertLinkedIdentity as bl, juniorConversationParticipants as bm, moveIdleConversationDestination as bn, saveEventAutomation as bo, getMcpProviderErrorAttributes as bp, createInboxItemShow as br, starterWatchId as bs, getPlugins as bt, getDashboardLinkFilter as bu, pendingMigrations as c, getPluginDispatchProjection as ca, CORE_ANNOTATION_PLUGIN as cc, eventBotAuthorId as cd, estimateTextTokens as cf, createPluginConversationChanges as ci, resolveViewerUser as cl, juniorAutomationRuns as cm, startConversationWork as cn, saveScheduledAutomation as co, createEncryptedState as cp, resolveSlackConversationContextFromThreadId as cr, slackChannelMessageEvent as cs, isAutomationAlertItem as ct, inboxItemInRow as cu, createSqlConversationEventStore as d, markDispatchAwaitingResume as da, createPluginConversationAnnotations as dc, CORE_EVENT_NAMESPACE as dd, gatewayRoutingAttributes as df, dismissPluginInboxItem as di, SYSTEM_IDENTITY_ID as dl, juniorAutomations as dm, takePendingEventMessages as dn, withScheduledAutomationLock as do, webActorUserIds as dp, readSlackRawMessageContext as dr, slackChannelMessageTrigger as ds, isPluginInboxItem as dt, readViewerInboxSnoozes as du, claimDispatchMailboxAppend as ea, subjectKey as ec, postsRunNotices as ed, readServedProviders as ef, pluginTaskId as ei, runWithWorkspaceTeamId as el, juniorWorkspaceRepos as em, getConversationWorkState as en, getConfigDefaults as eo, deleteMcpStoredOAuthCredentials as ep, readTurnEndedMessages as er, resolveTaskTitle as es, inboxItemAddedByAnyAutomation as et, parseAvatarUrl as eu, eventFromRow as f, markDispatchBlocked as fa, listConversationAnnotations as fc, automationEventCatalog as fd, COMPACTION_SUMMARY_PREFIX as ff, hasAssigneeRoles as fi, resolveActorIdentityId as fl, juniorStats as fm, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as fn, blockEventAutomation as fo, resolveApiHeaderTransforms as fp, resolveSlackChannelIdFromMessage as fr, WORKSPACE_SNAPSHOT_FAILED_EVENT as fs, itemNeedsUser as ft, settleInboxSnoozes as fu, conversationDescendants as g, notifyAutomationBlocked as ga, conversationAncestorsOrSelf as gc, eventWatchUnavailable as gd, createAssistantProviderError as gf, canAccessConversation as gi, findLinkedSlackUser as gl, juniorInboxItems as gm, hasConversationStop as gn, findMatchingEventAutomations as go, McpServiceAccountRequiredError as gp, withConversationEventLock as gr, AGENT_RESOURCE_TYPE as gs, requireInboxItemLinks as gt, snoozeTimerWakeAtMs as gu, conversationAncestors as h, markDispatchRunning as ha, upsertPluginAnnotation as hc, eventNamespaceSchema as hd, ProviderError as hf, createPluginCodeChanges as hi, deleteProviderIdentityForUser as hl, juniorInboxItemConversations as hm, deferConversationMove as hn, deleteEventAutomation as ho, McpProviderError as hp, resumeConversationTree as hr, workspaceSnapshotWatch as hs, requireInboxItemAssignees as ht, snoozeTimerTrigger as hu, getConversationStore as i, getDispatchIdForConversation as ia, assertNoObjectLinkConflicts as ic, watcherStartedConversation as id, requestPrefixAttributes as if, getTurnRequestDeadline as ii, readActorIdentity as il, todoSearchDocument as im, recordConversationRetry as in, deleteScheduledAutomation as io, patchMcpAuthSession as ip, conversationVisibilityFromSlackChannelType as ir, resolveAssignees as is, inboxItemPlugin as it, userAvatarUrlsFromJoinedPhotos as iu, destinationUpsertFromDestination as j, formatSlackLink as ja, lookupSlackUser as jc, searchedEventTextSql as jd, getAppContext as jf, viewerMarksFromParticipant as ji, dismissOpenInboxItems as jl, juniorCodeChanges as jm, turnGroupKey as jn, requireAutomationRevision as jo, addAgentTurnUsage as jp, questionsSchema as jr, listWatches as js, PARENT_AGENT_TARGET as jt, contentVersion as ju, claimProviderConversation as k, SLACK_USER_MENTION_RE as ka, findActorTimezone as kc, indexEndedTurnEvents as kd, context_exports as kf, readMemberParticipants as ki, INBOX_ITEM_REPLIED_REASON as kl, codeChangeSearchDocument as km, readParentMessage as kn, AutomationConflictError as ko, parsePluginManifest as kp, ownerLinks as kr, isQuietEvent as ks, getAgentBinding as kt, projectConversationMessages as ku, readMigrationRecords as l, isTerminalDispatchStatus as la, annotationSubject as lc, isEventAuthorId as ld, textCharsForTokens as lf, createPluginInboxItems as li, setUserAdminFromSql as ll, automationFuzzyTitle as lm, steerWebPendingMessages as ln, saveScheduledAutomationInLock as lo, readEncryptedState as lp, slackChannelTypeFromConversationInfo as lr, slackChannelMessageReplyThreadTs as ls, isInboxItemForEveryone as lt, inboxItemSnoozedBy as lu, deleteMessageLinks as m, markDispatchFailed as ma, replaceAnnotationSubjectId as mc, eventGuidance as md, isCompactionSummaryText as mf, takeOverPluginClose as mi, deleteProviderIdentityForSlackUser as ml, inboxItemSearchDocument as mm, countPendingConversationMessages as mn, createEventAutomation as mo, resolvePluginCommandEnv as mp, getConversationStoppedAtMs as mr, workspaceSnapshotFinishedEvent as ms, readInboxItemAgentScope as mt, snoozeTimerId as mu, getConversationEventStore as n, createOrGetDispatch as na, codeRepositoryUrl as nc, remindsNoReplyForChildStatus as nd, cacheKeyPrefix as nf, sendVercelPluginTask as ni, findUserByEmail as nl, juniorTodos as nm, listActiveConversationIds as nn, blockScheduledAutomation as no, getMcpServerSessionId as np, setActiveSpanAttributes as nr, automationCreatorUserId as ns, inboxItemForUser as nt, readUserAvatarUrls as nu, getSqlExecutor as o, getDispatchRecord as oa, linkTypeName as oc, EVENT_MESSAGE_AUTHOR as od, estimateMessagesTokens as of, createPluginConversationEventStats as oi, readIdentityByIdFromSql as ol, questionFuzzyTitle as om, requestAnotherSlice as on, parseScheduledAutomationRow as oo, putMcpServerSessionId as op, resolveSlackChannelTypeFromMessage as or, SLACK_EVENT_NAMESPACE as os, inboxItemReaderForUserInConversation as ot, clearInboxWakeReasons as ou, copyMessageLinks as p, markDispatchCompleted as pa, listConversationAnnotationsById as pc, describeRegisteredEventTrigger as pd, hasCompactedConversationContext as pf, leavePluginInboxItem as pi, saveActorAvatar as pl, inboxItemFuzzyTitle as pm, CONVERSATION_WORK_STALE_ENQUEUE_MS as pn, collectEventAutomationMatchKeys as po, resolvePluginHeaderEnvRefs as pp, legacyWebMailboxMetadataSchema as pr, WORKSPACE_SNAPSHOT_READY_EVENT as ps, questionSubject as pt, snoozeInboxItems as pu, hasUnexpiredAuthorizationRequest as q, createSandboxCapability as qa, isSlackRequestTimeout as qc, generateImages as qd, createMcpServiceAccountClientProvider as qf, annotationKeyDigest as qi, subjectKindActions as ql, publishTurnStep as qn, usdToMicroUsd as qo, spaceLeadIds as qp, resolveEventMentions as qr, resumeConversationDelivery as qs, completeConversationStop as qt, feedRowShowsThreads as qu, getConversationMessageSearchStore as r, getDispatchConversationId as ra, linkedCodeProviders as rc, turnBehavior as rd, createCache as rf, queueCallback as ri, listAdminUsersFromSql as rl, todoFuzzyTitle as rm, recordAttemptFailure as rn, createScheduledAutomation as ro, getMcpStoredOAuthCredentials as rp, withSpan as rr, resolveAssignee as rs, inboxItemNeedsInput as rt, userAvatarUrlsFromIdentities as ru, createJuniorSqlExecutor as s, getDispatchTurnId as sa, ANNOTATION_SUBJECT_KINDS as sc, EVENT_SYSTEM_ACTOR as sd, estimateRequestOverheadTokens as sf, createPluginTurnEventReader as si, readViewerAvatarUrl as sl, questionSearchDocument as sm, requestConversationWork as sn, readScheduledAutomation as so, putMcpStoredOAuthCredentials as sp, resolveSlackConversationContext as sr, requireSlackChannelMessageScope as ss, inboxItemVisibleTo as st, deleteExpiredInboxSnoozes as su, db_exports as t, confirmDispatchMailboxAppend as ta, codeChangeUrl as tc, promptModeTurnTools as td, saveEnabledProviders as tf, pluginTaskParamsSchema as ti, createPluginUsers as tl, juniorWorkspaces as tm, getConversationWorkStates as tn, truncateStatusText as to, getMcpAuthSession as tp, countMetric as tr, activeParticipantUserIds as ts, inboxItemAddedByAutomation as tt, readAvatarFetch as tu, isPostgresErrorCode as u, listPendingDispatchMailboxAppends as ua, createPluginAnnotations as uc, isEventConversationMessage as ud, readImageDimensions as uf, legacyChoiceAction as ui, updateViewerDisplayName as ul, automationSearchDocument as um, stopConversationWork as un, scheduledRunId as uo, findLegacyWebActorUserId as up, parseSlackThreadId as ur, slackChannelMessageRunsAutomation as us, isOnlyAssignee as ut, listFiringInboxSnoozeTriggers as uu, setArchivedAt as v, deleteSlackMessage as va, conversationSubtreeColumns as vc, registeredEventMatchSchema as vd, findProviderError as vf, canInviteToConversation as vi, findUserByVerifiedEmails as vl, juniorAgentBindings as vm, isFinalAttempt as vn, listDeletedEventAutomationsCreatedBy as vo, getMcpAwareErrorType as vp, isEventMailboxMetadata as vr, isAgentResourceType as vs, inboxItemOwnerConversationId as vt, getDashboardConversationLink as vu, withConversationMutationLock as w, removeReactionFromMessage as wa, resolveRootVisibility as wc, ToolInputError as wd, JUNIOR_NATIVE_EVENT_NAMESPACE as wf, readConversationAccessRows as wi, inboxItemsNeedingUserVersionQuery as wl, juniorConversationMetrics as wm, withIdleConversation as wn, automationDefinition as wo, getOAuthProviderErrorAttributes as wp, INBOX_TOOL_SOURCE as wr, createTimerWatch as ws, coreRegistrations as wt, getDashboardTaskLink as wu, lastMessageAtSql as x, openSlackModal as xa, readConversationMetadata as xc, registeredResourceTypeSchema as xd, isProviderRefusal as xf, createConversationAccessReader as xi, readCachedLinkedHandle as xl, juniorConversationEventLexemes as xm, pruneActiveConversation as xn, setEventAutomationStatus as xo, toMcpProviderError as xp, pushConversationInboxItemsNow as xr, cancelSubscriptions as xs, getRegistrations as xt, getDashboardPersonLink as xu, conversationSlackTenantId as y, getSlackMessagePermalink as ya, loadAnnotationLabeler as yc, registeredEventTriggerProblems as yd, getProviderErrorAttributes as yf, canReadConversation as yi, recordGoogleSignIn as yl, juniorConversationReadPositions as ym, isInvalidConversationRecordError as yn, parseEventAutomationRow as yo, getMcpAwareTelemetryMessage as yp, createSlackInboxItemToolServices as yr, publishAgentUpdate as ys, inboxItemVisibility as yt, getDashboardInboxItemLink as yu, conversationIsActiveSql as z, createPluginState as za, SlackActionError as zc, isEventEmbeddingsEnabled as zd, getServiceAccountStatus as zf, QUEUE_SIGNATURE_MAX_AGE_MS as zi, updateInboxItemContent as zl, juniorIdentities as zm, findDiscardedUsage as zn, readAutomationExecutions as zo, conversationDetailTouch as zp, SLACK_INBOX_ITEM_VIEW_ID as zr, verifyScheduledAutomationCredentialSubject as zs, appendInboundMessage as zt, prefixMatch as zu };
|