@sentry/junior 0.285.0 → 0.287.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-DN5AB4VU.js → adapter-CL-HUKgd.js} +1 -1
- package/dist/{admin-DOITMKnn.js → admin-C9urXVfi.js} +2 -1
- package/dist/{agent-runner-BsWhHe4N.js → agent-runner-Bfnw551N.js} +2174 -1323
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +7 -7
- package/dist/api.d.ts +1 -1
- package/dist/api.js +73 -112
- package/dist/{app-DyMs9330.d.ts → app-DBY5TnfY.d.ts} +2 -3
- package/dist/app.d.ts +1 -1
- package/dist/app.js +72 -42
- package/dist/{assistant-reply-9Jip5bsr.js → assistant-reply-u_PRYzuz.js} +1 -1
- package/dist/{automation-Mk8aaHzy.js → automation-DksGNDRO.js} +3 -6
- package/dist/{background-compaction-queue-DXkLsWoH.js → background-compaction-queue-CYI909P5.js} +137 -3
- package/dist/{briefs-Cl8-nK9B.js → briefs-DaXiMWzT.js} +6 -5
- package/dist/{catalog-runtime-Bte6jRB2.js → catalog-runtime-BCIuBe4d.js} +1 -1
- package/dist/cli/chat.js +14 -14
- package/dist/cli/check.js +3 -3
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +4 -4
- package/dist/cli/snapshot-create.js +5 -6
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -3
- package/dist/{client-DDbBucBw.js → config-CkHcUMN7.js} +580 -3
- package/dist/{connections-DA4LT9LL.js → connections-BnIj0wtx.js} +16 -50
- package/dist/{conversation-D8kVoCrP.js → conversation-E7ZPJx2H.js} +22 -6
- package/dist/{conversation-pending-messages-BvROq1bq.js → conversation-pending-messages-DVch6YQw.js} +2 -5
- package/dist/{conversation-privacy-D0j_h70R.js → conversation-privacy-DF1hW0ja.js} +1 -1
- package/dist/{credential-sync-hcsYatw-.js → credential-sync-CzMar9hq.js} +13 -13
- package/dist/{viewer-1Ea81s0b.js → db-DJ11eZqq.js} +64 -367
- package/dist/{db-BhHZSuFw.d.ts → db-YDKKDxlh.d.ts} +4 -4
- package/dist/{executor-BLEMIgIZ.js → executor-BY9TB31g.js} +20 -19
- package/dist/instrumentation.js +2 -2
- package/dist/{logging-BfORLKoq.js → logging-BO5zU6Mt.js} +1 -1
- package/dist/{media-Bu9C6lz0.js → media-Cz1ZiV1U.js} +16 -4
- package/dist/{message-DqjuKzUx.js → message-CsUbuEc8.js} +10 -10
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +2 -3
- package/dist/{oauth-callback-server-CFSRzu1n.js → oauth-callback-server-hiDKK0_n.js} +2 -2
- package/dist/{projection-DliWYrnT.js → projection-CL_YWeGf.js} +352 -356
- package/dist/{prompt-BvIUzY4y.js → prompt-BHOEQSmf.js} +182 -2
- package/dist/{registry-rC7MCxu8.js → registry-BriFLnaJ.js} +1 -1
- package/dist/{reporting-window-B4TwyuJo.js → reporting-window-B3Ze-Qnt.js} +4 -1
- package/dist/{resolve-Biu8Qw3u.js → resolve-Bt6GgAiA.js} +3 -3
- package/dist/{result-DxJMCX47.js → result-Bo1TZu0Q.js} +8 -8
- package/dist/{runner-BQJSFLKg.js → runner-D3YeCQgt.js} +16 -12
- package/dist/{sandbox-egress-signals-6aMxJSDn.js → sandbox-egress-signals-CcnSPP4S.js} +1 -1
- package/dist/{schema-BasXTvi2.js → schema-BWE3RJEB.js} +19 -7
- package/dist/{schema-BUviRAs8.d.ts → schema-C6fsEwjo.d.ts} +90 -8
- package/dist/{service-account-BI5Wgx22.js → service-account-DiQQuuw7.js} +3 -3
- package/dist/{service-account-CAE-_1dR.js → service-account-r6fl0b-9.js} +3 -3
- package/dist/{session-stop-CA-jOJ84.js → session-stop-B2Nut40V.js} +27 -25
- package/dist/{skills-B22duVJU.js → skills-CD5aJdzg.js} +2 -2
- package/dist/spawn-CalgZQiu.js +79 -0
- package/dist/{stop-DioIcEAu.js → stop-kujZLbi0.js} +233 -1127
- package/dist/{store-Dn4W7qgH.js → store-DdIEUL1q.js} +3 -3
- package/dist/{turn-session-routing-CGMKrYOj.js → task-runner-D_RDr2Hu.js} +1440 -993
- package/dist/{store-B26LV6UP.js → turn-failure-response-B5nV1Er-.js} +337 -6
- package/dist/{validation-TzhfQABF.js → validation-K4pqwoVZ.js} +1 -1
- package/dist/{version-DSk8CFvA.js → version-DBvhk1X9.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/viewer-DrMmFUul.js +337 -0
- package/dist/{work-ybG4_q5C.js → work-ljRoODGu.js} +110 -94
- package/dist/{worker-ccSyZRNz.js → worker-CYO1Q0Js.js} +5 -6
- package/migrations/0086_shared_archive.sql +31 -0
- package/migrations/0087_child_location.sql +64 -0
- package/migrations/0088_conversation_unsubscribe.sql +1 -0
- package/migrations/meta/0086_snapshot.json +4366 -0
- package/migrations/meta/0087_snapshot.json +4366 -0
- package/migrations/meta/0088_snapshot.json +4372 -0
- package/migrations/meta/_journal.json +21 -0
- package/package.json +5 -4
- package/dist/config-DqFnykQT.js +0 -579
- package/dist/spawn-BB2_4VYn.js +0 -31
- package/dist/task-queue-Bt0IoR2i.js +0 -139
- package/dist/task-runner-D8lddjzp.js +0 -290
- package/dist/thread-state-CrFk3K_7.js +0 -173
- package/dist/turn-failure-response-DaJ04qVj.js +0 -224
- package/dist/turn-lifecycle-C2mXS7AZ.js +0 -58
|
@@ -1,29 +1,30 @@
|
|
|
1
1
|
import { a as getClient$1, h as startSpan, n as captureMessage, r as continueTrace, v as __exportAll } from "./sentry-BRTJqumy.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { t as canExposeConversationPayload } from "./conversation-privacy-D0j_h70R.js";
|
|
2
|
+
import { E as resolveGatewayModel, M as escapeXml, S as completeObject, T as rerankTexts, U as toOptionalTrimmed, i as getChatConfig, j as unwrapCurrentInstruction, n as botConfig, o as getSlackBotToken, v as normalizeSlackEmojiName, w as embedTexts, x as completeDecision, y as GEN_AI_PROVIDER_NAME, z as isProviderRetryError } from "./config-CkHcUMN7.js";
|
|
3
|
+
import { E as withSpan, G as toOptionalNumber, K as toOptionalString, W as isRecord$2, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, c as getLogContextAttributes, d as logAudit, h as logWarn, m as logInfo, o as getActiveTraceContext, p as logException, t as buildTurnFailureResponse, x as setSpanStatus, y as setSentryUser } from "./logging-BO5zU6Mt.js";
|
|
4
|
+
import { t as canExposeConversationPayload } from "./conversation-privacy-DF1hW0ja.js";
|
|
6
5
|
import { c as parseStoredSlackActor, d as parseSlackChannelReferenceId, f as parseSlackTeamId, h as parseSlackMessageTs, i as isActorUserId, l as toStoredSlackActor, p as parseSlackUserId, s as parseActorUserId } from "./actor-6jsm_v96.js";
|
|
7
|
-
import {
|
|
8
|
-
import { D as juniorCodeChanges, E as juniorConversationAnnotations, M as
|
|
9
|
-
import { _ as instructionProvenanceFor, g as instructionActors, h as contextProvenance, o as agentHistoryItemSchema } from "./media-
|
|
10
|
-
import { _ as CredentialUnavailableError, a as resolveAuthTokenPlaceholder, f as credentialContextForActor, h as credentialSubjectSchema, m as credentialLogContext, o as resolvePluginCommandEnv, p as credentialContextSchema } from "./registry-
|
|
11
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
6
|
+
import { D as resolveActorIdentityId, G as hasAgentTurnUsage, I as bindProviderConversation, J as parseDestination, M as readUserTimezone, P as saveUserTimezone, R as conversationDetailTouch, V as addAgentTurnUsage, X as sameDestination, a as getConversationStore, d as createSqlConversationEventStore, f as eventFromRow, o as getDb, p as withConversationEventLock, r as getConversationEventStore, s as getSqlExecutor, w as startLocationThread, y as createSqlStore } from "./db-DJ11eZqq.js";
|
|
7
|
+
import { A as juniorConversations, D as juniorCodeChanges, E as juniorConversationAnnotations, M as juniorUsers, N as juniorDestinations, O as juniorCodeRepositories, a as juniorPushSubscriptions, b as juniorConversationBriefs, f as juniorAutomations, i as juniorWorkspaces, j as juniorIdentities, k as juniorAttachments, l as juniorReviewItems, m as juniorLocationConfigurations, n as juniorSnapshots, o as juniorReviewItemAssignees, r as juniorWorkspaceRepos, s as juniorReviewItemConversations, v as juniorConversationParticipants, w as juniorConversationEvents } from "./executor-BY9TB31g.js";
|
|
8
|
+
import { _ as instructionProvenanceFor, g as instructionActors, h as contextProvenance, o as agentHistoryItemSchema } from "./media-Cz1ZiV1U.js";
|
|
9
|
+
import { _ as CredentialUnavailableError, a as resolveAuthTokenPlaceholder, f as credentialContextForActor, h as credentialSubjectSchema, m as credentialLogContext, o as resolvePluginCommandEnv, p as credentialContextSchema } from "./registry-BriFLnaJ.js";
|
|
10
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-BCIuBe4d.js";
|
|
11
|
+
import { d as JUNIOR_NATIVE_EVENT_NAMESPACE, f as agentsInstructionsUpdatedEvent, g as renderJuniorNativeConversationEvent, l as completeObject$1, m as authenticationUnlinkedEvent, n as briefEntriesFromReportEvents, o as isEventConversationMessage, p as authenticationLinkedEvent, s as generateBrief, t as BRIEF_PROMPT, u as completeText } from "./prompt-BHOEQSmf.js";
|
|
12
12
|
import { a as withLock, i as fenceLock, n as MUTATION_LOCK_TTL_MS, r as acquireActiveLock } from "./locks-D-0h111u.js";
|
|
13
|
-
import { n as
|
|
13
|
+
import { g as createCache, i as readActorIdentity, l as resolveViewerUser, n as findUserByEmailFromSql, o as readIdentityById, p as parseAvatarUrl, s as readIdentityByIdFromSql } from "./viewer-DrMmFUul.js";
|
|
14
|
+
import { a as setStateValues, i as getStateValues, n as getDefaultRedisStateAdapterFor, r as getStateAdapter } from "./adapter-CL-HUKgd.js";
|
|
14
15
|
import { n as isWithinNotificationSchedule, r as notificationScheduleSchema, s as isValidTimeZone, t as DEFAULT_NOTIFICATION_SCHEDULE } from "./schedule-BTp__wrw.js";
|
|
15
|
-
import { A as reviewItemChangeRecordSchema, B as readMessageAttachments, G as conversationBriefSchema, K as parseBriefInput, M as messageCardRef, P as readMessageCardRefs, W as briefResourceLabel, _ as conversationReportEventSchema, q as parseStoredBrief, v as conversationReportMessageEventSchema } from "./conversation-
|
|
16
|
-
import { n as briefEntriesFromReportEvents, s as generateBrief, t as BRIEF_PROMPT } from "./prompt-BvIUzY4y.js";
|
|
16
|
+
import { A as reviewItemChangeRecordSchema, B as readMessageAttachments, G as conversationBriefSchema, K as parseBriefInput, M as messageCardRef, P as readMessageCardRefs, W as briefResourceLabel, _ as conversationReportEventSchema, q as parseStoredBrief, v as conversationReportMessageEventSchema } from "./conversation-E7ZPJx2H.js";
|
|
17
17
|
import { n as redactSandboxEgressProxyPath, t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
|
|
18
18
|
import path from "node:path";
|
|
19
19
|
import { isDeepStrictEqual } from "node:util";
|
|
20
20
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
21
21
|
import { createHash, createHmac, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, randomUUID, sign, timingSafeEqual } from "node:crypto";
|
|
22
22
|
import * as z from "zod";
|
|
23
|
-
import { and, arrayContains, asc, count, desc, eq, exists, getTableColumns, gt, gte, ilike, inArray, isNotNull, isNull, lt, lte, max, ne,
|
|
24
|
-
import { EgressAuthRequired, EgressPolicyDenied, actorSchema, codeChangeInputSchema, conversationAnnotationInputSchema,
|
|
23
|
+
import { and, arrayContains, asc, count, desc, eq, exists, getTableColumns, gt, gte, ilike, inArray, isNotNull, isNull, lt, lte, max, ne, notInArray, or, sql } from "drizzle-orm";
|
|
24
|
+
import { EgressAuthRequired, EgressPolicyDenied, actorSchema, codeChangeInputSchema, conversationAnnotationInputSchema, defineConversationEvent, destinationSchema, eventDataSchema, eventInputSchema, eventMatchSchema, eventMatches, eventTypeSchema, isPluginModelCostEventName, missingToolAnnotationKeys, normalizeEventIdentifier, objectAnnotationSchema, objectIconPath, objectTypeSchema, pluginAuthorizationSchema, pluginCredentialHeaderTransformSchema, pluginCredentialResultSchema, pluginEventsSchema, pluginGrantSchema, pluginModelCostEventNames, pluginProviderAccountSchema, pluginStoredTokensSchema, pluginToolReplySchema, promptContextSchema, promptMessageSchema, sourceSchema, stableEventMatchKey } from "@sentry/junior-plugin-api";
|
|
25
25
|
import { alias, union } from "drizzle-orm/pg-core";
|
|
26
26
|
import fs from "node:fs/promises";
|
|
27
|
+
import pLimit from "p-limit";
|
|
27
28
|
import http from "node:http";
|
|
28
29
|
import os from "node:os";
|
|
29
30
|
import dns from "node:dns/promises";
|
|
@@ -62,139 +63,6 @@ z.object({
|
|
|
62
63
|
content: z.array(z.unknown()),
|
|
63
64
|
role: z.string().min(1)
|
|
64
65
|
}).passthrough().transform((value) => value);
|
|
65
|
-
// src/chat/conversations/structured-events.ts
|
|
66
|
-
/** Reserved namespace for Junior-owned conversation metadata events. */
|
|
67
|
-
const JUNIOR_NATIVE_EVENT_NAMESPACE = "junior";
|
|
68
|
-
const authenticationEventContentSchema = z.object({
|
|
69
|
-
accountLabel: z.string().trim().min(1).max(120).optional(),
|
|
70
|
-
actorId: z.string().min(1),
|
|
71
|
-
authorizationId: z.string().min(1).optional(),
|
|
72
|
-
provider: z.string().regex(/^[a-z][a-z0-9-]*$/),
|
|
73
|
-
providerLabel: z.string().trim().min(1).max(80).optional()
|
|
74
|
-
}).strict();
|
|
75
|
-
const agentsInstructionsUpdatedContentSchema = z.object({
|
|
76
|
-
action: z.enum([
|
|
77
|
-
"loaded",
|
|
78
|
-
"replaced",
|
|
79
|
-
"cleared"
|
|
80
|
-
]),
|
|
81
|
-
directory: z.string().trim().min(1).max(500).optional(),
|
|
82
|
-
fingerprint: z.string().trim().min(1).max(128),
|
|
83
|
-
sources: z.array(z.object({
|
|
84
|
-
content: z.string().min(1).max(32768),
|
|
85
|
-
path: z.string().trim().min(1).max(500)
|
|
86
|
-
}).strict()).max(32),
|
|
87
|
-
textBytes: z.number().int().nonnegative().optional()
|
|
88
|
-
}).strict();
|
|
89
|
-
function providerTitle(content) {
|
|
90
|
-
return content.providerLabel?.trim() || content.provider;
|
|
91
|
-
}
|
|
92
|
-
function agentsInstructionsTitle(action) {
|
|
93
|
-
if (action === "loaded") return "Loaded AGENTS.md";
|
|
94
|
-
if (action === "replaced") return "Updated AGENTS.md";
|
|
95
|
-
return "Cleared AGENTS.md";
|
|
96
|
-
}
|
|
97
|
-
function sourceFilename(sourcePath) {
|
|
98
|
-
return sourcePath.split("/").at(-1) || sourcePath;
|
|
99
|
-
}
|
|
100
|
-
function formatBytes(bytes) {
|
|
101
|
-
if (bytes < 1024) return `${bytes} bytes`;
|
|
102
|
-
const kilobytes = bytes / 1024;
|
|
103
|
-
return `${Number.isInteger(kilobytes) ? kilobytes : kilobytes.toFixed(1)} KB`;
|
|
104
|
-
}
|
|
105
|
-
function agentsInstructionsPreview(content) {
|
|
106
|
-
const source = content.sources[0];
|
|
107
|
-
if (!source) return void 0;
|
|
108
|
-
const filename = sourceFilename(source.path);
|
|
109
|
-
const label = content.sources.length === 1 ? filename : `${content.sources.length} AGENTS.md files`;
|
|
110
|
-
return typeof content.textBytes === "number" ? `${label} · ${formatBytes(content.textBytes)}` : label;
|
|
111
|
-
}
|
|
112
|
-
/** Junior-owned account-link transcript event. */
|
|
113
|
-
const authenticationLinkedEvent = defineConversationEvent({
|
|
114
|
-
name: "authentication_linked",
|
|
115
|
-
version: 1,
|
|
116
|
-
schema: authenticationEventContentSchema,
|
|
117
|
-
renderEvent(event) {
|
|
118
|
-
const provider = providerTitle(event);
|
|
119
|
-
return {
|
|
120
|
-
icon: "link",
|
|
121
|
-
title: `${provider} connected`,
|
|
122
|
-
...event.accountLabel ? { preview: `Connected as \`${event.accountLabel}\`` } : void 0,
|
|
123
|
-
details: [{
|
|
124
|
-
title: `${provider} connected`,
|
|
125
|
-
...event.accountLabel ? { description: `Connected as \`${event.accountLabel}\`` } : void 0,
|
|
126
|
-
metadata: [event.provider]
|
|
127
|
-
}]
|
|
128
|
-
};
|
|
129
|
-
}
|
|
130
|
-
});
|
|
131
|
-
/** Junior-owned account-unlink transcript event. */
|
|
132
|
-
const authenticationUnlinkedEvent = defineConversationEvent({
|
|
133
|
-
name: "authentication_unlinked",
|
|
134
|
-
version: 1,
|
|
135
|
-
schema: authenticationEventContentSchema,
|
|
136
|
-
renderEvent(event) {
|
|
137
|
-
const provider = providerTitle(event);
|
|
138
|
-
return {
|
|
139
|
-
icon: "key",
|
|
140
|
-
title: `${provider} disconnected`,
|
|
141
|
-
details: [{
|
|
142
|
-
title: `${provider} disconnected`,
|
|
143
|
-
metadata: [event.provider]
|
|
144
|
-
}]
|
|
145
|
-
};
|
|
146
|
-
}
|
|
147
|
-
});
|
|
148
|
-
/** Junior-owned AGENTS.md bootstrap transition for the dashboard timeline. */
|
|
149
|
-
const agentsInstructionsUpdatedEvent = defineConversationEvent({
|
|
150
|
-
name: "agents_instructions_updated",
|
|
151
|
-
version: 1,
|
|
152
|
-
schema: agentsInstructionsUpdatedContentSchema,
|
|
153
|
-
renderEvent(event) {
|
|
154
|
-
const title = agentsInstructionsTitle(event.action);
|
|
155
|
-
const preview = agentsInstructionsPreview(event);
|
|
156
|
-
return {
|
|
157
|
-
icon: "brain",
|
|
158
|
-
title,
|
|
159
|
-
...preview ? { preview } : void 0,
|
|
160
|
-
...event.sources.length > 0 ? { details: event.sources.map((source) => ({
|
|
161
|
-
title: sourceFilename(source.path),
|
|
162
|
-
content: source.content
|
|
163
|
-
})) } : void 0
|
|
164
|
-
};
|
|
165
|
-
}
|
|
166
|
-
});
|
|
167
|
-
/** Core-written Conversation note. `notes.ts` owns when the model sees it. */
|
|
168
|
-
const conversationNoteEvent = defineConversationEvent({
|
|
169
|
-
name: "conversation_note",
|
|
170
|
-
version: 1,
|
|
171
|
-
schema: z.object({ text: z.string().trim().min(1).max(500) }).strict(),
|
|
172
|
-
renderEvent(event) {
|
|
173
|
-
return {
|
|
174
|
-
icon: "info",
|
|
175
|
-
title: "Note for the next Turn",
|
|
176
|
-
preview: event.text
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
});
|
|
180
|
-
const NATIVE_EVENT_DEFINITIONS = [
|
|
181
|
-
authenticationLinkedEvent,
|
|
182
|
-
authenticationUnlinkedEvent,
|
|
183
|
-
agentsInstructionsUpdatedEvent,
|
|
184
|
-
conversationNoteEvent
|
|
185
|
-
];
|
|
186
|
-
/** Resolve a registered Junior-native conversation event definition. */
|
|
187
|
-
function getJuniorNativeEventDefinition(args) {
|
|
188
|
-
return NATIVE_EVENT_DEFINITIONS.find((definition) => definition.eventName === args.name && definition.version === args.version);
|
|
189
|
-
}
|
|
190
|
-
/** Render one Junior-native event through its active definition. */
|
|
191
|
-
function renderJuniorNativeConversationEvent(args) {
|
|
192
|
-
if (args.namespace !== "junior") return void 0;
|
|
193
|
-
const definition = getJuniorNativeEventDefinition(args);
|
|
194
|
-
if (!definition) return void 0;
|
|
195
|
-
const presentation = definition.renderEvent(definition.parse(args.content));
|
|
196
|
-
return presentation === void 0 ? void 0 : conversationEventPresentationSchema.parse(presentation);
|
|
197
|
-
}
|
|
198
66
|
// src/chat/pi/conversation-events.ts
|
|
199
67
|
function authorizationObservationMessage(data, createdAtMs) {
|
|
200
68
|
const label = data.kind === "mcp" ? "MCP authorization" : "Authorization";
|
|
@@ -625,6 +493,49 @@ async function lookupSlackUser(teamId, userId) {
|
|
|
625
493
|
return null;
|
|
626
494
|
}
|
|
627
495
|
}
|
|
496
|
+
const USER_NAMES_SHARED_TTL_MS = 864e5;
|
|
497
|
+
const USER_NAMES_LOOKUP_CONCURRENCY = 5;
|
|
498
|
+
const sharedUserNamesSchema = z.object({
|
|
499
|
+
fullName: z.string().optional(),
|
|
500
|
+
userName: z.string().optional()
|
|
501
|
+
});
|
|
502
|
+
function sharedUserNamesKey(teamId, userId) {
|
|
503
|
+
return `slack-user-names:${teamId}:${userId}`;
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* Look up the names of Slack users in one workspace, shared across instances.
|
|
507
|
+
* A user is missing from the result when Slack has no answer for them.
|
|
508
|
+
*/
|
|
509
|
+
async function lookupSlackUserNames(teamId, userIds) {
|
|
510
|
+
const names = /* @__PURE__ */ new Map();
|
|
511
|
+
if (userIds.length === 0) return names;
|
|
512
|
+
const state = getStateAdapter();
|
|
513
|
+
const shared = await getStateValues(state, userIds.map((userId) => sharedUserNamesKey(teamId, userId)));
|
|
514
|
+
const missing = [];
|
|
515
|
+
for (const [index, userId] of userIds.entries()) {
|
|
516
|
+
const parsed = sharedUserNamesSchema.safeParse(shared[index]);
|
|
517
|
+
if (parsed.success) names.set(userId, parsed.data);
|
|
518
|
+
else missing.push(userId);
|
|
519
|
+
}
|
|
520
|
+
const limit = pLimit(USER_NAMES_LOOKUP_CONCURRENCY);
|
|
521
|
+
const profiles = await Promise.all(missing.map((userId) => limit(() => lookupSlackUser(teamId, userId))));
|
|
522
|
+
const found = [];
|
|
523
|
+
for (const [index, userId] of missing.entries()) {
|
|
524
|
+
const profile = profiles[index];
|
|
525
|
+
if (!profile) continue;
|
|
526
|
+
const value = {
|
|
527
|
+
...profile.fullName ? { fullName: profile.fullName } : void 0,
|
|
528
|
+
...profile.userName ? { userName: profile.userName } : void 0
|
|
529
|
+
};
|
|
530
|
+
names.set(userId, value);
|
|
531
|
+
found.push({
|
|
532
|
+
key: sharedUserNamesKey(teamId, userId),
|
|
533
|
+
value
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
await setStateValues(state, found, USER_NAMES_SHARED_TTL_MS);
|
|
537
|
+
return names;
|
|
538
|
+
}
|
|
628
539
|
// src/chat/identities/timezone.ts
|
|
629
540
|
const DEFAULT_TIMEZONE = "America/Los_Angeles";
|
|
630
541
|
/** The install timezone, used when Junior does not know a person's timezone. */
|
|
@@ -768,6 +679,36 @@ async function annotateToolResult(conversationId, plugin, result) {
|
|
|
768
679
|
};
|
|
769
680
|
return annotated;
|
|
770
681
|
}
|
|
682
|
+
// src/chat/conversations/tool-replies.ts
|
|
683
|
+
/**
|
|
684
|
+
* Record the reply that a plugin tool posted for Junior, such as a pull
|
|
685
|
+
* request comment, and remove it from the model-facing result. The model
|
|
686
|
+
* wrote the text, so it reads only the provider facts.
|
|
687
|
+
*/
|
|
688
|
+
async function recordToolReply(args) {
|
|
689
|
+
const { result } = args;
|
|
690
|
+
if (!isRecord$2(result) || result.isError === true) return result;
|
|
691
|
+
const details = isRecord$2(result.details) ? result.details : result;
|
|
692
|
+
if (details.reply === void 0) return result;
|
|
693
|
+
const reply = pluginToolReplySchema.parse(details.reply);
|
|
694
|
+
if (args.toolCallId) await getConversationEventStore().append(args.conversationId, [{
|
|
695
|
+
idempotencyKey: `reply_posted:tool:${args.toolCallId}`,
|
|
696
|
+
data: {
|
|
697
|
+
type: "reply_posted",
|
|
698
|
+
plugin: args.plugin,
|
|
699
|
+
text: reply.text,
|
|
700
|
+
...reply.url ? { url: reply.url } : void 0,
|
|
701
|
+
toolCallId: args.toolCallId
|
|
702
|
+
},
|
|
703
|
+
createdAtMs: Date.now()
|
|
704
|
+
}]);
|
|
705
|
+
const { reply: _reply, ...rest } = details;
|
|
706
|
+
if (isRecord$2(result.details)) return {
|
|
707
|
+
...result,
|
|
708
|
+
details: rest
|
|
709
|
+
};
|
|
710
|
+
return rest;
|
|
711
|
+
}
|
|
771
712
|
// src/chat/conversations/sql/privacy.ts
|
|
772
713
|
const privacyRoot = alias(juniorConversations, "privacy_root");
|
|
773
714
|
/** Accept only a structurally valid persisted root as privacy authority. */
|
|
@@ -1032,6 +973,7 @@ const conversationReportSourceEventTypes = [
|
|
|
1032
973
|
"turn_context",
|
|
1033
974
|
"structured_event",
|
|
1034
975
|
"attachments_delivered",
|
|
976
|
+
"reply_posted",
|
|
1035
977
|
"turn_completed",
|
|
1036
978
|
"turn_failed",
|
|
1037
979
|
"compaction",
|
|
@@ -1252,6 +1194,7 @@ function reportEventData(args) {
|
|
|
1252
1194
|
...args.canExposePayload ? reportReviewItemChanges(data.meta) : void 0,
|
|
1253
1195
|
eventObjectType: objectTypeSchema.safeParse(data.meta?.eventObjectType).data,
|
|
1254
1196
|
...typeof data.meta?.eventType === "string" ? { eventType: data.meta.eventType } : void 0,
|
|
1197
|
+
...typeof data.meta?.eventNamespace === "string" ? { eventNamespace: data.meta.eventNamespace } : void 0,
|
|
1255
1198
|
...typeof data.meta?.explicitMention === "boolean" ? { explicitMention: data.meta.explicitMention } : void 0,
|
|
1256
1199
|
...data.meta?.quiet === true ? { quiet: true } : void 0,
|
|
1257
1200
|
...args.canExposePayload && typeof data.meta?.trustedSummary === "string" ? { trustedSummary: data.meta.trustedSummary } : void 0,
|
|
@@ -1289,6 +1232,14 @@ function reportEventData(args) {
|
|
|
1289
1232
|
type: "attachments_delivered",
|
|
1290
1233
|
attachments: data.attachments
|
|
1291
1234
|
};
|
|
1235
|
+
case "reply_posted":
|
|
1236
|
+
if (!args.canExposePayload) return;
|
|
1237
|
+
return {
|
|
1238
|
+
type: "reply_posted",
|
|
1239
|
+
plugin: data.plugin,
|
|
1240
|
+
text: data.text,
|
|
1241
|
+
...data.url ? { url: data.url } : void 0
|
|
1242
|
+
};
|
|
1292
1243
|
case "guardian_action_reviewed": return {
|
|
1293
1244
|
type: "guardian_action_reviewed",
|
|
1294
1245
|
turnId: data.turnId,
|
|
@@ -1333,6 +1284,9 @@ function reportSubagentLabel(data, canExposePayload) {
|
|
|
1333
1284
|
...data.title ? { title: data.title } : void 0
|
|
1334
1285
|
};
|
|
1335
1286
|
}
|
|
1287
|
+
function childKind(threadIds, conversationId) {
|
|
1288
|
+
return threadIds?.has(conversationId) ? "thread" : "task";
|
|
1289
|
+
}
|
|
1336
1290
|
/**
|
|
1337
1291
|
* Project canonical events into the ordered reporting boundary.
|
|
1338
1292
|
*
|
|
@@ -1410,6 +1364,7 @@ function projectConversationReportEventPage(args) {
|
|
|
1410
1364
|
startedSeq: event.seq,
|
|
1411
1365
|
startedAt: new Date(event.createdAtMs).toISOString(),
|
|
1412
1366
|
childConversationId: event.data.childConversationId,
|
|
1367
|
+
childKind: childKind(args.threadIds, event.data.childConversationId),
|
|
1413
1368
|
subagentKind: event.data.subagentKind,
|
|
1414
1369
|
...reportSubagentLabel(event.data, args.canExposePayload),
|
|
1415
1370
|
status: "running",
|
|
@@ -1423,6 +1378,7 @@ function projectConversationReportEventPage(args) {
|
|
|
1423
1378
|
startedSeq: started.seq,
|
|
1424
1379
|
startedAt: new Date(started.createdAtMs).toISOString(),
|
|
1425
1380
|
childConversationId: started.data.childConversationId,
|
|
1381
|
+
childKind: childKind(args.threadIds, started.data.childConversationId),
|
|
1426
1382
|
subagentKind: started.data.subagentKind,
|
|
1427
1383
|
...reportSubagentLabel(started.data, args.canExposePayload),
|
|
1428
1384
|
...started.data.parentToolCallId ? { parentToolCallId: started.data.parentToolCallId } : void 0,
|
|
@@ -1476,6 +1432,13 @@ function readLatestTurnsPageStart(executor, conversationId, turns) {
|
|
|
1476
1432
|
const turnStart = executor.db().select({ seq: started.seq }).from(started).where(and(eq(started.conversationId, conversationId), eq(started.type, "turn_started"))).orderBy(desc(started.seq)).offset(turns - 1).limit(1);
|
|
1477
1433
|
return executor.db().select({ seq: max(ended.seq) }).from(ended).where(and(eq(ended.conversationId, conversationId), inArray(ended.type, ["turn_completed", "turn_failed"]), lt(ended.seq, sql`(${turnStart})`)));
|
|
1478
1434
|
}
|
|
1435
|
+
/** Read which children that the page's subagent events name are Threads. */
|
|
1436
|
+
async function readThreadIds(executor, events) {
|
|
1437
|
+
const ids = [...new Set(events.flatMap((event) => event.data.type === "subagent_started" ? [event.data.childConversationId] : []))];
|
|
1438
|
+
if (ids.length === 0) return /* @__PURE__ */ new Set();
|
|
1439
|
+
const rows = await executor.db().select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(inArray(juniorConversations.conversationId, ids), eq(juniorConversations.kind, "thread")));
|
|
1440
|
+
return new Set(rows.map((row) => row.conversationId));
|
|
1441
|
+
}
|
|
1479
1442
|
/** Read the first Turn start, which marks history inherited from a fork. */
|
|
1480
1443
|
async function readFirstTurnStart(executor, conversationId) {
|
|
1481
1444
|
const [row] = await readConversationEventRows(executor, {
|
|
@@ -1534,11 +1497,14 @@ async function projectConversationEvents(executor, args) {
|
|
|
1534
1497
|
}),
|
|
1535
1498
|
args.canExposePayload ? hydrateMessageAttachments(executor, args.conversationId, events) : void 0
|
|
1536
1499
|
]);
|
|
1500
|
+
const subagentStartEvents = subagentStartRows.map(eventFromRow);
|
|
1501
|
+
const threadIds = await readThreadIds(executor, [...events, ...subagentStartEvents]);
|
|
1537
1502
|
return projectEventPage({
|
|
1538
1503
|
canExposePayload: args.canExposePayload,
|
|
1539
1504
|
events,
|
|
1540
1505
|
...args.firstTurnStart ? { firstTurnStart: args.firstTurnStart } : void 0,
|
|
1541
|
-
subagentStartEvents
|
|
1506
|
+
subagentStartEvents,
|
|
1507
|
+
threadIds,
|
|
1542
1508
|
toolStartEvents: toolStartRows.map(eventFromRow),
|
|
1543
1509
|
modelContextEvents: [...turnBoundaryRows, ...modelCallRows].sort((left, right) => left.seq - right.seq).map(eventFromRow)
|
|
1544
1510
|
});
|
|
@@ -1958,10 +1924,11 @@ async function updateConversationBrief(context) {
|
|
|
1958
1924
|
const input = await briefInputFromSql(executor, run.conversationId, terminalSeq);
|
|
1959
1925
|
const modelId = botConfig.fastModelId;
|
|
1960
1926
|
const generation = await generateBrief({
|
|
1961
|
-
completeObject: (request) => completeObject({
|
|
1927
|
+
completeObject: (request) => completeObject$1({
|
|
1962
1928
|
...request,
|
|
1963
1929
|
modelId,
|
|
1964
|
-
|
|
1930
|
+
operation: "brief_update",
|
|
1931
|
+
cost: { owner: "caller" }
|
|
1965
1932
|
}),
|
|
1966
1933
|
input,
|
|
1967
1934
|
previous: previous?.content,
|
|
@@ -2066,25 +2033,27 @@ function conversationIsMemberRoot(member) {
|
|
|
2066
2033
|
const memberRoots = "userId" in member ? union(started.where(eq(juniorIdentities.userId, member.userId)), participating.where(eq(juniorConversationParticipants.userId, member.userId))) : union(started.innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(eq(juniorUsers.primaryEmailNormalized, member.email)), participating.innerJoin(juniorUsers, eq(juniorUsers.id, juniorConversationParticipants.userId)).where(eq(juniorUsers.primaryEmailNormalized, member.email)));
|
|
2067
2034
|
return inArray(juniorConversations.conversationId, memberRoots);
|
|
2068
2035
|
}
|
|
2069
|
-
/**
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
function
|
|
2075
|
-
|
|
2036
|
+
/**
|
|
2037
|
+
* True when the person has not unsubscribed from the conversation. The
|
|
2038
|
+
* active feed uses it, so a conversation that someone else carries on
|
|
2039
|
+
* leaves the feed of a person who left it.
|
|
2040
|
+
*/
|
|
2041
|
+
function conversationIsNotUnsubscribedRoot(member) {
|
|
2042
|
+
const rows = getDb().select({ conversationId: juniorConversationParticipants.rootConversationId }).from(juniorConversationParticipants);
|
|
2043
|
+
const left = isNotNull(juniorConversationParticipants.unsubscribedAt);
|
|
2044
|
+
const unsubscribedRoots = "userId" in member ? rows.where(and(eq(juniorConversationParticipants.userId, member.userId), left)) : rows.innerJoin(juniorUsers, eq(juniorUsers.id, juniorConversationParticipants.userId)).where(and(eq(juniorUsers.primaryEmailNormalized, member.email), left));
|
|
2045
|
+
return notInArray(juniorConversations.conversationId, unsubscribedRoots);
|
|
2076
2046
|
}
|
|
2077
2047
|
/** Root-actor ownership or a materialized participant row for the same person. */
|
|
2078
2048
|
function viewerConversationMembership(args) {
|
|
2079
2049
|
if (args.actorMatch && args.participantMatch) return or(args.actorMatch, args.participantMatch);
|
|
2080
2050
|
return args.actorMatch ?? args.participantMatch;
|
|
2081
2051
|
}
|
|
2082
|
-
/** Read personal
|
|
2052
|
+
/** Read personal pin marks for a bounded set of conversation roots. */
|
|
2083
2053
|
async function conversationViewerMarks(db, conversationIds, subject) {
|
|
2084
2054
|
if (!subject || conversationIds.length === 0) return /* @__PURE__ */ new Map();
|
|
2085
|
-
const marked = and(inArray(juniorConversationParticipants.rootConversationId, [...conversationIds]),
|
|
2055
|
+
const marked = and(inArray(juniorConversationParticipants.rootConversationId, [...conversationIds]), isNotNull(juniorConversationParticipants.pinnedAt));
|
|
2086
2056
|
const query = db.select({
|
|
2087
|
-
archivedAt: juniorConversationParticipants.archivedAt,
|
|
2088
2057
|
pinnedAt: juniorConversationParticipants.pinnedAt,
|
|
2089
2058
|
pinPosition: juniorConversationParticipants.pinPosition,
|
|
2090
2059
|
rootConversationId: juniorConversationParticipants.rootConversationId
|
|
@@ -2097,11 +2066,10 @@ async function conversationViewerMarks(db, conversationIds, subject) {
|
|
|
2097
2066
|
}
|
|
2098
2067
|
/** Project one participant row into marks, or undefined when it has none. */
|
|
2099
2068
|
function viewerMarksFromParticipant(row) {
|
|
2100
|
-
if (!row.
|
|
2069
|
+
if (!row.pinnedAt) return void 0;
|
|
2101
2070
|
return {
|
|
2102
|
-
|
|
2103
|
-
...row.
|
|
2104
|
-
...row.pinnedAt && row.pinPosition !== null ? { pinPosition: row.pinPosition } : void 0
|
|
2071
|
+
pinnedAtMs: row.pinnedAt.getTime(),
|
|
2072
|
+
...row.pinPosition !== null ? { pinPosition: row.pinPosition } : void 0
|
|
2105
2073
|
};
|
|
2106
2074
|
}
|
|
2107
2075
|
/** True when one user pinned this root. Feeds sort these rows first. */
|
|
@@ -2180,13 +2148,13 @@ function createConversationAccessReader(db, viewer) {
|
|
|
2180
2148
|
/**
|
|
2181
2149
|
* Apply `policies/conversation-access.md`: whether work in the `requester`
|
|
2182
2150
|
* Conversation may read or find the data of the `target` Conversation. The
|
|
2183
|
-
* person of the Turn does not change the result. A
|
|
2184
|
-
* reachable
|
|
2151
|
+
* person of the Turn does not change the result. A public Conversation is
|
|
2152
|
+
* reachable from any Conversation, on any surface and in any provider tenant.
|
|
2153
|
+
* A private Conversation is reachable only from its own tree.
|
|
2185
2154
|
*/
|
|
2186
2155
|
function canAccessConversation(args) {
|
|
2187
2156
|
const { requester, target } = args;
|
|
2188
2157
|
if (requester.rootConversationId !== void 0 && requester.rootConversationId === target.rootConversationId) return true;
|
|
2189
|
-
if (!requester.tenant || !target.tenant || requester.tenant.provider !== target.tenant.provider || requester.tenant.providerTenantId !== target.tenant.providerTenantId) return false;
|
|
2190
2158
|
return target.visibility === "public";
|
|
2191
2159
|
}
|
|
2192
2160
|
// src/chat/plugins/conversation-event-reader.ts
|
|
@@ -3546,7 +3514,7 @@ const BASE_IMAGE = {
|
|
|
3546
3514
|
};
|
|
3547
3515
|
const RUNTIME_REPOSITORY = "junior-sandbox-runtime";
|
|
3548
3516
|
/** System packages for each runtime, installed on top of the base image. */
|
|
3549
|
-
const RUNTIME_PACKAGES = {
|
|
3517
|
+
const RUNTIME_PACKAGES = { node24: ["nodejs24", "nodejs24-npm"] };
|
|
3550
3518
|
const COMMON_PACKAGES = [
|
|
3551
3519
|
"coreutils",
|
|
3552
3520
|
"diffutils",
|
|
@@ -3672,7 +3640,7 @@ async function ensureRuntimeImage(runtime, signal) {
|
|
|
3672
3640
|
}
|
|
3673
3641
|
// src/chat/sandbox/snapshot/runtime.ts
|
|
3674
3642
|
/** Runtime used to build and start reusable Sandbox snapshots. */
|
|
3675
|
-
const SANDBOX_RUNTIME = "
|
|
3643
|
+
const SANDBOX_RUNTIME = "node24";
|
|
3676
3644
|
// src/chat/sandbox/docker/relay.ts
|
|
3677
3645
|
/** Host name of the Docker host as seen from a container. */
|
|
3678
3646
|
const RELAY_PROXY_HOST = "host.docker.internal";
|
|
@@ -5029,7 +4997,7 @@ function adaptSession$1(container, options) {
|
|
|
5029
4997
|
// src/chat/sandbox/docker/provider.ts
|
|
5030
4998
|
/** Create a sandbox container and return a session for it. */
|
|
5031
4999
|
async function createSession(input) {
|
|
5032
|
-
const image = input.snapshotId ?? await ensureRuntimeImage(input.runtime ?? "
|
|
5000
|
+
const image = input.snapshotId ?? await ensureRuntimeImage(input.runtime ?? "node24", input.signal);
|
|
5033
5001
|
const container = await createContainer({
|
|
5034
5002
|
name: input.name ?? newSandboxName(),
|
|
5035
5003
|
image,
|
|
@@ -8247,7 +8215,7 @@ const RESOURCE_SUBSCRIPTION_MAX_TTL_MS = 2592e6;
|
|
|
8247
8215
|
const STOP_WATCHING_TOOL_NAME = "stopWatchingResources";
|
|
8248
8216
|
const RESOURCE_WATCH_TOOL_SOURCE = {
|
|
8249
8217
|
id: "resource-watches",
|
|
8250
|
-
description: "
|
|
8218
|
+
description: "Find event types, and inspect or stop watches for the current conversation and its child agents."
|
|
8251
8219
|
};
|
|
8252
8220
|
// src/chat/slack/tool-support/context.ts
|
|
8253
8221
|
/** Resolve Slack tool context from the Conversation Location. */
|
|
@@ -8436,6 +8404,13 @@ function reviewItemNeedsUser(userId) {
|
|
|
8436
8404
|
return and(eq(juniorReviewItems.status, "open"), eq(juniorReviewItems.kind, "action"), reviewItemAssignedTo(userId));
|
|
8437
8405
|
}
|
|
8438
8406
|
/**
|
|
8407
|
+
* SQL: the Review item needs some person: an open `action` item with an
|
|
8408
|
+
* assigned User. It is `reviewItemNeedsUser` for any User.
|
|
8409
|
+
*/
|
|
8410
|
+
function reviewItemNeedsSomeone() {
|
|
8411
|
+
return and(eq(juniorReviewItems.status, "open"), eq(juniorReviewItems.kind, "action"), sql`exists (select 1 from ${juniorReviewItemAssignees} where ${juniorReviewItemAssignees.itemId} = ${juniorReviewItems.id})`);
|
|
8412
|
+
}
|
|
8413
|
+
/**
|
|
8439
8414
|
* SQL: the Review item is not assigned only to other people. It is assigned
|
|
8440
8415
|
* to this User, to Everyone, or to no one. This is the assignee rule of
|
|
8441
8416
|
* `canActOnReviewItem`; keep the two the same.
|
|
@@ -9701,7 +9676,12 @@ function getPluginTools(context, sandbox = createSandboxCapability(context.works
|
|
|
9701
9676
|
const execute = definition.execute;
|
|
9702
9677
|
if (execute) {
|
|
9703
9678
|
const wrapped = Object.create(definition);
|
|
9704
|
-
wrapped.execute = async (input, options) => annotateToolResult(context.conversationId, pluginName, await
|
|
9679
|
+
wrapped.execute = async (input, options) => annotateToolResult(context.conversationId, pluginName, await recordToolReply({
|
|
9680
|
+
conversationId: context.conversationId,
|
|
9681
|
+
plugin: pluginName,
|
|
9682
|
+
result: await execute.call(definition, input, options),
|
|
9683
|
+
toolCallId: options.toolCallId
|
|
9684
|
+
}));
|
|
9705
9685
|
tools[name] = wrapped;
|
|
9706
9686
|
} else tools[name] = definition;
|
|
9707
9687
|
}
|
|
@@ -11211,6 +11191,14 @@ const CONTEXT_INPUT_LIMIT_RATIO = .95;
|
|
|
11211
11191
|
const COMPACTION_TARGET_RATIO = .8;
|
|
11212
11192
|
const BACKGROUND_COMPACTION_MARK_RATIO = .7;
|
|
11213
11193
|
const FALLBACK_CONTEXT_WINDOW_TOKENS = 4e5;
|
|
11194
|
+
const CLAUDE_TOKEN_ESTIMATE = {
|
|
11195
|
+
charsPerToken: 2.5,
|
|
11196
|
+
toolResultOverheadTokens: 150
|
|
11197
|
+
};
|
|
11198
|
+
const DEFAULT_TOKEN_ESTIMATE = {
|
|
11199
|
+
charsPerToken: 4,
|
|
11200
|
+
toolResultOverheadTokens: 0
|
|
11201
|
+
};
|
|
11214
11202
|
function positiveInteger(value, fallback) {
|
|
11215
11203
|
return Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
|
|
11216
11204
|
}
|
|
@@ -11218,14 +11206,19 @@ function positiveInteger(value, fallback) {
|
|
|
11218
11206
|
function estimateTextTokens(text) {
|
|
11219
11207
|
return Math.ceil(text.length / 4);
|
|
11220
11208
|
}
|
|
11209
|
+
/** Resolve the size-only token estimate inputs for one model's requests. */
|
|
11210
|
+
function getTokenEstimateProfile(modelId) {
|
|
11211
|
+
return modelId.startsWith("anthropic/") ? CLAUDE_TOKEN_ESTIMATE : DEFAULT_TOKEN_ESTIMATE;
|
|
11212
|
+
}
|
|
11221
11213
|
/** Estimate the tokens that the system prompt and tool definitions add to a model request. */
|
|
11222
|
-
function estimateRequestOverheadTokens(systemPrompt, tools) {
|
|
11214
|
+
function estimateRequestOverheadTokens(systemPrompt, tools, modelId) {
|
|
11223
11215
|
const definitions = tools.map(({ name, description, parameters }) => ({
|
|
11224
11216
|
name,
|
|
11225
11217
|
description,
|
|
11226
11218
|
parameters
|
|
11227
11219
|
}));
|
|
11228
|
-
|
|
11220
|
+
const chars = systemPrompt.length + JSON.stringify(definitions).length;
|
|
11221
|
+
return Math.ceil(chars / getTokenEstimateProfile(modelId).charsPerToken);
|
|
11229
11222
|
}
|
|
11230
11223
|
/** Derive the automatic compaction threshold from model context capacity. */
|
|
11231
11224
|
function calculateContextCompactionTriggerTokens(model) {
|
|
@@ -11607,7 +11600,8 @@ async function decideSubscribedThreadReply(args) {
|
|
|
11607
11600
|
actorId: args.input.context.actorId ?? "",
|
|
11608
11601
|
runId: args.input.context.runId ?? ""
|
|
11609
11602
|
},
|
|
11610
|
-
|
|
11603
|
+
operation: "passive_reply_route",
|
|
11604
|
+
cost: { owner: "caller" }
|
|
11611
11605
|
});
|
|
11612
11606
|
return {
|
|
11613
11607
|
...result.costUsd !== void 0 ? { costUsd: result.costUsd } : void 0,
|
|
@@ -11734,6 +11728,17 @@ function renderUntrustedTag(name, attrs, writer, text) {
|
|
|
11734
11728
|
function renderChildTag(name, text) {
|
|
11735
11729
|
return `<${name}>${text}</${name}>`;
|
|
11736
11730
|
}
|
|
11731
|
+
const PARENT_AGENT_TASK_OPEN = "<parent-agent-task>\n";
|
|
11732
|
+
const PARENT_AGENT_TASK_CLOSE = "\n</parent-agent-task>";
|
|
11733
|
+
/**
|
|
11734
|
+
* Return the text of a `<parent-agent-task>` input without its tag, as
|
|
11735
|
+
* `<current-instruction>` is read for a person. Returns nothing for another
|
|
11736
|
+
* input. The tag is only for the model: provenance decides authority.
|
|
11737
|
+
*/
|
|
11738
|
+
function readParentAgentTask(text) {
|
|
11739
|
+
if (!text.startsWith(PARENT_AGENT_TASK_OPEN) || !text.endsWith(PARENT_AGENT_TASK_CLOSE)) return;
|
|
11740
|
+
return text.slice(20, -21).replaceAll("</", "</");
|
|
11741
|
+
}
|
|
11737
11742
|
/**
|
|
11738
11743
|
* Return whether a prompt text part is a runtime-created input. Only the
|
|
11739
11744
|
* runtime writes a part that starts with one of these tags: typed person
|
|
@@ -11896,7 +11901,7 @@ function getUserMessageInstructionText(message) {
|
|
|
11896
11901
|
const texts = typeof content === "string" ? [content] : Array.isArray(content) ? content.flatMap((part) => textPartValue(part) ?? []) : [];
|
|
11897
11902
|
const inputs = texts.flatMap((text) => {
|
|
11898
11903
|
const withoutContext = text.replace(EMBEDDED_THREAD_CONTEXT_PATTERN, "").trim();
|
|
11899
|
-
if (isRuntimeInputText(withoutContext)) return [withoutContext];
|
|
11904
|
+
if (isRuntimeInputText(withoutContext)) return [readParentAgentTask(withoutContext) ?? withoutContext];
|
|
11900
11905
|
const instruction = unwrapCurrentInstruction(withoutContext);
|
|
11901
11906
|
return instruction === void 0 ? [] : [instruction.trim()];
|
|
11902
11907
|
});
|
|
@@ -12084,7 +12089,6 @@ const storedInboundMessageSchema = z.object({
|
|
|
12084
12089
|
delivery: inboundMessageDeliverySchema,
|
|
12085
12090
|
destination: destinationSchema.optional(),
|
|
12086
12091
|
inboundMessageId: z.string().refine((value) => value.trim().length > 0),
|
|
12087
|
-
injectedAtMs: z.number().finite().optional(),
|
|
12088
12092
|
input: agentInputSchema,
|
|
12089
12093
|
receivedAtMs: z.number().finite(),
|
|
12090
12094
|
source: inboundMessageSourceSchema,
|
|
@@ -12202,7 +12206,6 @@ function normalizeExecution(conversationId, value) {
|
|
|
12202
12206
|
for (const rawMessage of value.pendingMessages) {
|
|
12203
12207
|
const message = normalizeMessage(rawMessage);
|
|
12204
12208
|
if (!message || message.conversationId !== conversationId) return;
|
|
12205
|
-
if (message.injectedAtMs !== void 0) continue;
|
|
12206
12209
|
pendingMessages.push(message);
|
|
12207
12210
|
}
|
|
12208
12211
|
pendingMessages.sort(compareMessages);
|
|
@@ -13319,6 +13322,17 @@ async function executionMetricsForTurn(conversationStore, conversation, turnId)
|
|
|
13319
13322
|
function definedProps$1(values) {
|
|
13320
13323
|
return Object.fromEntries(Object.entries(values).filter(([, value]) => value !== void 0));
|
|
13321
13324
|
}
|
|
13325
|
+
/** A completed, failed, or abandoned Turn never runs again. */
|
|
13326
|
+
function isFinishedTurnState(state) {
|
|
13327
|
+
return state === "completed" || state === "failed" || state === "abandoned";
|
|
13328
|
+
}
|
|
13329
|
+
/** A running or paused write reached a Turn that already finished. */
|
|
13330
|
+
var TurnAlreadyFinishedError = class extends Error {
|
|
13331
|
+
constructor(turnId, state) {
|
|
13332
|
+
super(`Turn ${turnId} already finished as ${state}`);
|
|
13333
|
+
this.name = "TurnAlreadyFinishedError";
|
|
13334
|
+
}
|
|
13335
|
+
};
|
|
13322
13336
|
const turnStatusSchema = z.enum([
|
|
13323
13337
|
"running",
|
|
13324
13338
|
"paused",
|
|
@@ -13660,12 +13674,17 @@ async function updateTurnState(args) {
|
|
|
13660
13674
|
})
|
|
13661
13675
|
});
|
|
13662
13676
|
}
|
|
13663
|
-
/**
|
|
13677
|
+
/**
|
|
13678
|
+
* Commit stable Pi state and advance the turn cursor. A running or paused
|
|
13679
|
+
* write to a completed, failed, or abandoned Turn throws
|
|
13680
|
+
* `TurnAlreadyFinishedError`.
|
|
13681
|
+
*/
|
|
13664
13682
|
async function upsertTurnRecord(args) {
|
|
13665
13683
|
return await withTurnCursorMutation(args.conversationId, args.turnId, async (fence) => await upsertTurnRecordLocked(args, fence));
|
|
13666
13684
|
}
|
|
13667
13685
|
async function upsertTurnRecordLocked(args, fence) {
|
|
13668
13686
|
const existingRecord = await getStoredTurnRecord(args.conversationId, args.turnId);
|
|
13687
|
+
if (existingRecord && isFinishedTurnState(existingRecord.state) && !isFinishedTurnState(args.state)) throw new TurnAlreadyFinishedError(args.turnId, existingRecord.state);
|
|
13669
13688
|
const conversationStore = args.conversationStore ?? getConversationStore();
|
|
13670
13689
|
const conversation = await conversationStore.get({ conversationId: args.conversationId });
|
|
13671
13690
|
const executionMetrics = await executionMetricsForTurn(conversationStore, conversation, args.turnId);
|
|
@@ -13751,10 +13770,10 @@ async function recordTurnSummaryOwned(args, fence) {
|
|
|
13751
13770
|
const conversation = await conversationStore.get({ conversationId: args.conversationId });
|
|
13752
13771
|
const executionMetrics = await executionMetricsForTurn(conversationStore, conversation, args.turnId);
|
|
13753
13772
|
const priorSummary = (await listTurnSummaries(args.conversationId)).find((summary) => summary.turnId === args.turnId);
|
|
13754
|
-
const
|
|
13755
|
-
const
|
|
13756
|
-
const existing =
|
|
13757
|
-
if ((
|
|
13773
|
+
const finishedSummary = priorSummary && isFinishedTurnState(priorSummary.state) ? priorSummary : void 0;
|
|
13774
|
+
const finishedRecord = stored && isFinishedTurnState(stored.state) ? stored : void 0;
|
|
13775
|
+
const existing = finishedSummary ?? finishedRecord ?? stored ?? priorSummary;
|
|
13776
|
+
if ((finishedSummary || finishedRecord) && !isFinishedTurnState(args.state)) return;
|
|
13758
13777
|
const existingDispatchId = existing?.dispatchId;
|
|
13759
13778
|
const existingDispatchOutcome = priorSummary?.dispatchOutcome ?? stored?.dispatchOutcome;
|
|
13760
13779
|
const existingResultMessageId = priorSummary?.resultMessageId ?? stored?.resultMessageId;
|
|
@@ -13817,11 +13836,17 @@ async function readTurnSummaries(key) {
|
|
|
13817
13836
|
async function listTurnSummaries(conversationId) {
|
|
13818
13837
|
return readTurnSummaries(turnCursorIndexKey(conversationId));
|
|
13819
13838
|
}
|
|
13820
|
-
/**
|
|
13839
|
+
/**
|
|
13840
|
+
* Mark an unfinished turn cursor as abandoned when a newer turn wins. With
|
|
13841
|
+
* `onlyIfAuthPaused`, abandon only a Turn that still waits for sign-in. This
|
|
13842
|
+
* leaves a resumed Turn alone only after the worker's first running
|
|
13843
|
+
* checkpoint. Before that the Turn still reads as paused, so the stop abandons
|
|
13844
|
+
* it and signals the worker.
|
|
13845
|
+
*/
|
|
13821
13846
|
async function abandonTurnRecord(args) {
|
|
13822
13847
|
return await withTurnCursorMutation(args.conversationId, args.turnId, async (fence) => {
|
|
13823
13848
|
const existing = await getTurnRecord(args.conversationId, args.turnId);
|
|
13824
|
-
if (!existing || existing.state === "completed" || existing.state === "failed" || existing.state === "abandoned") return;
|
|
13849
|
+
if (!existing || existing.state === "completed" || existing.state === "failed" || existing.state === "abandoned" || args.onlyIfAuthPaused && (existing.state !== "paused" || existing.resumeReason !== "auth")) return;
|
|
13825
13850
|
return await updateTurnState({
|
|
13826
13851
|
existing,
|
|
13827
13852
|
fence,
|
|
@@ -13932,7 +13957,7 @@ async function saveRunning(args, traceContext) {
|
|
|
13932
13957
|
state: "running"
|
|
13933
13958
|
});
|
|
13934
13959
|
} catch (error) {
|
|
13935
|
-
if (!(error instanceof AgentHistoryBranchError)) logException(error, "agent.turn.checkpoint.running.failed", {
|
|
13960
|
+
if (!(error instanceof AgentHistoryBranchError) && !(error instanceof TurnAlreadyFinishedError)) logException(error, "agent.turn.checkpoint.running.failed", {
|
|
13936
13961
|
"app.ai.resume_conversation_id": args.conversationId,
|
|
13937
13962
|
"app.ai.resume_session_id": args.turnId,
|
|
13938
13963
|
"app.ai.resume_slice_id": args.sliceId
|
|
@@ -13978,6 +14003,7 @@ async function savePaused(args, traceContext) {
|
|
|
13978
14003
|
});
|
|
13979
14004
|
} catch (error) {
|
|
13980
14005
|
if (error instanceof TurnSliceLimitExceededError) throw error;
|
|
14006
|
+
if (error instanceof TurnAlreadyFinishedError) return;
|
|
13981
14007
|
logException(error, "agent.turn.checkpoint.paused.failed", {
|
|
13982
14008
|
"app.ai.resume_conversation_id": args.conversationId,
|
|
13983
14009
|
"app.ai.resume_session_id": args.turnId,
|
|
@@ -14011,6 +14037,42 @@ async function saveDone(args, traceContext) {
|
|
|
14011
14037
|
});
|
|
14012
14038
|
});
|
|
14013
14039
|
}
|
|
14040
|
+
/** Recovery resumes a turn at most once after its worker stops checking in. */
|
|
14041
|
+
const MAX_LOST_WORKER_RESUMES = 1;
|
|
14042
|
+
/**
|
|
14043
|
+
* Saved on the paused turn when recovery resumes it. The resumed run replaces
|
|
14044
|
+
* it at its first save.
|
|
14045
|
+
*/
|
|
14046
|
+
const LOST_WORKER_RESUME_MESSAGE = "Turn lost its worker; resuming from its last boundary";
|
|
14047
|
+
/** True when a resumed turn lost its worker again before it saved anything. */
|
|
14048
|
+
function lostWorkerBeforeFirstSave(turn) {
|
|
14049
|
+
return turn.errorMessage === "Turn lost its worker; resuming from its last boundary" && (turn.lostWorkerResumeCount ?? 0) >= MAX_LOST_WORKER_RESUMES;
|
|
14050
|
+
}
|
|
14051
|
+
/**
|
|
14052
|
+
* Pause a turn whose worker stopped checking in, so it resumes from its last
|
|
14053
|
+
* save. Returns false when the turn already used its resume or has no slice
|
|
14054
|
+
* left.
|
|
14055
|
+
*/
|
|
14056
|
+
async function pauseLostWorkerTurn(turn) {
|
|
14057
|
+
if ((turn.lostWorkerResumeCount ?? 0) >= MAX_LOST_WORKER_RESUMES || turn.sliceId + 1 > botConfig.maxSlicesPerTurn) return false;
|
|
14058
|
+
const paused = await saveTurnCheckpoint({
|
|
14059
|
+
mode: "paused",
|
|
14060
|
+
reason: "retry",
|
|
14061
|
+
conversationId: turn.conversationId,
|
|
14062
|
+
turnId: turn.turnId,
|
|
14063
|
+
sliceId: turn.sliceId,
|
|
14064
|
+
messages: turn.piMessages,
|
|
14065
|
+
lostWorkerResumeCount: (turn.lostWorkerResumeCount ?? 0) + 1,
|
|
14066
|
+
errorMessage: LOST_WORKER_RESUME_MESSAGE
|
|
14067
|
+
});
|
|
14068
|
+
if (!paused) return false;
|
|
14069
|
+
logWarn("agent.turn.lost_worker.resumed", {
|
|
14070
|
+
"app.ai.conversation_id": turn.conversationId,
|
|
14071
|
+
"app.ai.session_id": turn.turnId,
|
|
14072
|
+
"app.ai.resume_slice_id": paused.sliceId
|
|
14073
|
+
});
|
|
14074
|
+
return true;
|
|
14075
|
+
}
|
|
14014
14076
|
// src/chat/services/pending-auth.ts
|
|
14015
14077
|
const AUTH_LINK_REUSE_WINDOW_MS = 6e5;
|
|
14016
14078
|
/** Decide whether the same agent-run session can reuse its fresh auth link. */
|
|
@@ -14307,13 +14369,12 @@ async function getPluginConversationTitleContext(args) {
|
|
|
14307
14369
|
}
|
|
14308
14370
|
// src/chat/services/conversation-memory.ts
|
|
14309
14371
|
const CONTEXT_MIN_LIVE_MESSAGES = 12;
|
|
14310
|
-
const CONTEXT_COMPACTION_BATCH_SIZE = 24;
|
|
14311
|
-
const CONTEXT_MAX_COMPACTIONS = 16;
|
|
14312
14372
|
const CONTEXT_MAX_MESSAGE_CHARS = 3200;
|
|
14373
|
+
const THREAD_CONTEXT_MAX_CHARS = 6e4;
|
|
14374
|
+
const THREAD_CONTEXT_OPEN = "<thread-context authority=\"evidence-only\">";
|
|
14375
|
+
const THREAD_CONTEXT_CLOSE = "</thread-context>";
|
|
14376
|
+
const THREAD_CONTEXT_OMITTED_NOTE = "Older Messages of this thread are not shown. Find them with the searchConversationEvents and readConversationEvent tools.";
|
|
14313
14377
|
const SLACK_USER_ID_DISPLAY_PATTERN = /^[UW][A-Z0-9]{5,}$/;
|
|
14314
|
-
function generateConversationId(prefix) {
|
|
14315
|
-
return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
|
|
14316
|
-
}
|
|
14317
14378
|
/** Normalize message boundaries without changing transcript formatting. */
|
|
14318
14379
|
function normalizeConversationText(text) {
|
|
14319
14380
|
return text.replace(/\r\n?/g, "\n").trim();
|
|
@@ -14346,9 +14407,9 @@ function authorDisplayField(value, userId) {
|
|
|
14346
14407
|
if (!value || value === userId || SLACK_USER_ID_DISPLAY_PATTERN.test(value)) return;
|
|
14347
14408
|
return value;
|
|
14348
14409
|
}
|
|
14349
|
-
/** Estimate the
|
|
14350
|
-
function
|
|
14351
|
-
return estimateTextTokens(
|
|
14410
|
+
/** Estimate the visible Message working set that trimming bounds. */
|
|
14411
|
+
function estimateConversationMessagesTokens(conversation) {
|
|
14412
|
+
return estimateTextTokens(conversation.messages.map((message) => renderConversationMessageLine(message, conversation)).join("\n"));
|
|
14352
14413
|
}
|
|
14353
14414
|
function upsertConversationMessage(conversation, message) {
|
|
14354
14415
|
const existingIndex = conversation.messages.findIndex((entry) => entry.id === message.id);
|
|
@@ -14416,114 +14477,62 @@ function isTakeOnly(message) {
|
|
|
14416
14477
|
const changes = message.meta?.reviewItemChanges;
|
|
14417
14478
|
return Boolean(changes?.length && changes.every((change) => change.kind === "taken"));
|
|
14418
14479
|
}
|
|
14419
|
-
|
|
14420
|
-
|
|
14421
|
-
|
|
14422
|
-
|
|
14423
|
-
|
|
14424
|
-
|
|
14425
|
-
|
|
14426
|
-
|
|
14427
|
-
|
|
14428
|
-
|
|
14429
|
-
|
|
14430
|
-
|
|
14431
|
-
|
|
14432
|
-
|
|
14433
|
-
|
|
14434
|
-
|
|
14435
|
-
|
|
14436
|
-
|
|
14437
|
-
|
|
14438
|
-
const actorIdAttr = message.author?.userId ? ` actor_id="${escapeXml(message.author.userId)}"` : "";
|
|
14439
|
-
const ts = new Date(message.createdAtMs).toISOString();
|
|
14440
|
-
const slackTsAttr = message.meta?.slackTs ? ` slack_ts="${escapeXml(message.meta.slackTs)}"` : "";
|
|
14441
|
-
lines.push(` <message index="${index + 1}" ts="${ts}" role="${message.role}" author="${author}"${actorIdAttr}${slackTsAttr}>`, renderConversationMessageLine(message, conversation), " </message>");
|
|
14442
|
-
}
|
|
14443
|
-
lines.push("</thread-context>");
|
|
14444
|
-
}
|
|
14445
|
-
return lines.join("\n");
|
|
14480
|
+
function renderThreadContextMessage(message, conversation, index) {
|
|
14481
|
+
const author = escapeXml(conversationAuthorDisplayName(message));
|
|
14482
|
+
const actorIdAttr = message.author?.userId ? ` actor_id="${escapeXml(message.author.userId)}"` : "";
|
|
14483
|
+
const ts = new Date(message.createdAtMs).toISOString();
|
|
14484
|
+
const slackTsAttr = message.meta?.slackTs ? ` slack_ts="${escapeXml(message.meta.slackTs)}"` : "";
|
|
14485
|
+
return [
|
|
14486
|
+
` <message index="${index}" ts="${ts}" role="${message.role}" author="${author}"${actorIdAttr}${slackTsAttr}>`,
|
|
14487
|
+
renderConversationMessageLine(message, conversation),
|
|
14488
|
+
" </message>"
|
|
14489
|
+
].join("\n");
|
|
14490
|
+
}
|
|
14491
|
+
function isUntaggedThreadMessage(message) {
|
|
14492
|
+
return message.role === "user" && !message.meta?.explicitMention && !isEventConversationMessage(message);
|
|
14493
|
+
}
|
|
14494
|
+
/** Return the highest saved Message seq, the thread context cursor of a Turn. */
|
|
14495
|
+
function latestConversationMessageSeq(conversation) {
|
|
14496
|
+
let latest;
|
|
14497
|
+
for (const message of conversation.messages) if (message.seq !== void 0 && (latest ?? -1) < message.seq) latest = message.seq;
|
|
14498
|
+
return latest;
|
|
14446
14499
|
}
|
|
14447
|
-
const THREAD_CONTEXT_OPEN = "<thread-context authority=\"evidence-only\">";
|
|
14448
|
-
const THREAD_CONTEXT_CLOSE = "</thread-context>";
|
|
14449
14500
|
/**
|
|
14450
|
-
*
|
|
14501
|
+
* Render the thread Messages that this Turn needs as one evidence-only block.
|
|
14451
14502
|
*
|
|
14452
|
-
*
|
|
14453
|
-
*
|
|
14454
|
-
|
|
14455
|
-
|
|
14456
|
-
|
|
14457
|
-
|
|
14458
|
-
|
|
14459
|
-
|
|
14460
|
-
|
|
14461
|
-
|
|
14462
|
-
|
|
14463
|
-
|
|
14464
|
-
|
|
14465
|
-
|
|
14466
|
-
|
|
14467
|
-
|
|
14468
|
-
|
|
14503
|
+
* With agent history, earlier Turns already hold their thread context, Turn
|
|
14504
|
+
* input, and replies. So only untagged Messages saved after the cursor of the
|
|
14505
|
+
* previous Turn are new. Without history, show the latest Messages. Both keep
|
|
14506
|
+
* the newest Messages under one hard size cap, so the block cannot grow with
|
|
14507
|
+
* the thread.
|
|
14508
|
+
*/
|
|
14509
|
+
function buildConversationContext(conversation, options = {}) {
|
|
14510
|
+
const { history } = options;
|
|
14511
|
+
const candidates = conversation.messages.filter((entry) => !options.excludeMessageIds?.includes(entry.id) && !isTakeOnly(entry) && (!history || isUntaggedThreadMessage(entry) && (history.afterSeq === void 0 || entry.seq === void 0 || entry.seq > history.afterSeq)));
|
|
14512
|
+
let first = candidates.length;
|
|
14513
|
+
let chars = 0;
|
|
14514
|
+
while (first > 0) {
|
|
14515
|
+
const size = renderThreadContextMessage(candidates[first - 1], conversation, first).length;
|
|
14516
|
+
if (chars + size > THREAD_CONTEXT_MAX_CHARS) break;
|
|
14517
|
+
chars += size;
|
|
14518
|
+
first -= 1;
|
|
14519
|
+
}
|
|
14520
|
+
const shown = candidates.slice(first).map((message, index) => renderThreadContextMessage(message, conversation, index + 1));
|
|
14521
|
+
const counts = {
|
|
14522
|
+
shownMessages: shown.length,
|
|
14523
|
+
omittedMessages: candidates.length - shown.length
|
|
14524
|
+
};
|
|
14525
|
+
if (shown.length === 0) return counts;
|
|
14526
|
+
const lines = [
|
|
14469
14527
|
THREAD_CONTEXT_OPEN,
|
|
14470
|
-
|
|
14528
|
+
...shown,
|
|
14471
14529
|
THREAD_CONTEXT_CLOSE
|
|
14472
|
-
]
|
|
14473
|
-
|
|
14474
|
-
|
|
14475
|
-
|
|
14476
|
-
|
|
14477
|
-
|
|
14478
|
-
const mergedSummary = merged.map((entry) => entry.summary).join("\n").slice(0, 3500);
|
|
14479
|
-
const coveredMessageCount = merged.reduce((count, entry) => count + entry.coveredMessageCount, 0);
|
|
14480
|
-
return [{
|
|
14481
|
-
id: generateConversationId("compaction"),
|
|
14482
|
-
createdAtMs: Date.now(),
|
|
14483
|
-
summary: mergedSummary,
|
|
14484
|
-
coveredMessageCount
|
|
14485
|
-
}, ...compactions.slice(overflowCount)];
|
|
14486
|
-
}
|
|
14487
|
-
async function summarizeConversationChunk(messages, conversation, context, deps) {
|
|
14488
|
-
const transcript = messages.map((message) => renderConversationMessageLine(message, conversation)).join("\n");
|
|
14489
|
-
try {
|
|
14490
|
-
const summary = (await deps.completeText({
|
|
14491
|
-
modelId: botConfig.fastModelId,
|
|
14492
|
-
temperature: 0,
|
|
14493
|
-
promptName: "junior.thread_compaction",
|
|
14494
|
-
messages: [{
|
|
14495
|
-
role: "user",
|
|
14496
|
-
content: [
|
|
14497
|
-
"Summarize the following older Slack thread transcript segment for future assistant turns.",
|
|
14498
|
-
"Keep the summary factual and concise. Do not invent details.",
|
|
14499
|
-
"",
|
|
14500
|
-
"Output exactly three XML sections in this order:",
|
|
14501
|
-
"<active-asks> one bullet per outstanding user ask that has not been narrowed, answered, or replaced by a later turn. Omit the section body if none. </active-asks>",
|
|
14502
|
-
"<resolved-or-replaced-asks> one bullet per ask that has been replaced, narrowed, answered, or already acted on in this segment. Include the replacement/outcome inline. Omit the section body if none. </resolved-or-replaced-asks>",
|
|
14503
|
-
"<facts> one bullet per durable fact useful regardless of scope: names, ids, URLs, decisions, locations, preferences, constraints that remain true. Omit the section body if none. </facts>",
|
|
14504
|
-
"",
|
|
14505
|
-
"Do not output any text outside the three sections.",
|
|
14506
|
-
"",
|
|
14507
|
-
transcript
|
|
14508
|
-
].join("\n"),
|
|
14509
|
-
timestamp: Date.now()
|
|
14510
|
-
}],
|
|
14511
|
-
metadata: {
|
|
14512
|
-
modelId: botConfig.fastModelId,
|
|
14513
|
-
threadId: context.threadId ?? "",
|
|
14514
|
-
channelId: context.channelId ?? "",
|
|
14515
|
-
actorId: context.actorId ?? "",
|
|
14516
|
-
runId: context.runId ?? ""
|
|
14517
|
-
}
|
|
14518
|
-
})).text.trim();
|
|
14519
|
-
if (summary.length > 0) return summary.slice(0, 3500);
|
|
14520
|
-
} catch (error) {
|
|
14521
|
-
logWarn("conversation.compaction.summary.failed", {
|
|
14522
|
-
"exception.message": error instanceof Error ? error.message : String(error),
|
|
14523
|
-
"app.compaction_messages_covered": messages.length
|
|
14524
|
-
});
|
|
14525
|
-
}
|
|
14526
|
-
return transcript.slice(0, 2800);
|
|
14530
|
+
];
|
|
14531
|
+
if (shown.length < candidates.length || !history && conversation.historyFromSeq !== void 0) lines.push(THREAD_CONTEXT_OMITTED_NOTE);
|
|
14532
|
+
return {
|
|
14533
|
+
...counts,
|
|
14534
|
+
text: lines.join("\n")
|
|
14535
|
+
};
|
|
14527
14536
|
}
|
|
14528
14537
|
/** Return the earliest human-authored message known for a thread. */
|
|
14529
14538
|
function getThreadTitleSourceMessage(conversation) {
|
|
@@ -14542,37 +14551,35 @@ function getThreadTitleSourceMessage(conversation) {
|
|
|
14542
14551
|
}
|
|
14543
14552
|
return firstMessage;
|
|
14544
14553
|
}
|
|
14545
|
-
|
|
14546
|
-
|
|
14554
|
+
/**
|
|
14555
|
+
* Drop the oldest visible Messages until the working set fits the target, so
|
|
14556
|
+
* the Messages that each Turn loads stay bounded. This makes no model call.
|
|
14557
|
+
* Return whether a Message was dropped.
|
|
14558
|
+
*/
|
|
14559
|
+
async function trimConversationMessages(conversation, loadKeepAfterSeq) {
|
|
14560
|
+
let estimatedTokens = estimateConversationMessagesTokens(conversation);
|
|
14547
14561
|
setSpanAttributes({ "app.context_tokens_estimated": estimatedTokens });
|
|
14548
14562
|
const triggerTokens = getConversationContextCompactionTriggerTokens();
|
|
14563
|
+
if (estimatedTokens <= triggerTokens) return false;
|
|
14549
14564
|
const targetTokens = calculateContextCompactionTargetTokens(triggerTokens);
|
|
14550
|
-
|
|
14551
|
-
|
|
14552
|
-
|
|
14553
|
-
|
|
14554
|
-
const
|
|
14555
|
-
|
|
14556
|
-
|
|
14557
|
-
|
|
14558
|
-
|
|
14559
|
-
|
|
14560
|
-
|
|
14561
|
-
|
|
14562
|
-
|
|
14563
|
-
|
|
14564
|
-
|
|
14565
|
-
|
|
14566
|
-
|
|
14567
|
-
|
|
14568
|
-
"app.context_tokens_estimated": estimatedTokens
|
|
14569
|
-
});
|
|
14570
|
-
if (estimatedTokens <= targetTokens) break;
|
|
14571
|
-
}
|
|
14572
|
-
}
|
|
14573
|
-
/** Build the service that owns durable conversation memory compaction. */
|
|
14574
|
-
function createConversationMemoryService(deps) {
|
|
14575
|
-
return { compactConversationIfNeeded: async (conversation, context) => await compactConversationIfNeededWithDeps(conversation, context, deps) };
|
|
14565
|
+
const keepAfterSeq = await loadKeepAfterSeq();
|
|
14566
|
+
const maxDropped = conversation.messages.length - CONTEXT_MIN_LIVE_MESSAGES;
|
|
14567
|
+
let dropped = 0;
|
|
14568
|
+
while (dropped < maxDropped && estimatedTokens > targetTokens) {
|
|
14569
|
+
const message = conversation.messages[dropped];
|
|
14570
|
+
if (keepAfterSeq !== void 0 && (message.seq === void 0 || message.seq > keepAfterSeq)) break;
|
|
14571
|
+
estimatedTokens -= estimateTextTokens(`${renderConversationMessageLine(message, conversation)}\n`);
|
|
14572
|
+
dropped += 1;
|
|
14573
|
+
}
|
|
14574
|
+
if (dropped === 0) return false;
|
|
14575
|
+
conversation.messages = conversation.messages.slice(dropped);
|
|
14576
|
+
const historyFromSeq = conversation.messages[0]?.seq;
|
|
14577
|
+
if (historyFromSeq !== void 0) conversation.historyFromSeq = historyFromSeq;
|
|
14578
|
+
setSpanAttributes({
|
|
14579
|
+
"app.thread_messages.trimmed": dropped,
|
|
14580
|
+
"app.context_tokens_estimated": estimateConversationMessagesTokens(conversation)
|
|
14581
|
+
});
|
|
14582
|
+
return true;
|
|
14576
14583
|
}
|
|
14577
14584
|
function isHumanConversationMessage(message) {
|
|
14578
14585
|
return message.role === "user" && message.author?.isBot !== true;
|
|
@@ -14633,7 +14640,8 @@ async function generateShortTitle(args) {
|
|
|
14633
14640
|
signal: args.signal,
|
|
14634
14641
|
modelId: botConfig.fastModelId,
|
|
14635
14642
|
temperature: 0,
|
|
14636
|
-
|
|
14643
|
+
operation: `${args.kind}_title`,
|
|
14644
|
+
cost: args.cost,
|
|
14637
14645
|
messages: [{
|
|
14638
14646
|
role: "user",
|
|
14639
14647
|
content: [
|
|
@@ -14669,6 +14677,7 @@ async function resolveTaskTitle(args) {
|
|
|
14669
14677
|
if (explicit) return explicit;
|
|
14670
14678
|
return generateShortTitle({
|
|
14671
14679
|
completeText: args.completeText,
|
|
14680
|
+
cost: args.cost,
|
|
14672
14681
|
kind: "task",
|
|
14673
14682
|
sourceText: args.instruction,
|
|
14674
14683
|
signal: args.signal
|
|
@@ -14742,6 +14751,7 @@ async function ensureConversationTitleOnce(args) {
|
|
|
14742
14751
|
title = await generateShortTitle({
|
|
14743
14752
|
completeText,
|
|
14744
14753
|
context,
|
|
14754
|
+
cost: { conversationId: args.conversationId },
|
|
14745
14755
|
kind,
|
|
14746
14756
|
sourceText
|
|
14747
14757
|
});
|
|
@@ -14802,32 +14812,6 @@ async function resolveConversationTitle(args) {
|
|
|
14802
14812
|
}
|
|
14803
14813
|
return (await (args.conversationStore ?? getConversationStore()).get({ conversationId: args.conversationId }))?.title?.trim() || void 0;
|
|
14804
14814
|
}
|
|
14805
|
-
// src/chat/conversations/message-summaries.ts
|
|
14806
|
-
/** Project the latest source-message summary snapshot from event history. */
|
|
14807
|
-
function projectConversationMessageSummaries(events) {
|
|
14808
|
-
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
14809
|
-
const data = events[index]?.data;
|
|
14810
|
-
if (data?.type === "messages_summarized") return data.compactions;
|
|
14811
|
-
}
|
|
14812
|
-
return [];
|
|
14813
|
-
}
|
|
14814
|
-
/** Persist a changed source-message summary snapshot in event history. */
|
|
14815
|
-
async function persistConversationMessageSummaries(args) {
|
|
14816
|
-
const eventStore = getConversationEventStore();
|
|
14817
|
-
const history = await eventStore.loadMessageHistory(args.conversationId);
|
|
14818
|
-
const existing = history.compaction ? projectConversationMessageSummaries([history.compaction]) : [];
|
|
14819
|
-
if (isDeepStrictEqual(existing, args.conversation.compactions)) return;
|
|
14820
|
-
const liveMessageIds = new Set(args.conversation.messages.map((message) => message.id));
|
|
14821
|
-
const nextHistoryFromSeq = history.events.find((event) => event.data.type === "message" && liveMessageIds.has(event.data.messageId))?.seq ?? Math.max(history.historyFromSeq, (history.events.at(-1)?.seq ?? -1) + 1);
|
|
14822
|
-
await eventStore.append(args.conversationId, [{
|
|
14823
|
-
data: {
|
|
14824
|
-
type: "messages_summarized",
|
|
14825
|
-
historyFromSeq: nextHistoryFromSeq,
|
|
14826
|
-
compactions: args.conversation.compactions
|
|
14827
|
-
},
|
|
14828
|
-
createdAtMs: args.conversation.compactions.at(-1)?.createdAtMs ?? Date.now()
|
|
14829
|
-
}]);
|
|
14830
|
-
}
|
|
14831
14815
|
// src/chat/conversations/message-projection.ts
|
|
14832
14816
|
function isMessageEvent(event) {
|
|
14833
14817
|
return event.data.type === "message" || event.data.type === "message_updated" || event.data.type === "message_handled";
|
|
@@ -14868,7 +14852,8 @@ function projectConversationMessages(history) {
|
|
|
14868
14852
|
byId.set(data.messageId, {
|
|
14869
14853
|
message: {
|
|
14870
14854
|
...message,
|
|
14871
|
-
createdAtMs: current?.message.createdAtMs ?? message.createdAtMs
|
|
14855
|
+
createdAtMs: current?.message.createdAtMs ?? message.createdAtMs,
|
|
14856
|
+
seq: current?.message.seq ?? event.seq
|
|
14872
14857
|
},
|
|
14873
14858
|
...current?.repliedAtMs === void 0 ? void 0 : { repliedAtMs: current.repliedAtMs }
|
|
14874
14859
|
});
|
|
@@ -14926,9 +14911,20 @@ async function hydrateConversationMessages(args) {
|
|
|
14926
14911
|
return;
|
|
14927
14912
|
}
|
|
14928
14913
|
const history = await getConversationEventStore().loadMessageHistory(args.conversationId);
|
|
14929
|
-
args.conversation.
|
|
14914
|
+
args.conversation.historyFromSeq = history.historyFromSeq > 0 ? history.historyFromSeq : void 0;
|
|
14930
14915
|
args.conversation.messages = projectConversationMessages(history);
|
|
14931
14916
|
}
|
|
14917
|
+
/** Save where the trimmed Message window starts, so later loads skip older Messages. */
|
|
14918
|
+
async function persistConversationMessageWindow(args) {
|
|
14919
|
+
await getConversationEventStore().append(args.conversationId, [{
|
|
14920
|
+
data: {
|
|
14921
|
+
type: "messages_summarized",
|
|
14922
|
+
historyFromSeq: args.historyFromSeq,
|
|
14923
|
+
compactions: []
|
|
14924
|
+
},
|
|
14925
|
+
createdAtMs: Date.now()
|
|
14926
|
+
}]);
|
|
14927
|
+
}
|
|
14932
14928
|
/** Append new messages and handled markers idempotently. */
|
|
14933
14929
|
async function persistConversationMessages(args) {
|
|
14934
14930
|
if (!args.conversationId || args.conversation.messages.length === 0) return;
|
|
@@ -15117,7 +15113,7 @@ async function loadTurnProjection(args) {
|
|
|
15117
15113
|
}
|
|
15118
15114
|
/** Load MCP providers the credential subject connected in this conversation. */
|
|
15119
15115
|
async function loadConnectedMcpProviders(args) {
|
|
15120
|
-
return connectedMcpProvidersFromEvents(await getConversationEventStore().
|
|
15116
|
+
return connectedMcpProvidersFromEvents(await getConversationEventStore().loadEventsOfType(args.conversationId, "mcp_provider_connected"), args.credentialSubjectId);
|
|
15121
15117
|
}
|
|
15122
15118
|
function messageTimestamp(message) {
|
|
15123
15119
|
const timestamp = message.timestamp;
|
|
@@ -15412,4 +15408,4 @@ async function recordGuardianActionReviewed(args) {
|
|
|
15412
15408
|
createdAtMs: Date.now()
|
|
15413
15409
|
}]);
|
|
15414
15410
|
}
|
|
15415
|
-
export { abandonTurnRecord as $, conversationArchivedFor as $a, slackEntitySchema as $i, readWebPushConfig as $n, verifyEventAutomationCredentialSubject as $r, hasTurnInput as $t, estimateConversationContextTokens as A, SANDBOX_RUNTIME as Aa, isVercelSandboxEgressRequest as Ai, getAgentContextInputLimitTokens as An, lookupSlackUser as Ao, EVERYONE_ASSIGNEE as Ar, recordConversationRetry as At, createPluginAuthOrchestration as B, SANDBOX_SKILLS_ROOT as Ba, normalizeSlackStatusText as Bi, createPluginHookRunner as Bn, setConfigDefaults as Bo, cancelSubscriptions as Br, TurnBudgetExceededError as Bt, resolveConversationTitle as C, consumeSandboxEgressPermissionDeniedSignal as Ca, setWorkspaceSnapshot as Ci, getSubscribedReplyPreflightDecision as Cn, resolveRootVisibility as Co, canReadReviewItem as Cr, hasRunnableConversationWork as Ct, appendThreadContextMessages as D, buildSandboxEgressNetworkPolicy as Da, isStale as Di, estimateTextTokens as Dn, listConversationAnnotationsById as Do, requireReviewItemLinks as Dr, markConversationWorkEnqueued as Dt, resolveTaskTitle as E, sandboxEgressSignalsResponseSchema as Ea, hash as Ei, estimateRequestOverheadTokens as En, listConversationAnnotations as Eo, requireReviewItemAssignees as Er, listActiveConversationIds as Et, recordDeliveredAssistantMessage as F, createPluginEmbedder as Fa, resolveBaseUrl as Fi, findLegacyWebActorUserId as Fn, piMessageFromHistoryItem as Fo, getSlackToolContext as Fr, requestConversationWork as Ft, abandonReplacedPendingAuth as G, buildCommandScript as Ga, getSlackMessagePermalink as Gi, getPluginTools as Gn, deliverWatch as Gr, isTurnExecutionLimitExceededError as Gt, AuthPausePersistenceError as H, sandboxSkillDir as Ha, truncateStatusText as Hi, getPluginRoutes as Hn, collectEventMatchKeys as Hr, TurnToolCallLimitExceededError as Ht, turnHasReply as I, createPluginModel as Ia, startOAuthFlow as Ii, webActorUserIds as In, projectConversationEvents$1 as Io, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as Ir, startConversationWork as It, getConversationPendingAuth as J, createPluginModelCostRecorder as Ja, postSlackEphemeralMessage as Ji, setPlugins as Jn, listWatches as Jr, extractAssistantText as Jt, canReusePendingAuthLink as K, buildNonInteractiveShellScript as Ka, openSlackDirectMessage as Ki, getPluginUserPromptContributions as Kn, findMatchingWatches as Kr, CODEMODE_TOOL_NAME as Kt, upsertConversationMessage as L, SANDBOX_COMMAND_PATH as La, escapeSlackMrkdwnText as Li, getOAuthAccountProviders as Ln, JUNIOR_NATIVE_EVENT_NAMESPACE as Lo, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as Lr, steerWebPendingMessages as Lt, isHumanConversationMessage as M, tryWorkspaceRepoCheckoutPath as Ma, deliverOAuthAuthorization as Mi, isExperimentalFeatureEnabled as Mn, createDurableLocationConfigurationService as Mo, resolveAssignee as Mr, releaseInboundMessage as Mt, markConversationMessage as N, workspaceRepoCheckoutPath as Na, formatProviderLabel as Ni, setExperimentalFeatures as Nn, configValueSchema as No, resolveAssignees as Nr, removeActiveConversation as Nt, buildConversationContext as O, resolveSandboxCommandEnvironment as Oa, ensureDockerDaemon as Oi, getAgentBackgroundCompactionMarkTokens as On, defaultTimezone as Oo, reviewItemNeedsUser as Or, moveIdleConversationDestination as Ot, normalizeConversationText as P, PluginToolDeniedError as Pa, parseOAuthStatePayload as Pi, createUserTokenStore as Pn, historyItemFromPiMessage as Po, resolveChannelCapabilities as Pr, requestAnotherSlice as Pt, saveTurnCheckpoint as Q, readConversationAccessFromSql as Qa, uploadFilesToConversation as Qi, setBriefsConfig as Qn, bindSlackDirectCredentialSubject as Qr, hasRuntimeTurnContext as Qt, createPluginEgress as R, SANDBOX_DATA_ROOT as Ra, formatSlackLink as Ri, resolvePluginOAuthAccount as Rn, conversationNoteEvent as Ro, RESOURCE_WATCH_TOOL_SOURCE as Rr, stopConversationWork as Rt, persistConversationMessageSummaries as S, consumeSandboxEgressAuthRequiredSignal as Sa, loadSnapshotsForProfile as Si, decideSubscribedThreadReply as Sn, slackAttachmentsVersionQuery as So, canAgentChangeReviewItem as Sr, hasConversationStop as St, fallbackShortTitle as T, parseSandboxEgressCredentialToken as Ta, create as Ti, calculateContextCompactionTargetTokens as Tn, createPluginAnnotations as To, readReviewItemAgentScope as Tr, isInvalidConversationRecordError as Tt, AuthorizationFlowDisabledError as U, sandboxSkillFile as Ua, addReactionToMessage as Ui, getPluginSlackConversationLink as Un, createTimerWatch as Ur, buildTurnErrorResponse as Ut, authorizationId as V, SANDBOX_WORKSPACE_ROOT as Va, slackMention as Vi, getPluginApiRoutes as Vn, cancelWatch as Vr, TurnSliceLimitExceededError as Vt, AuthorizationPauseError as W, sandboxSkillPathResolution as Wa, deleteSlackMessage as Wi, getPluginSystemPromptContributions as Wn, createWatch as Wr, createTurnLimitGate as Wt, continuableMessages as X, canAccessConversation as Xa, removeReactionFromMessage as Xi, coreTaskRegistrations as Xn, bindEventAutomationCredentialSubject as Xr, getTerminalAssistantMessages as Xt, wasPendingAuthStopped as Y, createPluginLogger as Ya, postSlackMessage as Yi, validatePlugins as Yn, takeDueTimerWatches as Yr, getPiMessageRole as Yt, loadTurnCheckpoint as Z, createConversationAccessReader as Za, updateSlackMessage as Zi, registration_exports as Zn, bindScheduledAutomationCredentialSubject as Zr, getUserMessageInstructionText as Zt, appendConversationMessages as _, WorkspaceSnapshotNotReadyError as _a, listWorkspaces as _i, renderUntrustedTag as _n, notInheritedByForkChild as _o, searchReviewItems as _r, completeConversationWork as _t, loadProjection as a, getSlackClient as aa, getDashboardObjectIconLink as ai, isToolResultMessage as an, viewerConversationMembership as ao, saveNotificationSchedule as ar, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as at, toStoredConversationMessage as b, workspaceSnapshotNotReadyUserMessage as ba, WorkspaceValidationError as bi, buildDeterministicTurnId as bn, readAttachmentVisionSummary as bo, PLUGIN_REVIEW_ITEM_KEY_PREFIX as br, getConversation as bt, recordAgentsInstructionsUpdated as c, normalizeSlackConversationId as ca, getDashboardTaskLink as ci, stripRuntimeTurnContext as cn, readConversationBriefThrough as co, closeReviewItem as cr, appendExclusiveInboundMessage as ct, recordAuthorizationCompleted as d, getWorkspaceTeamId as da, createPluginState as di, SESSION_CONTEXT_SECTION_TAG as dn, readConversationEventPageAfter as do, getOpenReviewItemByDedupeKey as dr, cancelHumanFacingPendingMessages as dt, slackExternalRefIdSchema as ea, verifyScheduledAutomationCredentialSubject as ei, instructionTextForProjection as en, conversationHasParticipantUser as eo, sendPushNotificationToUser as er, completeTurnRecord as et, recordAuthorizationRequested as f, runWithWorkspaceTeamId as fa, renderToolResultNudge as fi, TURN_CONTEXT_TAG as fn, readConversationEventPageAround as fo, getReviewItem as fr, checkInConversationWork as ft, recordToolExecutionStarted as g, wrapSandboxSetupError as ga, getWorkspaceByName as gi, renderTag as gn, loadForkHistory as go, reviewItemsNeedingUserVersionQuery as gr, completeConversationStop as gt, recordSubscribedReplyRoute as h, throwSandboxOperationError as ha, getWorkspace as hi, renderChildTag as hn, buildSentryConversationUrl as ho, listWaitingConversations as hr, clearExpiredConversationLease as ht, loadConversationProjection as i, getHeaderString as ia, getDashboardConversationLink as ii, isToolResultError as in, conversationViewerMarks as io, readNotificationSchedule as ir, recordTurnSummary as it, getConversationMessageSlackTs as j, sleep$2 as ja, proxyVercelSandboxEgressRequest as ji, getExperimentalFeatures as jn, createPluginCache as jo, automationCreatorUserId as jr, releaseConversationWork as jt, createConversationMemoryService as k, normalizeSandboxEgressTracePropagationDomains as ka, getSandboxProvider as ki, getAgentContextCompactionTriggerTokens as kn, resolveUserTimezone as ko, reviewItemReaderForUser as kr, recordAttemptFailure as kt, recordAttachmentsDelivered as l, runWithSlackInstallationToken as la, setDashboardConversationLinkOptions as li, trimTrailingAssistantMessages as ln, readLatestConversationBrief as lo, countReviewItemsNeedingUser as lr, appendInboundMessage as lt, recordMcpProviderConnected as m, isAlreadyExistsError as ma, deleteWorkspace as mi, escapeTagText as mn, readConversationMessageEventSeq as mo, listReplyActionItems as mr, clearConsumedConversationWake as mt, commitMessages as n, downloadPrivateSlackFile as na, verifyTimerWatchCredentialSubject as ni, isContinuablePiBoundary as nn, conversationNotArchivedFor as no, deletePushSubscription as nr, getTurnRecord as nt, loadTurnProjection as o, isConversationScopedChannel as oa, getDashboardReviewItemLink as oi, normalizeToolNameFromResult as on, viewerMarksFromParticipant as oo, savePushSubscription as or, CONVERSATION_WORK_STALE_ENQUEUE_MS as ot, recordGuardianActionReviewed as p, isAbortError as pa, createWorkspace as pi, escapeClosingTags as pn, readConversationLastEventSeq as po, insertReviewItem as pr, claimInboundMessage as pt, clearPendingAuth as q, runNonInteractiveCommand as qa, openSlackModal as qi, getPlugins as qn, getWatch as qr, persistWithRetry as qt, loadConnectedMcpProviders as r, getFilePermalink as ra, JUNIOR_THREAD_STATE_TTL_MS as ri, isStandaloneRuntimeContextMessage as rn, conversationPinnedForUser as ro, listPushSubscriptions as rr, listTurnSummaries as rt, openConversationProjection as s, isDmChannel as sa, getDashboardSettingsLink as si, retainRuntimeTurnContext as sn, createPluginConversationEvents as so, REVIEW_ITEM_REPLIED_REASON as sr, ackMessages as st, commitAcceptedReply as t, SlackActionError as ta, verifySlackDirectCredentialSubject as ti, isAssistantMessage as tn, conversationIsMemberRoot as to, resolveNotificationTimezone as tr, failTurnRecord as tt, recordAuthenticationLinked as u, withSlackRetries as ua, ToolInputError as ui, REQUEST_CONTEXT_SECTION_TAG as un, readConversationEventPage as uo, dismissOpenReviewItems as ur, beginConversationResume as ut, hydrateConversationMessages as v, getWorkspaceSnapshotNotReadyError as va, listWorkspacesByRepository as vi, tagJson as vn, getSlackFileId as vo, takeReviewItem as vr, deadLetterAttempt as vt, settleConversationTitleWork as w, createSandboxEgressCredentialToken as wa, setWorkspaceSnapshotBuild as wi, getThreadStopDecision as wn, saveObjectAnnotations as wo, isOnlyAssignee as wr, isFinalAttempt as wt, projectConversationMessages as x, clearSandboxEgressSignals as xa, invalidateReadySnapshot as xi, SubscribedReplyReason as xn, recordSlackAttachment as xo, canActOnReviewItem as xr, getConversationWorkState as xt, persistConversationMessages as y, isWorkspaceSnapshotNotReadyError as ya, updateWorkspace as yi, buildDeterministicAssistantMessageId as yn, matchSlackAttachments as yo, updateReviewItemContent as yr, drainConversationMailbox as yt, PluginCredentialFailureError as z, SANDBOX_REPOS_ROOT as za, normalizeSlackReplyMarkdown as zi, agent_hooks_exports as zn, getConfigDefaults as zo, STOP_WATCHING_TOOL_NAME as zr, TURN_LIMIT_WRAP_UP_MESSAGE as zt };
|
|
15411
|
+
export { pauseLostWorkerTurn as $, createPluginLogger as $a, postSlackMessage as $i, validatePlugins as $n, takeDueTimerWatches as $r, getUserMessageInstructionText as $t, isHumanConversationMessage as A, sandboxEgressSignalsResponseSchema as Aa, hash as Ai, estimateTextTokens as An, listConversationAnnotationsById as Ao, requireReviewItemAssignees as Ar, moveIdleConversationDestination as At, createPluginAuthOrchestration as B, createPluginModel as Ba, startOAuthFlow as Bi, webActorUserIds as Bn, projectConversationEvents$1 as Bo, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as Br, stopConversationWork as Bt, resolveConversationTitle as C, isWorkspaceSnapshotNotReadyError as Ca, updateWorkspace as Ci, buildDeterministicTurnId as Cn, readAttachmentVisionSummary as Co, updateReviewItemContent as Cr, getConversationWorkState as Ct, buildConversationContext as D, consumeSandboxEgressPermissionDeniedSignal as Da, setWorkspaceSnapshot as Di, getThreadStopDecision as Dn, saveObjectAnnotations as Do, canReadReviewItem as Dr, isInvalidConversationRecordError as Dt, resolveTaskTitle as E, consumeSandboxEgressAuthRequiredSignal as Ea, loadSnapshotsForProfile as Ei, getSubscribedReplyPreflightDecision as En, resolveRootVisibility as Eo, canAgentChangeReviewItem as Er, isFinalAttempt as Et, trimConversationMessages as F, sleep$2 as Fa, proxyVercelSandboxEgressRequest as Fi, getExperimentalFeatures as Fn, createPluginCache as Fo, automationCreatorUserId as Fr, removeActiveConversation as Ft, abandonReplacedPendingAuth as G, SANDBOX_WORKSPACE_ROOT as Ga, slackMention as Gi, getPluginApiRoutes as Gn, cancelWatch as Gr, buildTurnErrorResponse as Gt, AuthPausePersistenceError as H, SANDBOX_DATA_ROOT as Ha, formatSlackLink as Hi, resolvePluginOAuthAccount as Hn, setConfigDefaults as Ho, RESOURCE_WATCH_TOOL_SOURCE as Hr, TurnBudgetExceededError as Ht, turnHasReply as I, tryWorkspaceRepoCheckoutPath as Ia, deliverOAuthAuthorization as Ii, isExperimentalFeatureEnabled as In, createDurableLocationConfigurationService as Io, resolveAssignee as Ir, requestAnotherSlice as It, getConversationPendingAuth as J, sandboxSkillPathResolution as Ja, deleteSlackMessage as Ji, getPluginSystemPromptContributions as Jn, createWatch as Jr, CODEMODE_TOOL_NAME as Jt, canReusePendingAuthLink as K, sandboxSkillDir as Ka, truncateStatusText as Ki, getPluginRoutes as Kn, collectEventMatchKeys as Kr, createTurnLimitGate as Kt, upsertConversationMessage as L, workspaceRepoCheckoutPath as La, formatProviderLabel as Li, setExperimentalFeatures as Ln, configValueSchema as Lo, resolveAssignees as Lr, requestConversationWork as Lt, markConversationMessage as M, resolveSandboxCommandEnvironment as Ma, ensureDockerDaemon as Mi, getAgentContextCompactionTriggerTokens as Mn, resolveUserTimezone as Mo, reviewItemNeedsSomeone as Mr, recordConversationRetry as Mt, normalizeConversationText as N, normalizeSandboxEgressTracePropagationDomains as Na, getSandboxProvider as Ni, getAgentContextInputLimitTokens as Nn, lookupSlackUser as No, reviewItemReaderForUser as Nr, releaseConversationWork as Nt, estimateConversationMessagesTokens as O, createSandboxEgressCredentialToken as Oa, setWorkspaceSnapshotBuild as Oi, calculateContextCompactionTargetTokens as On, createPluginAnnotations as Oo, isOnlyAssignee as Or, listActiveConversationIds as Ot, recordDeliveredAssistantMessage as P, SANDBOX_RUNTIME as Pa, isVercelSandboxEgressRequest as Pi, getTokenEstimateProfile as Pn, lookupSlackUserNames as Po, EVERYONE_ASSIGNEE as Pr, releaseInboundMessage as Pt, lostWorkerBeforeFirstSave as Q, createPluginModelCostRecorder as Qa, postSlackEphemeralMessage as Qi, setPlugins as Qn, listWatches as Qr, getTerminalAssistantMessages as Qt, createPluginEgress as R, PluginToolDeniedError as Ra, parseOAuthStatePayload as Ri, createUserTokenStore as Rn, historyItemFromPiMessage as Ro, resolveChannelCapabilities as Rr, startConversationWork as Rt, projectConversationMessages as S, getWorkspaceSnapshotNotReadyError as Sa, listWorkspacesByRepository as Si, buildDeterministicAssistantMessageId as Sn, matchSlackAttachments as So, takeReviewItem as Sr, getConversation as St, fallbackShortTitle as T, clearSandboxEgressSignals as Ta, invalidateReadySnapshot as Ti, decideSubscribedThreadReply as Tn, slackAttachmentsVersionQuery as To, canActOnReviewItem as Tr, hasRunnableConversationWork as Tt, AuthorizationFlowDisabledError as U, SANDBOX_REPOS_ROOT as Ua, normalizeSlackReplyMarkdown as Ui, agent_hooks_exports as Un, STOP_WATCHING_TOOL_NAME as Ur, TurnSliceLimitExceededError as Ut, authorizationId as V, SANDBOX_COMMAND_PATH as Va, escapeSlackMrkdwnText as Vi, getOAuthAccountProviders as Vn, getConfigDefaults as Vo, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as Vr, TURN_LIMIT_WRAP_UP_MESSAGE as Vt, AuthorizationPauseError as W, SANDBOX_SKILLS_ROOT as Wa, normalizeSlackStatusText as Wi, createPluginHookRunner as Wn, cancelSubscriptions as Wr, TurnToolCallLimitExceededError as Wt, continuableMessages as X, buildNonInteractiveShellScript as Xa, openSlackDirectMessage as Xi, getPluginUserPromptContributions as Xn, findMatchingWatches as Xr, extractAssistantText as Xt, wasPendingAuthStopped as Y, buildCommandScript as Ya, getSlackMessagePermalink as Yi, getPluginTools as Yn, deliverWatch as Yr, persistWithRetry as Yt, loadTurnCheckpoint as Z, runNonInteractiveCommand as Za, openSlackModal as Zi, getPlugins as Zn, getWatch as Zr, getPiMessageRole as Zt, appendConversationMessages as _, isAbortError as _a, createWorkspace as _i, readParentAgentTask as _n, readConversationMessageEventSeq as _o, insertReviewItem as _r, clearExpiredConversationLease as _t, loadProjection as a, SlackActionError as aa, verifySlackDirectCredentialSubject as ai, isStandaloneRuntimeContextMessage as an, conversationIsNotUnsubscribedRoot as ao, resolveNotificationTimezone as ar, listTurnSummaries as at, persistConversationMessages as b, wrapSandboxSetupError as ba, getWorkspaceByName as bi, renderUntrustedTag as bn, notInheritedByForkChild as bo, reviewItemsNeedingUserVersionQuery as br, deadLetterAttempt as bt, recordAgentsInstructionsUpdated as c, getHeaderString as ca, getDashboardConversationLink as ci, normalizeToolNameFromResult as cn, viewerConversationMembership as co, readNotificationSchedule as cr, CONVERSATION_WORK_STALE_ENQUEUE_MS as ct, recordAuthorizationCompleted as d, isDmChannel as da, getDashboardSettingsLink as di, trimTrailingAssistantMessages as dn, readConversationBriefThrough as do, REVIEW_ITEM_REPLIED_REASON as dr, appendInboundMessage as dt, removeReactionFromMessage as ea, bindEventAutomationCredentialSubject as ei, hasRuntimeTurnContext as en, canAccessConversation as eo, coreTaskRegistrations as er, saveTurnCheckpoint as et, recordAuthorizationRequested as f, normalizeSlackConversationId as fa, getDashboardTaskLink as fi, REQUEST_CONTEXT_SECTION_TAG as fn, readLatestConversationBrief as fo, closeReviewItem as fr, beginConversationResume as ft, recordToolExecutionStarted as g, runWithWorkspaceTeamId as ga, renderToolResultNudge as gi, escapeTagText as gn, readConversationLastEventSeq as go, getReviewItem as gr, clearConsumedConversationWake as gt, recordSubscribedReplyRoute as h, getWorkspaceTeamId as ha, createPluginState as hi, escapeClosingTags as hn, readConversationEventPageAround as ho, getOpenReviewItemByDedupeKey as hr, claimInboundMessage as ht, loadConversationProjection as i, slackExternalRefIdSchema as ia, verifyScheduledAutomationCredentialSubject as ii, isContinuablePiBoundary as in, conversationIsMemberRoot as io, sendPushNotificationToUser as ir, getTurnRecord as it, latestConversationMessageSeq as j, buildSandboxEgressNetworkPolicy as ja, isStale as ji, getAgentBackgroundCompactionMarkTokens as jn, defaultTimezone as jo, requireReviewItemLinks as jr, recordAttemptFailure as jt, getConversationMessageSlackTs as k, parseSandboxEgressCredentialToken as ka, create as ki, estimateRequestOverheadTokens as kn, listConversationAnnotations as ko, readReviewItemAgentScope as kr, markConversationWorkEnqueued as kt, recordAttachmentsDelivered as l, getSlackClient as la, getDashboardObjectIconLink as li, retainRuntimeTurnContext as ln, viewerMarksFromParticipant as lo, saveNotificationSchedule as lr, ackMessages as lt, recordMcpProviderConnected as m, withSlackRetries as ma, ToolInputError as mi, TURN_CONTEXT_TAG as mn, readConversationEventPageAfter as mo, dismissOpenReviewItems as mr, checkInConversationWork as mt, commitMessages as n, uploadFilesToConversation as na, bindSlackDirectCredentialSubject as ni, instructionTextForProjection as nn, readConversationAccessFromSql as no, setBriefsConfig as nr, completeTurnRecord as nt, loadTurnProjection as o, downloadPrivateSlackFile as oa, verifyTimerWatchCredentialSubject as oi, isToolResultError as on, conversationPinnedForUser as oo, deletePushSubscription as or, recordTurnSummary as ot, recordGuardianActionReviewed as p, runWithSlackInstallationToken as pa, setDashboardConversationLinkOptions as pi, SESSION_CONTEXT_SECTION_TAG as pn, readConversationEventPage as po, countReviewItemsNeedingUser as pr, cancelHumanFacingPendingMessages as pt, clearPendingAuth as q, sandboxSkillFile as qa, addReactionToMessage as qi, getPluginSlackConversationLink as qn, createTimerWatch as qr, isTurnExecutionLimitExceededError as qt, loadConnectedMcpProviders as r, slackEntitySchema as ra, verifyEventAutomationCredentialSubject as ri, isAssistantMessage as rn, conversationHasParticipantUser as ro, readWebPushConfig as rr, failTurnRecord as rt, openConversationProjection as s, getFilePermalink as sa, JUNIOR_THREAD_STATE_TTL_MS as si, isToolResultMessage as sn, conversationViewerMarks as so, listPushSubscriptions as sr, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as st, commitAcceptedReply as t, updateSlackMessage as ta, bindScheduledAutomationCredentialSubject as ti, hasTurnInput as tn, createConversationAccessReader as to, registration_exports as tr, abandonTurnRecord as tt, recordAuthenticationLinked as u, isConversationScopedChannel as ua, getDashboardReviewItemLink as ui, stripRuntimeTurnContext as un, createPluginConversationEvents as uo, savePushSubscription as ur, appendExclusiveInboundMessage as ut, hydrateConversationMessages as v, isAlreadyExistsError as va, deleteWorkspace as vi, renderChildTag as vn, buildSentryConversationUrl as vo, listReplyActionItems as vr, completeConversationStop as vt, settleConversationTitleWork as w, workspaceSnapshotNotReadyUserMessage as wa, WorkspaceValidationError as wi, SubscribedReplyReason as wn, recordSlackAttachment as wo, PLUGIN_REVIEW_ITEM_KEY_PREFIX as wr, hasConversationStop as wt, toStoredConversationMessage as x, WorkspaceSnapshotNotReadyError as xa, listWorkspaces as xi, tagJson as xn, getSlackFileId as xo, searchReviewItems as xr, drainConversationMailbox as xt, persistConversationMessageWindow as y, throwSandboxOperationError as ya, getWorkspace as yi, renderTag as yn, loadForkHistory as yo, listWaitingConversations as yr, completeConversationWork as yt, PluginCredentialFailureError as z, createPluginEmbedder as za, resolveBaseUrl as zi, findLegacyWebActorUserId as zn, piMessageFromHistoryItem as zo, getSlackToolContext as zr, steerWebPendingMessages as zt };
|