@sentry/junior 0.298.0 → 0.300.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/{actor-6jsm_v96.js → actor-D2iXzvlN.js} +2 -1
- package/dist/{state-CSuA2J1V.js → adapter-S5UkjNK3.js} +53 -136
- package/dist/{admin-BF3DbYGf.js → admin-UrTniSPO.js} +2 -2
- package/dist/{agent-runner-Q9GkoerG.js → agent-runner-bY4_0UPm.js} +1444 -1478
- 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 +382 -68
- package/dist/{app-DOg_mCtV.d.ts → app-D-AcIcCV.d.ts} +17 -4
- package/dist/app.d.ts +1 -1
- package/dist/app.js +148 -483
- package/dist/{automation-Cn8qmbdr.js → automation-Dw82oQ-h.js} +2 -2
- package/dist/{background-compaction-queue-BZhGFOK6.js → background-compaction-queue-B6U3060-.js} +9 -5
- package/dist/{briefs-CQrCRF6-.js → briefs-DqiwWu-n.js} +4 -4
- package/dist/{catalog-runtime-DZeD2WbL.js → catalog-runtime-D1oYNv04.js} +1 -1
- package/dist/cli/chat.js +17 -17
- package/dist/cli/check.js +3 -3
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +5 -5
- package/dist/cli/snapshot-create.js +4 -4
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +4 -4
- package/dist/{config-BOByVnxe.js → config-9nHoFiJP.js} +117 -12
- package/dist/{connections-BNN5cJam.js → connections-DZjTN3JC.js} +6 -6
- package/dist/continue-in-slack-Dtv7_U42.js +176 -0
- package/dist/{conversation-DCkzvxqB.js → conversation-Dyjq2CZ8.js} +36 -13
- package/dist/{conversation-feed-CMA12Rjs.js → conversation-feed-CcDxlrlQ.js} +109 -3
- package/dist/{conversation-privacy-C0eRxsgb.js → conversation-privacy-D-5HTXjS.js} +1 -1
- package/dist/{conversation-turn-D9qvcDX6.js → conversation-turn-Cxl8WZD7.js} +85 -68
- package/dist/{credential-sync-B_iUpxGL.js → credential-sync-C49ClwDX.js} +18 -18
- package/dist/{db-DoMcnYol.d.ts → db-2resqBh1.d.ts} +1 -1
- package/dist/{db-CoMNr2Zm.js → db-BJNo6fK5.js} +176 -12
- package/dist/{executor-C-m8VrzX.js → executor-DBIaOeJ_.js} +47 -13
- package/dist/{media-BepyEUNm.js → history-IjdmO_r6.js} +1 -85
- package/dist/instrumentation.js +14 -5
- package/dist/lineage-0dereG7H.js +37 -0
- package/dist/{logging-CJTi5niy.js → logging-BIclibct.js} +1 -1
- package/dist/{message-Q6_5DAWR.js → message-dkOl-Iii.js} +9 -10
- package/dist/model-input-CLo9TaUd.js +82 -0
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +17 -9
- package/dist/{oauth-callback-server-CH5XAyo-.js → oauth-callback-server-WmpjfJgQ.js} +2 -2
- package/dist/{plugins-HYh_JOdw.js → plugins-BBX07Jzt.js} +1 -1
- package/dist/{projection-BgwEE36_.js → projection-w_X-zi7v.js} +1035 -692
- package/dist/{prompt-DXc9DYT9.js → prompt-B1Xw46-S.js} +4 -4
- package/dist/{registry-9XwqSnM-.js → registry-BmP5vnlj.js} +4 -4
- package/dist/{resolve-DUIAbcRL.js → resolve-goo34bJK.js} +3 -3
- package/dist/{result-C2Vn8QGn.js → result-PVBeU0Wf.js} +158 -69
- package/dist/{runner-CXGtw-Mc.js → runner-DKrfvNV6.js} +9 -9
- package/dist/{sandbox-egress-signals-Di3S_dO7.js → sandbox-egress-signals-DsUcqrI0.js} +1 -1
- package/dist/{schema-Dyp7racy.js → schema-C9iNFz5n.js} +51 -7
- package/dist/{schema-BnbZ-rKv.d.ts → schema-Dns-sTas.d.ts} +1285 -761
- package/dist/{service-account-DM3KBBeG.js → service-account-CMAAloAL.js} +3 -3
- package/dist/{service-account-GzAMUQ8a.js → service-account-CmowamcB.js} +4 -4
- package/dist/session-stop-BcAXze8a.js +3330 -0
- package/dist/{skills-DCK9SD_l.js → skills-DfsazET6.js} +3 -3
- package/dist/slack-conversation-unfurl-CzQonuWz.js +370 -0
- package/dist/spawn-C7o0FDDp.js +73 -0
- package/dist/state-zSilNpbi.js +132 -0
- package/dist/{user-input-request-CXNIov9n.js → statuses-Hn-HsOph.js} +115 -26
- package/dist/{stop-Dh2DfwpK.js → stop-CFOujp8C.js} +9105 -6007
- package/dist/{store-DrA17Fbz.js → store-Dkeis_8o.js} +10 -10
- package/dist/{store-B1zepKG8.js → store-E3x2Fg_F.js} +24 -4
- package/dist/{task-queue-D1rXWfFN.js → task-queue-D-hCqdZW.js} +4 -4
- package/dist/{task-runner-CT4M8oDz.js → task-runner-vohUPLHe.js} +10 -10
- package/dist/{thread-context-DnqUkbzN.js → thread-context-BzvdkgI9.js} +18 -18
- package/dist/{turn-session-routing-VXDVXLRl.js → turn-session-routing-Bo_LxFum.js} +5 -5
- package/dist/turn-user-message-D5RnVmxQ.js +355 -0
- package/dist/users-2bggndVg.js +424 -0
- package/dist/{validation-zxAJBDDy.js → validation-BbWikeSa.js} +1 -1
- package/dist/{version-DcZ40a0g.js → version-GVBMW2jA.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-CgiGjW10.js → viewer-BpxRliyO.js} +36 -163
- package/dist/{warmup-CwKbxQLl.js → warmup-BW2qwnal.js} +1140 -145
- package/dist/{worker-CbDUzaBA.js → worker-Cbd-iuwZ.js} +25 -20
- package/migrations/0104_code_change_draft.sql +1 -0
- package/migrations/0105_attachment_uploads.sql +14 -0
- package/migrations/0106_conversation_agent_config.sql +1 -0
- package/migrations/0107_attachment_deferred_download.sql +2 -0
- package/migrations/meta/0104_snapshot.json +4516 -0
- package/migrations/meta/0105_snapshot.json +4611 -0
- package/migrations/meta/0106_snapshot.json +4617 -0
- package/migrations/meta/0107_snapshot.json +4617 -0
- package/migrations/meta/_journal.json +28 -0
- package/package.json +10 -8
- package/dist/attempt-selection-ClP3MMPr.js +0 -61
- package/dist/locks-D-0h111u.js +0 -48
- package/dist/notification-Bv25xbj0.js +0 -1284
- package/dist/prompt-input-BUr4J9RO.js +0 -1424
- package/dist/session-stop-D4i7e6iT.js +0 -181
- package/dist/spawn-6cX6xE9G.js +0 -80
- package/dist/turn-cancel-l460pfGW.js +0 -201
- package/dist/turn-user-message-BSPmkm7X.js +0 -608
- package/dist/turn-wake-DVFVXyhX.js +0 -161
- package/dist/{oauth-relay-CsfIazeF.js → oauth-relay-DRzq73b6.js} +1 -1
|
@@ -1,31 +1,32 @@
|
|
|
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 { E as withSpan, G as isRecord$2, K as toOptionalNumber, _ 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, q as toOptionalString, t as buildTurnFailureResponse, x as setSpanStatus, y as setSentryUser } from "./logging-
|
|
4
|
-
import { t as canExposeConversationPayload } from "./conversation-privacy-
|
|
5
|
-
import { c as parseStoredSlackActor, d as parseSlackChannelReferenceId, f as parseSlackTeamId,
|
|
6
|
-
import {
|
|
7
|
-
import { A as
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
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-CgiGjW10.js";
|
|
14
|
-
import { a as getStateAdapter, i as getDefaultRedisStateAdapterFor, n as readEncryptedState, o as getStateValues, s as setStateValues, t as createEncryptedState } from "./state-CSuA2J1V.js";
|
|
2
|
+
import { C as completeObject, D as resolveGatewayModel, E as rerankTexts, L as unwrapCurrentInstruction, Q as toOptionalTrimmed, R as escapeXml, S as completeDecision, T as embedTexts, b as GEN_AI_PROVIDER_NAME, i as getChatConfig, j as estimateTextTokens, n as botConfig, o as getSlackBotToken, y as normalizeSlackEmojiName } from "./config-9nHoFiJP.js";
|
|
3
|
+
import { E as withSpan, G as isRecord$2, K as toOptionalNumber, _ 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, q as toOptionalString, t as buildTurnFailureResponse, x as setSpanStatus, y as setSentryUser } from "./logging-BIclibct.js";
|
|
4
|
+
import { t as canExposeConversationPayload } from "./conversation-privacy-D-5HTXjS.js";
|
|
5
|
+
import { c as parseStoredSlackActor, d as parseSlackChannelReferenceId, f as parseSlackTeamId, i as isActorUserId, l as toStoredSlackActor, p as parseSlackUserId, s as parseActorUserId, v as parseSlackMessageTs } from "./actor-D2iXzvlN.js";
|
|
6
|
+
import { A as startLocationThread, B as saveUserTimezone, C as isPersonInput, G as claimProviderConversation, J as addAgentTurnUsage, N as resolveActorIdentityId, Q as hasAgentTurnUsage, R as readUserTimezone, W as createCache, a as getConversationStore, at as parseDestination, b as createSqlStore, d as eventFromRow, f as withConversationEventLock, o as getDb, r as getConversationEventStore, s as getSqlExecutor, st as sameDestination, tt as conversationDetailTouch, u as createSqlConversationEventStore } from "./db-BJNo6fK5.js";
|
|
7
|
+
import { A as juniorAttachments, D as juniorCodeChanges, E as juniorConversationAnnotations, M as juniorIdentities, N as juniorUsers, O as juniorCodeRepositories, P as juniorDestinations, a as juniorPushSubscriptions, b as juniorConversationBriefs, f as juniorAutomations, i as juniorWorkspaces, j as juniorConversations, 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-DBIaOeJ_.js";
|
|
8
|
+
import { d as contextProvenance, f as instructionActors, n as agentHistoryItemSchema, p as instructionProvenanceFor } from "./history-IjdmO_r6.js";
|
|
9
|
+
import { a as setStateValues, c as fenceLock, i as getStateValues, l as withLock, n as getDefaultRedisStateAdapterFor, o as MUTATION_LOCK_TTL_MS, r as getStateAdapter, s as acquireActiveLock } from "./adapter-S5UkjNK3.js";
|
|
10
|
+
import { _ as CredentialUnavailableError, a as resolveAuthTokenPlaceholder, f as credentialContextForActor, g as credentialUserSubjectId, h as credentialSubjectSchema, m as credentialLogContext, o as resolvePluginCommandEnv, p as credentialContextSchema } from "./registry-BmP5vnlj.js";
|
|
11
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-D1oYNv04.js";
|
|
12
|
+
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-B1Xw46-S.js";
|
|
15
13
|
import { n as isWithinNotificationSchedule, r as notificationScheduleSchema, s as isValidTimeZone, t as DEFAULT_NOTIFICATION_SCHEDULE } from "./schedule-cP0AACm1.js";
|
|
16
|
-
import {
|
|
14
|
+
import { i as readActorIdentity, l as resolveViewerUser, n as findUserByEmailFromSql, o as readIdentityById, p as parseAvatarUrl, s as readIdentityByIdFromSql } from "./viewer-BpxRliyO.js";
|
|
15
|
+
import { $ as briefResourceLabel, B as messageCardRef, H as readMessageCardRefs, R as reviewItemChangeRecordSchema, Y as readMessageAttachments, _ as conversationReportEventSchema, et as conversationBriefSchema, nt as parseStoredBrief, tt as parseBriefInput, v as conversationReportMessageEventSchema } from "./conversation-Dyjq2CZ8.js";
|
|
17
16
|
import { n as redactSandboxEgressProxyPath, t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
|
|
17
|
+
import { n as readEncryptedState, t as createEncryptedState } from "./state-zSilNpbi.js";
|
|
18
18
|
import { i as readWebPushPrivateKey, t as readJuniorSecret } from "./secrets-DebYU866.js";
|
|
19
|
+
import * as z from "zod";
|
|
19
20
|
import path from "node:path";
|
|
20
21
|
import { isDeepStrictEqual } from "node:util";
|
|
21
22
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
22
23
|
import { createHash, createHmac, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, randomUUID, sign, timingSafeEqual } from "node:crypto";
|
|
23
|
-
import * as z from "zod";
|
|
24
24
|
import { and, arrayContains, asc, count, desc, eq, exists, getTableColumns, gt, gte, ilike, inArray, isNotNull, isNull, lt, lte, max, ne, not, notLike, or, sql } from "drizzle-orm";
|
|
25
|
-
import { EgressAuthRequired, EgressPolicyDenied, actorSchema, codeChangeInputSchema, conversationAnnotationInputSchema, defineConversationEvent, destinationSchema, eventDataSchema, eventInputSchema, eventMatchSchema, eventMatches, eventTypeSchema, isPluginModelCostEventName, missingToolAnnotationKeys, normalizeEventIdentifier, objectAnnotationSchema, objectIconPath, objectTypeSchema, pluginAuditAttributesSchema, pluginAuthorizationSchema, pluginCredentialHeaderTransformSchema, pluginCredentialResultSchema, pluginEventsSchema, pluginGrantSchema, pluginModelCostEventNames, pluginProviderAccountSchema, pluginStoredTokensSchema, pluginToolReplySchema, promptContextSchema, promptMessageSchema, sourceSchema, stableEventMatchKey } from "@sentry/junior-plugin-api";
|
|
25
|
+
import { EgressAuthRequired, EgressPolicyDenied, PluginToolInputError, actorSchema, codeChangeInputSchema, conversationAnnotationInputSchema, defineConversationEvent, destinationSchema, eventDataSchema, eventInputSchema, eventMatchSchema, eventMatches, eventTypeSchema, isPluginModelCostEventName, missingToolAnnotationKeys, normalizeEventIdentifier, objectAnnotationSchema, objectIconPath, objectLinkFilterSchema, objectTypeSchema, pluginAuditAttributesSchema, pluginAuthorizationSchema, pluginCredentialHeaderTransformSchema, pluginCredentialResultSchema, pluginEventsSchema, pluginGrantSchema, pluginModelCostEventNames, pluginProviderAccountSchema, pluginStoredTokensSchema, pluginToolReplySchema, promptContextSchema, promptMessageSchema, sourceSchema, stableEventMatchKey } from "@sentry/junior-plugin-api";
|
|
26
26
|
import { alias } from "drizzle-orm/pg-core";
|
|
27
27
|
import fs from "node:fs/promises";
|
|
28
28
|
import pLimit from "p-limit";
|
|
29
|
+
import { WebClient } from "@slack/web-api";
|
|
29
30
|
import http from "node:http";
|
|
30
31
|
import os from "node:os";
|
|
31
32
|
import dns from "node:dns/promises";
|
|
@@ -33,7 +34,6 @@ import net from "node:net";
|
|
|
33
34
|
import { Duplex, Readable } from "node:stream";
|
|
34
35
|
import tls from "node:tls";
|
|
35
36
|
import { FileSystem, Sandbox } from "@vercel/sandbox";
|
|
36
|
-
import { WebClient } from "@slack/web-api";
|
|
37
37
|
import { createRemoteJWKSet, decodeJwt, jwtVerify } from "jose";
|
|
38
38
|
import webPush, { WebPushError } from "web-push";
|
|
39
39
|
// src/chat/configuration/defaults.ts
|
|
@@ -636,6 +636,8 @@ function fragmentSelectionSet(selection, fragments, seen) {
|
|
|
636
636
|
const slackUserInfoSchema = z.object({
|
|
637
637
|
ok: z.literal(true),
|
|
638
638
|
user: z.object({
|
|
639
|
+
is_restricted: z.boolean().nullish(),
|
|
640
|
+
is_ultra_restricted: z.boolean().nullish(),
|
|
639
641
|
name: z.string().nullish(),
|
|
640
642
|
tz: z.string().nullish(),
|
|
641
643
|
profile: z.object({
|
|
@@ -696,6 +698,8 @@ async function lookupSlackUser(teamId, userId) {
|
|
|
696
698
|
...avatarUrl ? { avatarUrl } : void 0,
|
|
697
699
|
timezone: payload.user.tz?.trim() || void 0
|
|
698
700
|
};
|
|
701
|
+
const { is_restricted, is_ultra_restricted } = payload.user;
|
|
702
|
+
if (typeof is_restricted === "boolean" && typeof is_ultra_restricted === "boolean") result.isGuest = is_restricted || is_ultra_restricted;
|
|
699
703
|
writeToCache(teamId, userId, result);
|
|
700
704
|
return result;
|
|
701
705
|
} catch (error) {
|
|
@@ -997,200 +1001,639 @@ const briefUpdatedEvent = defineConversationEvent({
|
|
|
997
1001
|
}).strict(),
|
|
998
1002
|
renderEvent: renderBriefUpdated
|
|
999
1003
|
});
|
|
1000
|
-
// src/chat/
|
|
1001
|
-
/**
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1004
|
+
// src/chat/attachments/source.ts
|
|
1005
|
+
/** The source deleted the file, or Junior can no longer read it. */
|
|
1006
|
+
var AttachmentSourceUnavailableError = class extends Error {
|
|
1007
|
+
constructor(message, options) {
|
|
1008
|
+
super(message, options);
|
|
1009
|
+
this.name = "AttachmentSourceUnavailableError";
|
|
1010
|
+
}
|
|
1011
|
+
};
|
|
1012
|
+
// src/chat/slack/workspace-context.ts
|
|
1013
|
+
const workspaceTeamIdStorage = new AsyncLocalStorage();
|
|
1014
|
+
/** Run a callback with the Slack workspace team ID for the inbound webhook. */
|
|
1015
|
+
function runWithWorkspaceTeamId(teamId, fn) {
|
|
1016
|
+
if (!teamId) return fn();
|
|
1017
|
+
return workspaceTeamIdStorage.run(teamId, fn);
|
|
1010
1018
|
}
|
|
1011
|
-
/**
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
return await args.db.db().select({
|
|
1015
|
-
id: juniorAttachments.id,
|
|
1016
|
-
providerId: juniorAttachments.providerId,
|
|
1017
|
-
bytes: juniorAttachments.bytes,
|
|
1018
|
-
contentType: juniorAttachments.contentType,
|
|
1019
|
-
filename: juniorAttachments.filename
|
|
1020
|
-
}).from(juniorAttachments).where(and(eq(juniorAttachments.conversationId, args.conversationId), eq(juniorAttachments.provider, "slack"), inArray(juniorAttachments.providerId, args.providerIds), isNull(juniorAttachments.deleteRequestedAt)));
|
|
1019
|
+
/** Return the Slack workspace team ID for the current inbound webhook. */
|
|
1020
|
+
function getWorkspaceTeamId() {
|
|
1021
|
+
return workspaceTeamIdStorage.getStore();
|
|
1021
1022
|
}
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1023
|
+
// src/chat/sleep.ts
|
|
1024
|
+
/** Wait for a duration, rejecting with the owning signal reason when cancelled. */
|
|
1025
|
+
function sleep$2(ms, signal) {
|
|
1026
|
+
if (!signal) return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1027
|
+
return new Promise((resolve, reject) => {
|
|
1028
|
+
if (signal.aborted) {
|
|
1029
|
+
reject(signal.reason);
|
|
1030
|
+
return;
|
|
1031
|
+
}
|
|
1032
|
+
const timeoutId = setTimeout(() => {
|
|
1033
|
+
signal.removeEventListener("abort", onAbort);
|
|
1034
|
+
resolve();
|
|
1035
|
+
}, ms);
|
|
1036
|
+
const onAbort = () => {
|
|
1037
|
+
clearTimeout(timeoutId);
|
|
1038
|
+
reject(signal.reason);
|
|
1039
|
+
};
|
|
1040
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1041
|
+
});
|
|
1029
1042
|
}
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1043
|
+
// src/chat/slack/client.ts
|
|
1044
|
+
var SlackActionError = class extends Error {
|
|
1045
|
+
code;
|
|
1046
|
+
apiError;
|
|
1047
|
+
needed;
|
|
1048
|
+
provided;
|
|
1049
|
+
statusCode;
|
|
1050
|
+
requestId;
|
|
1051
|
+
errorData;
|
|
1052
|
+
retryAfterSeconds;
|
|
1053
|
+
detail;
|
|
1054
|
+
detailLine;
|
|
1055
|
+
detailRule;
|
|
1056
|
+
/** Network error code, such as `ECONNABORTED`, when no Slack response arrived. */
|
|
1057
|
+
networkCode;
|
|
1058
|
+
constructor(message, code, options = {}) {
|
|
1059
|
+
super(message);
|
|
1060
|
+
this.name = "SlackActionError";
|
|
1061
|
+
this.code = code;
|
|
1062
|
+
this.apiError = options.apiError;
|
|
1063
|
+
this.needed = options.needed;
|
|
1064
|
+
this.provided = options.provided;
|
|
1065
|
+
this.statusCode = options.statusCode;
|
|
1066
|
+
this.requestId = options.requestId;
|
|
1067
|
+
this.errorData = options.errorData;
|
|
1068
|
+
this.retryAfterSeconds = options.retryAfterSeconds;
|
|
1069
|
+
this.detail = options.detail;
|
|
1070
|
+
this.detailLine = options.detailLine;
|
|
1071
|
+
this.detailRule = options.detailRule;
|
|
1072
|
+
this.networkCode = options.networkCode;
|
|
1073
|
+
}
|
|
1074
|
+
};
|
|
1075
|
+
function serializeSlackErrorData(data) {
|
|
1076
|
+
if (!data || typeof data !== "object") return;
|
|
1077
|
+
const filtered = Object.fromEntries(Object.entries(data).filter(([key]) => key !== "error"));
|
|
1078
|
+
if (Object.keys(filtered).length === 0) return;
|
|
1079
|
+
try {
|
|
1080
|
+
const serialized = JSON.stringify(filtered);
|
|
1081
|
+
return serialized.length <= 600 ? serialized : `${serialized.slice(0, 597)}...`;
|
|
1082
|
+
} catch {
|
|
1083
|
+
return;
|
|
1084
|
+
}
|
|
1035
1085
|
}
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
const
|
|
1040
|
-
const
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
for (const message of messages) {
|
|
1049
|
-
const stored = readMessageAttachments(message.meta?.attachments);
|
|
1050
|
-
const matched = slackFileIds(message.meta).flatMap((id) => {
|
|
1051
|
-
const attachment = byFileId.get(id);
|
|
1052
|
-
return attachment ? [attachment] : [];
|
|
1053
|
-
});
|
|
1054
|
-
if (matched.length) message.meta = {
|
|
1055
|
-
...message.meta,
|
|
1056
|
-
attachments: [...stored, ...matched]
|
|
1057
|
-
};
|
|
1086
|
+
/** Extract a header value by case-insensitive name from a raw headers object. */
|
|
1087
|
+
function getHeaderString(headers, name) {
|
|
1088
|
+
if (!headers || typeof headers !== "object") return;
|
|
1089
|
+
const key = name.toLowerCase();
|
|
1090
|
+
const entries = headers;
|
|
1091
|
+
for (const [entryKey, value] of Object.entries(entries)) {
|
|
1092
|
+
if (entryKey.toLowerCase() !== key) continue;
|
|
1093
|
+
if (typeof value === "string") return value;
|
|
1094
|
+
if (Array.isArray(value)) {
|
|
1095
|
+
const first = value.find((entry) => typeof entry === "string");
|
|
1096
|
+
return typeof first === "string" ? first : void 0;
|
|
1097
|
+
}
|
|
1058
1098
|
}
|
|
1059
1099
|
}
|
|
1060
|
-
function
|
|
1061
|
-
|
|
1062
|
-
|
|
1100
|
+
function parseSlackCanvasDetail(detail) {
|
|
1101
|
+
if (typeof detail !== "string") return {};
|
|
1102
|
+
const trimmed = detail.trim();
|
|
1103
|
+
if (!trimmed) return {};
|
|
1104
|
+
const parsed = { detail: trimmed };
|
|
1105
|
+
const lineMatch = trimmed.match(/line\s+(\d+):/i);
|
|
1106
|
+
if (lineMatch) {
|
|
1107
|
+
const line = Number.parseInt(lineMatch[1] ?? "", 10);
|
|
1108
|
+
if (Number.isFinite(line)) parsed.detailLine = line;
|
|
1109
|
+
}
|
|
1110
|
+
if (/unsupported heading depth/i.test(trimmed)) parsed.detailRule = "unsupported_heading_depth";
|
|
1111
|
+
return parsed;
|
|
1063
1112
|
}
|
|
1064
|
-
// src/chat/agent-invocations/fork-history.ts
|
|
1065
|
-
/** Instructions that a fork child reads with its first task. */
|
|
1066
|
-
const FORK_INSTRUCTIONS = "You are a fork of your parent agent. The messages before your first parent task are copied from the parent's conversation so you have its context. They are not your job: your job is the parent task below. Sandbox files, approvals, and credentials of the parent were not copied, and your sandbox is separate. Verify files in your own sandbox before you use them.";
|
|
1067
1113
|
/**
|
|
1068
|
-
*
|
|
1069
|
-
*
|
|
1070
|
-
*
|
|
1071
|
-
* can commit its history in the middle of a tool round.
|
|
1114
|
+
* Ambient destination-installation token for Slack outbound calls, bound by
|
|
1115
|
+
* installation-scoped entry points so writes carry the destination
|
|
1116
|
+
* workspace's credentials instead of the process-global env token.
|
|
1072
1117
|
*/
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
const before = spawnIndex >= 0 ? messages.slice(0, spawnIndex) : messages;
|
|
1076
|
-
const pending = /* @__PURE__ */ new Set();
|
|
1077
|
-
let end = 0;
|
|
1078
|
-
for (const [index, message] of before.entries()) {
|
|
1079
|
-
if (message.role === "assistant") {
|
|
1080
|
-
for (const part of message.content) if (part.type === "toolCall") pending.add(part.id);
|
|
1081
|
-
} else if (message.role === "toolResult") pending.delete(message.toolCallId);
|
|
1082
|
-
if (pending.size === 0) end = index + 1;
|
|
1083
|
-
}
|
|
1084
|
-
return before.slice(0, end);
|
|
1085
|
-
}
|
|
1118
|
+
const installationTokenStorage = new AsyncLocalStorage();
|
|
1119
|
+
const clientsByToken = /* @__PURE__ */ new Map();
|
|
1086
1120
|
/**
|
|
1087
|
-
*
|
|
1088
|
-
*
|
|
1089
|
-
*
|
|
1121
|
+
* Bind a workspace installation token for all Slack Web API calls inside
|
|
1122
|
+
* `fn`, so multi-workspace outbound writes use the destination workspace's
|
|
1123
|
+
* credentials rather than the env fallback token.
|
|
1090
1124
|
*/
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
function isInheritedForkHistory(event, firstTurnStart) {
|
|
1096
|
-
return firstTurnStart !== void 0 && event.seq > firstTurnStart.seq && event.createdAtMs < firstTurnStart.createdAtMs && (event.data.type === "assistant_message" || event.data.type === "tool_result");
|
|
1125
|
+
function runWithSlackInstallationToken(token, fn) {
|
|
1126
|
+
const trimmed = token.trim();
|
|
1127
|
+
if (!trimmed) throw new SlackActionError("Slack installation token binding requires a non-empty token", "missing_token");
|
|
1128
|
+
return installationTokenStorage.run({ token: trimmed }, fn);
|
|
1097
1129
|
}
|
|
1098
|
-
const firstTurn = alias(juniorConversationEvents, "first_turn");
|
|
1099
1130
|
/**
|
|
1100
|
-
*
|
|
1101
|
-
*
|
|
1102
|
-
*
|
|
1131
|
+
* Token precedence: ambient installation token, then env token, then a hard
|
|
1132
|
+
* failure for team-scoped calls — a call scoped to one workspace must never
|
|
1133
|
+
* silently fall through to another workspace's credentials.
|
|
1103
1134
|
*/
|
|
1104
|
-
function
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
limit 1
|
|
1113
|
-
), false)`;
|
|
1114
|
-
}
|
|
1115
|
-
// src/chat/sentry-links.ts
|
|
1116
|
-
function getSentryOrgSlug() {
|
|
1117
|
-
return process.env.SENTRY_ORG_SLUG?.trim() || void 0;
|
|
1135
|
+
function resolveSlackToken() {
|
|
1136
|
+
const ambientToken = installationTokenStorage.getStore()?.token;
|
|
1137
|
+
if (ambientToken) return ambientToken;
|
|
1138
|
+
const envToken = getSlackBotToken();
|
|
1139
|
+
if (envToken) return envToken;
|
|
1140
|
+
const teamId = getWorkspaceTeamId();
|
|
1141
|
+
if (teamId) throw new SlackActionError(`Slack call is scoped to workspace ${teamId} but no installation token is bound and no default bot token is configured`, "missing_token");
|
|
1142
|
+
throw new SlackActionError("SLACK_BOT_TOKEN (or SLACK_BOT_USER_TOKEN) is required for Slack Web API actions in this service", "missing_token");
|
|
1118
1143
|
}
|
|
1119
|
-
|
|
1120
|
-
|
|
1144
|
+
/** Normalize Junior Slack references to native Slack conversation IDs. */
|
|
1145
|
+
function normalizeSlackConversationId(channelId) {
|
|
1146
|
+
return parseSlackChannelReferenceId(channelId);
|
|
1121
1147
|
}
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1148
|
+
/**
|
|
1149
|
+
* Return the per-token cached WebClient. `withSlackRetries` owns retry
|
|
1150
|
+
* classification for this boundary: the WebClient's built-in policy would
|
|
1151
|
+
* re-post timed-out writes (a duplicate-message hazard) and sleep for the
|
|
1152
|
+
* full unbounded Retry-After inside the request, so both internal behaviors
|
|
1153
|
+
* are disabled here.
|
|
1154
|
+
*/
|
|
1155
|
+
function getClient() {
|
|
1156
|
+
const token = resolveSlackToken();
|
|
1157
|
+
let cached = clientsByToken.get(token);
|
|
1158
|
+
if (!cached) {
|
|
1159
|
+
cached = new WebClient(token, {
|
|
1160
|
+
retryConfig: { retries: 0 },
|
|
1161
|
+
rejectRateLimitedCalls: true
|
|
1162
|
+
});
|
|
1163
|
+
clientsByToken.set(token, cached);
|
|
1164
|
+
}
|
|
1165
|
+
return cached;
|
|
1127
1166
|
}
|
|
1128
|
-
function
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
const
|
|
1132
|
-
|
|
1133
|
-
const
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1167
|
+
function mapSlackError(error) {
|
|
1168
|
+
if (error instanceof SlackActionError) return error;
|
|
1169
|
+
const candidate = error;
|
|
1170
|
+
const apiError = candidate.data?.error;
|
|
1171
|
+
const message = candidate.message ?? "Slack action failed";
|
|
1172
|
+
const baseOptions = {
|
|
1173
|
+
apiError,
|
|
1174
|
+
networkCode: findNetworkErrorCode(error),
|
|
1175
|
+
statusCode: candidate.statusCode,
|
|
1176
|
+
requestId: getHeaderString(candidate.headers, "x-slack-req-id"),
|
|
1177
|
+
errorData: serializeSlackErrorData(candidate.data),
|
|
1178
|
+
...parseSlackCanvasDetail(candidate.data?.detail)
|
|
1179
|
+
};
|
|
1180
|
+
if (apiError === "missing_scope") return new SlackActionError(message, "missing_scope", {
|
|
1181
|
+
...baseOptions,
|
|
1182
|
+
needed: candidate.data?.needed,
|
|
1183
|
+
provided: candidate.data?.provided
|
|
1184
|
+
});
|
|
1185
|
+
if (apiError === "not_in_channel") return new SlackActionError(message, "not_in_channel", baseOptions);
|
|
1186
|
+
if (apiError === "restricted_action_read_only_channel") return new SlackActionError(message, "read_only_channel", baseOptions);
|
|
1187
|
+
if (apiError === "already_reacted") return new SlackActionError(message, "already_reacted", baseOptions);
|
|
1188
|
+
if (apiError === "no_reaction") return new SlackActionError(message, "no_reaction", baseOptions);
|
|
1189
|
+
if (apiError === "invalid_arguments") return new SlackActionError(message, "invalid_arguments", baseOptions);
|
|
1190
|
+
if (apiError === "invalid_cursor") return new SlackActionError(message, "invalid_arguments", baseOptions);
|
|
1191
|
+
if (apiError === "invalid_name") return new SlackActionError(message, "invalid_arguments", baseOptions);
|
|
1192
|
+
if (apiError === "not_found" || apiError === "channel_not_found" || apiError === "message_not_found") return new SlackActionError(message, "not_found", baseOptions);
|
|
1193
|
+
if (apiError === "feature_not_enabled" || apiError === "not_allowed_token_type") return new SlackActionError(message, "feature_unavailable", baseOptions);
|
|
1194
|
+
if (apiError === "canvas_creation_failed") return new SlackActionError(message, "canvas_creation_failed", baseOptions);
|
|
1195
|
+
if (apiError === "canvas_editing_failed") return new SlackActionError(message, "canvas_editing_failed", baseOptions);
|
|
1196
|
+
if (candidate.code === "slack_webapi_rate_limited_error" || candidate.statusCode === 429) return new SlackActionError(message, "rate_limited", {
|
|
1197
|
+
...baseOptions,
|
|
1198
|
+
retryAfterSeconds: candidate.retryAfter
|
|
1199
|
+
});
|
|
1200
|
+
return new SlackActionError(message, "internal_error", baseOptions);
|
|
1139
1201
|
}
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1202
|
+
const MAX_RETRY_DELAY_MS = 1e4;
|
|
1203
|
+
const MAX_TOTAL_RETRY_DELAY_MS = 2e4;
|
|
1204
|
+
const CONNECTION_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
1205
|
+
"ECONNREFUSED",
|
|
1206
|
+
"ECONNRESET",
|
|
1207
|
+
"ENOTFOUND",
|
|
1208
|
+
"EAI_AGAIN"
|
|
1209
|
+
]);
|
|
1210
|
+
const TIMEOUT_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
1211
|
+
"ETIMEDOUT",
|
|
1212
|
+
"ECONNABORTED",
|
|
1213
|
+
"ESOCKETTIMEDOUT"
|
|
1214
|
+
]);
|
|
1215
|
+
function findNetworkErrorCode(error, depth = 0) {
|
|
1216
|
+
if (!error || typeof error !== "object" || depth > 4) return;
|
|
1217
|
+
const candidate = error;
|
|
1218
|
+
if (typeof candidate.code === "string" && (CONNECTION_ERROR_CODES.has(candidate.code) || TIMEOUT_ERROR_CODES.has(candidate.code))) return candidate.code;
|
|
1219
|
+
return findNetworkErrorCode(candidate.original, depth + 1) ?? findNetworkErrorCode(candidate.cause, depth + 1);
|
|
1143
1220
|
}
|
|
1144
|
-
/**
|
|
1145
|
-
function
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
query: { query: eventId }
|
|
1149
|
-
});
|
|
1221
|
+
/** Report whether a Slack call failed because its request deadline elapsed. */
|
|
1222
|
+
function isSlackRequestTimeout(error) {
|
|
1223
|
+
const networkCode = error instanceof SlackActionError ? error.networkCode : findNetworkErrorCode(error);
|
|
1224
|
+
return networkCode !== void 0 && TIMEOUT_ERROR_CODES.has(networkCode);
|
|
1150
1225
|
}
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1226
|
+
function hasSocketHangUpMessage(error) {
|
|
1227
|
+
return error instanceof Error && error.message.toLowerCase().includes("socket hang up");
|
|
1228
|
+
}
|
|
1229
|
+
/**
|
|
1230
|
+
* Classify a failed Slack call for retry: rate limits, Slack 5xx, and
|
|
1231
|
+
* connection-phase failures are always retryable; timeouts are retried only
|
|
1232
|
+
* for idempotent operations because Slack may already have accepted the
|
|
1233
|
+
* request.
|
|
1234
|
+
*/
|
|
1235
|
+
function classifySlackRetry(raw, mapped) {
|
|
1236
|
+
if (mapped.code === "rate_limited") return "rate_limited";
|
|
1237
|
+
if (mapped.statusCode !== void 0 && mapped.statusCode >= 500) return "server_error";
|
|
1238
|
+
const networkCode = findNetworkErrorCode(raw);
|
|
1239
|
+
if (networkCode && CONNECTION_ERROR_CODES.has(networkCode)) return "connection";
|
|
1240
|
+
if (networkCode && TIMEOUT_ERROR_CODES.has(networkCode)) return "timeout";
|
|
1241
|
+
if (hasSocketHangUpMessage(raw)) return "connection";
|
|
1242
|
+
return "none";
|
|
1243
|
+
}
|
|
1244
|
+
/**
|
|
1245
|
+
* Run a Slack Web API call with bounded retries so transient platform
|
|
1246
|
+
* failures do not surface as turn failures, while non-idempotent posts are
|
|
1247
|
+
* never re-sent when Slack may already have accepted them.
|
|
1248
|
+
*
|
|
1249
|
+
* Retry classes: rate limits (bounded Retry-After), connection-phase network
|
|
1250
|
+
* failures, and Slack 5xx responses always retry; request timeouts retry only
|
|
1251
|
+
* when the caller marks the operation `idempotent`.
|
|
1252
|
+
*/
|
|
1253
|
+
async function withSlackRetries(task, maxAttempts = 3, context = {}) {
|
|
1254
|
+
let attempt = 0;
|
|
1255
|
+
let totalDelayMs = 0;
|
|
1256
|
+
const action = context.action ?? "unknown";
|
|
1257
|
+
while (attempt < maxAttempts) {
|
|
1258
|
+
attempt += 1;
|
|
1259
|
+
const attemptNumber = attempt;
|
|
1260
|
+
try {
|
|
1261
|
+
return await withSpan(`POST slack.com/api/${action}`, "http.client", {}, async () => {
|
|
1262
|
+
try {
|
|
1263
|
+
return await task();
|
|
1264
|
+
} catch (error) {
|
|
1265
|
+
const mapped = mapSlackError(error);
|
|
1266
|
+
const errorAttrs = { "error.type": mapped.code };
|
|
1267
|
+
if (mapped.apiError) errorAttrs["app.slack.api_error_code"] = mapped.apiError;
|
|
1268
|
+
if (mapped.code === "rate_limited") {
|
|
1269
|
+
errorAttrs["http.response.status_code"] = 429;
|
|
1270
|
+
if (mapped.retryAfterSeconds) errorAttrs["app.slack.retry_after_ms"] = mapped.retryAfterSeconds * 1e3;
|
|
1271
|
+
} else if (mapped.statusCode != null) errorAttrs["http.response.status_code"] = mapped.statusCode;
|
|
1272
|
+
setSpanAttributes(errorAttrs);
|
|
1273
|
+
throw error;
|
|
1274
|
+
}
|
|
1275
|
+
}, {
|
|
1276
|
+
"http.request.method": "POST",
|
|
1277
|
+
"server.address": "slack.com",
|
|
1278
|
+
"url.scheme": "https",
|
|
1279
|
+
"url.path": `/api/${action}`,
|
|
1280
|
+
"app.slack.method": action,
|
|
1281
|
+
"app.retry.max_attempts": maxAttempts,
|
|
1282
|
+
...attemptNumber > 1 ? { "http.request.resend_count": attemptNumber - 1 } : void 0,
|
|
1283
|
+
...context.attributes ?? {},
|
|
1284
|
+
...context.spanAttributes ?? {}
|
|
1285
|
+
});
|
|
1286
|
+
} catch (error) {
|
|
1287
|
+
const mapped = mapSlackError(error);
|
|
1288
|
+
const retryClass = classifySlackRetry(error, mapped);
|
|
1289
|
+
const isRetryable = retryClass === "rate_limited" || retryClass === "connection" || retryClass === "server_error" || retryClass === "timeout" && context.idempotent === true;
|
|
1290
|
+
const remainingDelayBudgetMs = MAX_TOTAL_RETRY_DELAY_MS - totalDelayMs;
|
|
1291
|
+
const baseLogAttributes = {
|
|
1292
|
+
"app.slack.action": action,
|
|
1293
|
+
"app.slack.error_code": mapped.code,
|
|
1294
|
+
...mapped.apiError ? { "app.slack.api_error": mapped.apiError } : void 0,
|
|
1295
|
+
...mapped.detail ? { "app.slack.detail": mapped.detail } : void 0,
|
|
1296
|
+
...mapped.detailLine !== void 0 ? { "app.slack.detail_line": mapped.detailLine } : void 0,
|
|
1297
|
+
...mapped.detailRule ? { "app.slack.detail_rule": mapped.detailRule } : void 0,
|
|
1298
|
+
...mapped.requestId ? { "app.slack.request_id": mapped.requestId } : void 0,
|
|
1299
|
+
...mapped.statusCode !== void 0 ? { "http.response.status_code": mapped.statusCode } : void 0,
|
|
1300
|
+
...context.attributes ?? {}
|
|
1301
|
+
};
|
|
1302
|
+
if (!isRetryable || attempt >= maxAttempts || remainingDelayBudgetMs <= 0) {
|
|
1303
|
+
if (context.expectedErrorCodes?.includes(mapped.code)) throw mapped;
|
|
1304
|
+
logWarn("slack.action.failed", {
|
|
1305
|
+
...baseLogAttributes,
|
|
1306
|
+
...mapped.errorData ? { "app.slack.error_data": mapped.errorData } : void 0
|
|
1307
|
+
});
|
|
1308
|
+
throw mapped;
|
|
1309
|
+
}
|
|
1310
|
+
logWarn("slack.action.retrying", {
|
|
1311
|
+
...baseLogAttributes,
|
|
1312
|
+
"app.slack.retry_attempt": attempt,
|
|
1313
|
+
"app.slack.retry_class": retryClass
|
|
1314
|
+
});
|
|
1315
|
+
const retryAfterMs = retryClass === "rate_limited" && mapped.retryAfterSeconds && mapped.retryAfterSeconds > 0 ? mapped.retryAfterSeconds * 1e3 : void 0;
|
|
1316
|
+
const backoffMs = Math.min(2e3, 250 * 2 ** (attempt - 1));
|
|
1317
|
+
const delayMs = Math.min(retryAfterMs ?? backoffMs, MAX_RETRY_DELAY_MS, remainingDelayBudgetMs);
|
|
1318
|
+
totalDelayMs += delayMs;
|
|
1319
|
+
await sleep$2(delayMs);
|
|
1320
|
+
}
|
|
1159
1321
|
}
|
|
1160
|
-
|
|
1322
|
+
throw new SlackActionError("Slack action exhausted retries", "internal_error");
|
|
1161
1323
|
}
|
|
1162
|
-
|
|
1163
|
-
|
|
1324
|
+
/**
|
|
1325
|
+
* Slack Web API client for the current destination workspace: the ambient
|
|
1326
|
+
* installation token when one is bound, otherwise the env bot token for
|
|
1327
|
+
* single-workspace deployments. Fails instead of falling back when the call
|
|
1328
|
+
* is workspace-scoped and no installation token can be resolved, so a write
|
|
1329
|
+
* never goes out with another workspace's credentials.
|
|
1330
|
+
*/
|
|
1331
|
+
function getSlackClient(options) {
|
|
1332
|
+
if (options) return new WebClient(resolveSlackToken(), {
|
|
1333
|
+
retryConfig: { retries: 0 },
|
|
1334
|
+
rejectRateLimitedCalls: true,
|
|
1335
|
+
timeout: options.timeoutMs
|
|
1336
|
+
});
|
|
1337
|
+
return getClient();
|
|
1164
1338
|
}
|
|
1165
|
-
/**
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1339
|
+
/**
|
|
1340
|
+
* Slack channel ID prefixes:
|
|
1341
|
+
* - C: channel — modern private channels also use C, so the prefix never
|
|
1342
|
+
* proves a channel is public
|
|
1343
|
+
* - G: legacy private channel / group DM
|
|
1344
|
+
* - D: direct message (1:1)
|
|
1345
|
+
*/
|
|
1346
|
+
function isDmChannel(channelId) {
|
|
1347
|
+
const normalized = normalizeSlackConversationId(channelId);
|
|
1348
|
+
return Boolean(normalized && normalized.startsWith("D"));
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* Conversation-scoped Slack contexts backed by a concrete conversation ID.
|
|
1352
|
+
* Includes channels/groups/DMs (C/G/D).
|
|
1353
|
+
*/
|
|
1354
|
+
function isConversationScopedChannel(channelId) {
|
|
1355
|
+
const normalized = normalizeSlackConversationId(channelId);
|
|
1356
|
+
if (!normalized) return false;
|
|
1357
|
+
return normalized.startsWith("C") || normalized.startsWith("G") || normalized.startsWith("D");
|
|
1358
|
+
}
|
|
1359
|
+
function isConversationChannel(channelId) {
|
|
1360
|
+
const normalized = normalizeSlackConversationId(channelId);
|
|
1361
|
+
if (!normalized) return false;
|
|
1362
|
+
return normalized.startsWith("C") || normalized.startsWith("G");
|
|
1363
|
+
}
|
|
1364
|
+
async function getFilePermalink(fileId) {
|
|
1365
|
+
const client = getClient();
|
|
1366
|
+
return (await withSlackRetries(() => client.files.info({ file: fileId }), 3, {
|
|
1367
|
+
action: "files.info",
|
|
1368
|
+
idempotent: true,
|
|
1369
|
+
spanAttributes: { "app.slack.file_id": fileId }
|
|
1370
|
+
})).file?.permalink;
|
|
1371
|
+
}
|
|
1372
|
+
/**
|
|
1373
|
+
* Read the private download URL and size of one Slack file.
|
|
1374
|
+
*
|
|
1375
|
+
* Return undefined when Slack no longer has the file, or keeps only a
|
|
1376
|
+
* tombstone without a download URL.
|
|
1377
|
+
*/
|
|
1378
|
+
async function readPrivateSlackFile(fileId) {
|
|
1379
|
+
const client = getClient();
|
|
1380
|
+
let response;
|
|
1381
|
+
try {
|
|
1382
|
+
response = await withSlackRetries(() => client.files.info({ file: fileId }), 3, {
|
|
1383
|
+
action: "files.info",
|
|
1384
|
+
idempotent: true,
|
|
1385
|
+
spanAttributes: { "app.slack.file_id": fileId }
|
|
1386
|
+
});
|
|
1387
|
+
} catch (error) {
|
|
1388
|
+
if (error instanceof SlackActionError && (error.code === "not_found" || error.apiError === "file_not_found" || error.apiError === "file_deleted")) return;
|
|
1389
|
+
throw error;
|
|
1390
|
+
}
|
|
1391
|
+
const url = response.file?.url_private_download ?? response.file?.url_private;
|
|
1392
|
+
const bytes = response.file?.size;
|
|
1393
|
+
if (!url || typeof bytes !== "number") return void 0;
|
|
1172
1394
|
return {
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
...stopReason ? { stopReason } : void 0,
|
|
1176
|
-
...hasAgentTurnUsage(usage) ? { usage } : void 0
|
|
1395
|
+
bytes,
|
|
1396
|
+
url
|
|
1177
1397
|
};
|
|
1178
1398
|
}
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
const
|
|
1182
|
-
"
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
"
|
|
1399
|
+
async function fetchPrivateSlackFile(url) {
|
|
1400
|
+
const token = resolveSlackToken();
|
|
1401
|
+
const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
|
|
1402
|
+
if (!response.ok) throw new SlackActionError(`Slack file download failed: ${response.status}`, response.status === 404 || response.status === 410 ? "not_found" : "internal_error", { statusCode: response.status });
|
|
1403
|
+
return response;
|
|
1404
|
+
}
|
|
1405
|
+
/** Download a small private Slack file into memory. */
|
|
1406
|
+
async function downloadPrivateSlackFile(url) {
|
|
1407
|
+
const response = await fetchPrivateSlackFile(url);
|
|
1408
|
+
return Buffer.from(await response.arrayBuffer());
|
|
1409
|
+
}
|
|
1410
|
+
/** Open a private Slack file as a stream, so a large file is never held whole. */
|
|
1411
|
+
async function streamPrivateSlackFile(url) {
|
|
1412
|
+
const response = await fetchPrivateSlackFile(url);
|
|
1413
|
+
if (!response.body) throw new Error("Slack file download returned no body");
|
|
1414
|
+
return response.body;
|
|
1415
|
+
}
|
|
1416
|
+
// src/chat/slack/attachments.ts
|
|
1417
|
+
/** Save the vision summary for a stored Slack attachment. */
|
|
1418
|
+
async function recordSlackAttachment(args) {
|
|
1419
|
+
const db = args.db.db();
|
|
1420
|
+
await db.with(conversationDetailTouch(db, [args.conversationId])).update(juniorAttachments).set({ visionSummary: args.visionSummary }).where(and(eq(juniorAttachments.id, args.attachmentId), eq(juniorAttachments.conversationId, args.conversationId), isNull(juniorAttachments.deleteRequestedAt)));
|
|
1421
|
+
}
|
|
1422
|
+
/** Read a saved vision summary for one live attachment. */
|
|
1423
|
+
async function readAttachmentVisionSummary(args) {
|
|
1424
|
+
const [row] = await args.db.db().select({ visionSummary: juniorAttachments.visionSummary }).from(juniorAttachments).where(and(eq(juniorAttachments.id, args.attachmentId), eq(juniorAttachments.conversationId, args.conversationId), isNull(juniorAttachments.deleteRequestedAt)));
|
|
1425
|
+
return row?.visionSummary;
|
|
1426
|
+
}
|
|
1427
|
+
/** Match live conversation attachments to Slack file ids. */
|
|
1428
|
+
async function matchSlackAttachments(args) {
|
|
1429
|
+
if (args.providerIds.length === 0) return [];
|
|
1430
|
+
return (await args.db.db().select({
|
|
1431
|
+
id: juniorAttachments.id,
|
|
1432
|
+
providerId: juniorAttachments.providerId,
|
|
1433
|
+
bytes: juniorAttachments.bytes,
|
|
1434
|
+
contentType: juniorAttachments.contentType,
|
|
1435
|
+
filename: juniorAttachments.filename,
|
|
1436
|
+
storageKey: juniorAttachments.storageKey
|
|
1437
|
+
}).from(juniorAttachments).where(and(eq(juniorAttachments.conversationId, args.conversationId), eq(juniorAttachments.provider, "slack"), inArray(juniorAttachments.providerId, args.providerIds), isNull(juniorAttachments.deleteRequestedAt)))).map(({ storageKey, ...row }) => storageKey === null ? {
|
|
1438
|
+
...row,
|
|
1439
|
+
pending: true
|
|
1440
|
+
} : row);
|
|
1441
|
+
}
|
|
1442
|
+
/**
|
|
1443
|
+
* Fingerprint the live Slack attachments that `matchSlackAttachments` can
|
|
1444
|
+
* return for a Conversation. It changes when one is stored or deleted, so a
|
|
1445
|
+
* reader can tell that stored messages may now show other files.
|
|
1446
|
+
*/
|
|
1447
|
+
function slackAttachmentsVersionQuery(db, conversationId) {
|
|
1448
|
+
return db.select({ version: sql`coalesce(md5(string_agg(${juniorAttachments.id}, ',' order by ${juniorAttachments.id})), '')` }).from(juniorAttachments).where(and(eq(juniorAttachments.conversationId, conversationId), eq(juniorAttachments.provider, "slack"), isNull(juniorAttachments.deleteRequestedAt)));
|
|
1449
|
+
}
|
|
1450
|
+
/** Read the Slack file identity retained by the Chat SDK. */
|
|
1451
|
+
function getSlackFileId(attachment) {
|
|
1452
|
+
const metadataId = attachment.fetchMetadata?.fileId;
|
|
1453
|
+
if (metadataId) return metadataId;
|
|
1454
|
+
return (attachment.url ?? attachment.fetchMetadata?.url ?? "").match(/(?:^|[-/])(F[A-Z0-9]+)(?:[-/]|$)/)?.[1];
|
|
1455
|
+
}
|
|
1456
|
+
/**
|
|
1457
|
+
* Look up a Slack file that Junior recorded without storing it.
|
|
1458
|
+
*
|
|
1459
|
+
* Uses the installation token that the caller binds: the Slack turn, or the
|
|
1460
|
+
* dashboard route for the conversation's Slack team.
|
|
1461
|
+
*/
|
|
1462
|
+
const readSlackAttachmentSource = async (source) => {
|
|
1463
|
+
const unavailable = (cause) => new AttachmentSourceUnavailableError("The Slack file was deleted, or Junior can no longer access it.", { cause });
|
|
1464
|
+
if (source.provider !== "slack") throw unavailable();
|
|
1465
|
+
const file = await readPrivateSlackFile(source.id);
|
|
1466
|
+
if (!file) throw unavailable();
|
|
1467
|
+
return {
|
|
1468
|
+
bytes: file.bytes,
|
|
1469
|
+
open: async () => {
|
|
1470
|
+
try {
|
|
1471
|
+
return await streamPrivateSlackFile(file.url);
|
|
1472
|
+
} catch (error) {
|
|
1473
|
+
if (error instanceof SlackActionError && (error.code === "not_found" || error.statusCode === 403)) throw unavailable(error);
|
|
1474
|
+
throw error;
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
};
|
|
1478
|
+
};
|
|
1479
|
+
// src/api/conversations/message-attachments.ts
|
|
1480
|
+
/** Resolve saved Slack file references without exposing private storage details. */
|
|
1481
|
+
async function hydrateMessageAttachments(db, conversationId, events) {
|
|
1482
|
+
const messages = events.flatMap((event) => event.data.type === "message" ? [event.data] : []);
|
|
1483
|
+
const ids = [...new Set(messages.flatMap((message) => slackFileIds(message.meta)))];
|
|
1484
|
+
if (!ids.length) return;
|
|
1485
|
+
const attachments = await matchSlackAttachments({
|
|
1486
|
+
db,
|
|
1487
|
+
conversationId,
|
|
1488
|
+
providerIds: ids
|
|
1489
|
+
});
|
|
1490
|
+
const byFileId = new Map(attachments.map(({ providerId, ...attachment }) => [providerId, attachment]));
|
|
1491
|
+
for (const message of messages) {
|
|
1492
|
+
const stored = readMessageAttachments(message.meta?.attachments);
|
|
1493
|
+
const matched = slackFileIds(message.meta).flatMap((id) => {
|
|
1494
|
+
const attachment = byFileId.get(id);
|
|
1495
|
+
return attachment ? [attachment] : [];
|
|
1496
|
+
});
|
|
1497
|
+
if (matched.length) message.meta = {
|
|
1498
|
+
...message.meta,
|
|
1499
|
+
attachments: [...stored, ...matched]
|
|
1500
|
+
};
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
function slackFileIds(meta) {
|
|
1504
|
+
const ids = meta?.slackFileIds ?? meta?.imageFileIds;
|
|
1505
|
+
return Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : [];
|
|
1506
|
+
}
|
|
1507
|
+
// src/chat/agent-invocations/fork-history.ts
|
|
1508
|
+
/** Instructions that a fork child reads with its first task. */
|
|
1509
|
+
const FORK_INSTRUCTIONS = "You are a fork of your parent agent. The messages before your first parent task are copied from the parent's conversation so you have its context. They are not your job: your job is the parent task below. Sandbox files, approvals, and credentials of the parent were not copied, and your sandbox is separate. Verify files in your own sandbox before you use them.";
|
|
1510
|
+
/**
|
|
1511
|
+
* Cut parent history for a fork: everything before the parent's message that
|
|
1512
|
+
* started the fork, through the last point where every tool call has its
|
|
1513
|
+
* result. A model request with an unanswered tool call fails, and the parent
|
|
1514
|
+
* can commit its history in the middle of a tool round.
|
|
1515
|
+
*/
|
|
1516
|
+
function forkHistoryFrom(messages, parentToolCallId) {
|
|
1517
|
+
const spawnIndex = parentToolCallId ? messages.findIndex((message) => message.role === "assistant" && message.content.some((part) => part.type === "toolCall" && part.id === parentToolCallId)) : -1;
|
|
1518
|
+
const before = spawnIndex >= 0 ? messages.slice(0, spawnIndex) : messages;
|
|
1519
|
+
const pending = /* @__PURE__ */ new Set();
|
|
1520
|
+
let end = 0;
|
|
1521
|
+
for (const [index, message] of before.entries()) {
|
|
1522
|
+
if (message.role === "assistant") {
|
|
1523
|
+
for (const part of message.content) if (part.type === "toolCall") pending.add(part.id);
|
|
1524
|
+
} else if (message.role === "toolResult") pending.delete(message.toolCallId);
|
|
1525
|
+
if (pending.size === 0) end = index + 1;
|
|
1526
|
+
}
|
|
1527
|
+
return before.slice(0, end);
|
|
1528
|
+
}
|
|
1529
|
+
/**
|
|
1530
|
+
* Load the start history of a fork child from its parent Conversation. The
|
|
1531
|
+
* child commits it as its own history in its first checkpoint, so later
|
|
1532
|
+
* agent invocations of the child read it from the child Conversation.
|
|
1533
|
+
*/
|
|
1534
|
+
async function loadForkHistory(invocation) {
|
|
1535
|
+
return forkHistoryFrom((await openConversationProjection({ conversationId: invocation.parentConversationId })).messages, invocation.parentToolCallId);
|
|
1536
|
+
}
|
|
1537
|
+
/** True for agent history that a fork child inherited from its parent. */
|
|
1538
|
+
function isInheritedForkHistory(event, firstTurnStart) {
|
|
1539
|
+
return firstTurnStart !== void 0 && event.seq > firstTurnStart.seq && event.createdAtMs < firstTurnStart.createdAtMs && (event.data.type === "assistant_message" || event.data.type === "tool_result");
|
|
1540
|
+
}
|
|
1541
|
+
const firstTurn = alias(juniorConversationEvents, "first_turn");
|
|
1542
|
+
/**
|
|
1543
|
+
* SQL filter for event rows that a fork child did not inherit from its
|
|
1544
|
+
* parent. Usage reports use it, so inherited model calls count only in the
|
|
1545
|
+
* parent.
|
|
1546
|
+
*/
|
|
1547
|
+
function notInheritedByForkChild() {
|
|
1548
|
+
return sql`not coalesce(${juniorConversationEvents.createdAt} < (
|
|
1549
|
+
select ${firstTurn.createdAt}
|
|
1550
|
+
from ${juniorConversationEvents} as ${sql.identifier("first_turn")}
|
|
1551
|
+
where ${firstTurn.conversationId} = ${juniorConversationEvents.conversationId}
|
|
1552
|
+
and ${firstTurn.type} = 'turn_started'
|
|
1553
|
+
and ${firstTurn.seq} < ${juniorConversationEvents.seq}
|
|
1554
|
+
order by ${firstTurn.seq}
|
|
1555
|
+
limit 1
|
|
1556
|
+
), false)`;
|
|
1557
|
+
}
|
|
1558
|
+
// src/chat/sentry-links.ts
|
|
1559
|
+
function getSentryOrgSlug() {
|
|
1560
|
+
return process.env.SENTRY_ORG_SLUG?.trim() || void 0;
|
|
1561
|
+
}
|
|
1562
|
+
function isSentrySaasDsnHost(host) {
|
|
1563
|
+
return host === "sentry.io" || host.endsWith(".sentry.io");
|
|
1564
|
+
}
|
|
1565
|
+
function buildSentryWebBaseUrl(dsn) {
|
|
1566
|
+
if (isSentrySaasDsnHost(dsn.host)) return "https://sentry.io";
|
|
1567
|
+
const port = dsn.port ? `:${dsn.port}` : "";
|
|
1568
|
+
const path = dsn.path ? `/${dsn.path}` : "";
|
|
1569
|
+
return `${dsn.protocol}://${dsn.host}${port}${path}`;
|
|
1570
|
+
}
|
|
1571
|
+
function buildSentryOrgPath(args) {
|
|
1572
|
+
const dsn = getClient$1()?.getDsn();
|
|
1573
|
+
if (!dsn?.host || !dsn.projectId) return;
|
|
1574
|
+
const orgSlug = getSentryOrgSlug();
|
|
1575
|
+
if (!orgSlug) return;
|
|
1576
|
+
const params = new URLSearchParams();
|
|
1577
|
+
params.set("project", dsn.projectId);
|
|
1578
|
+
if (args.query) for (const [key, value] of Object.entries(args.query)) params.set(key, value);
|
|
1579
|
+
const path = `${args.path}?${params.toString()}`;
|
|
1580
|
+
if (isSentrySaasDsnHost(dsn.host)) return `https://${orgSlug}.sentry.io/${path}`;
|
|
1581
|
+
return `${buildSentryWebBaseUrl(dsn)}/organizations/${orgSlug}/${path}`;
|
|
1582
|
+
}
|
|
1583
|
+
/** Build a Sentry conversation URL only when the runtime has enough Sentry config. */
|
|
1584
|
+
function buildSentryConversationUrl(conversationId) {
|
|
1585
|
+
return buildSentryOrgPath({ path: `explore/conversations/${encodeURIComponent(conversationId)}/` });
|
|
1586
|
+
}
|
|
1587
|
+
/** Build a Sentry event URL only when the runtime has enough Sentry config. */
|
|
1588
|
+
function buildSentryEventUrl(eventId) {
|
|
1589
|
+
return buildSentryOrgPath({
|
|
1590
|
+
path: "issues/",
|
|
1591
|
+
query: { query: eventId }
|
|
1592
|
+
});
|
|
1593
|
+
}
|
|
1594
|
+
// src/api/conversations/event-model.ts
|
|
1595
|
+
/** Apply recorded model choices without carrying a previous turn's settings forward. */
|
|
1596
|
+
function conversationEventModel(data, current) {
|
|
1597
|
+
if (data.type === "turn_started") return void 0;
|
|
1598
|
+
if (data.type === "assistant_message") {
|
|
1599
|
+
const model = text$1(data.model);
|
|
1600
|
+
const provider = text$1(data.provider);
|
|
1601
|
+
if (model) return { modelId: model.includes("/") || !provider ? model : `${provider}/${model}` };
|
|
1602
|
+
}
|
|
1603
|
+
return current;
|
|
1604
|
+
}
|
|
1605
|
+
function text$1(value) {
|
|
1606
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
1607
|
+
}
|
|
1608
|
+
/** Allowlist model-call diagnostics; never expose opaque provider metadata. */
|
|
1609
|
+
function conversationEventModelCall(data) {
|
|
1610
|
+
if (data.type !== "assistant_message") return void 0;
|
|
1611
|
+
const usage = extractGenAiUsageSummary(data);
|
|
1612
|
+
const provider = text$1(data.provider);
|
|
1613
|
+
const api = text$1(data.api);
|
|
1614
|
+
const stopReason = text$1(data.stopReason);
|
|
1615
|
+
return {
|
|
1616
|
+
...provider ? { provider } : void 0,
|
|
1617
|
+
...api ? { api } : void 0,
|
|
1618
|
+
...stopReason ? { stopReason } : void 0,
|
|
1619
|
+
...hasAgentTurnUsage(usage) ? { usage } : void 0
|
|
1620
|
+
};
|
|
1621
|
+
}
|
|
1622
|
+
// src/api/conversations/events.ts
|
|
1623
|
+
/** Canonical event types that can contribute to the reporting projection. */
|
|
1624
|
+
const conversationReportSourceEventTypes = [
|
|
1625
|
+
"message",
|
|
1626
|
+
"message_handled",
|
|
1627
|
+
"assistant_message",
|
|
1628
|
+
"tool_result",
|
|
1629
|
+
"tool_execution_started",
|
|
1630
|
+
"guardian_action_reviewed",
|
|
1631
|
+
"turn_started",
|
|
1632
|
+
"turn_context",
|
|
1633
|
+
"structured_event",
|
|
1634
|
+
"attachments_delivered",
|
|
1635
|
+
"reply_posted",
|
|
1636
|
+
"turn_completed",
|
|
1194
1637
|
"turn_failed",
|
|
1195
1638
|
"compaction",
|
|
1196
1639
|
"subagent_started",
|
|
@@ -2843,6 +3286,18 @@ var PluginToolDeniedError = class extends Error {
|
|
|
2843
3286
|
this.name = "PluginToolDeniedError";
|
|
2844
3287
|
}
|
|
2845
3288
|
};
|
|
3289
|
+
// src/chat/tools/execution/tool-input-error.ts
|
|
3290
|
+
/** Thrown when a tool fails due to invalid model/user input, not a system error. */
|
|
3291
|
+
var ToolInputError = class extends Error {
|
|
3292
|
+
constructor(message, options) {
|
|
3293
|
+
super(message, options);
|
|
3294
|
+
this.name = "ToolInputError";
|
|
3295
|
+
}
|
|
3296
|
+
};
|
|
3297
|
+
/** Whether an error is an expected tool input failure that is not a Sentry exception. */
|
|
3298
|
+
function isToolInputError(error) {
|
|
3299
|
+
return error instanceof ToolInputError || error instanceof PluginToolInputError || error instanceof Error && error.name === "PluginToolInputError";
|
|
3300
|
+
}
|
|
2846
3301
|
// src/chat/workspaces/checkout-path.ts
|
|
2847
3302
|
/** Derive the fixed sandbox checkout path for one repository, or undefined when invalid. */
|
|
2848
3303
|
function tryWorkspaceRepoCheckoutPath(repo) {
|
|
@@ -2935,26 +3390,6 @@ async function dockerOkStream(input) {
|
|
|
2935
3390
|
if ((response.statusCode ?? 0) >= 400) return await errorFrom(response);
|
|
2936
3391
|
return response;
|
|
2937
3392
|
}
|
|
2938
|
-
// src/chat/sleep.ts
|
|
2939
|
-
/** Wait for a duration, rejecting with the owning signal reason when cancelled. */
|
|
2940
|
-
function sleep$2(ms, signal) {
|
|
2941
|
-
if (!signal) return new Promise((resolve) => setTimeout(resolve, ms));
|
|
2942
|
-
return new Promise((resolve, reject) => {
|
|
2943
|
-
if (signal.aborted) {
|
|
2944
|
-
reject(signal.reason);
|
|
2945
|
-
return;
|
|
2946
|
-
}
|
|
2947
|
-
const timeoutId = setTimeout(() => {
|
|
2948
|
-
signal.removeEventListener("abort", onAbort);
|
|
2949
|
-
resolve();
|
|
2950
|
-
}, ms);
|
|
2951
|
-
const onAbort = () => {
|
|
2952
|
-
clearTimeout(timeoutId);
|
|
2953
|
-
reject(signal.reason);
|
|
2954
|
-
};
|
|
2955
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
2956
|
-
});
|
|
2957
|
-
}
|
|
2958
3393
|
// src/chat/sandbox/docker/exec.ts
|
|
2959
3394
|
/** Directory for command state in each sandbox. The runtime image creates it. */
|
|
2960
3395
|
const COMMAND_STATE_DIR = "/var/tmp/junior-commands";
|
|
@@ -5246,472 +5681,135 @@ function adaptSession$1(container, options) {
|
|
|
5246
5681
|
stop: () => run(() => stopContainer(container)),
|
|
5247
5682
|
update: (params) => run(async () => {
|
|
5248
5683
|
if (params.networkPolicy) await applyEgressPolicy(container, params.networkPolicy);
|
|
5249
|
-
}),
|
|
5250
|
-
writeFiles: (files) => run(() => writeFiles(id, files))
|
|
5251
|
-
};
|
|
5252
|
-
}
|
|
5253
|
-
// src/chat/sandbox/docker/provider.ts
|
|
5254
|
-
/** Create a sandbox container and return a session for it. */
|
|
5255
|
-
async function createSession(input) {
|
|
5256
|
-
const image = input.snapshotId ?? await ensureRuntimeImage(input.runtime ?? "node24", input.signal);
|
|
5257
|
-
const container = await createContainer({
|
|
5258
|
-
name: input.name ?? newSandboxName(),
|
|
5259
|
-
image,
|
|
5260
|
-
timeoutMs: input.timeoutMs,
|
|
5261
|
-
persistent: input.persistent ?? false,
|
|
5262
|
-
vcpus: input.resources?.vcpus,
|
|
5263
|
-
signal: input.signal
|
|
5264
|
-
}, await egressCaPem());
|
|
5265
|
-
try {
|
|
5266
|
-
if (input.networkPolicy) await applyEgressPolicy(container, input.networkPolicy);
|
|
5267
|
-
} catch (error) {
|
|
5268
|
-
await removeContainer(container.name).catch(() => void 0);
|
|
5269
|
-
throw error;
|
|
5270
|
-
}
|
|
5271
|
-
return adaptSession$1(container, input);
|
|
5272
|
-
}
|
|
5273
|
-
/** Return a session for a named sandbox container. Start it if it stopped. */
|
|
5274
|
-
async function getSession(input) {
|
|
5275
|
-
return adaptSession$1(await getContainer(input.name, await egressCaPem(), input.scopeSignal), input);
|
|
5276
|
-
}
|
|
5277
|
-
/** Create the persistent container that runs one Workspace snapshot build. */
|
|
5278
|
-
async function createWorkspaceSnapshotBuilder$1(input) {
|
|
5279
|
-
await createContainer({
|
|
5280
|
-
name: input.name,
|
|
5281
|
-
image: await ensureRuntimeImage(input.runtime, input.signal),
|
|
5282
|
-
timeoutMs: input.timeoutMs,
|
|
5283
|
-
persistent: true,
|
|
5284
|
-
vcpus: input.resources?.vcpus,
|
|
5285
|
-
signal: input.signal
|
|
5286
|
-
}, await egressCaPem());
|
|
5287
|
-
}
|
|
5288
|
-
/**
|
|
5289
|
-
* Return the container that runs one Workspace snapshot build.
|
|
5290
|
-
*
|
|
5291
|
-
* A Docker snapshot is an image that does not depend on its builder. So
|
|
5292
|
-
* `snapshot()` removes the builder right after the commit, and the image tag
|
|
5293
|
-
* keeps the builder's name. Deleting the builder later removes that tag.
|
|
5294
|
-
*/
|
|
5295
|
-
async function getWorkspaceSnapshotBuilder$1(name, signal) {
|
|
5296
|
-
const container = await getContainer(name, await egressCaPem(), signal);
|
|
5297
|
-
return {
|
|
5298
|
-
session: () => adaptSession$1(container),
|
|
5299
|
-
startDetachedCommand: (input) => startDetachedCommand(container.id, input),
|
|
5300
|
-
async getCommand(commandId) {
|
|
5301
|
-
return { wait: ({ signal: waitSignal }) => waitForDetachedCommand(container.id, commandId, waitSignal) };
|
|
5302
|
-
},
|
|
5303
|
-
async snapshot(options) {
|
|
5304
|
-
const snapshotId = await commitSnapshot(container.id, name, options?.signal);
|
|
5305
|
-
await removeContainer(name);
|
|
5306
|
-
return { snapshotId };
|
|
5307
|
-
}
|
|
5308
|
-
};
|
|
5309
|
-
}
|
|
5310
|
-
async function deleteSnapshotTag(name) {
|
|
5311
|
-
try {
|
|
5312
|
-
await dockerRequest({
|
|
5313
|
-
method: "DELETE",
|
|
5314
|
-
path: `/images/${encodeURIComponent(`${SNAPSHOT_REPOSITORY}:${name}`)}`,
|
|
5315
|
-
query: { force: true }
|
|
5316
|
-
});
|
|
5317
|
-
} catch (error) {
|
|
5318
|
-
if (!(error instanceof DockerApiError && error.statusCode === 404)) throw error;
|
|
5319
|
-
}
|
|
5320
|
-
}
|
|
5321
|
-
/**
|
|
5322
|
-
* Remove Workspace builders and the snapshot images tagged with their names.
|
|
5323
|
-
*
|
|
5324
|
-
* Shared snapshot code calls this when a Workspace snapshot is no longer
|
|
5325
|
-
* used. Each name is tried, and the first failure is thrown at the end.
|
|
5326
|
-
*/
|
|
5327
|
-
async function deleteWorkspaceSnapshotBuilders$1(names) {
|
|
5328
|
-
const failures = [];
|
|
5329
|
-
for (const name of new Set(names)) for (const remove of [removeContainer, deleteSnapshotTag]) try {
|
|
5330
|
-
await remove(name);
|
|
5331
|
-
} catch (error) {
|
|
5332
|
-
failures.push(error);
|
|
5333
|
-
}
|
|
5334
|
-
if (failures.length > 0) throw failures[0];
|
|
5335
|
-
}
|
|
5336
|
-
const DOCKER_SNAPSHOT_PACKAGES = /* @__PURE__ */ new Set([
|
|
5337
|
-
"spal-release",
|
|
5338
|
-
"ripgrep",
|
|
5339
|
-
"gh",
|
|
5340
|
-
"jq"
|
|
5341
|
-
]);
|
|
5342
|
-
/**
|
|
5343
|
-
* Keep only the small Docker base from the declared runtime dependencies.
|
|
5344
|
-
*
|
|
5345
|
-
* Postinstall commands are skipped, because they often download large tools.
|
|
5346
|
-
* A base package that no plugin declares is not installed.
|
|
5347
|
-
*/
|
|
5348
|
-
function selectSnapshotRuntime(runtime) {
|
|
5349
|
-
return {
|
|
5350
|
-
dependencies: runtime.dependencies.filter((dependency) => "package" in dependency && DOCKER_SNAPSHOT_PACKAGES.has(dependency.package)),
|
|
5351
|
-
postinstall: []
|
|
5352
|
-
};
|
|
5353
|
-
}
|
|
5354
|
-
/** Local Docker implementation of the sandbox provider contract. */
|
|
5355
|
-
const dockerSandboxProvider = {
|
|
5356
|
-
errors: dockerSandboxErrors,
|
|
5357
|
-
createSession,
|
|
5358
|
-
getSession,
|
|
5359
|
-
createWorkspaceSnapshotBuilder: createWorkspaceSnapshotBuilder$1,
|
|
5360
|
-
getWorkspaceSnapshotBuilder: getWorkspaceSnapshotBuilder$1,
|
|
5361
|
-
deleteWorkspaceSnapshotBuilders: deleteWorkspaceSnapshotBuilders$1,
|
|
5362
|
-
selectSnapshotRuntime
|
|
5363
|
-
};
|
|
5364
|
-
// src/chat/sandbox/vercel/credentials.ts
|
|
5365
|
-
/**
|
|
5366
|
-
* Resolve explicit Vercel Sandbox credentials, or return undefined to let
|
|
5367
|
-
* the SDK read ambient Vercel auth from its own environment detection.
|
|
5368
|
-
*/
|
|
5369
|
-
function getVercelSandboxCredentials() {
|
|
5370
|
-
const token = toOptionalTrimmed(process.env.VERCEL_TOKEN);
|
|
5371
|
-
const teamId = toOptionalTrimmed(process.env.VERCEL_TEAM_ID);
|
|
5372
|
-
const projectId = toOptionalTrimmed(process.env.VERCEL_PROJECT_ID);
|
|
5373
|
-
if (token && teamId && projectId) return {
|
|
5374
|
-
token,
|
|
5375
|
-
teamId,
|
|
5376
|
-
projectId
|
|
5377
|
-
};
|
|
5378
|
-
}
|
|
5379
|
-
// src/chat/slack/workspace-context.ts
|
|
5380
|
-
const workspaceTeamIdStorage = new AsyncLocalStorage();
|
|
5381
|
-
/** Run a callback with the Slack workspace team ID for the inbound webhook. */
|
|
5382
|
-
function runWithWorkspaceTeamId(teamId, fn) {
|
|
5383
|
-
if (!teamId) return fn();
|
|
5384
|
-
return workspaceTeamIdStorage.run(teamId, fn);
|
|
5385
|
-
}
|
|
5386
|
-
/** Return the Slack workspace team ID for the current inbound webhook. */
|
|
5387
|
-
function getWorkspaceTeamId() {
|
|
5388
|
-
return workspaceTeamIdStorage.getStore();
|
|
5389
|
-
}
|
|
5390
|
-
// src/chat/slack/client.ts
|
|
5391
|
-
var SlackActionError = class extends Error {
|
|
5392
|
-
code;
|
|
5393
|
-
apiError;
|
|
5394
|
-
needed;
|
|
5395
|
-
provided;
|
|
5396
|
-
statusCode;
|
|
5397
|
-
requestId;
|
|
5398
|
-
errorData;
|
|
5399
|
-
retryAfterSeconds;
|
|
5400
|
-
detail;
|
|
5401
|
-
detailLine;
|
|
5402
|
-
detailRule;
|
|
5403
|
-
constructor(message, code, options = {}) {
|
|
5404
|
-
super(message);
|
|
5405
|
-
this.name = "SlackActionError";
|
|
5406
|
-
this.code = code;
|
|
5407
|
-
this.apiError = options.apiError;
|
|
5408
|
-
this.needed = options.needed;
|
|
5409
|
-
this.provided = options.provided;
|
|
5410
|
-
this.statusCode = options.statusCode;
|
|
5411
|
-
this.requestId = options.requestId;
|
|
5412
|
-
this.errorData = options.errorData;
|
|
5413
|
-
this.retryAfterSeconds = options.retryAfterSeconds;
|
|
5414
|
-
this.detail = options.detail;
|
|
5415
|
-
this.detailLine = options.detailLine;
|
|
5416
|
-
this.detailRule = options.detailRule;
|
|
5417
|
-
}
|
|
5418
|
-
};
|
|
5419
|
-
function serializeSlackErrorData(data) {
|
|
5420
|
-
if (!data || typeof data !== "object") return;
|
|
5421
|
-
const filtered = Object.fromEntries(Object.entries(data).filter(([key]) => key !== "error"));
|
|
5422
|
-
if (Object.keys(filtered).length === 0) return;
|
|
5423
|
-
try {
|
|
5424
|
-
const serialized = JSON.stringify(filtered);
|
|
5425
|
-
return serialized.length <= 600 ? serialized : `${serialized.slice(0, 597)}...`;
|
|
5426
|
-
} catch {
|
|
5427
|
-
return;
|
|
5428
|
-
}
|
|
5429
|
-
}
|
|
5430
|
-
/** Extract a header value by case-insensitive name from a raw headers object. */
|
|
5431
|
-
function getHeaderString(headers, name) {
|
|
5432
|
-
if (!headers || typeof headers !== "object") return;
|
|
5433
|
-
const key = name.toLowerCase();
|
|
5434
|
-
const entries = headers;
|
|
5435
|
-
for (const [entryKey, value] of Object.entries(entries)) {
|
|
5436
|
-
if (entryKey.toLowerCase() !== key) continue;
|
|
5437
|
-
if (typeof value === "string") return value;
|
|
5438
|
-
if (Array.isArray(value)) {
|
|
5439
|
-
const first = value.find((entry) => typeof entry === "string");
|
|
5440
|
-
return typeof first === "string" ? first : void 0;
|
|
5441
|
-
}
|
|
5442
|
-
}
|
|
5443
|
-
}
|
|
5444
|
-
function parseSlackCanvasDetail(detail) {
|
|
5445
|
-
if (typeof detail !== "string") return {};
|
|
5446
|
-
const trimmed = detail.trim();
|
|
5447
|
-
if (!trimmed) return {};
|
|
5448
|
-
const parsed = { detail: trimmed };
|
|
5449
|
-
const lineMatch = trimmed.match(/line\s+(\d+):/i);
|
|
5450
|
-
if (lineMatch) {
|
|
5451
|
-
const line = Number.parseInt(lineMatch[1] ?? "", 10);
|
|
5452
|
-
if (Number.isFinite(line)) parsed.detailLine = line;
|
|
5453
|
-
}
|
|
5454
|
-
if (/unsupported heading depth/i.test(trimmed)) parsed.detailRule = "unsupported_heading_depth";
|
|
5455
|
-
return parsed;
|
|
5456
|
-
}
|
|
5457
|
-
/**
|
|
5458
|
-
* Ambient destination-installation token for Slack outbound calls, bound by
|
|
5459
|
-
* installation-scoped entry points so writes carry the destination
|
|
5460
|
-
* workspace's credentials instead of the process-global env token.
|
|
5461
|
-
*/
|
|
5462
|
-
const installationTokenStorage = new AsyncLocalStorage();
|
|
5463
|
-
const clientsByToken = /* @__PURE__ */ new Map();
|
|
5464
|
-
/**
|
|
5465
|
-
* Bind a workspace installation token for all Slack Web API calls inside
|
|
5466
|
-
* `fn`, so multi-workspace outbound writes use the destination workspace's
|
|
5467
|
-
* credentials rather than the env fallback token.
|
|
5468
|
-
*/
|
|
5469
|
-
function runWithSlackInstallationToken(token, fn) {
|
|
5470
|
-
const trimmed = token.trim();
|
|
5471
|
-
if (!trimmed) throw new SlackActionError("Slack installation token binding requires a non-empty token", "missing_token");
|
|
5472
|
-
return installationTokenStorage.run({ token: trimmed }, fn);
|
|
5473
|
-
}
|
|
5474
|
-
/**
|
|
5475
|
-
* Token precedence: ambient installation token, then env token, then a hard
|
|
5476
|
-
* failure for team-scoped calls — a call scoped to one workspace must never
|
|
5477
|
-
* silently fall through to another workspace's credentials.
|
|
5478
|
-
*/
|
|
5479
|
-
function resolveSlackToken() {
|
|
5480
|
-
const ambientToken = installationTokenStorage.getStore()?.token;
|
|
5481
|
-
if (ambientToken) return ambientToken;
|
|
5482
|
-
const envToken = getSlackBotToken();
|
|
5483
|
-
if (envToken) return envToken;
|
|
5484
|
-
const teamId = getWorkspaceTeamId();
|
|
5485
|
-
if (teamId) throw new SlackActionError(`Slack call is scoped to workspace ${teamId} but no installation token is bound and no default bot token is configured`, "missing_token");
|
|
5486
|
-
throw new SlackActionError("SLACK_BOT_TOKEN (or SLACK_BOT_USER_TOKEN) is required for Slack Web API actions in this service", "missing_token");
|
|
5487
|
-
}
|
|
5488
|
-
/** Normalize Junior Slack references to native Slack conversation IDs. */
|
|
5489
|
-
function normalizeSlackConversationId(channelId) {
|
|
5490
|
-
return parseSlackChannelReferenceId(channelId);
|
|
5491
|
-
}
|
|
5492
|
-
/**
|
|
5493
|
-
* Return the per-token cached WebClient. `withSlackRetries` owns retry
|
|
5494
|
-
* classification for this boundary: the WebClient's built-in policy would
|
|
5495
|
-
* re-post timed-out writes (a duplicate-message hazard) and sleep for the
|
|
5496
|
-
* full unbounded Retry-After inside the request, so both internal behaviors
|
|
5497
|
-
* are disabled here.
|
|
5498
|
-
*/
|
|
5499
|
-
function getClient() {
|
|
5500
|
-
const token = resolveSlackToken();
|
|
5501
|
-
let cached = clientsByToken.get(token);
|
|
5502
|
-
if (!cached) {
|
|
5503
|
-
cached = new WebClient(token, {
|
|
5504
|
-
retryConfig: { retries: 0 },
|
|
5505
|
-
rejectRateLimitedCalls: true
|
|
5506
|
-
});
|
|
5507
|
-
clientsByToken.set(token, cached);
|
|
5508
|
-
}
|
|
5509
|
-
return cached;
|
|
5510
|
-
}
|
|
5511
|
-
function mapSlackError(error) {
|
|
5512
|
-
if (error instanceof SlackActionError) return error;
|
|
5513
|
-
const candidate = error;
|
|
5514
|
-
const apiError = candidate.data?.error;
|
|
5515
|
-
const message = candidate.message ?? "Slack action failed";
|
|
5516
|
-
const baseOptions = {
|
|
5517
|
-
apiError,
|
|
5518
|
-
statusCode: candidate.statusCode,
|
|
5519
|
-
requestId: getHeaderString(candidate.headers, "x-slack-req-id"),
|
|
5520
|
-
errorData: serializeSlackErrorData(candidate.data),
|
|
5521
|
-
...parseSlackCanvasDetail(candidate.data?.detail)
|
|
5522
|
-
};
|
|
5523
|
-
if (apiError === "missing_scope") return new SlackActionError(message, "missing_scope", {
|
|
5524
|
-
...baseOptions,
|
|
5525
|
-
needed: candidate.data?.needed,
|
|
5526
|
-
provided: candidate.data?.provided
|
|
5527
|
-
});
|
|
5528
|
-
if (apiError === "not_in_channel") return new SlackActionError(message, "not_in_channel", baseOptions);
|
|
5529
|
-
if (apiError === "restricted_action_read_only_channel") return new SlackActionError(message, "read_only_channel", baseOptions);
|
|
5530
|
-
if (apiError === "already_reacted") return new SlackActionError(message, "already_reacted", baseOptions);
|
|
5531
|
-
if (apiError === "no_reaction") return new SlackActionError(message, "no_reaction", baseOptions);
|
|
5532
|
-
if (apiError === "invalid_arguments") return new SlackActionError(message, "invalid_arguments", baseOptions);
|
|
5533
|
-
if (apiError === "invalid_cursor") return new SlackActionError(message, "invalid_arguments", baseOptions);
|
|
5534
|
-
if (apiError === "invalid_name") return new SlackActionError(message, "invalid_arguments", baseOptions);
|
|
5535
|
-
if (apiError === "not_found" || apiError === "channel_not_found" || apiError === "message_not_found") return new SlackActionError(message, "not_found", baseOptions);
|
|
5536
|
-
if (apiError === "feature_not_enabled" || apiError === "not_allowed_token_type") return new SlackActionError(message, "feature_unavailable", baseOptions);
|
|
5537
|
-
if (apiError === "canvas_creation_failed") return new SlackActionError(message, "canvas_creation_failed", baseOptions);
|
|
5538
|
-
if (apiError === "canvas_editing_failed") return new SlackActionError(message, "canvas_editing_failed", baseOptions);
|
|
5539
|
-
if (candidate.code === "slack_webapi_rate_limited_error" || candidate.statusCode === 429) return new SlackActionError(message, "rate_limited", {
|
|
5540
|
-
...baseOptions,
|
|
5541
|
-
retryAfterSeconds: candidate.retryAfter
|
|
5542
|
-
});
|
|
5543
|
-
return new SlackActionError(message, "internal_error", baseOptions);
|
|
5544
|
-
}
|
|
5545
|
-
const MAX_RETRY_DELAY_MS = 1e4;
|
|
5546
|
-
const MAX_TOTAL_RETRY_DELAY_MS = 2e4;
|
|
5547
|
-
const CONNECTION_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
5548
|
-
"ECONNREFUSED",
|
|
5549
|
-
"ECONNRESET",
|
|
5550
|
-
"ENOTFOUND",
|
|
5551
|
-
"EAI_AGAIN"
|
|
5552
|
-
]);
|
|
5553
|
-
const TIMEOUT_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
5554
|
-
"ETIMEDOUT",
|
|
5555
|
-
"ECONNABORTED",
|
|
5556
|
-
"ESOCKETTIMEDOUT"
|
|
5557
|
-
]);
|
|
5558
|
-
function findNetworkErrorCode(error, depth = 0) {
|
|
5559
|
-
if (!error || typeof error !== "object" || depth > 4) return;
|
|
5560
|
-
const candidate = error;
|
|
5561
|
-
if (typeof candidate.code === "string" && (CONNECTION_ERROR_CODES.has(candidate.code) || TIMEOUT_ERROR_CODES.has(candidate.code))) return candidate.code;
|
|
5562
|
-
return findNetworkErrorCode(candidate.original, depth + 1) ?? findNetworkErrorCode(candidate.cause, depth + 1);
|
|
5563
|
-
}
|
|
5564
|
-
function hasSocketHangUpMessage(error) {
|
|
5565
|
-
return error instanceof Error && error.message.toLowerCase().includes("socket hang up");
|
|
5566
|
-
}
|
|
5567
|
-
/**
|
|
5568
|
-
* Classify a failed Slack call for retry: rate limits, Slack 5xx, and
|
|
5569
|
-
* connection-phase failures are always retryable; timeouts are retried only
|
|
5570
|
-
* for idempotent operations because Slack may already have accepted the
|
|
5571
|
-
* request.
|
|
5572
|
-
*/
|
|
5573
|
-
function classifySlackRetry(raw, mapped) {
|
|
5574
|
-
if (mapped.code === "rate_limited") return "rate_limited";
|
|
5575
|
-
if (mapped.statusCode !== void 0 && mapped.statusCode >= 500) return "server_error";
|
|
5576
|
-
const networkCode = findNetworkErrorCode(raw);
|
|
5577
|
-
if (networkCode && CONNECTION_ERROR_CODES.has(networkCode)) return "connection";
|
|
5578
|
-
if (networkCode && TIMEOUT_ERROR_CODES.has(networkCode)) return "timeout";
|
|
5579
|
-
if (hasSocketHangUpMessage(raw)) return "connection";
|
|
5580
|
-
return "none";
|
|
5581
|
-
}
|
|
5582
|
-
/**
|
|
5583
|
-
* Run a Slack Web API call with bounded retries so transient platform
|
|
5584
|
-
* failures do not surface as turn failures, while non-idempotent posts are
|
|
5585
|
-
* never re-sent when Slack may already have accepted them.
|
|
5586
|
-
*
|
|
5587
|
-
* Retry classes: rate limits (bounded Retry-After), connection-phase network
|
|
5588
|
-
* failures, and Slack 5xx responses always retry; request timeouts retry only
|
|
5589
|
-
* when the caller marks the operation `idempotent`.
|
|
5590
|
-
*/
|
|
5591
|
-
async function withSlackRetries(task, maxAttempts = 3, context = {}) {
|
|
5592
|
-
let attempt = 0;
|
|
5593
|
-
let totalDelayMs = 0;
|
|
5594
|
-
const action = context.action ?? "unknown";
|
|
5595
|
-
while (attempt < maxAttempts) {
|
|
5596
|
-
attempt += 1;
|
|
5597
|
-
const attemptNumber = attempt;
|
|
5598
|
-
try {
|
|
5599
|
-
return await withSpan(`POST slack.com/api/${action}`, "http.client", {}, async () => {
|
|
5600
|
-
try {
|
|
5601
|
-
return await task();
|
|
5602
|
-
} catch (error) {
|
|
5603
|
-
const mapped = mapSlackError(error);
|
|
5604
|
-
const errorAttrs = { "error.type": mapped.code };
|
|
5605
|
-
if (mapped.apiError) errorAttrs["app.slack.api_error_code"] = mapped.apiError;
|
|
5606
|
-
if (mapped.code === "rate_limited") {
|
|
5607
|
-
errorAttrs["http.response.status_code"] = 429;
|
|
5608
|
-
if (mapped.retryAfterSeconds) errorAttrs["app.slack.retry_after_ms"] = mapped.retryAfterSeconds * 1e3;
|
|
5609
|
-
} else if (mapped.statusCode != null) errorAttrs["http.response.status_code"] = mapped.statusCode;
|
|
5610
|
-
setSpanAttributes(errorAttrs);
|
|
5611
|
-
throw error;
|
|
5612
|
-
}
|
|
5613
|
-
}, {
|
|
5614
|
-
"http.request.method": "POST",
|
|
5615
|
-
"server.address": "slack.com",
|
|
5616
|
-
"url.scheme": "https",
|
|
5617
|
-
"url.path": `/api/${action}`,
|
|
5618
|
-
"app.slack.method": action,
|
|
5619
|
-
"app.retry.max_attempts": maxAttempts,
|
|
5620
|
-
...attemptNumber > 1 ? { "http.request.resend_count": attemptNumber - 1 } : void 0,
|
|
5621
|
-
...context.attributes ?? {},
|
|
5622
|
-
...context.spanAttributes ?? {}
|
|
5623
|
-
});
|
|
5624
|
-
} catch (error) {
|
|
5625
|
-
const mapped = mapSlackError(error);
|
|
5626
|
-
const retryClass = classifySlackRetry(error, mapped);
|
|
5627
|
-
const isRetryable = retryClass === "rate_limited" || retryClass === "connection" || retryClass === "server_error" || retryClass === "timeout" && context.idempotent === true;
|
|
5628
|
-
const remainingDelayBudgetMs = MAX_TOTAL_RETRY_DELAY_MS - totalDelayMs;
|
|
5629
|
-
const baseLogAttributes = {
|
|
5630
|
-
"app.slack.action": action,
|
|
5631
|
-
"app.slack.error_code": mapped.code,
|
|
5632
|
-
...mapped.apiError ? { "app.slack.api_error": mapped.apiError } : void 0,
|
|
5633
|
-
...mapped.detail ? { "app.slack.detail": mapped.detail } : void 0,
|
|
5634
|
-
...mapped.detailLine !== void 0 ? { "app.slack.detail_line": mapped.detailLine } : void 0,
|
|
5635
|
-
...mapped.detailRule ? { "app.slack.detail_rule": mapped.detailRule } : void 0,
|
|
5636
|
-
...mapped.requestId ? { "app.slack.request_id": mapped.requestId } : void 0,
|
|
5637
|
-
...mapped.statusCode !== void 0 ? { "http.response.status_code": mapped.statusCode } : void 0,
|
|
5638
|
-
...context.attributes ?? {}
|
|
5639
|
-
};
|
|
5640
|
-
if (!isRetryable || attempt >= maxAttempts || remainingDelayBudgetMs <= 0) {
|
|
5641
|
-
if (context.expectedErrorCodes?.includes(mapped.code)) throw mapped;
|
|
5642
|
-
logWarn("slack.action.failed", {
|
|
5643
|
-
...baseLogAttributes,
|
|
5644
|
-
...mapped.errorData ? { "app.slack.error_data": mapped.errorData } : void 0
|
|
5645
|
-
});
|
|
5646
|
-
throw mapped;
|
|
5647
|
-
}
|
|
5648
|
-
logWarn("slack.action.retrying", {
|
|
5649
|
-
...baseLogAttributes,
|
|
5650
|
-
"app.slack.retry_attempt": attempt,
|
|
5651
|
-
"app.slack.retry_class": retryClass
|
|
5652
|
-
});
|
|
5653
|
-
const retryAfterMs = retryClass === "rate_limited" && mapped.retryAfterSeconds && mapped.retryAfterSeconds > 0 ? mapped.retryAfterSeconds * 1e3 : void 0;
|
|
5654
|
-
const backoffMs = Math.min(2e3, 250 * 2 ** (attempt - 1));
|
|
5655
|
-
const delayMs = Math.min(retryAfterMs ?? backoffMs, MAX_RETRY_DELAY_MS, remainingDelayBudgetMs);
|
|
5656
|
-
totalDelayMs += delayMs;
|
|
5657
|
-
await sleep$2(delayMs);
|
|
5658
|
-
}
|
|
5684
|
+
}),
|
|
5685
|
+
writeFiles: (files) => run(() => writeFiles(id, files))
|
|
5686
|
+
};
|
|
5687
|
+
}
|
|
5688
|
+
// src/chat/sandbox/docker/provider.ts
|
|
5689
|
+
/** Create a sandbox container and return a session for it. */
|
|
5690
|
+
async function createSession(input) {
|
|
5691
|
+
const image = input.snapshotId ?? await ensureRuntimeImage(input.runtime ?? "node24", input.signal);
|
|
5692
|
+
const container = await createContainer({
|
|
5693
|
+
name: input.name ?? newSandboxName(),
|
|
5694
|
+
image,
|
|
5695
|
+
timeoutMs: input.timeoutMs,
|
|
5696
|
+
persistent: input.persistent ?? false,
|
|
5697
|
+
vcpus: input.resources?.vcpus,
|
|
5698
|
+
signal: input.signal
|
|
5699
|
+
}, await egressCaPem());
|
|
5700
|
+
try {
|
|
5701
|
+
if (input.networkPolicy) await applyEgressPolicy(container, input.networkPolicy);
|
|
5702
|
+
} catch (error) {
|
|
5703
|
+
await removeContainer(container.name).catch(() => void 0);
|
|
5704
|
+
throw error;
|
|
5659
5705
|
}
|
|
5660
|
-
|
|
5706
|
+
return adaptSession$1(container, input);
|
|
5707
|
+
}
|
|
5708
|
+
/** Return a session for a named sandbox container. Start it if it stopped. */
|
|
5709
|
+
async function getSession(input) {
|
|
5710
|
+
return adaptSession$1(await getContainer(input.name, await egressCaPem(), input.scopeSignal), input);
|
|
5711
|
+
}
|
|
5712
|
+
/** Create the persistent container that runs one Workspace snapshot build. */
|
|
5713
|
+
async function createWorkspaceSnapshotBuilder$1(input) {
|
|
5714
|
+
await createContainer({
|
|
5715
|
+
name: input.name,
|
|
5716
|
+
image: await ensureRuntimeImage(input.runtime, input.signal),
|
|
5717
|
+
timeoutMs: input.timeoutMs,
|
|
5718
|
+
persistent: true,
|
|
5719
|
+
vcpus: input.resources?.vcpus,
|
|
5720
|
+
signal: input.signal
|
|
5721
|
+
}, await egressCaPem());
|
|
5661
5722
|
}
|
|
5662
5723
|
/**
|
|
5663
|
-
*
|
|
5664
|
-
*
|
|
5665
|
-
*
|
|
5666
|
-
*
|
|
5667
|
-
*
|
|
5724
|
+
* Return the container that runs one Workspace snapshot build.
|
|
5725
|
+
*
|
|
5726
|
+
* A Docker snapshot is an image that does not depend on its builder. So
|
|
5727
|
+
* `snapshot()` removes the builder right after the commit, and the image tag
|
|
5728
|
+
* keeps the builder's name. Deleting the builder later removes that tag.
|
|
5668
5729
|
*/
|
|
5669
|
-
function
|
|
5670
|
-
|
|
5671
|
-
|
|
5672
|
-
|
|
5673
|
-
|
|
5674
|
-
|
|
5675
|
-
|
|
5730
|
+
async function getWorkspaceSnapshotBuilder$1(name, signal) {
|
|
5731
|
+
const container = await getContainer(name, await egressCaPem(), signal);
|
|
5732
|
+
return {
|
|
5733
|
+
session: () => adaptSession$1(container),
|
|
5734
|
+
startDetachedCommand: (input) => startDetachedCommand(container.id, input),
|
|
5735
|
+
async getCommand(commandId) {
|
|
5736
|
+
return { wait: ({ signal: waitSignal }) => waitForDetachedCommand(container.id, commandId, waitSignal) };
|
|
5737
|
+
},
|
|
5738
|
+
async snapshot(options) {
|
|
5739
|
+
const snapshotId = await commitSnapshot(container.id, name, options?.signal);
|
|
5740
|
+
await removeContainer(name);
|
|
5741
|
+
return { snapshotId };
|
|
5742
|
+
}
|
|
5743
|
+
};
|
|
5744
|
+
}
|
|
5745
|
+
async function deleteSnapshotTag(name) {
|
|
5746
|
+
try {
|
|
5747
|
+
await dockerRequest({
|
|
5748
|
+
method: "DELETE",
|
|
5749
|
+
path: `/images/${encodeURIComponent(`${SNAPSHOT_REPOSITORY}:${name}`)}`,
|
|
5750
|
+
query: { force: true }
|
|
5751
|
+
});
|
|
5752
|
+
} catch (error) {
|
|
5753
|
+
if (!(error instanceof DockerApiError && error.statusCode === 404)) throw error;
|
|
5754
|
+
}
|
|
5676
5755
|
}
|
|
5677
5756
|
/**
|
|
5678
|
-
*
|
|
5679
|
-
*
|
|
5680
|
-
*
|
|
5681
|
-
*
|
|
5682
|
-
* - D: direct message (1:1)
|
|
5757
|
+
* Remove Workspace builders and the snapshot images tagged with their names.
|
|
5758
|
+
*
|
|
5759
|
+
* Shared snapshot code calls this when a Workspace snapshot is no longer
|
|
5760
|
+
* used. Each name is tried, and the first failure is thrown at the end.
|
|
5683
5761
|
*/
|
|
5684
|
-
function
|
|
5685
|
-
const
|
|
5686
|
-
|
|
5762
|
+
async function deleteWorkspaceSnapshotBuilders$1(names) {
|
|
5763
|
+
const failures = [];
|
|
5764
|
+
for (const name of new Set(names)) for (const remove of [removeContainer, deleteSnapshotTag]) try {
|
|
5765
|
+
await remove(name);
|
|
5766
|
+
} catch (error) {
|
|
5767
|
+
failures.push(error);
|
|
5768
|
+
}
|
|
5769
|
+
if (failures.length > 0) throw failures[0];
|
|
5687
5770
|
}
|
|
5771
|
+
const DOCKER_SNAPSHOT_PACKAGES = /* @__PURE__ */ new Set([
|
|
5772
|
+
"spal-release",
|
|
5773
|
+
"ripgrep",
|
|
5774
|
+
"gh",
|
|
5775
|
+
"jq"
|
|
5776
|
+
]);
|
|
5688
5777
|
/**
|
|
5689
|
-
*
|
|
5690
|
-
*
|
|
5778
|
+
* Keep only the small Docker base from the declared runtime dependencies.
|
|
5779
|
+
*
|
|
5780
|
+
* Postinstall commands are skipped, because they often download large tools.
|
|
5781
|
+
* A base package that no plugin declares is not installed.
|
|
5691
5782
|
*/
|
|
5692
|
-
function
|
|
5693
|
-
|
|
5694
|
-
|
|
5695
|
-
|
|
5696
|
-
}
|
|
5697
|
-
function isConversationChannel(channelId) {
|
|
5698
|
-
const normalized = normalizeSlackConversationId(channelId);
|
|
5699
|
-
if (!normalized) return false;
|
|
5700
|
-
return normalized.startsWith("C") || normalized.startsWith("G");
|
|
5701
|
-
}
|
|
5702
|
-
async function getFilePermalink(fileId) {
|
|
5703
|
-
const client = getClient();
|
|
5704
|
-
return (await withSlackRetries(() => client.files.info({ file: fileId }), 3, {
|
|
5705
|
-
action: "files.info",
|
|
5706
|
-
idempotent: true,
|
|
5707
|
-
spanAttributes: { "app.slack.file_id": fileId }
|
|
5708
|
-
})).file?.permalink;
|
|
5783
|
+
function selectSnapshotRuntime(runtime) {
|
|
5784
|
+
return {
|
|
5785
|
+
dependencies: runtime.dependencies.filter((dependency) => "package" in dependency && DOCKER_SNAPSHOT_PACKAGES.has(dependency.package)),
|
|
5786
|
+
postinstall: []
|
|
5787
|
+
};
|
|
5709
5788
|
}
|
|
5710
|
-
|
|
5711
|
-
|
|
5712
|
-
|
|
5713
|
-
|
|
5714
|
-
|
|
5789
|
+
/** Local Docker implementation of the sandbox provider contract. */
|
|
5790
|
+
const dockerSandboxProvider = {
|
|
5791
|
+
errors: dockerSandboxErrors,
|
|
5792
|
+
createSession,
|
|
5793
|
+
getSession,
|
|
5794
|
+
createWorkspaceSnapshotBuilder: createWorkspaceSnapshotBuilder$1,
|
|
5795
|
+
getWorkspaceSnapshotBuilder: getWorkspaceSnapshotBuilder$1,
|
|
5796
|
+
deleteWorkspaceSnapshotBuilders: deleteWorkspaceSnapshotBuilders$1,
|
|
5797
|
+
selectSnapshotRuntime
|
|
5798
|
+
};
|
|
5799
|
+
// src/chat/sandbox/vercel/credentials.ts
|
|
5800
|
+
/**
|
|
5801
|
+
* Resolve explicit Vercel Sandbox credentials, or return undefined to let
|
|
5802
|
+
* the SDK read ambient Vercel auth from its own environment detection.
|
|
5803
|
+
*/
|
|
5804
|
+
function getVercelSandboxCredentials() {
|
|
5805
|
+
const token = toOptionalTrimmed(process.env.VERCEL_TOKEN);
|
|
5806
|
+
const teamId = toOptionalTrimmed(process.env.VERCEL_TEAM_ID);
|
|
5807
|
+
const projectId = toOptionalTrimmed(process.env.VERCEL_PROJECT_ID);
|
|
5808
|
+
if (token && teamId && projectId) return {
|
|
5809
|
+
token,
|
|
5810
|
+
teamId,
|
|
5811
|
+
projectId
|
|
5812
|
+
};
|
|
5715
5813
|
}
|
|
5716
5814
|
// src/chat/slack/post-warning.ts
|
|
5717
5815
|
const codes = /* @__PURE__ */ new Set([
|
|
@@ -6167,7 +6265,13 @@ function readExistingSlackAngleToken(line, start) {
|
|
|
6167
6265
|
const close = line.indexOf(">", start + 1);
|
|
6168
6266
|
if (close === -1) return;
|
|
6169
6267
|
const body = line.slice(start + 1, close);
|
|
6170
|
-
if (
|
|
6268
|
+
if ([
|
|
6269
|
+
"https://",
|
|
6270
|
+
"http://",
|
|
6271
|
+
"@",
|
|
6272
|
+
"#",
|
|
6273
|
+
"!"
|
|
6274
|
+
].some((prefix) => body.startsWith(prefix))) return {
|
|
6171
6275
|
text: line.slice(start, close + 1),
|
|
6172
6276
|
end: close + 1
|
|
6173
6277
|
};
|
|
@@ -6207,7 +6311,8 @@ function readBareUrl(line, start) {
|
|
|
6207
6311
|
};
|
|
6208
6312
|
const shouldPeel = () => raw.endsWith("_") || /[.,!?;:]$/.test(raw) || raw.endsWith(")") && hasUnmatchedClosingParen(raw);
|
|
6209
6313
|
while (raw.length > 0 && shouldPeel()) peel();
|
|
6210
|
-
|
|
6314
|
+
const scheme = ["https://", "http://"].find((prefix) => raw.startsWith(prefix));
|
|
6315
|
+
if (!scheme || raw.length === scheme.length) return;
|
|
6211
6316
|
return {
|
|
6212
6317
|
url: raw,
|
|
6213
6318
|
suffix,
|
|
@@ -6369,6 +6474,12 @@ function normalizeSlackStatusText(text) {
|
|
|
6369
6474
|
function slackMention(userId) {
|
|
6370
6475
|
return `<@${userId}>`;
|
|
6371
6476
|
}
|
|
6477
|
+
/** Slack user mentions: `<@U123>` or `<@U123|label>`. */
|
|
6478
|
+
const SLACK_USER_MENTION_RE = /<@([UW][A-Z0-9]+)(?:\|[^<>]*)?>/g;
|
|
6479
|
+
/** Return the Slack user IDs that the text mentions, once each, in order. */
|
|
6480
|
+
function slackMentionedUserIds(text) {
|
|
6481
|
+
return [...new Set([...text.matchAll(SLACK_USER_MENTION_RE)].map((m) => m[1]))];
|
|
6482
|
+
}
|
|
6372
6483
|
// src/chat/slack/oauth-authorization-message.ts
|
|
6373
6484
|
const ACCOUNT_SCOPE_NOTE = "This connects only your account. I can see only what you can see.";
|
|
6374
6485
|
/** Present private OAuth authorization with a clear action and text fallback. */
|
|
@@ -6857,10 +6968,14 @@ function isTransient(error) {
|
|
|
6857
6968
|
return isRecord$1(response) && typeof response.status === "number" && response.status >= 500 && response.status < 600;
|
|
6858
6969
|
});
|
|
6859
6970
|
}
|
|
6971
|
+
const SOCKET_FAILURE_CODES = /* @__PURE__ */ new Set(["ECONNRESET", "UND_ERR_SOCKET"]);
|
|
6972
|
+
function isFetchSocketFailure(error) {
|
|
6973
|
+
return error.name === "TypeError" && (error.message === "terminated" || error.message === "fetch failed") && isRecord$1(error.cause) && typeof error.cause.code === "string" && SOCKET_FAILURE_CODES.has(error.cause.code);
|
|
6974
|
+
}
|
|
6860
6975
|
function isCommandStreamInterrupted(error) {
|
|
6861
6976
|
return findInErrorChain(error, (candidate) => {
|
|
6862
6977
|
if (!(candidate instanceof Error)) return false;
|
|
6863
|
-
return candidate.name === "StreamError" && candidate.message.toLowerCase().includes("stream ended before command finished");
|
|
6978
|
+
return candidate.name === "StreamError" && candidate.message.toLowerCase().includes("stream ended before command finished") || isFetchSocketFailure(candidate);
|
|
6864
6979
|
});
|
|
6865
6980
|
}
|
|
6866
6981
|
/** Map Vercel Sandbox API and SDK errors to the shared sandbox error cases. */
|
|
@@ -7713,10 +7828,15 @@ async function runAfterToolExecuteHooks(args) {
|
|
|
7713
7828
|
}));
|
|
7714
7829
|
} catch (error) {
|
|
7715
7830
|
if (signal?.aborted) break;
|
|
7716
|
-
|
|
7831
|
+
const attributes = {
|
|
7717
7832
|
"app.plugin.name": pluginName,
|
|
7718
7833
|
"gen_ai.tool.name": args.tool.name
|
|
7834
|
+
};
|
|
7835
|
+
if (isToolInputError(error)) logWarn("agent.plugin.after_tool_execute.failed", {
|
|
7836
|
+
...attributes,
|
|
7837
|
+
"error.type": "tool_input_error"
|
|
7719
7838
|
});
|
|
7839
|
+
else logException(error, "agent.plugin.after_tool_execute.failed", attributes);
|
|
7720
7840
|
continue;
|
|
7721
7841
|
}
|
|
7722
7842
|
if (denial !== void 0) throw new PluginToolDeniedError(denial, { ran: true });
|
|
@@ -7780,18 +7900,10 @@ function createPluginState(plugin, adapter) {
|
|
|
7780
7900
|
}
|
|
7781
7901
|
};
|
|
7782
7902
|
}
|
|
7783
|
-
// src/chat/tools/execution/tool-input-error.ts
|
|
7784
|
-
/** Thrown when a tool fails due to invalid model/user input, not a system error. */
|
|
7785
|
-
var ToolInputError = class extends Error {
|
|
7786
|
-
constructor(message, options) {
|
|
7787
|
-
super(message, options);
|
|
7788
|
-
this.name = "ToolInputError";
|
|
7789
|
-
}
|
|
7790
|
-
};
|
|
7791
7903
|
// src/chat/dashboard-link.ts
|
|
7792
7904
|
let dashboardConversationLinkOptions;
|
|
7793
7905
|
function withHttps(host) {
|
|
7794
|
-
return
|
|
7906
|
+
return host.startsWith("https://") || host.startsWith("http://") ? host : `https://${host}`;
|
|
7795
7907
|
}
|
|
7796
7908
|
function stripTrailingSlashes(value) {
|
|
7797
7909
|
let end = value.length;
|
|
@@ -7827,18 +7939,29 @@ function resolveDashboardPath(segmentPath) {
|
|
|
7827
7939
|
function getDashboardConversationLink(conversationId) {
|
|
7828
7940
|
return resolveDashboardPath(`/conversations/${encodeURIComponent(conversationId)}`);
|
|
7829
7941
|
}
|
|
7942
|
+
/**
|
|
7943
|
+
* Return whether a URL is under the core dashboard base path. Other pages on
|
|
7944
|
+
* the same host are not Junior's.
|
|
7945
|
+
*/
|
|
7946
|
+
function isDashboardLink(url) {
|
|
7947
|
+
const root = resolveDashboardPath("/");
|
|
7948
|
+
if (!root) return false;
|
|
7949
|
+
const base = new URL(root);
|
|
7950
|
+
const prefix = base.pathname.endsWith("/") ? base.pathname : `${base.pathname}/`;
|
|
7951
|
+
return url.origin === base.origin && (url.pathname.startsWith(prefix) || `${url.pathname}/` === prefix);
|
|
7952
|
+
}
|
|
7830
7953
|
/** Build the dashboard settings URL when the core dashboard is enabled. */
|
|
7831
7954
|
function getDashboardSettingsLink() {
|
|
7832
7955
|
return resolveDashboardPath("/settings");
|
|
7833
7956
|
}
|
|
7834
|
-
|
|
7835
|
-
|
|
7836
|
-
const prefix = resolveDashboardPath("/conversations/");
|
|
7957
|
+
function parseDashboardPageLink(url, pagePrefix) {
|
|
7958
|
+
const prefix = resolveDashboardPath(pagePrefix);
|
|
7837
7959
|
if (!prefix || !URL.canParse(url)) return void 0;
|
|
7838
7960
|
const base = new URL(prefix);
|
|
7839
7961
|
const link = new URL(url);
|
|
7840
7962
|
if (link.origin !== base.origin || !link.pathname.startsWith(base.pathname)) return;
|
|
7841
|
-
const
|
|
7963
|
+
const path = link.pathname.slice(base.pathname.length);
|
|
7964
|
+
const segment = path.endsWith("/") ? path.slice(0, -1) : path;
|
|
7842
7965
|
if (!segment || segment.includes("/")) return void 0;
|
|
7843
7966
|
try {
|
|
7844
7967
|
return decodeURIComponent(segment);
|
|
@@ -7846,6 +7969,32 @@ function parseDashboardConversationLink(url) {
|
|
|
7846
7969
|
return;
|
|
7847
7970
|
}
|
|
7848
7971
|
}
|
|
7972
|
+
/** Return the Conversation id in a dashboard conversation URL, if it is one. */
|
|
7973
|
+
function parseDashboardConversationLink(url) {
|
|
7974
|
+
return parseDashboardPageLink(url, "/conversations/");
|
|
7975
|
+
}
|
|
7976
|
+
/** Build the dashboard URL of one person's page. */
|
|
7977
|
+
function getDashboardPersonLink(email) {
|
|
7978
|
+
return resolveDashboardPath(`/people/${encodeURIComponent(email)}`);
|
|
7979
|
+
}
|
|
7980
|
+
/** Return the email in a dashboard person URL, if it is one. */
|
|
7981
|
+
function parseDashboardPersonLink(url) {
|
|
7982
|
+
return parseDashboardPageLink(url, "/people/");
|
|
7983
|
+
}
|
|
7984
|
+
/**
|
|
7985
|
+
* Return the link filter for one dashboard page pattern, such as
|
|
7986
|
+
* `/conversations/*`, when the core dashboard is enabled.
|
|
7987
|
+
*/
|
|
7988
|
+
function getDashboardLinkFilter(pagePattern) {
|
|
7989
|
+
const link = resolveDashboardPath(pagePattern);
|
|
7990
|
+
if (!link) return void 0;
|
|
7991
|
+
const url = new URL(link);
|
|
7992
|
+
return objectLinkFilterSchema.parse({
|
|
7993
|
+
scheme: url.protocol.slice(0, -1),
|
|
7994
|
+
host: url.host,
|
|
7995
|
+
pathPattern: url.pathname
|
|
7996
|
+
});
|
|
7997
|
+
}
|
|
7849
7998
|
/** Build the dashboard task detail URL when the core dashboard is enabled. */
|
|
7850
7999
|
function getDashboardTaskLink(taskId) {
|
|
7851
8000
|
return resolveDashboardPath(`/automations/${encodeURIComponent(taskId)}`);
|
|
@@ -8584,6 +8733,7 @@ async function recordCodeChange(db, provider, input) {
|
|
|
8584
8733
|
) AS value
|
|
8585
8734
|
ORDER BY value
|
|
8586
8735
|
)` : juniorCodeChanges.conversationIds,
|
|
8736
|
+
...change.draft !== void 0 ? { draft: change.draft } : void 0,
|
|
8587
8737
|
mergedAt: change.mergedAt ?? null,
|
|
8588
8738
|
number: change.number,
|
|
8589
8739
|
openedAt: change.openedAt,
|
|
@@ -9432,11 +9582,11 @@ const PUSH_TIMEOUT_MS = 1e4;
|
|
|
9432
9582
|
function subjectFromBaseUrl() {
|
|
9433
9583
|
const baseUrl = process.env.JUNIOR_BASE_URL?.trim();
|
|
9434
9584
|
if (!baseUrl) return void 0;
|
|
9435
|
-
return
|
|
9585
|
+
return baseUrl.startsWith("https://") || baseUrl.startsWith("http://") ? baseUrl : `https://${baseUrl}`;
|
|
9436
9586
|
}
|
|
9437
9587
|
/** Web Push accepts only an `https:` or `mailto:` VAPID subject. */
|
|
9438
9588
|
function isVapidSubject(subject) {
|
|
9439
|
-
return
|
|
9589
|
+
return subject.startsWith("https://") || subject.startsWith("mailto:");
|
|
9440
9590
|
}
|
|
9441
9591
|
/**
|
|
9442
9592
|
* Read VAPID settings from the environment. Push notifications are off when
|
|
@@ -10048,6 +10198,7 @@ function getPluginTools(context, sandbox = createSandboxCapability(context.works
|
|
|
10048
10198
|
locationId: context.locationId,
|
|
10049
10199
|
...slackContext ? { slack: slackContext } : void 0,
|
|
10050
10200
|
userText: context.userText,
|
|
10201
|
+
decider: createPluginDecider(pluginName, { onCost }),
|
|
10051
10202
|
embedder: createPluginEmbedder(pluginName, { onCost }),
|
|
10052
10203
|
egress: context.egress,
|
|
10053
10204
|
...mcp ? { mcp } : void 0,
|
|
@@ -11766,6 +11917,23 @@ const TURN_CONTEXT_TAG = "runtime-turn-context";
|
|
|
11766
11917
|
/** Turn context section that only session context includes. */
|
|
11767
11918
|
const SESSION_CONTEXT_SECTION_TAG = "runtime";
|
|
11768
11919
|
/**
|
|
11920
|
+
* Turn context section with the tools a Code Mode script can call. A Turn
|
|
11921
|
+
* adds it only when it differs from the latest copy in history, and context
|
|
11922
|
+
* compaction keeps only that latest copy.
|
|
11923
|
+
*/
|
|
11924
|
+
const SCRIPT_TOOLS_SECTION_TAG = "script-tools";
|
|
11925
|
+
/**
|
|
11926
|
+
* Turn context sections that list what the model can use now. A Turn adds
|
|
11927
|
+
* one only when it differs from the latest copy in history, and context
|
|
11928
|
+
* compaction keeps only that latest copy.
|
|
11929
|
+
*/
|
|
11930
|
+
const CAPABILITY_SECTION_TAG = {
|
|
11931
|
+
availableSkills: "available-skills",
|
|
11932
|
+
activeMcpCatalogs: "active-mcp-catalogs",
|
|
11933
|
+
toolGuidance: "tool-guidance",
|
|
11934
|
+
workspaces: "workspaces"
|
|
11935
|
+
};
|
|
11936
|
+
/**
|
|
11769
11937
|
* Turn context sections that are true only for the Turn that received them.
|
|
11770
11938
|
* Context compaction removes them from the context of earlier Turns.
|
|
11771
11939
|
*/
|
|
@@ -11880,6 +12048,23 @@ function retainRuntimeTurnContext(messages) {
|
|
|
11880
12048
|
});
|
|
11881
12049
|
}
|
|
11882
12050
|
/**
|
|
12051
|
+
* Find the latest copy of one `<runtime-turn-context>` section in history,
|
|
12052
|
+
* such as `<script-tools>`, with its tags.
|
|
12053
|
+
*/
|
|
12054
|
+
function latestTurnContextSection(messages, tag) {
|
|
12055
|
+
const section = new RegExp(`\\n<${tag}>\\n[\\s\\S]*?\\n</${tag}>`, "g");
|
|
12056
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
12057
|
+
const texts = (userMessageContent(messages[index]) ?? []).flatMap((part) => {
|
|
12058
|
+
const text = textPartValue(part);
|
|
12059
|
+
return text?.startsWith(RUNTIME_TURN_CONTEXT_START) ? [text] : [];
|
|
12060
|
+
});
|
|
12061
|
+
for (const text of texts.reverse()) {
|
|
12062
|
+
const match = [...text.matchAll(section)].at(-1);
|
|
12063
|
+
if (match) return match[0].slice(1);
|
|
12064
|
+
}
|
|
12065
|
+
}
|
|
12066
|
+
}
|
|
12067
|
+
/**
|
|
11883
12068
|
* Reduce a runtime user-turn prompt to only the current turn's instruction.
|
|
11884
12069
|
*
|
|
11885
12070
|
* Live user prompts embed prior-thread context as `<thread-context
|
|
@@ -11978,6 +12163,17 @@ function readBlockedReport(messages) {
|
|
|
11978
12163
|
* their dispatcher name.
|
|
11979
12164
|
*/
|
|
11980
12165
|
const CODEMODE_TOOL_NAME = "codemode";
|
|
12166
|
+
/**
|
|
12167
|
+
* How the `codemode` result text names each call status. The eval harness
|
|
12168
|
+
* reads script calls back from this text.
|
|
12169
|
+
*/
|
|
12170
|
+
const CODE_MODE_CALL_STATUS_TEXT = {
|
|
12171
|
+
ok: "ok",
|
|
12172
|
+
error: "failed",
|
|
12173
|
+
rejected: "rejected by action review",
|
|
12174
|
+
interrupted: "interrupted, outcome unknown",
|
|
12175
|
+
not_started: "not started"
|
|
12176
|
+
};
|
|
11981
12177
|
// src/chat/no-reply.ts
|
|
11982
12178
|
/** No-reply result of a Turn. */
|
|
11983
12179
|
/** Model-facing tool that ends a Turn with no reply. */
|
|
@@ -12201,6 +12397,48 @@ function buildTurnLimitResponse(eventId) {
|
|
|
12201
12397
|
function buildTurnErrorResponse(error, eventId) {
|
|
12202
12398
|
return isTurnExecutionLimitExceededError(error) ? buildTurnLimitResponse(eventId) : buildTurnFailureResponse(eventId);
|
|
12203
12399
|
}
|
|
12400
|
+
// src/chat/task-execution/message-sender.ts
|
|
12401
|
+
/**
|
|
12402
|
+
* The Conversation and Turn that sent one inbound message, such as a child's
|
|
12403
|
+
* reply to its parent. The sender writes it at `input.metadata.sender`, so
|
|
12404
|
+
* readers never take meaning from the message id. `agentInvocationId` names
|
|
12405
|
+
* the Agent invocation that the message comes from, when there is one.
|
|
12406
|
+
*/
|
|
12407
|
+
const inboundMessageSenderSchema = z.object({
|
|
12408
|
+
agentInvocationId: z.string().min(1).optional(),
|
|
12409
|
+
conversationId: z.string().min(1),
|
|
12410
|
+
turnId: z.string().min(1)
|
|
12411
|
+
}).strict();
|
|
12412
|
+
/** Read the sender fields that one inbound message stores, if any. */
|
|
12413
|
+
function readInboundMessageSender(message) {
|
|
12414
|
+
const parsed = inboundMessageSenderSchema.safeParse(message.input.metadata?.sender);
|
|
12415
|
+
return parsed.success ? parsed.data : void 0;
|
|
12416
|
+
}
|
|
12417
|
+
/**
|
|
12418
|
+
* Keep the sender fields of `messages` next to their ids, so a reader still
|
|
12419
|
+
* has them after the mailbox drops the message itself.
|
|
12420
|
+
*/
|
|
12421
|
+
function withMessageSenders(senders, messages) {
|
|
12422
|
+
let next = senders;
|
|
12423
|
+
for (const message of messages) {
|
|
12424
|
+
const sender = readInboundMessageSender(message);
|
|
12425
|
+
if (sender && !next?.[message.inboundMessageId]) next = {
|
|
12426
|
+
...next,
|
|
12427
|
+
[message.inboundMessageId]: sender
|
|
12428
|
+
};
|
|
12429
|
+
}
|
|
12430
|
+
return next;
|
|
12431
|
+
}
|
|
12432
|
+
/** Decode stored sender fields. Invalid entries are dropped. */
|
|
12433
|
+
function normalizeMessageSenders(value) {
|
|
12434
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return;
|
|
12435
|
+
const senders = {};
|
|
12436
|
+
for (const [id, raw] of Object.entries(value)) {
|
|
12437
|
+
const parsed = inboundMessageSenderSchema.safeParse(raw);
|
|
12438
|
+
if (parsed.success) senders[id] = parsed.data;
|
|
12439
|
+
}
|
|
12440
|
+
return Object.keys(senders).length ? senders : void 0;
|
|
12441
|
+
}
|
|
12204
12442
|
// src/chat/task-execution/state.ts
|
|
12205
12443
|
/**
|
|
12206
12444
|
* Expiring conversation mailbox and execution index store.
|
|
@@ -12287,6 +12525,9 @@ function conversationKey(conversationId) {
|
|
|
12287
12525
|
function conversationStopKey(conversationId) {
|
|
12288
12526
|
return `${CONVERSATION_PREFIX}:stop:${conversationId}`;
|
|
12289
12527
|
}
|
|
12528
|
+
function deferredMoveKey(conversationId) {
|
|
12529
|
+
return `${CONVERSATION_PREFIX}:deferred-move:${conversationId}`;
|
|
12530
|
+
}
|
|
12290
12531
|
function indexLockKey(indexKey) {
|
|
12291
12532
|
return `${indexKey}:lock`;
|
|
12292
12533
|
}
|
|
@@ -12397,9 +12638,12 @@ function normalizeExecution(conversationId, value) {
|
|
|
12397
12638
|
}
|
|
12398
12639
|
pendingMessages.sort(compareMessages);
|
|
12399
12640
|
}
|
|
12641
|
+
const inboundMessageIds = Array.isArray(value.inboundMessageIds) ? uniqueStrings(value.inboundMessageIds.map((id) => typeof id === "string" ? id : void 0).filter((id) => Boolean(id))) : [];
|
|
12642
|
+
const messageSenders = withMessageSenders(normalizeMessageSenders(value.messageSenders), pendingMessages);
|
|
12400
12643
|
return {
|
|
12401
12644
|
status,
|
|
12402
|
-
inboundMessageIds: uniqueStrings([...
|
|
12645
|
+
inboundMessageIds: uniqueStrings([...inboundMessageIds, ...pendingMessages.map((message) => message.inboundMessageId)]),
|
|
12646
|
+
...messageSenders ? { messageSenders } : void 0,
|
|
12403
12647
|
pendingCount: pendingMessages.length,
|
|
12404
12648
|
pendingMessages,
|
|
12405
12649
|
lease: normalizeLease(value.lease),
|
|
@@ -12482,9 +12726,11 @@ function assertLegalExecution(conversationId, execution) {
|
|
|
12482
12726
|
}
|
|
12483
12727
|
function executionWithPendingMessages(execution, pending) {
|
|
12484
12728
|
const pendingMessages = [...pending].sort(compareMessages);
|
|
12729
|
+
const messageSenders = withMessageSenders(execution.messageSenders, pendingMessages);
|
|
12485
12730
|
return {
|
|
12486
12731
|
...execution,
|
|
12487
12732
|
inboundMessageIds: uniqueStrings([...execution.inboundMessageIds, ...pendingMessages.map((message) => message.inboundMessageId)]),
|
|
12733
|
+
...messageSenders ? { messageSenders } : void 0,
|
|
12488
12734
|
pendingMessages,
|
|
12489
12735
|
pendingCount: pendingMessages.length
|
|
12490
12736
|
};
|
|
@@ -12711,7 +12957,9 @@ async function withConversationMutation(args, callback) {
|
|
|
12711
12957
|
}
|
|
12712
12958
|
}
|
|
12713
12959
|
async function readConversation(state, conversationId) {
|
|
12714
|
-
|
|
12960
|
+
return conversationFromValue(conversationId, await state.get(conversationKey(conversationId)));
|
|
12961
|
+
}
|
|
12962
|
+
function conversationFromValue(conversationId, raw) {
|
|
12715
12963
|
if (raw == null) return;
|
|
12716
12964
|
const conversation = normalizeConversation(conversationId, raw);
|
|
12717
12965
|
if (!conversation) throw new InvalidConversationRecordError(conversationId);
|
|
@@ -12792,6 +13040,20 @@ async function getConversationWorkState(args) {
|
|
|
12792
13040
|
const conversation = await getConversation(args);
|
|
12793
13041
|
return conversation ? conversationWorkState(conversation) : void 0;
|
|
12794
13042
|
}
|
|
13043
|
+
/**
|
|
13044
|
+
* Return the persisted work records of several Conversations in one state
|
|
13045
|
+
* read. A Conversation with no record has no entry.
|
|
13046
|
+
*/
|
|
13047
|
+
async function getConversationWorkStates(conversationIds) {
|
|
13048
|
+
const state = await getConnectedState();
|
|
13049
|
+
const values = await getStateValues(state, conversationIds.map(conversationKey));
|
|
13050
|
+
const workStates = /* @__PURE__ */ new Map();
|
|
13051
|
+
for (const [index, conversationId] of conversationIds.entries()) {
|
|
13052
|
+
const conversation = conversationFromValue(conversationId, values[index]);
|
|
13053
|
+
if (conversation) workStates.set(conversationId, conversationWorkState(conversation));
|
|
13054
|
+
}
|
|
13055
|
+
return workStates;
|
|
13056
|
+
}
|
|
12795
13057
|
/** Count mailbox messages that have not yet reached the conversation event log. */
|
|
12796
13058
|
function countPendingConversationMessages(conversation) {
|
|
12797
13059
|
return pendingMessages(conversation).length;
|
|
@@ -12835,11 +13097,12 @@ async function appendInboundMessageWithAdmission(args) {
|
|
|
12835
13097
|
return { status: "duplicate" };
|
|
12836
13098
|
}
|
|
12837
13099
|
if (args.exclusive && hasRunnableWork(current)) return { status: "active" };
|
|
12838
|
-
const text = args.renderText ? await args.renderText(current.execution.inboundMessageIds) : args.message.input.text;
|
|
13100
|
+
const text = args.renderText ? await args.renderText(current.execution.inboundMessageIds, current.execution.messageSenders ?? {}) : args.message.input.text;
|
|
12839
13101
|
if (text === void 0) {
|
|
12840
13102
|
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
12841
13103
|
...current.execution,
|
|
12842
|
-
inboundMessageIds: [...current.execution.inboundMessageIds, args.message.inboundMessageId]
|
|
13104
|
+
inboundMessageIds: [...current.execution.inboundMessageIds, args.message.inboundMessageId],
|
|
13105
|
+
messageSenders: withMessageSenders(current.execution.messageSenders, [args.message])
|
|
12843
13106
|
}, nowMs));
|
|
12844
13107
|
return { status: "duplicate" };
|
|
12845
13108
|
}
|
|
@@ -12982,7 +13245,7 @@ async function requestConversationWork(args) {
|
|
|
12982
13245
|
async function moveIdleConversationDestination(args) {
|
|
12983
13246
|
return await withConversationMutation(args, async (state, lock) => {
|
|
12984
13247
|
const existing = await readConversation(state, args.conversationId);
|
|
12985
|
-
if (existing && (existing
|
|
13248
|
+
if (existing && isHeldByRun(existing)) return "busy";
|
|
12986
13249
|
if (!await args.move()) return "not_moved";
|
|
12987
13250
|
if (existing) await writeConversation(state, lock, {
|
|
12988
13251
|
...existing,
|
|
@@ -12998,6 +13261,50 @@ async function moveIdleConversationDestination(args) {
|
|
|
12998
13261
|
return "moved";
|
|
12999
13262
|
});
|
|
13000
13263
|
}
|
|
13264
|
+
function isHeldByRun(conversation) {
|
|
13265
|
+
return conversation.execution.lease !== void 0 || conversation.execution.status === "running" || conversation.execution.status === "paused";
|
|
13266
|
+
}
|
|
13267
|
+
/**
|
|
13268
|
+
* Store one Destination move until the Run that holds the Conversation ends.
|
|
13269
|
+
*
|
|
13270
|
+
* The first stored move wins: a later call gets it back. With no Run, this
|
|
13271
|
+
* stores nothing and returns `idle`, so the caller moves now.
|
|
13272
|
+
*/
|
|
13273
|
+
async function deferConversationMove(args) {
|
|
13274
|
+
return await withConversationMutation(args, async (state, lock) => {
|
|
13275
|
+
const existing = await readConversation(state, args.conversationId);
|
|
13276
|
+
if (!existing || !isHeldByRun(existing)) return { status: "idle" };
|
|
13277
|
+
const key = deferredMoveKey(args.conversationId);
|
|
13278
|
+
const stored = await state.get(key);
|
|
13279
|
+
if (stored !== null) return {
|
|
13280
|
+
move: stored,
|
|
13281
|
+
status: "deferred"
|
|
13282
|
+
};
|
|
13283
|
+
await fenceConversationMutation(state, lock, args.conversationId);
|
|
13284
|
+
await state.set(key, args.move, JUNIOR_THREAD_STATE_TTL_MS);
|
|
13285
|
+
return {
|
|
13286
|
+
move: args.move,
|
|
13287
|
+
status: "deferred"
|
|
13288
|
+
};
|
|
13289
|
+
});
|
|
13290
|
+
}
|
|
13291
|
+
/**
|
|
13292
|
+
* Remove and return the deferred move once no Run holds the Conversation.
|
|
13293
|
+
* The caller runs it, and defers it again when a new Run started first.
|
|
13294
|
+
*/
|
|
13295
|
+
async function takeDeferredConversationMove(args) {
|
|
13296
|
+
const key = deferredMoveKey(args.conversationId);
|
|
13297
|
+
if (await (await getConnectedState(args.state)).get(key) === null) return;
|
|
13298
|
+
return await withConversationMutation(args, async (state, lock) => {
|
|
13299
|
+
const existing = await readConversation(state, args.conversationId);
|
|
13300
|
+
if (existing && isHeldByRun(existing)) return void 0;
|
|
13301
|
+
const stored = await state.get(key);
|
|
13302
|
+
if (stored === null) return void 0;
|
|
13303
|
+
await fenceConversationMutation(state, lock, args.conversationId);
|
|
13304
|
+
await state.delete(key);
|
|
13305
|
+
return stored;
|
|
13306
|
+
});
|
|
13307
|
+
}
|
|
13001
13308
|
/** Record that a wake-up nudge was accepted for the conversation. */
|
|
13002
13309
|
async function markConversationWorkEnqueued(args) {
|
|
13003
13310
|
const nowMs = args.nowMs ?? now();
|
|
@@ -13323,6 +13630,7 @@ async function recordConversationRetry(args) {
|
|
|
13323
13630
|
if (!current || current.execution.lease?.token !== args.leaseToken) return "lost_lease";
|
|
13324
13631
|
const count = (current.execution.retryCount ?? 0) + 1;
|
|
13325
13632
|
const stopped = count >= 5;
|
|
13633
|
+
if (stopped) await args.beforeWorkStops?.(args.conversationId, current.execution.inboundMessageIds);
|
|
13326
13634
|
await writeConversation(state, lock, withExecutionUpdate(current, {
|
|
13327
13635
|
...current.execution,
|
|
13328
13636
|
lastEnqueuedAtMs: void 0,
|
|
@@ -13546,9 +13854,11 @@ function isFinishedTurnState(state) {
|
|
|
13546
13854
|
}
|
|
13547
13855
|
/** A running or paused write reached a Turn that already finished. */
|
|
13548
13856
|
var TurnAlreadyFinishedError = class extends Error {
|
|
13857
|
+
state;
|
|
13549
13858
|
constructor(turnId, state) {
|
|
13550
13859
|
super(`Turn ${turnId} already finished as ${state}`);
|
|
13551
13860
|
this.name = "TurnAlreadyFinishedError";
|
|
13861
|
+
this.state = state;
|
|
13552
13862
|
}
|
|
13553
13863
|
};
|
|
13554
13864
|
const turnStatusSchema = z.enum([
|
|
@@ -13745,6 +14055,15 @@ async function getStoredTurnRecord(conversationId, turnId) {
|
|
|
13745
14055
|
const value = await stateAdapter.get(turnCursorKey(conversationId, turnId));
|
|
13746
14056
|
return value == null ? void 0 : parseTurnRecord(value);
|
|
13747
14057
|
}
|
|
14058
|
+
/**
|
|
14059
|
+
* Read several stored Turn cursors in one state read, without their Turn
|
|
14060
|
+
* history. A missing cursor gives `undefined`.
|
|
14061
|
+
*/
|
|
14062
|
+
async function getStoredTurnFields(turns) {
|
|
14063
|
+
const stateAdapter = getStateAdapter();
|
|
14064
|
+
await stateAdapter.connect();
|
|
14065
|
+
return (await getStateValues(stateAdapter, turns.map((turn) => turnCursorKey(turn.conversationId, turn.turnId)))).map((value) => value == null ? void 0 : parseTurnRecord(value));
|
|
14066
|
+
}
|
|
13748
14067
|
/** Read a materialized turn cursor for resume and history loading. */
|
|
13749
14068
|
async function materializeStoredTurnRecord(conversationId, turnId, followCurrentReplacement) {
|
|
13750
14069
|
const parsed = await getStoredTurnRecord(conversationId, turnId);
|
|
@@ -13850,6 +14169,19 @@ async function setStoredRecord(args) {
|
|
|
13850
14169
|
* version it loaded, preventing stale resume callbacks from winning.
|
|
13851
14170
|
*/
|
|
13852
14171
|
async function updateTurnState(args) {
|
|
14172
|
+
return await withSpan("turn.state.finish", "turn.state.finish", {}, async (setSpanAttributes) => {
|
|
14173
|
+
const updated = await writeTurnState(args);
|
|
14174
|
+
setSpanAttributes({ "app.turn.state.written": updated !== void 0 });
|
|
14175
|
+
return updated;
|
|
14176
|
+
}, {
|
|
14177
|
+
"app.turn.state": args.state,
|
|
14178
|
+
"app.turn.previous_state": args.existing.state,
|
|
14179
|
+
"app.turn.resume_reason": args.existing.resumeReason,
|
|
14180
|
+
"app.turn.slice_id": args.existing.sliceId,
|
|
14181
|
+
"app.turn.error_message": args.errorMessage
|
|
14182
|
+
});
|
|
14183
|
+
}
|
|
14184
|
+
async function writeTurnState(args) {
|
|
13853
14185
|
const parsed = await getStoredTurnRecord(args.existing.conversationId, args.existing.turnId);
|
|
13854
14186
|
if (!parsed || parsed.version !== args.existing.version) return;
|
|
13855
14187
|
return await setStoredRecord({
|
|
@@ -14140,9 +14472,9 @@ async function loadTurnCheckpoint(args) {
|
|
|
14140
14472
|
}
|
|
14141
14473
|
async function saveTurnCheckpoint(args) {
|
|
14142
14474
|
const traceContext = getActiveTraceContext();
|
|
14143
|
-
return await withSpan("turn.checkpoint.save", "turn.checkpoint.save", {}, async () => {
|
|
14144
|
-
if (args.mode === "running") return await saveRunning(args, traceContext);
|
|
14145
|
-
if (args.mode === "paused") return await savePaused(args, traceContext);
|
|
14475
|
+
return await withSpan("turn.checkpoint.save", "turn.checkpoint.save", {}, async (setSpanAttributes) => {
|
|
14476
|
+
if (args.mode === "running") return await saveRunning(args, traceContext, setSpanAttributes);
|
|
14477
|
+
if (args.mode === "paused") return await savePaused(args, traceContext, setSpanAttributes);
|
|
14146
14478
|
await saveDone(args, traceContext);
|
|
14147
14479
|
}, { "app.turn.checkpoint.mode": args.mode });
|
|
14148
14480
|
}
|
|
@@ -14167,7 +14499,7 @@ function sharedWrite(args, traceContext, latest) {
|
|
|
14167
14499
|
})
|
|
14168
14500
|
};
|
|
14169
14501
|
}
|
|
14170
|
-
async function saveRunning(args, traceContext) {
|
|
14502
|
+
async function saveRunning(args, traceContext, setSpanAttributes) {
|
|
14171
14503
|
if (args.messages.length === 0 || !isContinuablePiBoundary(args.messages)) return;
|
|
14172
14504
|
try {
|
|
14173
14505
|
const latest = await getTurnRecord(args.conversationId, args.turnId);
|
|
@@ -14185,7 +14517,12 @@ async function saveRunning(args, traceContext) {
|
|
|
14185
14517
|
state: "running"
|
|
14186
14518
|
});
|
|
14187
14519
|
} catch (error) {
|
|
14188
|
-
if (
|
|
14520
|
+
if (error instanceof TurnAlreadyFinishedError) setSpanAttributes({
|
|
14521
|
+
"app.turn.checkpoint.rejected": error.name,
|
|
14522
|
+
"app.turn.previous_state": error.state
|
|
14523
|
+
});
|
|
14524
|
+
else if (error instanceof AgentHistoryBranchError) setSpanAttributes({ "app.turn.checkpoint.rejected": error.name });
|
|
14525
|
+
else logException(error, "agent.turn.checkpoint.running.failed", {
|
|
14189
14526
|
"app.ai.resume_conversation_id": args.conversationId,
|
|
14190
14527
|
"app.ai.resume_session_id": args.turnId,
|
|
14191
14528
|
"app.ai.resume_slice_id": args.sliceId
|
|
@@ -14193,7 +14530,7 @@ async function saveRunning(args, traceContext) {
|
|
|
14193
14530
|
return;
|
|
14194
14531
|
}
|
|
14195
14532
|
}
|
|
14196
|
-
async function savePaused(args, traceContext) {
|
|
14533
|
+
async function savePaused(args, traceContext, setSpanAttributes) {
|
|
14197
14534
|
const keepSlice = args.reason === "yield";
|
|
14198
14535
|
const nextSliceId = keepSlice ? args.sliceId : args.sliceId + 1;
|
|
14199
14536
|
try {
|
|
@@ -14231,7 +14568,13 @@ async function savePaused(args, traceContext) {
|
|
|
14231
14568
|
});
|
|
14232
14569
|
} catch (error) {
|
|
14233
14570
|
if (error instanceof TurnSliceLimitExceededError) throw error;
|
|
14234
|
-
if (error instanceof TurnAlreadyFinishedError)
|
|
14571
|
+
if (error instanceof TurnAlreadyFinishedError) {
|
|
14572
|
+
setSpanAttributes({
|
|
14573
|
+
"app.turn.checkpoint.rejected": error.name,
|
|
14574
|
+
"app.turn.previous_state": error.state
|
|
14575
|
+
});
|
|
14576
|
+
return;
|
|
14577
|
+
}
|
|
14235
14578
|
logException(error, "agent.turn.checkpoint.paused.failed", {
|
|
14236
14579
|
"app.ai.resume_conversation_id": args.conversationId,
|
|
14237
14580
|
"app.ai.resume_session_id": args.turnId,
|
|
@@ -15649,4 +15992,4 @@ async function recordGuardianActionReviewed(args) {
|
|
|
15649
15992
|
createdAtMs: Date.now()
|
|
15650
15993
|
}]);
|
|
15651
15994
|
}
|
|
15652
|
-
export { loadTurnCheckpoint as $, createPluginModel as $a, escapeSlackMrkdwnText as $i, getPluginSystemPromptContributions as $n, configValueSchema as $o, RESOURCE_WATCH_TOOL_SOURCE as $r, REPLY_TOOL_NAME as $t, latestConversationMessageSeq as A, isAbortError as Aa, deleteWorkspace as Ai, trimTrailingAssistantMessages as An, readConversationMessageEventSeq as Ao, updateReviewItemContent as Ar, isFinalAttempt as At, getAgentContextInputLimitTokens as B, consumeSandboxEgressPermissionDeniedSignal as Ba, setWorkspaceSnapshotBuild as Bi, tagJson as Bn, resolveRootVisibility as Bo, reviewItemNeedsSomeone as Br, requestAnotherSlice as Bt, settleConversationTitleWork as C, isConversationScopedChannel as Ca, getDashboardTaskLink as Ci, isContinuablePiBoundary as Cn, createPluginConversationEvents as Co, getReviewItem as Cr, deadLetterAttempt as Ct, estimateConversationMessagesTokens as D, withSlackRetries as Da, createPluginState as Di, normalizeToolNameFromResult as Dn, readConversationEventPageAfter as Do, reviewItemsNeedingUserVersionQuery as Dr, getConversationWorkState as Dt, buildConversationContext as E, runWithSlackInstallationToken as Ea, ToolInputError as Ei, isToolResultMessage as En, readConversationEventPage as Eo, listWaitingConversations as Er, getConversation as Et, turnHasReply as F, getWorkspaceSnapshotNotReadyError as Fa, updateWorkspace as Fi, escapeTagText as Fn, getSlackFileId as Fo, canUserReadReviewItem as Fr, pruneActiveConversation as Ft, AuthPausePersistenceError as G, resolveSandboxCommandEnvironment as Ga, getSandboxProvider as Gi, getOAuthAccountProviders as Gn, defaultTimezone as Go, automationCreatorUserId as Gr, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as Gt, PluginCredentialFailureError as H, parseSandboxEgressCredentialToken as Ha, hash as Hi, createUserTokenStore as Hn, createPluginAnnotations as Ho, reviewItemReaderForUserInConversation as Hr, startConversationWork as Ht, upsertConversationMessage as I, isWorkspaceSnapshotNotReadyError as Ia, WorkspaceValidationError as Ii, readParentAgentTask as In, matchSlackAttachments as Io, isOnlyAssignee as Ir, recordAttemptFailure as It, abandonReplacedPendingAuth as J, sleep$2 as Ja, deliverOAuthAuthorization as Ji, createPluginEventPublisher as Jn, lookupSlackUserNames as Jo, createCodeChangePublisher as Jr, TurnSliceLimitExceededError as Jt, AuthorizationFlowDisabledError as K, normalizeSandboxEgressTracePropagationDomains as Ka, isVercelSandboxEgressRequest as Ki, resolvePluginOAuthAccount as Kn, resolveUserTimezone as Ko, resolveAssignee as Kr, TURN_LIMIT_WRAP_UP_MESSAGE as Kt, calculateContextCompactionTargetTokens as L, workspaceSnapshotNotReadyUserMessage as La, invalidateReadySnapshot as Li, renderChildTag as Ln, readAttachmentVisionSummary as Lo, readReviewItemAgentScope as Lr, recordConversationRetry as Lt, normalizeConversationText as M, throwSandboxOperationError as Ma, getWorkspaceByName as Mi, SESSION_CONTEXT_SECTION_TAG as Mn, FORK_INSTRUCTIONS as Mo, canActOnReviewItem as Mr, listActiveConversationIds as Mt, recordDeliveredAssistantMessage as N, wrapSandboxSetupError as Na, listWorkspaces as Ni, TURN_CONTEXT_TAG as Nn, loadForkHistory as No, canAgentChangeReviewItem as Nr, markConversationWorkEnqueued as Nt, getConversationMessageSlackTs as O, getWorkspaceTeamId as Oa, renderToolResultNudge as Oi, retainRuntimeTurnContext as On, readConversationEventPageAround as Oo, searchReviewItems as Or, hasConversationStop as Ot, trimConversationMessages as P, WorkspaceSnapshotNotReadyError as Pa, listWorkspacesByRepository as Pi, escapeClosingTags as Pn, notInheritedByForkChild as Po, canReadReviewItem as Pr, moveIdleConversationDestination as Pt, continuableMessages as Q, createPluginEmbedder as Qa, startOAuthFlow as Qi, getPluginSlackConversationLink as Qn, createDurableLocationConfigurationService as Qo, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as Qr, isTurnExecutionLimitExceededError as Qt, getAgentBackgroundCompactionMarkTokens as R, clearSandboxEgressSignals as Ra, loadSnapshotsForProfile as Ri, renderTag as Rn, recordSlackAttachment as Ro, requireReviewItemAssignees as Rr, releaseConversationWork as Rt, resolveConversationTitle as S, getSlackClient as Sa, getDashboardSettingsLink as Si, isAssistantMessage as Sn, viewerMarksFromParticipant as So, getOpenReviewItemByDedupeKey as Sr, countPendingConversationMessages as St, resolveTaskTitle as T, normalizeSlackConversationId as Ta, setDashboardConversationLinkOptions as Ti, isToolResultError as Tn, readLatestConversationBrief as To, listReplyActionItems as Tr, dropPendingMessages as Tt, createPluginAuthOrchestration as U, sandboxEgressSignalsResponseSchema as Ua, isStale as Ui, findLegacyWebActorUserId as Un, listConversationAnnotations as Uo, EVERYONE_ASSIGNEE as Ur, steerWebPendingMessages as Ut, createPluginEgress as V, createSandboxEgressCredentialToken as Va, create as Vi, SANDBOX_EGRESS_AUTH_REQUIRED_MARKER as Vn, saveObjectAnnotations as Vo, reviewItemReaderForUser as Vr, requestConversationWork as Vt, authorizationId as W, buildSandboxEgressNetworkPolicy as Wa, ensureDockerDaemon as Wi, webActorUserIds as Wn, listConversationAnnotationsById as Wo, activeParticipantUserIds as Wr, stopConversationWork as Wt, clearPendingAuth as X, workspaceRepoCheckoutPath as Xa, parseOAuthStatePayload as Xi, getPluginApiRoutes as Xn, credentialAuditSource as Xo, getSlackToolContext as Xr, buildTurnErrorResponse as Xt, canReusePendingAuthLink as Y, tryWorkspaceRepoCheckoutPath as Ya, formatProviderLabel as Yi, createPluginHookRunner as Yn, credentialAuditAttributes as Yo, resolveChannelCapabilities as Yr, TurnToolCallLimitExceededError as Yt, getConversationPendingAuth as Z, PluginToolDeniedError as Za, resolveBaseUrl as Zi, getPluginRoutes as Zn, createPluginCache as Zo, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as Zr, createTurnLimitGate as Zt, appendConversationMessages as _, slackExternalRefIdSchema as _a, verifyTimerWatchCredentialSubject as _i, getTerminalAssistantMessages as _n, conversationHasParticipantUser as _o, projectConversationMessages as _r, claimInboundMessage as _t, loadProjection as a, addReactionToMessage as aa, createWatch as ai, getAssistantReplyText as an, sandboxSkillDir as ao, coreTaskRegistrations as ar, failTurnRecord as at, persistConversationMessages as b, getFilePermalink as ba, getDashboardObjectIconLink as bi, hasTurnInput as bn, conversationPinnedForUser as bo, countReviewItemsNeedingUser as br, completeConversationStop as bt, recordAgentsInstructionsUpdated as c, openSlackDirectMessage as ca, getWatch as ci, findLegacyNoReplyMarker as cn, buildCommandScript as co, readWebPushConfig as cr, recordTurnSummary as ct, recordAuthorizationCompleted as d, postSlackMessage as da, bindEventAutomationCredentialSubject as di, CODEMODE_TOOL_NAME as dn, createPluginModelCostRecorder as do, deletePushSubscription as dr, ackMessages as dt, formatSlackLink as ea, STOP_WATCHING_TOOL_NAME as ei, isAnswerToolName as en, SANDBOX_COMMAND_PATH as eo, getPluginTools as er, historyItemFromPiMessage as es, lostWorkerBeforeFirstSave as et, recordAuthorizationRequested as f, removeReactionFromMessage as fa, bindScheduledAutomationCredentialSubject as fi, REPORT_BLOCKED_TOOL_NAME as fn, createPluginLogger as fo, listPushSubscriptions as fr, appendExclusiveInboundMessage as ft, recordToolExecutionStarted as g, slackEntitySchema as ga, verifySlackDirectCredentialSubject as gi, getPiMessageRole as gn, readConversationAccessFromSql as go, isPausedBySlack as gr, checkInConversationWork as gt, recordSubscribedReplyRoute as h, uploadFilesToConversation as ha, verifyScheduledAutomationCredentialSubject as hi, extractAssistantText as hn, createConversationAccessReader as ho, savePushSubscription as hr, cancelHumanFacingPendingMessages as ht, loadConversationProjection as i, truncateStatusText as ia, createTimerWatch as ii, decideReply as in, SANDBOX_WORKSPACE_ROOT as io, validatePlugins as ir, setConfigDefaults as is, completeTurnRecord as it, markConversationMessage as j, isAlreadyExistsError as ja, getWorkspace as ji, REQUEST_CONTEXT_SECTION_TAG as jn, buildSentryConversationUrl as jo, PLUGIN_REVIEW_ITEM_KEY_PREFIX as jr, isInvalidConversationRecordError as jt, isHumanConversationMessage as k, runWithWorkspaceTeamId as ka, createWorkspace as ki, stripRuntimeTurnContext as kn, readConversationLastEventSeq as ko, takeReviewItem as kr, hasRunnableConversationWork as kt, recordAttachmentsDelivered as l, openSlackModal as la, listWatches as li, isLegacyNoReplyMarker as ln, buildNonInteractiveShellScript as lo, sendPushNotificationToUser as lr, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as lt, recordMcpProviderConnected as m, updateSlackMessage as ma, verifyEventAutomationCredentialSubject as mi, persistWithRetry as mn, canAddConversationMessages as mo, saveNotificationSchedule as mr, beginConversationResume as mt, commitMessages as n, normalizeSlackStatusText as na, cancelWatch as ni, remindMissingAnswer as nn, SANDBOX_REPOS_ROOT as no, getPlugins as nr, projectConversationEvents$1 as ns, saveTurnCheckpoint as nt, loadTurnProjection as o, deleteSlackMessage as oa, deliverWatch as oi, sanitizeAssistantText as on, sandboxSkillFile as oo, registration_exports as or, getTurnRecord as ot, recordGuardianActionReviewed as p, unfurlSlackLinks as pa, bindSlackDirectCredentialSubject as pi, readBlockedReport as pn, canAccessConversation as po, readNotificationSchedule as pr, appendInboundMessage as pt, AuthorizationPauseError as q, SANDBOX_RUNTIME as qa, proxyVercelSandboxEgressRequest as qi, agent_hooks_exports as qn, lookupSlackUser as qo, resolveAssignees as qr, TurnBudgetExceededError as qt, loadConnectedMcpProviders as r, slackMention as ra, collectEventMatchKeys as ri, replyTextSchema as rn, SANDBOX_SKILLS_ROOT as ro, setPlugins as rr, getConfigDefaults as rs, abandonTurnRecord as rt, openConversationProjection as s, getSlackMessagePermalink as sa, findMatchingWatches as si, NO_REPLY_TOOL_NAME as sn, sandboxSkillPathResolution as so, setBriefsConfig as sr, listTurnSummaries as st, commitAcceptedReply as t, normalizeSlackReplyMarkdown as ta, cancelSubscriptions as ti, readTurnAnswer as tn, SANDBOX_DATA_ROOT as to, getPluginUserPromptContributions as tr, piMessageFromHistoryItem as ts, pauseLostWorkerTurn as tt, recordAuthenticationLinked as u, postSlackEphemeralMessage as ua, takeDueTimerWatches as ui, readNoReply as un, runNonInteractiveCommand as uo, resolveNotificationTimezone as ur, CONVERSATION_WORK_STALE_ENQUEUE_MS as ut, hydrateConversationMessages as v, SlackActionError as va, JUNIOR_THREAD_STATE_TTL_MS as vi, getUserMessageInstructionText as vn, conversationIsMemberRoot as vo, REVIEW_ITEM_REPLIED_REASON as vr, clearConsumedConversationWake as vt, fallbackShortTitle as w, isDmChannel as wa, parseDashboardConversationLink as wi, isStandaloneRuntimeContextMessage as wn, readConversationBriefThrough as wo, insertReviewItem as wr, drainConversationMailbox as wt, toStoredConversationMessage as x, getHeaderString as xa, getDashboardReviewItemLink as xi, instructionTextForProjection as xn, conversationViewerMarks as xo, dismissOpenReviewItems as xr, completeConversationWork as xt, persistConversationMessageWindow as y, downloadPrivateSlackFile as ya, getDashboardConversationLink as yi, hasRuntimeTurnContext as yn, conversationIsNotUnsubscribedRoot as yo, closeReviewItem as yr, clearExpiredConversationLease as yt, getAgentContextCompactionTriggerTokens as z, consumeSandboxEgressAuthRequiredSignal as za, setWorkspaceSnapshot as zi, renderUntrustedTag as zn, slackAttachmentsVersionQuery as zo, requireReviewItemLinks as zr, releaseInboundMessage as zt };
|
|
15995
|
+
export { loadTurnCheckpoint as $, isToolInputError as $a, create as $i, webActorUserIds as $n, runWithSlackInstallationToken as $o, activeParticipantUserIds as $r, TurnSliceLimitExceededError as $t, latestConversationMessageSeq as A, slackEntitySchema as Aa, getDashboardObjectIconLink as Ai, isStandaloneRuntimeContextMessage as An, readConversationEventPageAfter as Ao, dismissOpenReviewItems as Ar, getConversationWorkStates as At, getAgentContextInputLimitTokens as B, clearSandboxEgressSignals as Ba, renderToolResultNudge as Bi, SCRIPT_TOOLS_SECTION_TAG as Bn, readAttachmentVisionSummary as Bo, PLUGIN_REVIEW_ITEM_KEY_PREFIX as Br, recordConversationRetry as Bt, settleConversationTitleWork as C, openSlackModal as Ca, verifyEventAutomationCredentialSubject as Ci, getTerminalAssistantMessages as Cn, conversationPinnedForUser as Co, saveNotificationSchedule as Cr, getConfigDefaults as Cs, countPendingConversationMessages as Ct, estimateConversationMessagesTokens as D, unfurlSlackLinks as Da, JUNIOR_THREAD_STATE_TTL_MS as Di, instructionTextForProjection as Dn, readConversationBriefThrough as Do, REVIEW_ITEM_REPLIED_REASON as Dr, dropPendingMessages as Dt, buildConversationContext as E, removeReactionFromMessage as Ea, verifyTimerWatchCredentialSubject as Ei, hasTurnInput as En, createPluginConversationEvents as Eo, projectConversationMessages as Er, drainConversationMailbox as Et, turnHasReply as F, wrapSandboxSetupError as Fa, isDashboardLink as Fi, retainRuntimeTurnContext as Fn, FORK_INSTRUCTIONS as Fo, listWaitingConversations as Fr, listActiveConversationIds as Ft, AuthPausePersistenceError as G, sandboxEgressSignalsResponseSchema as Ga, listWorkspaces as Gi, readParentAgentTask as Gn, downloadPrivateSlackFile as Go, isOnlyAssignee as Gr, startConversationWork as Gt, PluginCredentialFailureError as H, consumeSandboxEgressPermissionDeniedSignal as Ha, deleteWorkspace as Hi, TURN_CONTEXT_TAG as Hn, recordSlackAttachment as Ho, canAgentChangeReviewItem as Hr, releaseInboundMessage as Ht, upsertConversationMessage as I, WorkspaceSnapshotNotReadyError as Ia, parseDashboardConversationLink as Ii, stripRuntimeTurnContext as In, loadForkHistory as Io, reviewItemsNeedingUserVersionQuery as Ir, markConversationWorkEnqueued as It, abandonReplacedPendingAuth as J, normalizeSandboxEgressTracePropagationDomains as Ja, WorkspaceValidationError as Ji, renderUntrustedTag as Jn, getSlackClient as Jo, requireReviewItemLinks as Jr, takeDeferredConversationMove as Jt, AuthorizationFlowDisabledError as K, buildSandboxEgressNetworkPolicy as Ka, listWorkspacesByRepository as Ki, renderChildTag as Kn, getFilePermalink as Ko, readReviewItemAgentScope as Kr, steerWebPendingMessages as Kt, calculateContextCompactionTargetTokens as L, getWorkspaceSnapshotNotReadyError as La, parseDashboardPersonLink as Li, trimTrailingAssistantMessages as Ln, notInheritedByForkChild as Lo, searchReviewItems as Lr, moveIdleConversationDestination as Lt, normalizeConversationText as M, isAbortError as Ma, getDashboardReviewItemLink as Mi, isToolResultMessage as Mn, readConversationLastEventSeq as Mo, getReviewItem as Mr, hasRunnableConversationWork as Mt, recordDeliveredAssistantMessage as N, isAlreadyExistsError as Na, getDashboardSettingsLink as Ni, latestTurnContextSection as Nn, readConversationMessageEventSeq as No, insertReviewItem as Nr, isFinalAttempt as Nt, getConversationMessageSlackTs as O, updateSlackMessage as Oa, getDashboardConversationLink as Oi, isAssistantMessage as On, readLatestConversationBrief as Oo, closeReviewItem as Or, getConversation as Ot, trimConversationMessages as P, throwSandboxOperationError as Pa, getDashboardTaskLink as Pi, normalizeToolNameFromResult as Pn, buildSentryConversationUrl as Po, listReplyActionItems as Pr, isInvalidConversationRecordError as Pt, continuableMessages as Q, ToolInputError as Qa, setWorkspaceSnapshotBuild as Qi, findLegacyWebActorUserId as Qn, normalizeSlackConversationId as Qo, EVERYONE_ASSIGNEE as Qr, TurnBudgetExceededError as Qt, getAgentBackgroundCompactionMarkTokens as R, isWorkspaceSnapshotNotReadyError as Ra, setDashboardConversationLinkOptions as Ri, CAPABILITY_SECTION_TAG as Rn, getSlackFileId as Ro, takeReviewItem as Rr, pruneActiveConversation as Rt, resolveConversationTitle as S, openSlackDirectMessage as Sa, bindSlackDirectCredentialSubject as Si, getPiMessageRole as Sn, conversationIsNotUnsubscribedRoot as So, readNotificationSchedule as Sr, projectConversationEvents$1 as Ss, completeConversationWork as St, resolveTaskTitle as T, postSlackMessage as Ta, verifySlackDirectCredentialSubject as Ti, hasRuntimeTurnContext as Tn, viewerMarksFromParticipant as To, isPausedBySlack as Tr, deferConversationMove as Tt, createPluginAuthOrchestration as U, createSandboxEgressCredentialToken as Ua, getWorkspace as Ui, escapeClosingTags as Un, slackAttachmentsVersionQuery as Uo, canReadReviewItem as Ur, requestAnotherSlice as Ut, createPluginEgress as V, consumeSandboxEgressAuthRequiredSignal as Va, createWorkspace as Vi, SESSION_CONTEXT_SECTION_TAG as Vn, readSlackAttachmentSource as Vo, canActOnReviewItem as Vr, releaseConversationWork as Vt, authorizationId as W, parseSandboxEgressCredentialToken as Wa, getWorkspaceByName as Wi, escapeTagText as Wn, SlackActionError as Wo, canUserReadReviewItem as Wr, requestConversationWork as Wt, clearPendingAuth as X, tryWorkspaceRepoCheckoutPath as Xa, loadSnapshotsForProfile as Xi, SANDBOX_EGRESS_AUTH_REQUIRED_MARKER as Xn, isDmChannel as Xo, reviewItemReaderForUser as Xr, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as Xt, canReusePendingAuthLink as Y, SANDBOX_RUNTIME as Ya, invalidateReadySnapshot as Yi, tagJson as Yn, isConversationScopedChannel as Yo, reviewItemNeedsSomeone as Yr, readInboundMessageSender as Yt, getConversationPendingAuth as Z, workspaceRepoCheckoutPath as Za, setWorkspaceSnapshot as Zi, createUserTokenStore as Zn, isSlackRequestTimeout as Zo, reviewItemReaderForUserInConversation as Zr, TURN_LIMIT_WRAP_UP_MESSAGE as Zt, appendConversationMessages as _, slackMentionedUserIds as _a, getWatch as _i, CODE_MODE_CALL_STATUS_TEXT as _n, canAddConversationMessages as _o, readWebPushConfig as _r, createPluginCache as _s, checkInConversationWork as _t, loadProjection as a, proxyVercelSandboxEgressRequest as aa, getSlackToolContext as ai, isAnswerToolName as an, SANDBOX_REPOS_ROOT as ao, getPluginApiRoutes as ar, AttachmentSourceUnavailableError as as, failTurnRecord as at, persistConversationMessages as b, deleteSlackMessage as ba, bindEventAutomationCredentialSubject as bi, persistWithRetry as bn, conversationHasParticipantUser as bo, deletePushSubscription as br, historyItemFromPiMessage as bs, clearExpiredConversationLease as bt, recordAgentsInstructionsUpdated as c, parseOAuthStatePayload as ca, RESOURCE_WATCH_TOOL_SOURCE as ci, replyTextSchema as cn, sandboxSkillDir as co, getPluginSystemPromptContributions as cr, createPluginAnnotations as cs, listTurnSummaries as ct, recordAuthorizationCompleted as d, SLACK_USER_MENTION_RE as da, cancelWatch as di, sanitizeAssistantText as dn, buildCommandScript as do, getPlugins as dr, defaultTimezone as ds, CONVERSATION_WORK_STALE_ENQUEUE_MS as dt, hash as ea, automationCreatorUserId as ei, TurnToolCallLimitExceededError as en, PluginToolDeniedError as eo, getOAuthAccountProviders as er, streamPrivateSlackFile as es, lostWorkerBeforeFirstSave as et, recordAuthorizationRequested as f, escapeSlackMrkdwnText as fa, collectEventMatchKeys as fi, NO_REPLY_TOOL_NAME as fn, buildNonInteractiveShellScript as fo, setPlugins as fr, resolveUserTimezone as fs, ackMessages as ft, recordToolExecutionStarted as g, slackMention as ga, findMatchingWatches as gi, CODEMODE_TOOL_NAME as gn, canAccessConversation as go, setBriefsConfig as gr, credentialAuditSource as gs, cancelHumanFacingPendingMessages as gt, recordSubscribedReplyRoute as h, normalizeSlackStatusText as ha, deliverWatch as hi, readNoReply as hn, createPluginLogger as ho, registration_exports as hr, credentialAuditAttributes as hs, beginConversationResume as ht, loadConversationProjection as i, isVercelSandboxEgressRequest as ia, resolveChannelCapabilities as ii, REPLY_TOOL_NAME as in, SANDBOX_DATA_ROOT as io, createPluginHookRunner as ir, runWithWorkspaceTeamId as is, completeTurnRecord as it, markConversationMessage as j, slackExternalRefIdSchema as ja, getDashboardPersonLink as ji, isToolResultError as jn, readConversationEventPageAround as jo, getOpenReviewItemByDedupeKey as jr, hasConversationStop as jt, isHumanConversationMessage as k, uploadFilesToConversation as ka, getDashboardLinkFilter as ki, isContinuablePiBoundary as kn, readConversationEventPage as ko, countReviewItemsNeedingUser as kr, getConversationWorkState as kt, recordAttachmentsDelivered as l, resolveBaseUrl as la, STOP_WATCHING_TOOL_NAME as li, decideReply as ln, sandboxSkillFile as lo, getPluginTools as lr, listConversationAnnotations as ls, recordTurnSummary as lt, recordMcpProviderConnected as m, normalizeSlackReplyMarkdown as ma, createWatch as mi, isLegacyNoReplyMarker as mn, createPluginModelCostRecorder as mo, coreTaskRegistrations as mr, lookupSlackUserNames as ms, appendInboundMessage as mt, commitMessages as n, ensureDockerDaemon as na, resolveAssignees as ni, createTurnLimitGate as nn, createPluginModel as no, agent_hooks_exports as nr, sleep$2 as ns, saveTurnCheckpoint as nt, loadTurnProjection as o, deliverOAuthAuthorization as oa, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as oi, readTurnAnswer as on, SANDBOX_SKILLS_ROOT as oo, getPluginRoutes as or, resolveRootVisibility as os, getStoredTurnFields as ot, recordGuardianActionReviewed as p, formatSlackLink as pa, createTimerWatch as pi, findLegacyNoReplyMarker as pn, runNonInteractiveCommand as po, validatePlugins as pr, lookupSlackUser as ps, appendExclusiveInboundMessage as pt, AuthorizationPauseError as q, resolveSandboxCommandEnvironment as qa, updateWorkspace as qi, renderTag as qn, getHeaderString as qo, requireReviewItemAssignees as qr, stopConversationWork as qt, loadConnectedMcpProviders as r, getSandboxProvider as ra, createCodeChangePublisher as ri, isTurnExecutionLimitExceededError as rn, SANDBOX_COMMAND_PATH as ro, createPluginEventPublisher as rr, getWorkspaceTeamId as rs, abandonTurnRecord as rt, openConversationProjection as s, formatProviderLabel as sa, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as si, remindMissingAnswer as sn, SANDBOX_WORKSPACE_ROOT as so, getPluginSlackConversationLink as sr, saveObjectAnnotations as ss, getTurnRecord as st, commitAcceptedReply as t, isStale as ta, resolveAssignee as ti, buildTurnErrorResponse as tn, createPluginEmbedder as to, resolvePluginOAuthAccount as tr, withSlackRetries as ts, pauseLostWorkerTurn as tt, recordAuthenticationLinked as u, startOAuthFlow as ua, cancelSubscriptions as ui, getAssistantReplyText as un, sandboxSkillPathResolution as uo, getPluginUserPromptContributions as ur, listConversationAnnotationsById as us, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as ut, hydrateConversationMessages as v, truncateStatusText as va, listWatches as vi, REPORT_BLOCKED_TOOL_NAME as vn, createConversationAccessReader as vo, sendPushNotificationToUser as vr, createDurableLocationConfigurationService as vs, claimInboundMessage as vt, fallbackShortTitle as w, postSlackEphemeralMessage as wa, verifyScheduledAutomationCredentialSubject as wi, getUserMessageInstructionText as wn, conversationViewerMarks as wo, savePushSubscription as wr, setConfigDefaults as ws, deadLetterAttempt as wt, toStoredConversationMessage as x, getSlackMessagePermalink as xa, bindScheduledAutomationCredentialSubject as xi, extractAssistantText as xn, conversationIsMemberRoot as xo, listPushSubscriptions as xr, piMessageFromHistoryItem as xs, completeConversationStop as xt, persistConversationMessageWindow as y, addReactionToMessage as ya, takeDueTimerWatches as yi, readBlockedReport as yn, readConversationAccessFromSql as yo, resolveNotificationTimezone as yr, configValueSchema as ys, clearConsumedConversationWake as yt, getAgentContextCompactionTriggerTokens as z, workspaceSnapshotNotReadyUserMessage as za, createPluginState as zi, REQUEST_CONTEXT_SECTION_TAG as zn, matchSlackAttachments as zo, updateReviewItemContent as zr, recordAttemptFailure as zt };
|